@frumu/tandem-panel 0.4.7 → 0.4.8
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 +11 -0
- package/README.md +36 -2
- package/bin/setup.js +188 -0
- package/dist/assets/index-BIn54WIy.js +2460 -0
- package/dist/assets/index-CCT37xUj.css +1 -0
- package/dist/assets/{markdown-CscybTAD.js → markdown-DMcD1LHz.js} +13 -13
- package/dist/assets/{motion-1UTHZOUD.js → motion-BCvrfAt1.js} +2 -2
- package/dist/assets/preact-vendor-jo0muZ28.js +1 -0
- package/dist/assets/{react-query-tfsRN0su.js → react-query-CeeFMKtE.js} +1 -1
- package/dist/assets/vendor-UXzYZoAT.js +180 -0
- package/dist/index.html +7 -7
- package/package.json +5 -4
- package/dist/assets/index-BklSdD7w.js +0 -558
- package/dist/assets/index-CGq1XaYq.css +0 -1
- package/dist/assets/preact-vendor-CErzQRjo.js +0 -1
- package/dist/assets/vendor-B5SLbWPm.js +0 -42
|
@@ -0,0 +1,2460 @@
|
|
|
1
|
+
import{u as e,d as w,A as Pt,y as be,T as L,q as ut,R as Oi,x as Ei,k as ta,h as Di,e as ji,f as Ui}from"./preact-vendor-jo0muZ28.js";import{u as Z,a as aa,b as xe,c as Bi,Q as Fi}from"./react-query-CeeFMKtE.js";import{c as ie,o as $t,d as un,r as Tr,e as mn,f as ha,g as Fa,h as Ki,W as Li,U as Wi,C as zi,X as Ji,T as Qi,j as Gi,S as Hi,k as Vi,l as Yi,m as Xi,p as Zi,q as eo,t as to,u as ao,v as no,w as ro,x as so,y as io,z as oo,R as lo,A as co,B as uo,P as mo,D as po,E as ho,F as go,G as fo,H as bo,I as vo,J as yo,N as wo,K as xo,L as ko,O as No,V as _o,Y as So,Z as Io,_ as Co,$ as Ao,a0 as Po,a1 as To,a2 as Ro,a3 as qo,a4 as Mo,a5 as $o,a6 as Oo,a7 as Eo,a8 as Do,a9 as jo,aa as Uo,ab as Bo,ac as Fo,ad as Ko,ae as Lo,af as Wo,ag as zo,ah as Jo,ai as Qo,aj as Go,ak as Ho,al as Vo,am as Yo,an as Xo,ao as Zo,ap as el,aq as tl,ar as al,as as nl,at as rl,au as sl,av as il,aw as nr,ax as ol}from"./vendor-UXzYZoAT.js";import{m as Me,A as Tt,u as Fs}from"./motion-BCvrfAt1.js";import{g as Ks,p as ll}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 l of s)if(l.type==="childList")for(const d of l.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function n(s){const l={};return s.integrity&&(l.integrity=s.integrity),s.referrerPolicy&&(l.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?l.credentials="include":s.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(s){if(s.ep)return;s.ep=!0;const l=n(s);fetch(s.href,l)}})();class cl 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 Vr=ie().or($t({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);un().transform(a=>a);Tr(ie(),un()).transform(a=>a);const dl=$t({ready:mn().optional(),phase:ie().optional(),workspace_root:ie().optional(),workspaceRoot:ie().optional()}).passthrough().transform(a=>({...a,workspaceRoot:a.workspace_root??a.workspaceRoot})),Jn=$t({id:ie(),title:ie(),created_at_ms:ha().optional(),createdAtMs:ha().optional(),directory:ie().optional(),workspace_root:ie().optional(),workspaceRoot:ie().optional(),archived:mn().optional()}).passthrough().transform(a=>({...a,createdAtMs:a.created_at_ms??a.createdAtMs??0,workspaceRoot:a.workspace_root??a.workspaceRoot})),Yr=$t({sessions:Fa(Jn).optional().default([]),count:ha().optional().default(0)}).passthrough(),ul=$t({active:$t({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}),Ls=$t({ok:mn().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})),Ws=$t({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:ha().optional(),finished_at_ms:ha().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})),Xr=$t({ok:mn().default(!0),rev:ha().optional()}).passthrough(),zs=$t({key:ie(),value:un(),rev:ha().optional(),updated_at_ms:ha().optional(),updated_by:ie().optional()}).passthrough().transform(a=>({...a,updatedAtMs:a.updated_at_ms,updatedBy:a.updated_by})),ml=$t({items:Fa(zs).optional().default([]),count:ha().optional().default(0)}).passthrough(),pl=$t({id:ie().optional(),text:ie().optional(),content:ie().optional(),user_id:ie().optional(),userID:ie().optional(),source_type:ie().optional(),sourceType:ie().optional(),tags:Fa(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})),hl=$t({items:Fa(pl).optional().default([]),count:ha().optional().default(0)}).passthrough(),gl=$t({id:ie(),text:ie().optional(),content:ie().optional(),score:ha().optional(),source_type:ie().optional(),sourceType:ie().optional(),run_id:ie().optional(),runID:ie().optional(),tags:Fa(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})),fl=$t({results:Fa(gl).optional().default([]),count:ha().optional().default(0)}).passthrough(),Js=$t({id:ie(),uri:ie(),parent_uri:ie().optional(),node_type:ie(),created_at:ie(),updated_at:ie(),metadata:Tr(ie(),un()).optional()}).passthrough(),bl=$t({l0_preview:ie().optional(),l1_preview:ie().optional(),has_l2:mn()}).passthrough(),vl=$t({node:Js,children:Fa(un()).optional().default([]),layer_summary:bl.optional()}).passthrough(),yl=$t({node:Js.optional()}).passthrough(),wl=$t({tree:Fa(vl).optional().default([])}).passthrough(),xl=$t({ok:mn(),distillation_id:ie().optional(),session_id:ie().optional(),facts_extracted:ha().optional()}).passthrough(),kl=$t({type:ie(),properties:Tr(ie(),un()).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 l=JSON.stringify(t).substring(0,200);throw new cl(n,r,s.error.issues,l)}return s.data}function Nl(a){const t=a.trim();if(!t||t===": keep-alive"||t.startsWith(":"))return null;try{const n=JSON.parse(t),r=kl.safeParse(n);return r.success?r.data:null}catch{return null}}async function*Ya(a,t,n){const r=n?.connectTimeoutMs??3e4,s=new AbortController,l=setTimeout(()=>s.abort(),r),d=n?.signal?_l([s.signal,n.signal]):s.signal;let u;try{u=await fetch(a,{headers:{Accept:"text/event-stream",Authorization:`Bearer ${t}`,"Cache-Control":"no-cache"},signal:d})}finally{clearTimeout(l)}if(!u.ok){const 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,_=u.body.getReader();let D="";try{for(;;){const{done:x,value:P}=await _.read();if(x)break;D+=p.decode(P,{stream:!0});const O=D.split(`
|
|
2
|
+
`);D=O.pop()??"";let k="";for(const J of O)if(J.startsWith("data:"))k+=J.slice(5).trimStart();else if(J===""&&k){const A=Nl(k);A&&(yield A),k=""}}}finally{_.releaseLock()}}function _l(a){const t=new AbortController;for(const n of a){if(n.aborted){t.abort(n.reason);break}n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}const da=a=>typeof a=="string"&&a.trim().length>0?a:null,Sl=a=>{try{const t=Vr.parse(a);if(t)return t}catch{const t=a.run||null;if(t)try{const n=Vr.parse(t);if(n)return n}catch{}}throw new Error("Run ID missing in engine response")};class Il{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 Tl(this.baseUrl,this.token,this.timeoutMs,n),this.permissions=new Rl(n),this.questions=new ql(n),this.providers=new Ml(n),this.identity=new $l(n),this.channels=new Ol(n),this.mcp=new El(n,this._requestText.bind(this));const r=()=>this.token;this.routines=new Ll(this.baseUrl,r,n),this.automations=new zl(this.baseUrl,r,n),this.automationsV2=new Jl(this.baseUrl,r,n),this.optimizations=new Ql(n),this.workflowPlans=new Wl(n),this.memory=new Dl(n),this.skills=new jl(n),this.packs=new Ul(n),this.capabilities=new Bl(n),this.resources=new Fl(this.baseUrl,r,n),this.browser=new Cl(n),this.workflows=new Al(this.baseUrl,r,n),this.bugMonitor=new Pl(n),this.coder=new Kl(n),this.agentTeams=new Gl(n),this.missions=new Hl(n)}setToken(t){this.token=t,this.sessions.setToken(t)}async health(){const t=await this._request("/global/health");return jt(dl,t,"/global/health",200)}async listToolIds(){return this._request("/tool/ids")}async listTools(){const t=await this._request("/tool");return Array.isArray(t)?t:[]}async executeTool(t,n){return this._request("/tool/execute",{method:"POST",body:JSON.stringify({tool:t,args:n??{}})})}stream(t,n,r){const s=new URLSearchParams({sessionID:t});n&&s.set("runID",n);const l=`${this.baseUrl}/event?${s.toString()}`;return Ya(l,this.token,r)}globalStream(t){const n=`${this.baseUrl}/global/event`;return Ya(n,this.token,t)}async runEvents(t,n){const r=new URLSearchParams;n?.sinceSeq!==void 0&&r.set("since_seq",String(n.sinceSeq)),n?.tail!==void 0&&r.set("tail",String(n.tail));const s=r.toString()?`?${r.toString()}`:"",l=await this._request(`/run/${encodeURIComponent(t)}/events${s}`);return Array.isArray(l)?l:[]}async _request(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let l;try{l=await fetch(`${this.baseUrl}${t}`,{...n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(l.status!==204){if(!l.ok){const d=await l.text().catch(()=>"");throw new Error(`Request failed (${l.status} ${l.statusText}): ${d}`)}return l.json()}}async _requestText(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let l;try{l=await fetch(`${this.baseUrl}${t}`,{...n,headers:{Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(!l.ok){const d=await l.text().catch(()=>"");throw new Error(`Request failed (${l.status} ${l.statusText}): ${d}`)}return l.text()}}class Cl{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 Al{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){const n=await this.req("/workflows")??{},r=Array.isArray(n.workflows)?n.workflows:[];return{workflows:r,count:typeof n.count=="number"?n.count:r.length}}async get(t){return(await this.req(`/workflows/${encodeURIComponent(t)}`)).workflow??{}}async validate(t){return this.req("/workflows/validate",{method:"POST",body:JSON.stringify(t??{})})}async simulate(t){return this.req("/workflows/simulate",{method:"POST",body:JSON.stringify(t)})}events(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId,s=t?.run_id??t?.runId;r&&n.set("workflow_id",r),s&&n.set("run_id",s);const l=n.toString()?`?${n.toString()}`:"";return Ya(`${this.baseUrl}/workflows/events${l}`,this.getToken(),{signal:t?.signal})}async listRuns(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r),t?.limit!==void 0&&n.set("limit",String(t.limit));const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflows/runs${s}`)??{},u=Array.isArray(d.runs)?d.runs:[];return{runs:u,count:typeof d.count=="number"?d.count:u.length}}async getRun(t){return(await this.req(`/workflows/runs/${encodeURIComponent(t)}`)).run??{}}async run(t,n){return this.req(`/workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n??{})})}async listHooks(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r);const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflow-hooks${s}`)??{},u=Array.isArray(d.hooks)?d.hooks:[];return{hooks:u,count:typeof d.count=="number"?d.count:u.length}}async patchHook(t,n){return this.req(`/workflow-hooks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}}class Pl{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 Tl{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(Yr,s,"/session",200)}async get(t){const n=await this.req(`/session/${encodeURIComponent(t)}`);return jt(Jn,n,`/session/${t}`,200)}async update(t,n){const r=await this.req(`/session/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return jt(Jn,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(ul,n,`/session/${t}/run`,200)}async promptAsync(t,n,r,s){return this.promptAsyncParts(t,[{type:"text",text:n}],r,s)}async promptAsyncParts(t,n,r,s){const l={parts:n};r?.provider&&r?.model&&(l.model={providerID:r.provider,modelID:r.model}),s?.toolMode&&(l.toolMode=s.toolMode),s?.toolAllowlist?.length&&(l.toolAllowlist=s.toolAllowlist),s?.contextMode&&(l.contextMode=s.contextMode);const d=`/session/${encodeURIComponent(t)}/prompt_async?return=run`,u=new AbortController,p=setTimeout(()=>u.abort(),this.timeoutMs);let _;try{_=await fetch(`${this.baseUrl}${d}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(l),signal:u.signal})}finally{clearTimeout(p)}if(_.status===409){const P=(await _.json().catch(()=>({}))).activeRun,O=da(P?.runID)||da(P?.runId)||da(P?.run_id);if(O)return{runId:O}}if(!_.ok){const x=await _.text().catch(()=>"");throw new Error(`promptAsyncParts failed (${_.status}): ${x}`)}const D=await _.json();return{runId:Sl(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 da(s.reply)||da(s.text)||da(s.output)||""}async abort(t){return this.req(`/session/${encodeURIComponent(t)}/abort`,{method:"POST",body:JSON.stringify({})})}async cancel(t){return this.req(`/session/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})})}async cancelRun(t,n){return this.req(`/session/${encodeURIComponent(t)}/run/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})})}async fork(t){const n=await this.req(`/session/${encodeURIComponent(t)}/fork`,{method:"POST",body:JSON.stringify({})});return jt(Jn,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(Yr,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 Rl{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 ql{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 Ml{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 $l{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 Ol{constructor(t){this.req=t}async config(){return this.req("/channels/config")}async status(){return this.req("/channels/status")}async put(t,n){return this.req(`/channels/${t}`,{method:"PUT",body:JSON.stringify(n)})}async delete(t){return this.req(`/channels/${t}`,{method:"DELETE"})}async verify(t,n={}){return this.req(`/channels/${t}/verify`,{method:"POST",body:JSON.stringify(n)})}}class El{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 Dl{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(fl,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(hl,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(yl,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()}`:"",l=await this.req(`/memory/context/tree${s}`);return jt(wl,l,"/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 jl{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 Ul{constructor(t){this.req=t}async list(){return this.req("/packs")}async inspect(t){return this.req(`/packs/${encodeURIComponent(t)}`)}async install(t){return this.req("/packs/install",{method:"POST",body:JSON.stringify(t)})}async installFromAttachment(t){return this.req("/packs/install_from_attachment",{method:"POST",body:JSON.stringify(t)})}async uninstall(t){return this.req("/packs/uninstall",{method:"POST",body:JSON.stringify(t)})}async export(t){return this.req("/packs/export",{method:"POST",body:JSON.stringify(t)})}async detect(t){return this.req("/packs/detect",{method:"POST",body:JSON.stringify(t)})}async updates(t){const r=await this.req(`/packs/${encodeURIComponent(t)}/updates`)||{},s=Array.isArray(r.updates)?r.updates:[];return{pack_id:da(r.pack_id)??void 0,name:da(r.name)??void 0,current_version:da(r.current_version)??void 0,updates:s}}async update(t,n){const r=await this.req(`/packs/${encodeURIComponent(t)}/update`,{method:"POST",body:JSON.stringify(n??{})});return{updated:!!r.updated,pack_id:da(r.pack_id)??void 0,name:da(r.name)??void 0,current_version:da(r.current_version)??void 0,target_version:da(r.target_version)??void 0,reason:da(r.reason)??void 0}}}class Bl{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 Fl{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(ml,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(zs,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(Xr,s,`/resource/${t}`,200)}async patchKey(t,n){const r=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return jt(Xr,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 Ya(`${this.baseUrl}/resource/events${r}`,this.getToken())}}class Kl{constructor(t){this.req=t}async createRun(t){return this.req("/coder/runs",{method:"POST",body:JSON.stringify(t)})}async listRuns(t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit));const r=t?.workflow_mode??t?.workflowMode,s=t?.repo_slug??t?.repoSlug;r&&n.set("workflow_mode",r),s&&n.set("repo_slug",s);const l=n.toString()?`?${n.toString()}`:"",u=await this.req(`/coder/runs${l}`)??{},p=Array.isArray(u.runs)?u.runs:[];return{runs:p,count:typeof u.count=="number"?u.count:p.length}}async getRun(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}`)??{};return{...r,coderRun:r.coder_run??void 0,coder_run:r.coder_run??void 0,run:r.run??void 0}}async executeNext(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-next`,{method:"POST",body:JSON.stringify(n??{})})}async executeAll(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-all`,{method:"POST",body:JSON.stringify(n??{})})}async createFollowOnRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/follow-on-run`,{method:"POST",body:JSON.stringify(n)})}async approveRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n})})}async cancelRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:n})})}async listArtifacts(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/artifacts`)??{},s=Array.isArray(r.artifacts)?r.artifacts:[];return{...r,artifacts:s,count:typeof r.count=="number"?r.count:s.length}}async getMemoryHits(t,n){const r=new URLSearchParams;n?.query&&r.set("q",n.query),n?.limit!==void 0&&r.set("limit",String(n.limit));const s=r.toString()?`?${r.toString()}`:"",d=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-hits${s}`)??{},u=Array.isArray(d.hits)?d.hits:[];return{...d,hits:u,count:typeof d.count=="number"?d.count:u.length}}async createTriageInspectionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-inspection-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageReproductionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-reproduction-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewEvidence(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-evidence`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-summary`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixValidationReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-validation-report`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrDraft(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-draft`,{method:"POST",body:JSON.stringify(n??{})})}async submitPr(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-submit`,{method:"POST",body:JSON.stringify(n??{})})}async createMergeReadinessReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-readiness-report`,{method:"POST",body:JSON.stringify(n)})}async createMergeRecommendationSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-recommendation-summary`,{method:"POST",body:JSON.stringify(n)})}async listMemoryCandidates(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`)??{},s=Array.isArray(r.candidates)?r.candidates:[];return{...r,candidates:s,count:typeof r.count=="number"?r.count:s.length}}async createMemoryCandidate(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`,{method:"POST",body:JSON.stringify(n)})}async promoteMemoryCandidate(t,n,r){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates/${encodeURIComponent(n)}/promote`,{method:"POST",body:JSON.stringify(r??{})})}}class Ll{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(Ls,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(Ws,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 Ya(`${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 Wl{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 zl{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(Ls,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(Ws,n,`/automations/runs/${t}`,200)}async listArtifacts(t){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denyRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}async pauseRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async history(t,n){const r=n!==void 0?`?limit=${n}`:"",s=await this.req(`/automations/${encodeURIComponent(t)}/history${r}`);return Array.isArray(s)?{history:s,count:s.length}:s}events(t){const n=new URLSearchParams,r=t?.automation_id??t?.automationId,s=t?.run_id??t?.runId;r&&n.set("automation_id",r),s&&n.set("run_id",s);const l=n.toString()?`?${n.toString()}`:"";return Ya(`${this.baseUrl}/automations/events${l}`,this.getToken(),{signal:t?.signal})}addArtifact(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(n)})}}class Jl{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 l=n.toString()?`?${n.toString()}`:"";return Ya(`${this.baseUrl}/automations/v2/events${l}`,this.getToken(),{signal:t?.signal})}}class Ql{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 Gl{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 Hl{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 Xn="charcoal_fire",ln=[{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)"}}],Aa={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 Rr(a){let t=String(a||"").trim()||Xn;return t==="web_control"&&(t=Xn),ln.find(n=>n.id===t)||ln[0]}function Vl(a){const t=Rr(a).id,n=ln.findIndex(r=>r.id===t);return n<0?Xn:ln[(n+1)%ln.length].id}function Qs(a,t=typeof document<"u"?document.documentElement:null){const n=Rr(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 Gs(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const Hs="tandem.themeId";function Yl(){try{const a=localStorage.getItem(Hs);return Rr(a).id}catch{return Xn}}function Xl(a){return Qs(a)}function Zl(a){const t=Qs(a);try{localStorage.setItem(Hs,t.id)}catch{}return t}function qn(){const[a,t]=w(()=>Gs());return be(()=>{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 ec(a,t,n){return Math.min(n,Math.max(t,a))}function Zn({className:a="",children:t}){return e("div",{className:`tcp-glow-layer ${a}`.trim(),children:t})}function Mn({className:a="",children:t}){const n=qn();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:Aa.duration.normal,ease:Aa.easing.standard},children:t})}function tc({className:a="",children:t}){const n=qn();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 Vs({className:a="",children:t,as:n="div"}){const r=qn(),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:Aa.duration.normal,ease:Aa.easing.standard}}},initial:r?!1:"hidden",animate:r?void 0:"show",children:t})}function ac({value:a,format:t=r=>String(r),className:n=""}){const r=qn(),[s,l]=w(()=>Number(a||0)),d=Pt(Number(a||0));return be(()=>{const u=Number(a||0);if(!Number.isFinite(u)){l(0),d.current=0;return}if(r){l(u),d.current=u;return}const p=d.current,_=u-p;if(!_){l(u),d.current=u;return}const D=performance.now();let x=0;const P=O=>{const k=ec((O-D)/420,0,1),J=1-Math.pow(1-k,3),A=p+_*J;l(A),k<1?x=window.requestAnimationFrame(P):d.current=u};return x=window.requestAnimationFrame(P),()=>window.cancelAnimationFrame(x)},[r,a]),e("span",{className:n,children:t(Number.isFinite(s)?s:0)})}function ka({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 va({className:a="",children:t}){return e("div",{className:`tcp-toolbar ${a}`.trim(),children:t})}function Nn({className:a="",title:t,children:n,...r}){return e("button",{type:"button",title:t,className:`tcp-icon-btn ${a}`.trim(),...r,children:n})}function je({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 or({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 ft({title:a,subtitle:t,actions:n,className:r="",children:s}){return e(Vs,{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 nc({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 rc({eyebrow:a,title:t,subtitle:n,badges:r,actions:s,className:l=""}){return e(Vs,{className:`tcp-page-header ${l}`.trim(),children:[e(Zn,{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(va,{className:"justify-start lg:justify-end",children:s}):null]})]})}function In({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 er({open:a,title:t,onClose:n,children:r}){const s=qn();return e(Tt,{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:Aa.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(Nn,{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 sc({loginMutation:a,savedToken:t,onCheckEngine:n,controlPanelName:r}){const[s,l]=w(t),[d,u]=w(!0),[p,_]=w(""),[D,x]=w(!1);return e("main",{className:"relative min-h-screen overflow-hidden px-5 py-8",children:[e(Zn,{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(ft,{title:r,subtitle:"Authenticate against your Tandem engine to continue.",children:e("form",{className:"grid gap-3",onSubmit:P=>{if(P.preventDefault(),!s.trim()){x(!1),_("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:P=>l(P.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:P=>u(P.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 P=await n();x(!0),_(P)}catch(P){x(!1),_(P instanceof Error?P.message:String(P))}},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(ka,{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 ic(a){be(()=>{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 oc({open:a,onClose:t,actions:n}){const[r,s]=w("");be(()=>{a||s("")},[a]),be(()=>{if(!a)return;const d=u=>{u.key==="Escape"&&t()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[a,t]);const l=L(()=>{const d=r.trim().toLowerCase();return d?n.filter(u=>`${u.label} ${u.group}`.toLowerCase().includes(d)):n},[n,r]);return e(Tt,{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:[l.map(d=>e("button",{type:"button",className:"tcp-btn w-full justify-between",onClick:()=>{d.onSelect(),t()},children:[e("span",{className:"inline-flex items-center gap-1.5",children:[e("i",{"data-lucide":"list"}),e("span",{children:d.label})]}),e("span",{className:"tcp-subtle text-xs",children:d.group})]},d.id)),l.length?null:e("p",{className:"tcp-subtle px-1 py-2",children:"No matching action."})]})]})]})}):null})}const Ys=[["dashboard","Dashboard","home"],["chat","Chat","message-square"],["studio","Studio","network"],["automations","Automations","bot"],["agents","Agents","users"],["orchestrator","Orchestrator","sparkles"],["memory","Memory","database"],["feed","Live Feed","radio"],["settings","Settings","settings"],["packs","Packs","package"],["teams","Teams","users"],["channels","Channels","message-circle"],["mcp","MCP","link"],["bug-monitor","Bug Monitor","bug-play"],["files","Files","folder-open"],["packs-detail","Packs","package"],["teams-detail","Teams","users"]],lc=Ys.filter(([a])=>["dashboard","chat","studio","automations","agents","orchestrator","memory","feed","settings"].includes(a)),Xs={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"}},Zs=Ys,cc=lc,dc=new Map([["packs","automations"],["teams","automations"],["swarm","orchestrator"],["failure-reporter","bug-monitor"]]),uc=new Set(Zs.map(([a])=>a));function qr(a,t="dashboard"){const n=dc.get(String(a||"").trim());return n||(uc.has(a)?a:t)}function Zr(a="dashboard"){const t=(window.location.hash||`#/${a}`).replace(/^#\//,"");return qr(t.split("?")[0].split("/")[0].trim(),a)}function mc(a){window.location.hash=`#/${a}`}function pc(){const[a,t]=w(()=>Zr());be(()=>{const r=()=>t(Zr());return window.addEventListener("hashchange",r),()=>window.removeEventListener("hashchange",r)},[]);const n=ut(r=>{const s=qr(r);if(window.location.hash!==`#/${s}`){mc(s);return}t(s)},[]);return{route:a,navigate:n}}const ei=Oi({toast:()=>{}});function hc({children:a}){const[t,n]=w([]),r=ut((l,d)=>{const u=Math.random().toString(36).slice(2);n(p=>[...p,{id:u,kind:l,text:d}].slice(-4)),window.setTimeout(()=>{n(p=>p.filter(_=>_.id!==u))},3500)},[]),s=L(()=>({toast:r}),[r]);return e(ei.Provider,{value:s,children:[a,e("div",{className:"toasts","aria-live":"polite","aria-atomic":"true",children:e(Tt,{children:t.map(l=>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-${l.kind}`,children:l.text},l.id))})})]})}function gc(){return Ei(ei)}function Kt({title:a,subtitle:t,children:n,actions:r,className:s}){return e(ft,{title:a,subtitle:t,actions:r,className:s||"",children:n})}function We({text:a,title:t,action:n}){return e(nc,{text:a,title:t,action:n})}function Ht(a){return JSON.stringify(a,null,2)}function lr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function fc(a){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(Number(a||0))}function bc(a){const{api:t,client:n,navigate:r,providerStatus:s}=a,[l,d]=w(""),u=new Set(["workflow","bug_monitor_triage"]),p=Z({queryKey:["dashboard","health"],queryFn:()=>t("/api/system/health"),refetchInterval:15e3}),_=Z({queryKey:["dashboard","sessions"],queryFn:()=>n.sessions.list({pageSize:8}).catch(()=>[]),refetchInterval:15e3}),D=Z({queryKey:["dashboard","routines"],queryFn:()=>n.routines.list().catch(()=>({routines:[]})),refetchInterval:2e4}),x=Z({queryKey:["dashboard","swarm"],queryFn:()=>t("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:6e3}),P=Z({queryKey:["dashboard","workflow-context-runs"],queryFn:()=>t("/api/engine/context/runs?limit=12").catch(()=>({runs:[]})),refetchInterval:6e3}),O=Z({queryKey:["dashboard","workflow-context-run",l],enabled:!!l,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(l)}`).catch(()=>({run:null}))}),k=Z({queryKey:["dashboard","workflow-context-blackboard",l],enabled:!!l,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(l)}/blackboard`).catch(()=>({blackboard:null}))}),J=lr(_.data,"sessions"),A=lr(D.data,"routines"),G=lr(P.data,"runs").filter(R=>u.has(String(R?.run_type||"").trim().toLowerCase())),ee=!!(p.data?.engine?.ready||p.data?.engine?.healthy),de=String(x.data?.status||"unknown"),S=["planning","awaiting_approval","running","executing"].includes(de.toLowerCase()),I=G.filter(R=>["queued","planning","running","awaiting_approval"].includes(String(R?.status||"").trim().toLowerCase())),Q=L(()=>[{label:"Recent sessions",value:J.length,tone:"info",helper:"Latest active conversation surfaces"},{label:"Automations",value:A.length,tone:"ok",helper:"Configured routines and schedules"},{label:"Swarm status",value:S?1:0,tone:S?"warn":"ghost",helper:de},{label:"Provider ready",value:s.ready?1:0,tone:s.ready?"ok":"warn",helper:s.ready?s.defaultModel:"Needs setup"},{label:"Context runs",value:G.length,tone:I.length?"warn":"info",helper:I.length?`${I.length} active`:"Workflow + triage visibility"}],[I.length,s.defaultModel,s.ready,A.length,J.length,S,de,G.length]);return e(Mn,{className:"grid gap-4",children:[e(ft,{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(je,{tone:ee?"ok":"warn",children:ee?"Engine healthy":"Engine checking"}),e(je,{tone:s.ready?"ok":"warn",children:s.ready?s.defaultProvider:"Provider setup required"}),S?e(ka,{tone:"live",text:`Swarm ${de}`}):e(je,{tone:"ghost",children:["Swarm ",de]})]})]}),e("div",{className:"grid gap-3",children:e(va,{className:"justify-start",children:[e("button",{className:"tcp-btn-primary w-full sm:w-auto",onClick:()=>r("chat"),children:[e("i",{"data-lucide":"message-square"}),"Chat session"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"sparkles"}),"Plan work"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Automations"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("settings"),children:[e("i",{"data-lucide":"settings"}),"Configure runtime"]})]})})]}),e("div",{className:"mt-5",children:[e("div",{className:"dashboard-kpis",children:Q.map(R=>e("div",{children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("span",{className:"dashboard-kpi-label",children:R.label}),e(je,{tone:R.tone,children:R.helper})]}),e("strong",{children:e(ac,{value:R.value,format:fc})})]},R.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:[A.length," routines"]})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${A.length?"scheduled":"manual"}`,style:{width:`${Math.min(100,Math.max(12,A.length*12))}%`}})})]})]})]})]}),e(In,{main:e(ft,{title:"Recent sessions",subtitle:"Latest conversations, ready to reopen.",children:e("div",{className:"grid gap-2",children:J.length?J.map(R=>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(R.title||R.id||"Session")]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(R.id||R.session_id||"")})]},String(R.id||R.session_id||Math.random()))):e(We,{text:"Start a conversation to populate recent sessions here."})})}),aside:e("div",{className:"grid gap-4",children:[e(ft,{title:"Context visibility",subtitle:"Recent workflow and failure-triage context runs with their current projection state.",children:[e(va,{className:"mb-3",children:[e(je,{tone:I.length?"warn":"info",children:[G.length," recent"]}),e("button",{className:"tcp-btn",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]})]}),e("div",{className:"grid gap-2",children:G.length?G.slice(0,5).map(R=>e("button",{className:"tcp-list-item text-left",onClick:()=>d(String(R?.run_id||"").trim()),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:String(R?.objective||R?.run_id||"Context run")}),e("div",{className:"flex flex-wrap items-center gap-2",children:[e(je,{tone:"ghost",children:String(R?.run_type||"context")}),e(je,{tone:["failed","cancelled"].includes(String(R?.status||"").toLowerCase())?"err":["running","queued","planning"].includes(String(R?.status||"").toLowerCase())?"warn":"ok",children:String(R?.status||"unknown")})]})]}),e("div",{className:"tcp-subtle text-xs",children:String(R?.run_id||"")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Array.isArray(R?.tasks)?R.tasks.length:0," tasks ·"," ",Array.isArray(R?.steps)?R.steps.length:0," steps"]})]},String(R?.run_id||Math.random()))):e(We,{text:"Workflow and failure-triage context runs will appear here once they execute."})})]}),e(ft,{title:"Automation snapshot",subtitle:"Schedules and run-ready routines.",children:[e(va,{className:"mb-3",children:[e(je,{tone:"info",children:[A.length," loaded"]}),e("button",{className:"tcp-btn",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Manage"]})]}),e("div",{className:"grid gap-2",children:A.length?A.slice(0,4).map(R=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:String(R.name||R.id||"Routine")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(R.schedule||R.status||"manual")})]},String(R.id||R.routine_id||Math.random()))):e(We,{text:"No routines are configured yet."})})]}),e(ft,{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: ",de]})]}),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(er,{open:!!l,onClose:()=>d(""),title:l||"Workflow context run",children:l?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(O.data?.run?.objective||l)}),e(je,{tone:"info",children:String(O.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["type: ",String(O.data?.run?.run_type||"workflow")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium mb-2",children:"Projected blackboard"}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(k.data?.blackboard?.tasks)?k.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(k.data?.blackboard?.artifacts)?k.data.blackboard.artifacts.length:0]})]}),e("pre",{className:"tcp-code",children:Ht({run:O.data?.run||null,blackboard:k.data?.blackboard||null})})]}):null})]})}const vc={Activity:il,Archive:sl,ArrowLeftToLine:rl,ArrowUpCircle:nl,BadgeCheck:al,Binary:tl,Bug:el,BugPlay:Zo,Bot:Xo,BookOpen:Yo,Check:Vo,ChevronDown:Ho,ChevronRight:Go,ClipboardList:Qo,Clock:Jo,Clock3:zo,Copy:Wo,CopyPlus:Lo,ExternalLink:Ko,Cpu:Fo,Database:Bo,Download:Uo,FileUp:jo,Filter:Do,FilterX:Eo,FlaskConical:Oo,FolderOpen:$o,History:Mo,Home:qo,Info:Ro,KeyRound:To,Link:Po,LoaderCircle:Ao,List:Co,LogOut:Io,MessageCircle:So,MessageSquare:_o,MessagesSquare:No,Menu:ko,MonitorCog:xo,Network:wo,Paperclip:yo,Package:vo,PaintBucket:bo,Pencil:fo,Play:go,PlugZap:ho,Plus:po,Pause:mo,Radio:uo,RefreshCw:co,RotateCw:lo,Save:oo,Search:io,Send:so,Settings:ro,Settings2:no,ShieldAlert:ao,ShieldCheck:to,SlidersHorizontal:eo,Sparkles:Zi,Siren:Xi,Share2:Yi,Shield:Vi,Square:Hi,Trash2:Gi,TriangleAlert:Qi,X:Ji,XCircle:zi,Users:Wi,Workflow:Li},xr=new Set;let kr=0;function yc(){kr=0;const a=[...xr];xr.clear();for(const t of a)Ki({icons:vc,attrs:{width:"16",height:"16","stroke-width":"1.8"},...t?{root:t}:{}})}function ya(a){xr.add(a||null),!kr&&(kr=window.requestAnimationFrame(yc))}Ks.setOptions({gfm:!0,breaks:!0});function cn(a){const t=String(a||""),n=Ks.parse(t,{async:!1});return ll.sanitize(n)}const Nr="tcp.chat.session";function ti(a){return String(a?.id||a?.session_id||a?.sessionID||"").trim()}function wc(a){const t=String(a?.title||a?.name||"").trim();if(t)return t;const n=ti(a);return n?`Session ${n.slice(0,8)}`:"Session"}function xc(a){return Array.isArray(a)?a:Array.isArray(a?.sessions)?a.sessions:[]}function kc(a){return String(a?.title||"").trim().toLowerCase().startsWith("__provider_test__")}function es(a){return xc(a).filter(t=>!kc(t)).map(t=>({id:ti(t),title:wc(t),raw:t})).filter(t=>!!t.id)}async function Nc(a,t){try{const n=await a.sessions.list({pageSize:50}),r=es(n);if(r.length>0)return r}catch{}try{const n=await t("/api/engine/session?page_size=50",{method:"GET"});return es(n)}catch{return[]}}function ts(){try{return localStorage.getItem(Nr)||""}catch{return""}}function _c(a){try{a?localStorage.setItem(Nr,a):localStorage.removeItem(Nr)}catch{}}function Sc(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 Ic(a){return String(a?.info?.role||a?.role||a?.message_role||a?.type||a?.author||"assistant").trim().toLowerCase()}function Cc(a){const t=Sc(a?.parts);if(t)return t;const n=[a?.content,a?.text,a?.message,a?.delta,a?.body].map(s=>typeof s=="string"?s:"").find(s=>s.trim().length>0);if(n)return n.trim();const r=a?.content;if(Array.isArray(r)){const s=r.map(l=>l?typeof l=="string"?l:typeof l?.text=="string"?l.text:typeof l?.content=="string"?l.content:"":"").filter(Boolean);if(s.length)return s.join(`
|
|
4
|
+
`).trim()}return""}function Ac(a,t){return a==="assistant"?t||"Assistant":a==="user"?"User":a==="system"?"System":a||"Assistant"}function Pc(a,t,n){const r=Ic(a),s=Cc(a),l=r==="assistant"||r==="system";return{id:String(a?.id||a?.messageID||a?.message_id||a?.event_id||`${r}-${t}`).trim()||`${r}-${t}`,role:r,displayRole:Ac(r,n),text:s,markdown:l}}function ai(a,t){return(Array.isArray(a)?a:Array.isArray(a?.messages)?a.messages:[]).map((r,s)=>Pc(r,s,t))}const as=new Set(["tool.called","tool_call.started","session.tool_call"]),ns=new Set(["tool.result","tool_call.completed","tool_call.failed","session.tool_result"]),Tc=new Set(["run.complete","run.completed","session.run.finished","session.run.completed"]),Rc=new Set(["run.failed","session.run.failed","run.cancelled","run.canceled","session.run.cancelled","session.run.canceled"]);function ni(a){return String(a||"").trim().replace(/\s+/g," ").replace(/[<>]/g,"")}function rn(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return ni(t.tool||t.name||t.toolName||t.tool_id||t.toolID||n.tool||n.name||n.toolName||"")}function bn(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 cr(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 jn(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:ni(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 rs(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 qc(a,t){const n=t&&typeof t=="object"?t:{},r=String(a||"").trim()||"pack.event",s=String(n.path||"").trim(),l=String(n.attachment_id||n.attachmentId||"").trim(),d=String(n.connector||"").trim(),u=String(n.channel_id||n.channelId||"").trim(),p=String(n.sender_id||n.senderId||"").trim(),_=String(n.name||"").trim(),D=String(n.version||"").trim(),x=String(n.error||"").trim(),P=[];_&&P.push(_),D&&P.push(D),s&&P.push(s),d&&P.push(d),u&&P.push(`channel=${u}`),p&&P.push(`sender=${p}`);const O=P.join(" · ");return{id:`${r}:${l||s||_||"event"}`,type:r,path:s,attachmentId:l,connector:d,channelId:u,senderId:p,error:x,summary:O||r,at:Date.now()}}const Cn=new Map;function ri(a,t){return`${t?"cred":"anon"}:${a}`}function Mc(a,t=!0){const n=ri(a,t),r=Cn.get(n);if(r&&!r.closed)return r;const s=new EventSource(a,{withCredentials:t}),l={source:s,listeners:new Set,errorListeners:new Set,refs:0,closed:!1};return s.onmessage=d=>{for(const u of[...l.listeners])try{u(d)}catch{}},s.onerror=d=>{for(const u of[...l.errorListeners])try{u(d)}catch{}s.readyState===EventSource.CLOSED&&(l.closed=!0,Cn.delete(n))},Cn.set(n,l),l}function Mr(a,t,n={}){const r=n.withCredentials!==!1,s=ri(a,r),l=Mc(a,r);return l.refs+=1,l.listeners.add(t),typeof n.onError=="function"&&l.errorListeners.add(n.onError),()=>{const d=Cn.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(),Cn.delete(s)))}}const $c="control-panel",si="tandem_control_panel_chat_auto_approve_tools",Oc="tandem.automations.plannerSeed",Ec={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 ss(a=""){const t=String(a).toLowerCase().split(".").pop()||"";return Ec[t]||"application/octet-stream"}function Dc(a="",t=""){if(!a||!t)return t||"";const n=String(a).replace(/[\\/]+$/,""),r=String(t).replace(/^[\\/]+/,"");return`${n}/${r}`}function jc(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 dr(a,t){return!a||!t?!0:String(a).trim()===String(t).trim()}function Uc(a){const t=String(a||"").trim();return t!=="server.connected"&&t!=="engine.lifecycle.ready"}function Bc(a){return a==="completed"?"chat-tool-chip-ok":a==="failed"?"chat-tool-chip-failed":"chat-tool-chip-running"}function Fc(){try{return localStorage.getItem(si)==="1"}catch{return!1}}function Kc(a){try{localStorage.setItem(si,a?"1":"0")}catch{}}function Lc(a){try{const t=String(a?.prompt||a?.goal||"").trim();if(!t)return;sessionStorage.setItem(Oc,JSON.stringify({prompt:t,plan_source:String(a?.plan_source||"chat_setup").trim()||"chat_setup"}))}catch{}}function Ja(a){return a instanceof Error?a.message:String(a)}function Wc(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 zc({client:a,api:t,toast:n,providerStatus:r,identity:s,navigate:l}){const d=aa(),u=!!Fs(),p=Pt(null),_=Pt(null),D=Pt(null),x=Pt(null),P=Pt(null),O=Pt(!0),k=Pt(null),J=Pt(null),[A,G]=w([]),[ee,de]=w(!1),[S,I]=w(ts()),[Q,R]=w([]),[we,y]=w(!1),[v,U]=w(""),[pe,X]=w([]),[$e,Oe]=w([]),[Ke,ae]=w(!1),[ue,M]=w(""),[he,Te]=w(!1),[Re,re]=w([]),[Ue,qe]=w(new Set),[ze,V]=w([]),[He,ne]=w(new Set),[Ie,ht]=w([]),[se,F]=w(new Set),[rt,mt]=w(Fc()),[ot,St]=w(!1),[Ee,Rt]=w([]),[yt,Ot]=w(null),[Je,Qe]=w(null),nt=L(()=>A.find(j=>j.id===S)?.title||"Chat",[S,A]);be(()=>(O.current=!0,()=>{O.current=!1,P.current?.abort(),k.current&&window.clearTimeout(k.current),J.current&&window.clearTimeout(J.current)}),[]),be(()=>{const h=p.current;h&&ya(h)},[A,pe,$e,Ie,Re,ze,Q,ee,he,ue]),be(()=>{_c(S)},[S]),be(()=>{const h=_.current;h&&(h.style.height="0px",h.style.height=`${Math.min(h.scrollHeight,180)}px`)},[v]),be(()=>{const h=x.current;h&&(h.scrollTop=h.scrollHeight)},[Q,ue,he]);const ye=ut(async()=>{const h=await Nc(a,t);O.current&&(G(h),I(j=>{if(j&&h.some(K=>K.id===j))return j;const z=ts();return z&&h.some(K=>K.id===z)?z:h[0]?.id||""}))},[t,a]),Ne=ut(async()=>{const h=String(r.defaultProvider||"").trim(),j=String(r.defaultModel||"").trim();if(h&&j)return{providerID:h,modelID:j};try{const z=await a.providers.config(),K=String(z?.default||"").trim(),H=String(z?.providers?.[K]?.defaultModel||"").trim();if(K&&H)return{providerID:K,modelID:H}}catch{}return null},[a.providers,r.defaultModel,r.defaultProvider]),Ve=ut(async()=>{const h=await Ne(),j={title:`Chat ${new Date().toLocaleTimeString()}`};h&&(j.provider=h.providerID,j.model=h.modelID);const z=await a.sessions.create(j),K=String(z||"").trim();if(!K)throw new Error("Failed to create session.");return I(K),await ye(),K},[a.sessions,ye,Ne]),le=ut(h=>{const j=ai(h,s.botName||"Assistant");R(j)},[s.botName]),it=ut(async()=>{if(!S){R([]);return}y(!0);try{const h=await a.sessions.messages(S).catch(()=>({messages:[]}));if(!O.current)return;le(h)}finally{O.current&&y(!1)}},[a.sessions,le,S]),N=ut(()=>{re([]),qe(new Set)},[]),W=ut(()=>{V([]),ne(new Set)},[]),ve=ut((h,j,z="")=>{const K=String(h||"").trim();if(!K)return;let H=!0;z&&(qe(fe=>{if(fe.has(z))return H=!1,fe;const Be=new Set(fe);return Be.add(z),Be.size>1e3?new Set([z]):Be}),!H)||re(fe=>[{id:`${K}:${j}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,tool:K,status:j,at:Date.now()},...fe].slice(0,80))},[]),De=ut((h,j)=>{const z=qc(h,j);if(!String(z.type).toLowerCase().startsWith("pack."))return;let H=!0;ne(fe=>{if(fe.has(z.id))return H=!1,fe;const Be=new Set(fe);return Be.add(z.id),Be.size>400?new Set([z.id]):Be}),H&&V(fe=>[z,...fe].slice(0,80))},[]),o=ut(h=>{rs(h?.status||"")&&ht(j=>{const z=j.findIndex(K=>K.id===h.id);if(z>=0){const K=[...j];return K[z]={...K[z],...h},K}return[h,...j]})},[]),b=ut(h=>{ht(j=>j.filter(z=>z.id!==h))},[]),T=ut(async()=>{const h=await a.permissions.list().catch(()=>({requests:[]})),z=(Array.isArray(h?.requests)?h.requests:[]).map(K=>jn(K)).filter(K=>!!K).filter(K=>dr(K.sessionId,S)).filter(K=>rs(K.status));O.current&&ht(z.slice(0,80))},[a.permissions,S]),C=ut(async(h,j,z=!1)=>{if(!(!h||se.has(h))){F(H=>{const fe=new Set(H);return fe.add(h),fe});try{await a.permissions.reply(h,j),b(h),z||n("ok",`Permission ${j==="deny"?"denied":"approved"} (${h}).`)}catch(H){z||n("err",Ja(H))}finally{F(H=>{const fe=new Set(H);return fe.delete(h),fe}),T()}}},[a.permissions,se,T,b,n]),$=ut(async()=>{if(!(!rt||ot||Ie.length===0)){St(!0);try{for(const h of[...Ie])await C(h.id,"always",!0)}finally{O.current&&St(!1)}}},[rt,ot,Ie,C]),Ye=ut(h=>(Array.isArray(h)?h:Array.isArray(h?.tools)?h.tools:[]).map(z=>{if(typeof z=="string")return z;const K=z||{};return String(K.name||K.id||K.tool||"").trim()}).filter(Boolean),[]),Ze=ut(async()=>{try{const h=await a.listTools?.().catch(()=>null);let j=Ye(h||[]);if(!j.length){const z=await t("/api/engine/tool",{method:"GET"}).catch(()=>[]);j=Ye(z||[])}if(O.current){const z=[...new Set(j)].sort((K,H)=>K.localeCompare(H));Rt(z)}}catch{O.current&&Rt([])}},[t,a,Ye]),bt=ut(h=>new Promise((j,z)=>{const K=`${Date.now()}-${Math.random().toString(16).slice(2)}`;Oe(fe=>[...fe,{id:K,name:h.name,progress:0,error:""}]);const H=new XMLHttpRequest;H.open("POST",`/api/files/upload?dir=${encodeURIComponent($c)}`),H.withCredentials=!0,H.responseType="json",H.setRequestHeader("x-file-name",encodeURIComponent(h.name)),H.upload.onprogress=fe=>{if(!fe.lengthComputable)return;const Be=fe.loaded/fe.total*100;Oe(pt=>pt.map(lt=>lt.id===K?{...lt,progress:Be}:lt))},H.onerror=()=>{Oe(fe=>fe.map(Be=>Be.id===K?{...Be,error:"Network error"}:Be)),window.setTimeout(()=>{Oe(fe=>fe.filter(Be=>Be.id!==K))},1200),z(new Error(`Upload failed: ${h.name}`))},H.onload=()=>{const fe=H.response||{};if(H.status<200||H.status>=300||fe?.ok===!1){const Be=String(fe?.error||`Upload failed (${H.status})`);Oe(pt=>pt.map(lt=>lt.id===K?{...lt,error:Be}:lt)),window.setTimeout(()=>{Oe(pt=>pt.filter(lt=>lt.id!==K))},1600),z(new Error(Be));return}Oe(Be=>Be.filter(pt=>pt.id!==K)),j(fe)},H.send(h)}),[]),qt=ut(async h=>{const j=[...h||[]];if(!j.length)return;let z=0;for(const K of j)try{const H=await bt(K);X(fe=>[{name:String(H?.name||K.name),path:String(H?.path||K.name),size:Number(H?.size||K.size||0),mime:K.type||ss(String(H?.name||K.name)),url:String(H?.absPath||Dc(H?.root,H?.path)||H?.path||K.name)},...fe]),z+=1}catch(H){n("err",Ja(H))}z>0&&n("ok",`Uploaded ${z} file${z===1?"":"s"}.`)},[n,bt]),Ae=ut(async h=>{if(await a.sessions.delete(h),G(j=>j.filter(z=>z.id!==h)),Ot(null),n("ok","Session deleted."),S===h){const j=A.find(z=>z.id!==h)?.id||"";if(j)I(j);else{const z=await Ve();I(z)}}},[a.sessions,Ve,S,A,n]),wt=ut((h,j)=>{const z=String(h||"").trim();if(!z)return;const K=j>0?`
|
|
5
|
+
|
|
6
|
+
${j} attachment${j===1?"":"s"}`:"";R(H=>[...H,{id:`local-user-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"user",displayRole:"User",text:`${z}${K}`,markdown:!1}])},[]),It=ut(async()=>{if(Ke)return;const h=v.trim(),j=[...pe],z=h||(j.length?"Please analyze the attached file(s).":"");if(z){try{const K=await t("/api/engine/setup/understand",{method:"POST",body:JSON.stringify({surface:"control_panel_chat",session_id:S||void 0,text:z,channel:null,trigger:{source:"direct_message",is_direct_message:!0,was_explicitly_mentioned:!1,is_reply_to_bot:!1},scope:{kind:"direct",id:S||"control-panel-chat"}})});if(K.decision!=="pass_through"){const H=Wc(K);if(H){Qe(H),U("");return}}}catch{}U(""),ae(!0),wt(z,j.length);try{let K=S;if(K||(K=await Ve()),!K)throw new Error("No active session.");const H=await Ne();if(!H)throw new Error("No default provider/model configured. Set it in Settings before sending chat.");const fe=j.map(ke=>({type:"file",mime:ke.mime||ss(ke.name||ke.path),filename:ke.name||ke.path||"attachment",url:ke.url||ke.path}));fe.push({type:"text",text:z});const Be=async()=>{const ke=await fetch(`/api/engine/session/${encodeURIComponent(K)}/run`,{method:"GET",credentials:"include"});if(!ke.ok)return"";const ge=await ke.json().catch(()=>({}));return ge?.active?.runID||ge?.active?.runId||ge?.active?.run_id||""},pt=async()=>{const ke=await Be().catch(()=>"");ke&&await fetch(`/api/engine/session/${encodeURIComponent(K)}/run/${encodeURIComponent(ke)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),await fetch(`/api/engine/session/${encodeURIComponent(K)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{});for(let ge=0;ge<50;ge+=1){if(!await Be().catch(()=>""))return!0;await new Promise(Ge=>window.setTimeout(Ge,200))}return!1},lt=async()=>fetch(`/api/engine/session/${encodeURIComponent(K)}/prompt_async?return=run`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({parts:fe,model:{providerID:H.providerID,modelID:H.modelID}})});let xt=await lt(),et="";if(xt.status===409){if(!await pt())throw new Error("Session has a stuck active run. Cancel it and retry.");if(xt=await lt(),xt.ok){const ge=await xt.json().catch(()=>({}));et=ge?.runID||ge?.runId||ge?.run_id||""}else{if(xt.status===409)throw new Error("Session is still busy with another run. Retry in a moment.");{const ge=await xt.text().catch(()=>"");throw new Error(`prompt_async retry failed (${xt.status}): ${ge}`)}}}else if(xt.ok){const ke=await xt.json().catch(()=>({}));et=ke?.runID||ke?.runId||ke?.run_id||""}else{const ke=await xt.text().catch(()=>"");throw new Error(`prompt_async failed (${xt.status}): ${ke}`)}if(!et)throw new Error("No run ID returned from engine.");j.length&&X([]),M(""),Te(!0);const kt=new AbortController;P.current?.abort(),P.current=kt;let Et=!1,Wt=!1,vt="";const ct=3e4,Se=18e4,Pe=async(ke,ge)=>{const dt=Date.now();for(;Date.now()-dt<ge;){const Ge=await Be().catch(()=>ke);if(await it(),!Ge||Ge!==ke)return!0;await new Promise(Nt=>window.setTimeout(Nt,350))}return!1},ga=()=>{k.current&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{Wt=!0,vt="no-events-timeout",kt.abort("no-events-timeout")},ct)};ga(),J.current&&window.clearTimeout(J.current),J.current=window.setTimeout(()=>{Wt=!0,vt="max-stream-window",kt.abort("max-stream-window")},Se);try{for await(const ke of a.stream(K,et,{signal:kt.signal})){const ge=ke;if(Uc(ge.type)&&ga(),ge.type==="approval.requested"||ge.type==="permission.request"||ge.type==="permission.asked"){const Ge=jn(ge.properties||{});Ge&&dr(Ge.sessionId,K)?(o(Ge),$()):T()}if(ge.type==="approval.resolved"||ge.type==="permission.resolved"||ge.type==="permission.replied"){const Ge=jn(ge.properties||{});Ge?.id&&b(Ge.id),T()}String(ge.type||"").toLowerCase().startsWith("pack.")&&De(ge.type,ge.properties||{});const dt=cr(ge);if(!(dt&&dt!==et)){if(ge.type==="session.response"){const Ge=String(ge.properties?.delta||"");if(!Ge)continue;Et=!0,Te(!1),M(Nt=>`${Nt}${Ge}`)}if(as.has(ge.type)){const Ge=rn(ge.properties)||"tool",Nt=bn(ge.properties);ve(Ge,"started",`${Nt||dt||et}:${Ge}:started`)}if(ns.has(ge.type)){const Ge=rn(ge.properties)||"tool",Nt=bn(ge.properties),Ut=String(ge.properties?.status||ge.properties?.state||"").toLowerCase(),ra=ge.type==="tool_call.failed"||Ut.includes("fail")||Ut.includes("error")||!!ge.properties?.error;ve(Ge,ra?"failed":"completed",`${Nt||dt||et}:${Ge}:${ra?"failed":"completed"}`)}if(ge.type==="message.part.updated"){const Ge=ge.properties?.part||{},Nt=String(Ge.type||"").trim().toLowerCase().replace(/_/g,"-"),Ut=rn(Ge)||rn(ge.properties),ra=bn(Ge),Mt=Ge?.state,zt=String((Mt&&typeof Mt=="object"?Mt.status:Mt)||Ge.status||"").trim().toLowerCase(),Ct=!!Ge.error||!!(Mt&&typeof Mt=="object"&&Mt.error)||zt.includes("fail")||zt.includes("error")||zt.includes("deny")||zt.includes("reject")||zt.includes("cancel"),Vt=!!Ge.result||!!Ge.output||!!(Mt&&typeof Mt=="object"&&(Mt.output||Mt.result))||zt.includes("done")||zt.includes("complete")||zt.includes("success");if(Ut&&(Nt==="tool"||Nt==="tool-invocation")){const Yt=Ct?"failed":Vt?"completed":"started";ve(Ut,Yt,`${ra||dt||et}:${Ut}:${Yt}`)}Ut&&Nt==="tool-result"&&ve(Ut,Ct?"failed":"completed",`${ra||dt||et}:${Ut}:${Ct?"failed":"completed"}`)}if(Rc.has(ge.type))throw new Error(String(ge.properties?.error||"Run failed."));if((ge.type==="session.updated"||ge.type==="session.status")&&String(ge.properties?.status||"").toLowerCase()==="idle"||Tc.has(ge.type))break}}}catch(ke){const ge=String(ke?.message||ke||"").toLowerCase();if(!(Wt||ge.includes("abort")||ge.includes("terminated")||ge.includes("networkerror")))throw ke}finally{k.current&&window.clearTimeout(k.current),J.current&&window.clearTimeout(J.current)}if(Wt){const ke=await Pe(et,45e3);if(await it(),!ke)throw new Error("Run stream timed out and the run is still active. Check logs and retry.")}if(Et||Te(!0),await it(),await new Promise(ke=>window.setTimeout(ke,180)),await it(),await new Promise(ke=>window.setTimeout(ke,220)),await it(),!Et&&await Be().catch(()=>"")===et)if(await Pe(et,3e4))await it();else throw new Error(`Run ${et} is still active without a final response (${vt||"stream-ended"}).`);M(""),Te(!1),await ye(),await d.invalidateQueries({queryKey:["chat"]}).catch(()=>{})}catch(K){const H=Ja(K),fe=H.includes("no-events-timeout")||H.includes("max-stream-window")||H.includes("AbortError")||H.toLowerCase().includes("terminated")?"Run stream timed out before events were received. Check engine/provider logs and retry.":H;n("err",fe),await it()}finally{O.current&&(ae(!1),Te(!1))}}},[t,wt,$,a,Ve,v,d,De,ve,it,T,ye,b,Ne,S,Ke,n,pe,o]);be(()=>{ye(),Ze();const h=async()=>{const z=await Ve().catch(()=>"");z&&I(z),de(!1)};window.addEventListener("tcp:new-chat",h);const j=window.setInterval(()=>{ye()},8e3);return()=>{window.removeEventListener("tcp:new-chat",h),window.clearInterval(j)}},[Ve,Ze,ye]),be(()=>{S&&(P.current?.abort(),de(!1),N(),W(),T(),it())},[it,T,W,N,S]),be(()=>{S||R([])},[S]),be(()=>{!S&&A.length===0&&Ve().catch(()=>{})},[Ve,S,A.length]),be(()=>{Kc(rt),rt&&$()},[rt,$]),be(()=>{const h=window.setInterval(()=>{S&&T()},2500);return()=>window.clearInterval(h)},[T,S]),be(()=>{const h=Mr("/api/global/event",j=>{let z=null;try{z=JSON.parse(String(j.data||"{}"))}catch{return}const K=String(z?.type||"").trim();if(!K)return;const H=z?.properties||{},fe=jn(H);if(fe&&dr(fe.sessionId,S)&&((K==="approval.requested"||K==="permission.request"||K==="permission.asked")&&o(fe),(K==="approval.resolved"||K==="permission.resolved"||K==="permission.replied")&&b(fe.id)),K.toLowerCase().startsWith("pack.")&&De(K,H),as.has(K)){const Be=rn(H)||"tool",pt=bn(H),lt=cr(z,"global");ve(Be,"started",`${pt||lt}:${Be}:started`)}if(ns.has(K)){const Be=rn(H)||"tool",pt=bn(H),lt=cr(z,"global"),xt=String(H?.status||H?.state||"").toLowerCase(),et=K==="tool_call.failed"||xt.includes("fail")||!!H?.error;ve(Be,et?"failed":"completed",`${pt||lt}:${Be}:${et?"failed":"completed"}`)}},{withCredentials:!0});return()=>h()},[De,ve,b,S,o]);const te=pe.length,_e=!we&&!Q.length&&!he&&!ue;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",Ja(h))),de(!1)},children:[e("i",{"data-lucide":"plus"}),"New"]}),e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{ye()},children:e("i",{"data-lucide":"refresh-cw"})})]})]}),e("div",{className:"chat-session-list",children:[e(Tt,{children:A.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===S?"active":""}`,title:h.id,onClick:()=>{I(h.id),de(!1)},children:e("span",{className:"block truncate",children:h.title})}),e("button",{type:"button",className:"chat-session-del",title:"Delete session",onClick:()=>Ot({id:h.id,title:h.title}),children:e("i",{"data-lucide":"trash-2"})})]},h.id))}),A.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No sessions yet."})]})]}),e(Tt,{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:()=>de(!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:()=>de(h=>!h),children:e("i",{"data-lucide":"history"})}),e("div",{className:"chat-main-dot"}),e("h3",{className:"tcp-title chat-main-title",children:nt}),Ee.length?e("span",{className:"chat-main-tools",children:[Ee.length," tools"]}):null]}),Je?e("div",{className:"mx-3 mb-2 rounded-xl border border-amber-500/30 bg-amber-500/8 p-3",children:[e("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"tcp-title text-sm",children:Je.title}),e("div",{className:"tcp-subtle text-sm",children:Je.body})]}),e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>Qe(null),children:"Dismiss"})]}),Je.clarifier?e("div",{className:"mb-2 flex flex-wrap gap-2",children:Je.clarifier.options.map(h=>e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>Qe({title:h.id==="provider_setup"?"Provider setup":h.id==="integration_setup"?"Tool connection":"Automation setup",body:h.id==="provider_setup"?"Open Settings to configure a provider.":h.id==="integration_setup"?"Open MCP to connect the tool you need.":"Open Automations to build the workflow.",cta:h.id==="provider_setup"?"Open Settings":h.id==="integration_setup"?"Open MCP":"Open Automations",actionType:h.id==="provider_setup"?"open_provider_setup":h.id==="integration_setup"?"open_mcp_setup":"open_automations",payload:Je.payload}),children:h.label},h.id))}):null,e("button",{type:"button",className:"tcp-btn",onClick:()=>{Je.actionType==="open_provider_setup"?l("settings"):Je.actionType==="open_mcp_setup"?l("mcp"):Je.actionType==="open_automations"&&(Lc(Je.payload),l("automations"))},children:Je.cta})]}):null,e("div",{ref:x,className:`chat-messages mb-2 min-h-0 min-w-0 flex-1 overflow-auto p-3 ${_e?"chat-messages-empty":"space-y-2"}`,children:[we&&!Q.length?e("p",{className:"chat-rail-empty",children:"Loading messages..."}):null,_e?e("div",{className:"chat-empty-state",children:e("p",{className:"chat-rail-empty",children:"No messages yet. Send a prompt to start."})}):null,e(Tt,{initial:!1,children:Q.map(h=>{const j=h.role==="assistant"||h.role==="system",z=j?"assistant":"user";return e(Me.article,{className:`chat-msg ${z}`,initial:u?!1:{opacity:0,y:4},animate:u?void 0:{opacity:1,y:0},exit:u?void 0:{opacity:0,y:-4},children:[e("div",{className:"chat-msg-role",children:j?e("span",{className:"inline-flex items-center gap-2",children:[s.botAvatarUrl?e("img",{src:s.botAvatarUrl,alt:s.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:h.displayRole})]}):h.displayRole}),h.markdown?e("div",{className:"tcp-markdown tcp-markdown-ai",dangerouslySetInnerHTML:{__html:cn(h.text||"")}}):e("pre",{className:"chat-msg-pre",children:h.text})]},h.id)})}),he||ue?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"})]})}),he&&!ue?e("div",{className:"tcp-thinking","aria-live":"polite",children:[e("span",{children:"Thinking"}),e("i",{}),e("i",{}),e("i",{})]}):null,ue?e("pre",{className:"chat-msg-pre",children:ue}):null]}):null]}),e("div",{className:"chat-composer shrink-0",children:[e("div",{className:`chat-attach-row mb-2 ${te?"":"hidden"}`,children:[e("span",{className:"tcp-subtle",children:[te," attached"]}),e("div",{className:"chat-files-line",children:pe.map((h,j)=>e("span",{className:"chat-file-pill min-w-0",children:[e("span",{className:"chat-file-pill-name",title:h.path,children:h.path}),e("span",{className:"chat-file-pill-size",children:jc(h.size)}),e("button",{type:"button",className:"chat-file-pill-btn chat-file-pill-btn-danger",title:"Remove from list",onClick:()=>X(z=>z.filter((K,H)=>H!==j)),children:e("i",{"data-lucide":"x"})})]},`${h.path}-${j}`))})]}),$e.length?e("div",{className:"mb-2 grid gap-1.5",children:$e.map(h=>{const j=Math.max(0,Math.min(100,Number(h.progress||0)));return e("div",{className:"chat-upload-card",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2 text-xs",children:[e("span",{className:"chat-upload-name truncate",children:h.name}),e("span",{className:h.error?"chat-upload-meta-error":"chat-upload-meta",children:h.error||`${j.toFixed(0)}%`})]}),e("div",{className:"chat-upload-bar",children:e("div",{className:"chat-upload-bar-fill",style:{width:`${j}%`}})})]},h.id)})}):null,e("div",{className:"chat-input-wrap",children:[e("input",{ref:D,type:"file",className:"hidden",multiple:!0,onChange:h=>{qt(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:_,rows:1,value:v,className:"tcp-input chat-input-with-clip chat-input-modern resize-none",placeholder:"Ask anything... (Enter to send, Shift+Enter newline)",onInput:h=>U(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),It())}}),e("button",{type:"button",className:"chat-send-btn",title:"Send",disabled:Ke,onClick:()=>{It()},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:Ee.length})]}),e("div",{className:"chat-tools-list",children:Ee.length?Ee.slice(0,32).map(h=>e("button",{type:"button",className:"chat-tool-pill",title:`Insert ${h}`,onClick:()=>{U(j=>j.trim()?`${j} ${h}`:h),_.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:Ie.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:!Ie.length||ot,onClick:async()=>{const h=Ie.map(z=>z.id).filter(Boolean);if(!h.length)return;for(const z of h)await C(z,"once",!0);await T();const j=h.filter(z=>Ie.some(K=>String(K.id||"").trim()===z)).length;j>0?n("warn",`${j} request${j===1?"":"s"} still pending (likely stale/expired).`):n("ok",`Approved ${h.length} pending request${h.length===1?"":"s"}.`)},children:"Approve all"}),e("label",{className:"chat-auto-approve-label",children:[e("input",{type:"checkbox",className:"chat-auto-approve-checkbox",checked:rt,onChange:h=>mt(h.target.checked)}),"Auto"]})]}),e("div",{className:"chat-tools-activity",children:Ie.length?Ie.slice(0,20).map(h=>{const j=se.has(h.id),z=[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:z||h.id}),e("div",{className:"mt-1 flex gap-1",children:[e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:j,onClick:()=>{C(h.id,"once")},children:"Allow"}),e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:j,onClick:()=>{C(h.id,"always")},children:"Always"}),e("button",{className:"tcp-btn-danger h-6 px-1.5 text-[10px]",disabled:j,onClick:()=>{C(h.id,"deny")},children:"Deny"})]})]},h.id)}):e("p",{className:"chat-rail-empty",children:"No pending approvals."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Pack Events"}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:"chat-rail-count",children:ze.length}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:()=>{W()},children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]})]}),e("div",{className:"chat-tools-activity",children:ze.length?ze.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:()=>l("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Packs"]}),h.path?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const j=await t("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:h.path,source:{kind:"control_panel_chat",event:"pack.detected"}})});n("ok",`Installed ${j?.installed?.name||"pack"} ${j?.installed?.version||""}`.trim())}catch(j){n("err",`Install failed: ${Ja(j)}`)}},children:[e("i",{"data-lucide":"download"}),"Install path"]}):null,h.path&&h.attachmentId?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const j=await t("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:h.attachmentId,path:h.path,connector:h.connector||void 0,channel_id:h.channelId||void 0,sender_id:h.senderId||void 0})});n("ok",`Installed ${j?.installed?.name||"pack"} ${j?.installed?.version||""}`.trim())}catch(j){n("err",`Install failed: ${Ja(j)}`)}},children:[e("i",{"data-lucide":"paperclip"}),"Install attach"]}):null]})]},`${h.id}-${h.at}`)):e("p",{className:"chat-rail-empty",children:"No pack events yet."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Tool Activity"}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:N,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 ${Bc(h.status)}`,children:[h.tool,": ",h.status]},h.id)):e("p",{className:"chat-rail-empty",children:"No tool events yet."})})]})]})]}),e(Tt,{children:yt?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:()=>Ot(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:yt.title})," and all its messages."]}),e("div",{className:"tcp-confirm-actions",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>Ot(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{type:"button",className:"tcp-btn-danger",onClick:()=>{Ae(yt.id).catch(h=>n("err",Ja(h)))},children:[e("i",{"data-lucide":"trash-2"}),"Delete session"]})]})]})}):null})]})}function pn(a){return a?.checkpoint||{}}function _r(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function is(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 Ca(a){return String(a?.type||a?.event_type||a?.event||"").trim()}function dn(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 rr(a){const t=a?.properties||a||{};return String(t?.reason||t?.detail||t?.error?.message||t?.error||t?.message||t?.status||"").trim()}function ii(a,t=""){return String(a?.properties?.sessionID||a?.sessionID||t||"").trim()}function $r(a,t,n){return(Array.isArray(a?.[t])?a[t]:Array.isArray(a?.[n])?a[n]:[]).map(s=>String(s||"").trim()).filter(Boolean)}function Qa(a){return Array.isArray(a)?a.map(t=>String(t||"").trim()).filter(Boolean):[]}function Or(a){return $r(pn(a),"completed_nodes","completedNodes")}function oi(a){return String(a?.status||a?.content?.status||"").trim().toLowerCase()}function li(a){const t=new Set($r(pn(a),"blocked_nodes","blockedNodes"));for(const{nodeId:n,value:r}of Dr(a))oi(r)==="blocked"&&t.add(n);return Array.from(t)}function Jc(a){const t=new Set;for(const{nodeId:n,value:r}of Dr(a)){const s=oi(r);(s==="verify_failed"||s==="failed")&&t.add(n)}return Array.from(t)}function Er(a){return $r(pn(a),"pending_nodes","pendingNodes")}function os(a){return Or(a).length}function Qc(a){return Er(a).length}function Qn(a){return li(a).length}function Ua(a){const t=String(a?.status||"").trim().toLowerCase();return(t==="completed"||t==="done")&&Qn(a)>0?"blocked":(t==="completed"||t==="done")&&Jc(a).length>0?"failed":t||"unknown"}function ls(a){return(Array.isArray(a?.active_session_ids)?a.active_session_ids:Array.isArray(a?.activeSessionIds)?a.activeSessionIds:[]).length}function sr(a){const t=pn(a);return t?.node_outputs||t?.nodeOutputs||{}}function Dr(a){return Object.entries(sr(a)).map(([t,n])=>({nodeId:t,value:n}))}function ir(a,t){const n=String(t||"").trim();return n&&sr(a)[n]||null}function Gc(a,t){const n=pn(a),r=String(t||"").trim();return r?Number(n?.node_attempts?.[r]||n?.nodeAttempts?.[r]||0):0}function Hc(a,t){const n=ir(a,t);return String(n?.content?.session_id||n?.content?.sessionId||"").trim()}function Vc(a,t,n){const r=new Set(Or(a)),s=new Set(li(a)),l=new Set(Er(a)),d=String(t||"").trim();if(!d)return n.length?"pending":"runnable";if(r.has(d))return"done";const u=ir(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 _=String(u?.error||u?.content?.error||u?.content?.message||u?.content?.status_message||"").trim().toLowerCase();return _&&(_.includes("failed")||_.includes("error"))?"failed":(l.has(d),n.length?"pending":"runnable")}function Yc(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 Xc(a){const t=Er(a),n=String(t[0]||"").trim();return n?n.startsWith("node-")?n:`node-${n}`:""}function Zc(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(Or(a)),s=n.map(l=>{const d=String(l?.node_id||"").trim(),u=`node-${d}`,p=Array.isArray(l?.depends_on)?l.depends_on.map(k=>`node-${String(k||"").trim()}`).filter(Boolean):[],_=p.every(k=>r.has(k.replace(/^node-/,""))),D=Vc(a,d,_?[]:p),x=ir(a,d)||{},P=t===u&&String(a?.status||"").trim().toLowerCase()==="running"?"in_progress":D==="pending"&&_?"runnable":D,O=l?.metadata?.builder||{};return{id:u,title:String(l?.objective||d||"Workflow node"),description:l?.agent_id?`agent: ${l.agent_id}`:"",dependencies:p,state:P,retry_count:Gc(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(l?.agent_id||""),workflow_id:String(a?.automation_id||""),session_id:Hc(a,d),projects_backlog_tasks:!!O?.project_backlog_tasks,backlog_task_id:String(O?.task_id||""),task_kind:String(O?.task_kind||""),repo_root:String(O?.repo_root||""),write_scope:String(O?.write_scope||""),acceptance_criteria:String(O?.acceptance_criteria||""),task_dependencies:String(O?.task_dependencies||""),verification_state:String(O?.verification_state||""),task_owner:String(O?.task_owner||""),verification_command:String(O?.verification_command||""),output_path:String(O?.output_path||"")}});return{currentTaskId:Yc(s,t),taskSource:"checkpoint",tasks:s}}function ci(a){const t=pn(a);return Array.isArray(t?.lifecycle_history)?t.lifecycle_history:Array.isArray(t?.lifecycleHistory)?t.lifecycleHistory:[]}function di(a){const t=ci(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 jr(a){return String(a?.metadata?.node_id||a?.metadata?.nodeId||"").trim()}function ui(a){const t=jr(a);return t?t.startsWith("node-")?t:`node-${t}`:""}function ed(a,t,n=8){const r=String(t||"").trim();return r?ci(a).filter(s=>jr(s)===r).slice(-n).reverse():[]}function td(a,t,n=8){return ed(a,t,n).map(r=>({...od(r),raw:r}))}function ad(a){const t=di(a);return ui(t)}function nd(a){const t=Object.values(sr(a)).filter(Boolean);return t.length&&t[t.length-1]||null}function rd(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||{},l=String(s?.text||s?.raw_text||"").trim();return[t,n?`status: ${n}`:"",r,l].filter(Boolean).join(`
|
|
7
|
+
`).trim()}function Ur(a){return a?.tool_telemetry||a?.toolTelemetry||null}function $n(a){return a?.artifact_validation||a?.artifactValidation||null}function sd(a){const t=$n(a);return Array.isArray(t?.artifact_candidates)?t.artifact_candidates:[]}function mi(a){const t=$n(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 id(a){const t=nd(a),n=di(a),r=mi(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 od(a){const t=a?.metadata||{};return{event:String(a?.event||"event").trim()||"event",recordedAtMs:Number(a?.recorded_at_ms||a?.recordedAtMs||0),nodeId:jr(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 ld(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:_r(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:_r(s?.created_at_ms||s?.timestamp_ms)||Number(s?.seq||0),raw:s}));return[...n,...r].sort((s,l)=>Number(l.at||0)-Number(s.at||0))}function cd(a,t=""){return(Array.isArray(a)?a:[]).map((n,r)=>({id:`persisted:${String(t||"")}:${r}`,family:"run_event",type:String(Ca(n)||"run.event"),detail:String(rr(n)||"").trim(),at:dn(n),raw:n})).sort((n,r)=>Number(r.at||0)-Number(n.at||0))}function dd(a,t,n,r=""){const s=(Array.isArray(a)?a:[]).map((l,d)=>({id:`persisted:${String(r||"")}:${String(l?.seq||d)}:${String(Ca(l)||"")}`,source:"automations",at:dn(l),event:l}));return n?[...s,...(Array.isArray(t)?t:[]).map(l=>({id:`context:${String(l?.seq||"")}:${String(l?.event_type||"")}`,source:"context",at:_r(l?.created_at_ms||l?.timestamp_ms||l?.timestampMs)||Date.now(),event:l}))]:s}function ud(a,t=""){return(Array.isArray(a)?a:[]).map(n=>{const r=ii(n?.event,t),s=Ca(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:rr(n?.event),raw:n?.event,parts:[]}})}function md(a){const t=[],n=(r,s,l,d,u)=>{String(l||"").trim()&&(t.some(p=>p.key===r)||t.push({key:r,title:s,reason:String(l).trim(),source:d,at:u}))};for(const r of Array.isArray(a)?a:[]){const s=r?.event||r||{},l=String(Ca(s)||"").trim(),d=rr(s),u=Number(r?.at||dn(s)||0);(l==="permission.asked"||l==="approval.required"||l==="routine.approval_required")&&n(`event-${l}`,"Permission or approval required",d||l,"permission",u),l==="mcp.auth.required"&&n(`event-${l}`,"MCP auth required",d||"An MCP connector requires authorization.","mcp",u),(l==="session.error"||l==="run.failed"||l==="routine.run.failed")&&n(`event-${l}`,"Execution failure",d||l,"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-${l||u}`,"Timeout",d,"session",u)}return t.sort((r,s)=>(s.at||0)-(r.at||0))}function pd(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:Ca(t?.event)||"event",detail:rr(t?.event)||"No summary available.",raw:t?.event?.properties||t?.event||null,event:t?.event||null}))}function hd(a,t){const n=Ur(t),r=$n(t),s=mi(t),l=(()=>{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 _=String(a?.state||"").trim().toLowerCase();return _==="done"?"completed":_==="blocked"?"blocked":_==="failed"?"failed":_||"unknown"})();return{telemetry:n,artifactValidation:r,touchedFiles:Qa(r?.touched_files),undeclaredFiles:Qa(r?.undeclared_files_created),researchReadPaths:Qa(r?.read_paths),discoveredRelevantPaths:Qa(r?.discovered_relevant_paths),reviewedPathsBackedByRead:Qa(r?.reviewed_paths_backed_by_read),unreviewedRelevantPaths:Qa(r?.unreviewed_relevant_paths),unmetResearchRequirements:Qa(r?.unmet_requirements),verificationOutcome:l,verificationPassed:typeof t?.approved=="boolean"?t.approved:["approved","completed","done"].includes(l)?!0:["blocked","failed","not approved"].includes(l)?!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:sd(t)}}function pi(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(sr(a)).map(s=>{const l=s?.content||{};return String(l?.session_id||l?.sessionId||"").trim()}).filter(Boolean);return Array.from(new Set([...n,...t.map(s=>String(s||"").trim()).filter(Boolean),...r].filter(Boolean)))}async function Lt(a,t={}){const n=await fetch(a,{...t,credentials:"include",headers:{"content-type":"application/json",...t.headers||{}}});if(!n.ok){const s=await n.text().catch(()=>"");let l=s||`${a} failed (${n.status})`;try{const d=s?JSON.parse(s):null;d?.error&&(l=d.error)}catch{}throw new Error(l)}const r=await n.text();return r?JSON.parse(r):{}}function hi(a=!0){return Z({queryKey:["system","health"],queryFn:()=>Lt("/api/system/health"),enabled:a,refetchInterval:a?15e3:!1})}function gd(a=!0){return Z({queryKey:["swarm","status"],queryFn:()=>Lt("/api/swarm/status"),enabled:a,refetchInterval:a?5e3:!1})}const fd=`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
|
+
`,bd=`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
|
+
`,vd=`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
|
+
`,yd=`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
|
+
`,wd=`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
|
+
`,kd=`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
|
+
`,Nd=Object.assign({"./templates/competitor-research-pipeline.yaml":fd,"./templates/marketing-content-pipeline.yaml":bd,"./templates/prd-to-launch-plan-team.yaml":vd,"./templates/repo-coding-backlog.yaml":yd,"./templates/sales-prospecting-team.yaml":wd,"./templates/support-triage-team.yaml":xd,"./templates/weekly-newsletter-builder.yaml":kd});function _d(a,t){const n=nr.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(),l=String(r.name||"").trim(),d=String(r.icon||"").trim(),u=String(r.summary||"").trim(),p=String(r.description||"").trim(),_=Number(r.order),D=r.suggestedOutputs,x=r.agents,P=r.nodes;if(!s)throw new Error("Invalid studio template at "+t+": missing id.");if(!l)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(_))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(P))throw new Error("Invalid studio template at "+t+": nodes must be an array.");return{id:s,name:l,icon:d,summary:u,description:p,order:_,suggestedOutputs:D,agents:x,nodes:P}}const qa=Object.entries(Nd).map(([a,t])=>_d(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 Gn(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 Sd(a={}){return{role:"",mission:"",inputs:"",outputContract:"",guardrails:"",...a}}function cs(a,t,n={}){return{agentId:a,displayName:t,role:"worker",avatarUrl:"",templateId:"",linkedTemplateId:"",skills:[],prompt:Sd(),modelProvider:"",modelId:"",toolAllowlist:["read","write","glob"],toolDenylist:[],mcpAllowedServers:[],...n}}function Id(a,t,n,r=[],s=[],l={}){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:"",...l}}const Cd=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],Ad="tandem.automations.studioHandoff";function Hn(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function g(a){return String(a||"").trim()}function Pd(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 Br(a){const t=g(a.taskKind).toLowerCase();return t==="code_change"||t==="repo_fix"||t==="implementation"||Pd(a.outputPath)}function gi(a){return!!a.projectBacklogTasks}function Fr(a){const t=a.map(n=>g(n)).filter(Boolean);return t.includes("*")?["*"]:Array.from(new Set(t))}function ds(a,t){const n=Fr(a);if(n.includes("*"))return["*"];const s=t.some(l=>Br(l))?["read","glob","edit","apply_patch","write","bash"]:[];return Array.from(new Set([...n,...s]))}function Td(a){const t=g(a);return t?t.length<=18?t:`${t.slice(0,8)}...${t.slice(-6)}`:""}function us(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 vn(a){return String(a||"").split(",").map(t=>t.trim()).filter(Boolean)}function yn(a){return a.join(", ")}function Sr(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function Un(a,t){return Sr(a)||t}function Ir(a){const t=g(a);return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function ms(a){try{sessionStorage.setItem(Ad,JSON.stringify(a))}catch{}}function tr(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 Rd(a){if(!(!g(a.modelProvider)||!g(a.modelId)))return{default_model:{provider_id:g(a.modelProvider),model_id:g(a.modelId)}}}function qd(a,t){const r=g(t?.default)||a[0]?.id||"";if(!r)return{provider:"",model:""};const s=a.find(d=>d.id===r)?.models||[],l=g(t?.providers?.[r]?.default_model||s[0]);return{provider:r,model:l}}function sn(a,t){return a.find(n=>n.id===t)?.models||[]}function wn(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 fi(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 ps(a,t,n){const r=g(t),s=g(n);return!r||!s?a:a.map(l=>({...l,modelProvider:r,modelId:s}))}function Md(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 $d(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 Od(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 Kr(a){return{role:"",mission:g(a),inputs:"",outputContract:"",guardrails:""}}function An(a,t){return a.map(r=>t.find(l=>l.fromStepId===r)||{fromStepId:r,alias:r.replace(/-/g,"_")})}function bi(a){const t=new Map(a.map(s=>[s.nodeId,s])),n=new Map,r=(s,l=new Set)=>{if(n.has(s))return Number(n.get(s)||0);if(l.has(s))return 0;const d=t.get(s);if(!d||!d.dependsOn.length)return n.set(s,0),0;const u=new Set(l);u.add(s);const p=Math.max(...d.dependsOn.map(_=>r(_,u)))+1;return n.set(s,p),p};for(const s of a)r(s.nodeId);return n}function hs(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)}:Kr(g(a?.systemPrompt||a?.system_prompt)),modelProvider:g(a?.modelProvider||a?.model_provider),modelId:g(a?.modelId||a?.model_id),toolAllowlist:Fr(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 gs(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:An(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 Ed(a,t){const n=Br(a),r=t.toolAllowlist.includes("glob"),s=t.toolAllowlist.includes("read"),l=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)}.`:"",gi(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&&l?"- 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 vi(a,t,n){const r=qa.find(l=>l.id===a);return r&&Gn(r,n||"").agents.find(l=>l.agentId===t)||null}function Cr(a,t){const n=[],r=[],s=a.nodes.map(d=>d.agentId).filter((d,u,p)=>!!d&&p.indexOf(d)===u&&!a.agents.some(_=>_.agentId===d)),l=a.agents.map(d=>{const u=g(d.linkedTemplateId||d.templateId);if(!u||t.has(u))return d;const p=vi(a.starterTemplateId,d.agentId,a.workspaceRoot);return n.push(d.agentId),r.push(u),{...d,templateId:"",linkedTemplateId:"",prompt:tr(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:Fr(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:l},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 Dd(a,t){const n=[],r=Ir(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(_=>_.agentId===d));s.length&&n.push(`Stages reference missing agents: ${s.join(", ")}.`);const l=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:l}}function jd(a,t,n){const r=a?.metadata&&typeof a.metadata=="object"?a.metadata:{},s=r?.studio&&typeof r.studio=="object"?r.studio:{},l=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(hs):[],p=Array.isArray(s?.node_drafts)?s.node_drafts.map(gs):[],_=Array.isArray(a?.agents)?a.agents.map(k=>{const J=g(k?.template_id||k?.templateId),A=J?n.get(J):null,G=!A&&d?vi(d,g(k?.agent_id||k?.agentId),g(a?.workspace_root||a?.workspaceRoot||r?.workspace_root||t)):null;return hs({agentId:k?.agent_id||k?.agentId,displayName:k?.display_name||k?.displayName||G?.displayName||k?.agent_id||k?.agentId,role:A?.role||G?.role||"worker",templateId:J,linkedTemplateId:J,skills:Array.isArray(k?.skills)?k.skills:A?.skills||G?.skills||[],prompt:A?.systemPrompt?Kr(A.systemPrompt):G?.prompt,modelProvider:k?.model_policy?.default_model?.provider_id||k?.modelPolicy?.defaultModel?.providerId||G?.modelProvider||A?.modelProvider||"",modelId:k?.model_policy?.default_model?.model_id||k?.modelPolicy?.defaultModel?.modelId||G?.modelId||A?.modelId||"",toolAllowlist:k?.tool_policy?.allowlist||k?.toolPolicy?.allowlist||[],toolDenylist:k?.tool_policy?.denylist||k?.toolPolicy?.denylist||[],mcpAllowedServers:k?.mcp_policy?.allowed_servers||k?.mcpPolicy?.allowedServers||[]})}):[],D=Array.isArray(a?.flow?.nodes)?a.flow.nodes.map(k=>gs({nodeId:k?.node_id||k?.nodeId,title:k?.metadata?.builder?.title||k?.metadata?.studio?.title||k?.objective||k?.node_id||k?.nodeId,agentId:k?.agent_id||k?.agentId,objective:k?.objective,dependsOn:k?.depends_on||k?.dependsOn||[],inputRefs:k?.input_refs||k?.inputRefs||[],outputKind:k?.output_contract?.kind||k?.outputContract?.kind||"artifact",metadata:k?.metadata})):[],x={automationId:g(a?.automation_id||a?.automationId||a?.id),starterTemplateId:d,name:g(a?.name||"Workflow"),description:g(a?.description),summary:g(s?.summary),icon:g(s?.icon),workspaceRoot:g(a?.workspace_root||a?.workspaceRoot||r?.workspace_root||t),status:g(a?.status||l?.status||"draft")||"draft",scheduleType:g(a?.schedule?.type||l?.schedule_type||"manual")||"manual",cronExpression:g(a?.schedule?.cron_expression||a?.schedule?.cronExpression||l?.cron_expression),intervalSeconds:String(a?.schedule?.interval_seconds||a?.schedule?.intervalSeconds||l?.interval_seconds||3600),maxParallelAgents:String(a?.execution?.max_parallel_agents||a?.execution?.maxParallelAgents||l?.max_parallel_agents||1),useSharedModel:!1,sharedModelProvider:"",sharedModelId:"",outputTargets:Array.isArray(a?.output_targets||a?.outputTargets)?(a.output_targets||a.outputTargets).map(k=>g(k)).filter(Boolean):Array.isArray(l?.output_targets)?l.output_targets.map(k=>g(k)).filter(Boolean):[],agents:u.length?u:_,nodes:p.length?p:D},P=fi(x.agents);return x.useSharedModel=P.useSharedModel,x.sharedModelProvider=P.provider,x.sharedModelId=P.model,Cr(x,n)}function Ud(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:tr(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 Bd(a,t,n){const r=bi(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 Fd(a){const t=new Map,n=new Set;for(const r of a){const s=Un(r.nodeId||r.title,"stage");let l=s,d=2;for(;n.has(l);)l=`${s}-${d}`,d+=1;n.add(l),t.set(r.nodeId,l)}return a.map(r=>{const s=t.get(r.nodeId)||Un(r.nodeId||r.title,"stage"),l=r.dependsOn.map(u=>t.get(u)||Un(u,u)).filter(Boolean),d=An(l,r.inputRefs.map(u=>({fromStepId:t.get(u.fromStepId)||Un(u.fromStepId,u.fromStepId),alias:u.alias})));return{...r,nodeId:s,dependsOn:l,inputRefs:d}})}async function Kd(a,t,n=4){for(let r=0;r<n;r+=1){const s=await a.automationsV2.list().catch(()=>({automations:[]}));if(!Hn(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 Ld({client:a,api:t,toast:n,navigate:r}){const s=aa(),l=hi(!0),d=Z({queryKey:["studio","automations"],queryFn:()=>a.automationsV2.list().catch(()=>({automations:[]})),refetchInterval:15e3}),u=Z({queryKey:["studio","templates"],queryFn:()=>a.agentTeams.listTemplates().catch(()=>({templates:[]})),refetchInterval:1e4}),p=Z({queryKey:["studio","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),_=Z({queryKey:["studio","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),D=Z({queryKey:["studio","mcp"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:15e3}),x=g(l.data?.workspaceRoot||l.data?.workspace_root),P=L(()=>Hn(u.data,"templates").map(Od).filter(o=>o.templateId),[u.data]),O=L(()=>new Map(P.map(o=>[o.templateId,o])),[P]),k=L(()=>(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]),J=L(()=>qd(k,_.data),[k,_.data]),A=L(()=>Hn(d.data,"automations").filter(o=>{const b=o?.metadata?.studio;return!!b&&(Number(b?.version||0)>0||g(b?.created_from)==="studio")}),[d.data]),G=L(()=>A.map(o=>g(o?.automation_id||o?.automationId||o?.id)).filter(Boolean),[A]),ee=Z({queryKey:["studio","workflow-runs",G],enabled:!!a?.automationsV2?.listRuns&&G.length>0,queryFn:async()=>({runs:(await Promise.all(G.map(async b=>{const T=await a.automationsV2.listRuns(b,6).catch(()=>({runs:[]}));return Array.isArray(T?.runs)?T.runs:[]}))).flat()}),refetchInterval:12e3}),de=L(()=>{const o=Hn(ee.data,"runs"),b=new Map;return o.forEach(T=>{const C=g(T?.automation_id||T?.automationId);if(!C)return;const $=b.get(C),Ye=Number($?.updated_at_ms||$?.updatedAtMs||$?.created_at_ms||$?.createdAtMs||0),Ze=Number(T?.updated_at_ms||T?.updatedAtMs||T?.created_at_ms||T?.createdAtMs||0);(!$||Ze>=Ye)&&b.set(C,T)}),b},[ee.data]),S=L(()=>$d(D.data),[D.data]),[I,Q]=w(()=>Gn(qa[0],"")),[R,we]=w(()=>qa[0]?.nodes?.[0]?.nodeId||""),[y,v]=w(()=>qa[0]?.agents?.[0]?.agentId||""),[U,pe]=w(""),[X,$e]=w(!1),[Oe,Ke]=w(!1),[ae,ue]=w(!0),[M,he]=w(!0),[Te,Re]=w(!1),[re,Ue]=w(""),[qe,ze]=w(""),[V,He]=w(null),[ne,Ie]=w(null);be(()=>{x&&Q(o=>g(o.workspaceRoot)?o:{...o,workspaceRoot:x})},[x]),be(()=>{!J.provider||!J.model||Q(o=>{const b=wn(o.agents,J);return b.some((C,$)=>C.modelProvider!==o.agents[$]?.modelProvider||C.modelId!==o.agents[$]?.modelId)?{...o,agents:b}:o})},[J]),be(()=>{I.useSharedModel&&(!g(I.sharedModelProvider)||!g(I.sharedModelId)||Q(o=>{if(!o.useSharedModel)return o;const b=ps(o.agents,o.sharedModelProvider,o.sharedModelId);return b.some((C,$)=>C.modelProvider!==o.agents[$]?.modelProvider||C.modelId!==o.agents[$]?.modelId)?{...o,agents:b}:o}))},[I.useSharedModel,I.sharedModelProvider,I.sharedModelId]),be(()=>{new Set(I.nodes.map(b=>b.nodeId)).has(R)||we(I.nodes[0]?.nodeId||"")},[I.nodes,R]),be(()=>{new Set(I.agents.map(b=>b.agentId)).has(y)||v(I.agents[0]?.agentId||"")},[I.agents,y]),be(()=>{try{ya()}catch{}},[I,R,U,ae,M,A.length,P.length,Te,qe]);const ht=Z({queryKey:["studio","workspace-browser",re],enabled:Te&&!!re,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(re)}`,{method:"GET"}),refetchInterval:Te?15e3:!1}),se=I.nodes.find(o=>o.nodeId===R)||I.nodes[0]||null,F=I.agents.find(o=>o.agentId===(y||se?.agentId))||I.agents.find(o=>o.agentId===se?.agentId)||I.agents[0]||null,rt=Ir(I.workspaceRoot),mt=Array.isArray(ht.data?.directories)?ht.data.directories:[],ot=g(ht.data?.parent),St=g(ht.data?.dir||re||""),Ee=L(()=>{const o=g(qe).toLowerCase();return o?mt.filter(b=>g(b?.name||b?.path).toLowerCase().includes(o)):mt},[qe,mt]),Rt=L(()=>bi(I.nodes),[I.nodes]),yt=L(()=>{const o=new Map;for(const b of I.nodes){const T=Number(Rt.get(b.nodeId)||0);o.has(T)||o.set(T,[]),o.get(T)?.push(b)}return Array.from(o.entries()).sort((b,T)=>b[0]-T[0])},[I.nodes,Rt]),Ot=o=>{const b=qa.find(C=>C.id===o)||qa[0],T=Gn(b,I.workspaceRoot||x);Q({...T,agents:wn(T.agents,J)}),we(T.nodes[0]?.nodeId||""),v(T.agents[0]?.agentId||""),$e(!1),Ie(null)},Je=o=>Q(b=>({...b,...o})),Qe=(o,b)=>Q(T=>({...T,nodes:T.nodes.map(C=>C.nodeId===o?{...C,...b,inputRefs:b.dependsOn||b.inputRefs?An(b.dependsOn?[...b.dependsOn]:C.dependsOn,b.inputRefs?[...b.inputRefs]:C.inputRefs):C.inputRefs}:C)})),nt=(o,b)=>Q(T=>({...T,agents:T.agents.map(C=>C.agentId===o?{...C,...b}:C)})),ye=()=>{const o=`agent-${I.agents.length+1}`,b=I.agents.some(T=>T.agentId===o)?`agent-${Date.now().toString().slice(-5)}`:o;Q(T=>({...T,agents:[...T.agents,wn([cs(b,`Agent ${T.agents.length+1}`)],J)[0]]})),v(b)},Ne=()=>{const o=I.nodes.length+1,b=`stage-${o}`,T=F?.agentId||I.agents[0]?.agentId||"",C=Id(b,`Stage ${o}`,T,se?[se.nodeId]:[],se?[{fromStepId:se.nodeId,alias:se.nodeId.replace(/-/g,"_")}]:[],{objective:"Describe what this stage should produce."});Q($=>({...$,nodes:[...$.nodes,C]})),we(b),T&&v(T)},Ve=()=>{se&&Q(o=>({...o,nodes:o.nodes.filter(b=>b.nodeId!==se.nodeId).map(b=>{const T=b.dependsOn.filter(C=>C!==se.nodeId);return{...b,dependsOn:T,inputRefs:An(T,b.inputRefs.filter(C=>C.fromStepId!==se.nodeId))}})}))},le=()=>{if(!F)return;if(I.nodes.some(b=>b.agentId===F.agentId)){n("warn","Reassign or remove the stages using this agent first.");return}Q(b=>({...b,agents:b.agents.filter(T=>T.agentId!==F.agentId)})),v("")},it=()=>{if(!F||!U)return;const o=O.get(U);o&&(nt(F.agentId,{displayName:o.displayName||F.displayName,avatarUrl:o.avatarUrl||F.avatarUrl,role:o.role||F.role,linkedTemplateId:o.templateId,templateId:o.templateId,prompt:o.systemPrompt?Kr(o.systemPrompt):F.prompt,modelProvider:o.modelProvider||F.modelProvider,modelId:o.modelId||F.modelId,skills:o.skills.length?o.skills:F.skills}),Ie(b=>b&&{...b,repairedAgentIds:b.repairedAgentIds.filter(T=>T!==F.agentId),repairedTemplateIds:b.repairedTemplateIds.filter(T=>T!==o.templateId)}),n("ok",`Loaded template ${o.templateId}.`))},N=o=>{const b=jd(o,x,O),T={...b.draft,agents:wn(b.draft.agents,J)};Q(T),we(T.nodes[0]?.nodeId||""),v(T.agents[0]?.agentId||""),$e(b.draft.agents.some(C=>!!g(C.linkedTemplateId||C.templateId))),Ie(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")},W=async o=>{const b=g(o?.automation_id||o?.automationId||o?.id);if(fs(o,O).isBroken){N(o),n("warn","This workflow references missing agent templates. It was repaired in Studio. Save it before running.");return}const C=await a.automationsV2.runNow(b),$=g(C?.run?.run_id||C?.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."),ms({tab:"running",runId:$,automationId:b,openTaskInspector:!0}),r("automations")},ve=xe({mutationFn:async()=>{const o=X?I:Cr(I,O).draft;let b={...o,agents:wn(o.agents,J)};b.useSharedModel&&g(b.sharedModelProvider)&&g(b.sharedModelId)&&(b={...b,agents:ps(b.agents,b.sharedModelProvider,b.sharedModelId)});const T=Ir(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 C=Dd(b,O);if(C.errors.length)throw new Error(C.errors[0]);const $=b.agents.filter(te=>!g(te.modelProvider)||!g(te.modelId)).map(te=>te.displayName||te.agentId);if($.length)throw new Error(`Model selection is required. Set a default provider/model in Settings or choose one for: ${$.join(", ")}.`);const Ye=Sr(b.name)||"studio-workflow",Ze=new Map;if(X)for(const te of b.agents){const _e=g(te.linkedTemplateId)||g(te.templateId)||`${Ye}--${Sr(te.agentId)||"agent"}`;Ze.set(te.agentId,_e),O.has(_e)?await a.agentTeams.updateTemplate(_e,{display_name:g(te.displayName)||_e,avatar_url:g(te.avatarUrl)||void 0,role:g(te.role)||"worker",system_prompt:tr(te.prompt)||void 0,default_model:g(te.modelProvider)&&g(te.modelId)?{provider_id:g(te.modelProvider),model_id:g(te.modelId)}:void 0,skills:te.skills.map(h=>({id:h,skill_id:h,name:h}))}):await a.agentTeams.createTemplate({template:Ud(te,_e)})}const bt=Fd(b.nodes),qt={name:g(b.name),description:g(b.description)||void 0,status:b.status,schedule:Md(b),workspace_root:g(b.workspaceRoot),execution:{max_parallel_agents:Math.max(1,Number.parseInt(String(b.maxParallelAgents||"1"),10)||1)},output_targets:b.outputTargets.map(te=>g(te)).filter(Boolean),agents:b.agents.map(te=>({agent_id:g(te.agentId),template_id:X&&(Ze.get(te.agentId)||g(te.linkedTemplateId))||void 0,display_name:g(te.displayName)||g(te.agentId),avatar_url:g(te.avatarUrl)||void 0,model_policy:Rd(te),skills:te.skills.map(_e=>g(_e)).filter(Boolean),tool_policy:{allowlist:ds(te.toolAllowlist,bt.filter(_e=>_e.agentId===te.agentId)),denylist:te.toolDenylist.map(_e=>g(_e)).filter(Boolean)},mcp_policy:{allowed_servers:te.mcpAllowedServers.map(_e=>g(_e)).filter(Boolean),allowed_tools:[]}})),flow:{nodes:bt.map(te=>{const _e=b.agents.find(Pe=>Pe.agentId===te.agentId),h=g(te.outputPath),j=Br(te),z=g(te.stageKind),K=z==="research_finalize",H=!!z&&!h,fe=te.inputRefs.some(Pe=>g(Pe.alias)==="external_research"),Be=ds(_e?.toolAllowlist||[],bt.filter(Pe=>Pe.agentId===te.agentId)),pt=!!_e?.toolAllowlist?.includes("websearch")&&!K,lt=g(te.outputKind)==="brief",xt=H&&z==="research_discover",et=H&&(z==="research_discover"||z==="research_local_sources"),kt=H&&z==="research_external_sources"&&pt,Et=h?[Be.includes("read")&&!K?"read":null,Be.includes("websearch")&&!K?"websearch":null].filter(Pe=>!!Pe).filter((Pe,ga,ke)=>ke.indexOf(Pe)===ga):H?[et?"read":null,kt?"websearch":null].filter(Pe=>!!Pe):[],Wt=h?[!K&&(Et.includes("read")||lt)?"local_source_reads":null,!K&&pt?"external_sources":null].filter(Pe=>!!Pe):H?[et?"local_source_reads":null,kt?"external_sources":null].filter(Pe=>!!Pe):[],vt=lt?["files_reviewed","files_not_reviewed","citations",pt||fe?"web_sources_reviewed":null].filter(Pe=>!!Pe):[],ct=h?[K?null:"workspace_inspection",!K&&(Et.includes("read")||lt)?"concrete_reads":null,!K&&pt?"successful_web_research":null].filter(Pe=>!!Pe):H?[xt?"workspace_inspection":null,et?"concrete_reads":null,kt?"successful_web_research":null].filter(Pe=>!!Pe):[],Se=[...Wt,...vt,...ct];return{node_id:g(te.nodeId),agent_id:g(te.agentId),objective:g(te.objective)||g(te.title),depends_on:te.dependsOn.map(Pe=>g(Pe)).filter(Boolean),input_refs:An(te.dependsOn,te.inputRefs).map(Pe=>({from_step_id:g(Pe.fromStepId),alias:g(Pe.alias)||g(Pe.fromStepId).replace(/-/g,"_")})),stage_kind:z?"workstream":void 0,output_contract:{kind:g(te.outputKind)||"artifact",enforcement:h?{required_tools:Et,required_evidence:Wt,required_sections:vt,prewrite_gates:ct,retry_on_missing:Se,terminal_on:Se.length?["tool_unavailable","repair_budget_exhausted"]:[],repair_budget:Se.length?5:void 0,session_text_recovery:Se.length||lt?"require_prewrite_satisfied":"allow"}:void 0,summary_guidance:h?j?`Apply the scoped repository changes, update \`${h}\` in the workspace, and use patch/edit/write tools before completing this stage.`:`Create or update \`${h}\` in the workspace and use the write tool before completing this stage.`:H?"Return a structured handoff in the final response instead of writing workspace files.":void 0},metadata:{studio:{output_path:h||void 0,research_stage:z||void 0},builder:{title:g(te.title)||g(te.nodeId),role:g(_e?.role)||"worker",output_path:h||void 0,research_stage:z||void 0,write_required:!!h,required_tools:Et,web_research_expected:pt,task_kind:g(te.taskKind)||void 0,project_backlog_tasks:gi(te)||void 0,task_id:g(te.backlogTaskId)||void 0,repo_root:g(te.repoRoot)||void 0,write_scope:g(te.writeScope)||void 0,acceptance_criteria:g(te.acceptanceCriteria)||void 0,task_dependencies:g(te.taskDependencies)||void 0,verification_state:g(te.verificationState)||void 0,task_owner:g(te.taskOwner)||void 0,verification_command:g(te.verificationCommand)||void 0,prompt:Ed(te,_e||cs(g(te.agentId),g(te.agentId)))}}}})},metadata:{workspace_root:g(I.workspaceRoot),studio:Bd({...b,agents:b.agents.map(te=>({...te,templateId:X?Ze.get(te.agentId)||g(te.linkedTemplateId)||g(te.templateId):"",linkedTemplateId:X?Ze.get(te.agentId)||g(te.linkedTemplateId)||g(te.templateId):""}))},bt,X?null:ne||Cr(b,O).repairState)}},Ae=I.automationId?await a.automationsV2.update(I.automationId,qt):await a.automationsV2.create(qt),wt=g(Ae?.automation?.automation_id||Ae?.automation?.automationId);let It="";if(Oe&&wt){const te=await a.automationsV2.runNow(wt);It=g(te?.run?.run_id||te?.run?.runId)}return{response:Ae,automationId:wt,linkedTemplateIds:Ze,workingDraft:b,startedRunId:It}},onSuccess:async({response:o,automationId:b,linkedTemplateIds:T,workingDraft:C,startedRunId:$})=>{n("ok",Oe?"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"]})]),Q(Ye=>({...Ye,...C,automationId:b||g(o?.automation?.automation_id||o?.automation?.automationId),agents:C.agents.map(Ze=>({...Ze,templateId:X?T.get(Ze.agentId)||Ze.templateId:"",linkedTemplateId:X?T.get(Ze.agentId)||Ze.linkedTemplateId:""}))})),Ie(Ye=>Ye?{...Ye,requiresSave:!1,reason:"save"}:null),Oe&&(ms({tab:"running",runId:$,automationId:b||g(o?.automation?.automation_id||o?.automation?.automationId),openTaskInspector:!0}),r("automations"))},onError:o=>n("err",o instanceof Error?o.message:String(o))}),De=xe({mutationFn:async o=>(await a.automationsV2.delete(o),await Kd(a,o),o),onSuccess:async o=>{if(I.automationId===o){const b=Gn(qa[0],x||"");Q(b),we(b.nodes[0]?.nodeId||""),v(b.agents[0]?.agentId||"")}await Promise.all([s.invalidateQueries({queryKey:["studio","automations"]}),s.invalidateQueries({queryKey:["automations"]})]),n("ok","Studio workflow deleted.")},onError:o=>n("err",o instanceof Error?o.message:String(o))});return e("div",{className:"grid gap-4",children:e(Kt,{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:()=>Ot(I.starterTemplateId||qa[0].id),children:[e("i",{"data-lucide":"rotate-ccw"}),"Reset From Template"]}),e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:ye,children:[e("i",{"data-lucide":"user-plus"}),"Add Agent"]}),e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:Ne,children:[e("i",{"data-lucide":"plus"}),"Add Stage"]}),e("button",{className:"tcp-btn-primary inline-flex items-center gap-2",disabled:ve.isPending,onClick:()=>ve.mutate(),children:[e("i",{"data-lucide":ve.isPending?"loader-circle":"save"}),ve.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(Kt,{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":ae,onClick:()=>ue(o=>!o),children:[e("i",{"data-lucide":ae?"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(Tt,{initial:!1,children:ae?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:qa.map(o=>e("button",{className:`tcp-list-item text-left ${I.starterTemplateId===o.id?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>Ot(o.id),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:o.name}),e("span",{className:"tcp-badge-info",children:o.icon})]}),e("div",{className:"mt-1 text-sm text-slate-300",children:o.summary})]},o.id))}):null})]}),e("section",{className:"grid gap-2 border-t border-slate-800/80 pt-3",children:[e("button",{type:"button",className:"flex w-full items-center gap-2 text-left","aria-expanded":M,onClick:()=>he(o=>!o),children:[e("i",{"data-lucide":M?"chevron-down":"chevron-right",className:"text-slate-400"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Saved Studio Workflows"}),e("div",{className:"text-xs text-slate-400",children:"Reopen workflows created from Studio metadata."})]})]}),e(Tt,{initial:!1,children:M?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:A.length?[...A].sort((o,b)=>{const T=Number(o?.updated_at_ms||o?.updatedAtMs||o?.created_at_ms||o?.createdAtMs||0);return Number(b?.updated_at_ms||b?.updatedAtMs||b?.created_at_ms||b?.createdAtMs||0)-T}).slice(0,12).map(o=>{const b=g(o?.automation_id||o?.automationId||o?.id),T=de.get(b)||null,C=id(T),$=g(C.status),Ye=g(C.failureKind),Ze=g(C.phase),bt=us(T?.updated_at_ms||T?.updatedAtMs||T?.created_at_ms||T?.createdAtMs),qt=o?.metadata?.studio||{},Ae=fs(o,O),wt=g(qt?.template_id||qt?.templateId||qt?.starter_template_id||qt?.starterTemplateId),It=us(o?.updated_at_ms||o?.updatedAtMs||o?.created_at_ms||o?.createdAtMs),te=De.isPending&&De.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(o?.name)||b}),e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[Ae.isBroken?e("span",{className:"tcp-badge-warn",children:"broken links"}):null,e("span",{className:"tcp-badge-info",children:g(o?.status)||"draft"})]})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:g(qt?.summary)||"Studio workflow"}),e("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-slate-500",children:[wt?e("span",{className:"tcp-badge-info",children:["template: ",wt]}):null,e("span",{className:"tcp-badge-muted",children:["id: ",Td(b)]}),It?e("span",{className:"tcp-badge-muted",children:["updated: ",It]}):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: ",$]}),Ze?e("span",{className:"tcp-badge-muted",children:["phase: ",Ze]}):null,Ye?e("span",{className:"tcp-badge-warn",children:["failure: ",Ye]}):null,bt?e("span",{className:"tcp-badge-muted",children:["run: ",bt]}):null]}),g(C.reason)?e("div",{className:"mt-2 text-xs text-slate-300",children:g(C.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:()=>{N(o)},children:[e("i",{"data-lucide":"folder-open"}),"Open"]}),e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:async()=>{try{await W(o)}catch(_e){n("err",_e instanceof Error?_e.message:String(_e))}},children:[e("i",{"data-lucide":"play"}),Ae.isBroken?"Repair & Open":"Run Now"]}),e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs text-rose-200",disabled:te,onClick:()=>{He({automationId:b,title:g(o?.name)||b})},children:[e("i",{"data-lucide":"trash-2"}),te?"Deleting...":"Delete"]})]})]},b)}):e(We,{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(Kt,{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:()=>ve.mutate(),disabled:ve.isPending,children:[e("i",{"data-lucide":ve.isPending?"loader-circle":"save"}),ve.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(Kt,{title:"Workflow Settings",subtitle:"Name, schedule, workspace, and save behavior.",children:e("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.3fr)_minmax(18rem,0.95fr)]",children:[e("div",{className:"grid content-start gap-3",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Name"}),e("input",{className:"tcp-input text-sm",value:I.name,onInput:o=>Je({name:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Description"}),e("textarea",{className:"tcp-input min-h-[88px] text-sm",value:I.description,onInput:o=>Je({description:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Workspace Root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:()=>{const o=g(I.workspaceRoot||x||"/");Ue(o||"/"),ze(""),Re(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:`tcp-input text-sm ${rt?"border-red-500/60 text-red-100":""}`,value:I.workspaceRoot,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:()=>Je({workspaceRoot:""}),disabled:!I.workspaceRoot,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),rt?e("span",{className:"text-xs text-red-300",children:rt}):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:yn(I.outputTargets),onInput:o=>Je({outputTargets:vn(o.target.value)}),placeholder:"content-brief.md, approved-post.md"})]})]}),e("div",{className:"grid content-start gap-3",children:[e("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Status"}),e("select",{className:"tcp-input text-sm",value:I.status,onInput:o=>Je({status:o.target.value}),children:[e("option",{value:"draft",children:"draft"}),e("option",{value:"active",children:"active"}),e("option",{value:"paused",children:"paused"})]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Max Parallel Agents"}),e("input",{className:"tcp-input text-sm",value:I.maxParallelAgents,onInput:o=>Je({maxParallelAgents:o.target.value})})]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Schedule"}),e("select",{className:"tcp-input text-sm",value:I.scheduleType,onInput:o=>Je({scheduleType:o.target.value}),children:[e("option",{value:"manual",children:"manual"}),e("option",{value:"cron",children:"cron"}),e("option",{value:"interval",children:"interval"})]})]}),I.scheduleType==="cron"?e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Cron Expression"}),e("input",{className:"tcp-input text-sm",value:I.cronExpression,onInput:o=>Je({cronExpression:o.target.value}),placeholder:"0 9 * * 1"})]}):null,I.scheduleType==="interval"?e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Interval Seconds"}),e("input",{className:"tcp-input text-sm",value:I.intervalSeconds,onInput:o=>Je({intervalSeconds:o.target.value})})]}):null,e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:X,onInput:o=>$e(o.target.checked)}),"Save agent prompts as reusable templates"]}),e("div",{className:"text-xs text-slate-400",children:"Off: this workflow runs from Studio-local prompts only. On: Studio also creates shared Agent Team templates and links the workflow to them at runtime."}),e("div",{className:"text-xs text-slate-500",children:["Default model fallback:"," ",J.provider&&J.model?`${J.provider}/${J.model}`:"No provider default configured in Settings."]}),e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:I.useSharedModel,onInput:o=>{const b=o.target.checked,T=fi(I.agents);Je({useSharedModel:b,sharedModelProvider:b?g(I.sharedModelProvider)||T.provider||J.provider:I.sharedModelProvider,sharedModelId:b?g(I.sharedModelId)||T.model||J.model:I.sharedModelId})}}),"Use one model for all agents in this workflow"]}),I.useSharedModel?e(ta,{children:[e("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Shared Model Provider"}),e("select",{className:"tcp-input text-sm",value:I.sharedModelProvider,onInput:o=>{const b=o.target.value,T=sn(k,b);Je({sharedModelProvider:b,sharedModelId:T.includes(I.sharedModelId)?I.sharedModelId:T[0]||I.sharedModelId})},children:[e("option",{value:"",children:"Select provider..."}),k.map(o=>e("option",{value:o.id,children:o.id},o.id))]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Shared Model"}),sn(k,I.sharedModelProvider).length?e("select",{className:"tcp-input text-sm",value:I.sharedModelId,onInput:o=>Je({sharedModelId:o.target.value}),children:sn(k,I.sharedModelProvider).map(o=>e("option",{value:o,children:o},o))}):e("input",{className:"tcp-input text-sm",value:I.sharedModelId,onInput:o=>Je({sharedModelId:o.target.value}),placeholder:"provider-specific model id"})]})]}),e("div",{className:"rounded-lg border border-amber-500/20 bg-amber-500/8 px-3 py-2 text-xs text-amber-100",children:"Shared model mode applies the same provider/model to every agent on save and while editing."})]}):null,e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:Oe,onInput:o=>Ke(o.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),ze("")}}),e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",St||re||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:()=>{ot&&Ue(ot)},disabled:!ot,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:()=>{St&&(Je({workspaceRoot:St}),Re(!1),ze(""),n("ok",`Workspace selected: ${St}`))},disabled:!St,children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>{Re(!1),ze("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:qe,onInput:o=>ze(o.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:Ee.length?Ee.map(o=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>Ue(String(o?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(o?.name||o?.path||"")})]})},String(o?.path||o?.name))):e(We,{text:g(qe)?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null,V?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:()=>He(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:V.title}),"."]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:()=>He(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{className:"tcp-btn-danger inline-flex items-center gap-2",disabled:De.isPending,onClick:()=>De.mutate(V.automationId,{onSettled:()=>He(null)}),children:[e("i",{"data-lucide":"trash-2"}),De.isPending?"Deleting...":"Delete workflow"]})]})]})]}):null,e(Kt,{title:"Workflow Map",subtitle:"Select a stage to edit its objective, dependencies, and bound agent.",children:yt.length?e("div",{className:"grid gap-3 xl:grid-cols-4 xl:items-start",children:yt.map(([o,b])=>e("div",{className:"grid content-start gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:["Column ",o+1]}),b.map(T=>{const C=I.agents.find(Ye=>Ye.agentId===T.agentId),$=T.nodeId===R;return e("button",{className:`tcp-list-item flex flex-col text-left ${$?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{we(T.nodeId),v(T.agentId)},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:T.title}),e("span",{className:"tcp-badge-info",children:T.outputKind||"artifact"})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:C?.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)})]},o))}):e(We,{text:"No stages yet. Add one to start shaping the workflow."})}),e(Kt,{title:"Agent Directory",subtitle:"All agents currently participating in this workflow.",children:e("div",{className:"grid gap-2 md:grid-cols-2",children:I.agents.map(o=>{const b=F?.agentId===o.agentId;return e("button",{className:`tcp-list-item text-left ${b?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{v(o.agentId);const T=I.nodes.find(C=>C.agentId===o.agentId);T&&we(T.nodeId)},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:o.displayName||o.agentId}),e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e("span",{className:"tcp-badge-info",children:o.role}),ne?.repairedAgentIds.includes(o.agentId)?e("span",{className:"tcp-badge-warn",children:"missing/repaired"}):g(o.linkedTemplateId||o.templateId)?O.has(g(o.linkedTemplateId||o.templateId))?e("span",{className:"tcp-badge-info",children:"linked"}):e("span",{className:"tcp-badge-warn",children:"missing/repaired"}):e("span",{className:"tcp-badge-muted",children:"local"})]})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:o.agentId}),o.linkedTemplateId?e("div",{className:"mt-2 text-xs text-emerald-200",children:["linked template: ",o.linkedTemplateId]}):null]},o.agentId)})})})]}),e("div",{className:"grid auto-rows-max content-start self-start gap-4",children:[e(Kt,{title:se?`Stage: ${se.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:!se,children:[e("i",{"data-lucide":"trash-2"}),"Remove Stage"]}),children:se?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:se.title,onInput:o=>{Qe(se.nodeId,{title:o.target.value})}})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Bound Agent"}),e("select",{className:"tcp-input text-sm",value:se.agentId,onInput:o=>{const b=o.target.value;Qe(se.nodeId,{agentId:b}),v(b)},children:I.agents.map(o=>e("option",{value:o.agentId,children:o.displayName||o.agentId},o.agentId))})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Objective"}),e("textarea",{className:"tcp-input min-h-[110px] text-sm",value:se.objective,onInput:o=>Qe(se.nodeId,{objective:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Kind"}),e("input",{className:"tcp-input text-sm",value:se.outputKind,onInput:o=>Qe(se.nodeId,{outputKind:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Required Output File"}),e("input",{className:"tcp-input text-sm",placeholder:"marketing-brief.md",value:se.outputPath,onInput:o=>Qe(se.nodeId,{outputPath:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Task Kind"}),e("input",{className:"tcp-input text-sm",placeholder:"code_change",value:se.taskKind||"",onInput:o=>Qe(se.nodeId,{taskKind:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Project Backlog Tasks"}),e("input",{type:"checkbox",checked:!!se.projectBacklogTasks,onChange:o=>Qe(se.nodeId,{projectBacklogTasks:o.target.checked})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Backlog Task ID"}),e("input",{className:"tcp-input text-sm",placeholder:"BACKLOG-123",value:se.backlogTaskId||"",onInput:o=>Qe(se.nodeId,{backlogTaskId:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Repo Root"}),e("input",{className:"tcp-input text-sm",placeholder:".",value:se.repoRoot||"",onInput:o=>Qe(se.nodeId,{repoRoot:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Write Scope"}),e("input",{className:"tcp-input text-sm",placeholder:"src/api, tests/api, Cargo.toml",value:se.writeScope||"",onInput:o=>Qe(se.nodeId,{writeScope:o.target.value})})]}),e("label",{className:"grid gap-1 sm:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Acceptance Criteria"}),e("input",{className:"tcp-input text-sm",placeholder:"Describe what must be true for this coding task to count as done.",value:se.acceptanceCriteria||"",onInput:o=>Qe(se.nodeId,{acceptanceCriteria:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Backlog Dependencies"}),e("input",{className:"tcp-input text-sm",placeholder:"BACKLOG-101, BACKLOG-102",value:se.taskDependencies||"",onInput:o=>Qe(se.nodeId,{taskDependencies:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Verification State"}),e("input",{className:"tcp-input text-sm",placeholder:"pending",value:se.verificationState||"",onInput:o=>Qe(se.nodeId,{verificationState:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Task Owner / Claimer"}),e("input",{className:"tcp-input text-sm",placeholder:"implementer",value:se.taskOwner||"",onInput:o=>Qe(se.nodeId,{taskOwner:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Verification Command"}),e("input",{className:"tcp-input text-sm",placeholder:"cargo test -p tandem-server",value:se.verificationCommand||"",onInput:o=>Qe(se.nodeId,{verificationCommand:o.target.value})})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs text-slate-400",children:"Dependencies"}),e("div",{className:"flex flex-wrap gap-2",children:I.nodes.filter(o=>o.nodeId!==se.nodeId).map(o=>{const b=se.dependsOn.includes(o.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?se.dependsOn.filter(C=>C!==o.nodeId):[...se.dependsOn,o.nodeId];Qe(se.nodeId,{dependsOn:T})},children:[e("i",{"data-lucide":b?"check":"plus"}),o.title]},`${se.nodeId}-${o.nodeId}`)})})]}),se.inputRefs.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs text-slate-400",children:"Input Aliases"}),se.inputRefs.map(o=>e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500",children:o.fromStepId}),e("input",{className:"tcp-input text-sm",value:o.alias,onInput:b=>Qe(se.nodeId,{inputRefs:se.inputRefs.map(T=>T.fromStepId===o.fromStepId?{...T,alias:b.target.value}:T)})})]},`${se.nodeId}-${o.fromStepId}`))]}):null]}):e(We,{text:"Select a stage to edit it."})}),e(Kt,{title:F?`Agent: ${F.displayName||F.agentId}`:"Agent",subtitle:"Role prompt, policies, reusable template link, and model settings.",actions:e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:le,disabled:!F,children:[e("i",{"data-lucide":"trash-2"}),"Remove Agent"]}),children:F?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:F.displayName,onInput:o=>nt(F.agentId,{displayName:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Role"}),e("select",{className:"tcp-input text-sm",value:F.role,onInput:o=>nt(F.agentId,{role:o.target.value}),children:Cd.map(o=>e("option",{value:o,children:o},o))})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Skills"}),e("input",{className:"tcp-input text-sm",value:yn(F.skills),onInput:o=>nt(F.agentId,{skills:vn(o.target.value)}),placeholder:"copywriting, websearch, qa"})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Template Link"}),F.linkedTemplateId?e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>nt(F.agentId,{linkedTemplateId:"",templateId:""}),children:[e("i",{"data-lucide":"unlink"}),"Detach"]}):null]}),e("div",{className:"grid gap-2 md:grid-cols-[minmax(0,1fr)_auto]",children:[e("select",{className:"tcp-input text-sm",value:U,onInput:o=>pe(o.target.value),children:[e("option",{value:"",children:"Select an existing agent template..."}),P.map(o=>e("option",{value:o.templateId,children:o.displayName||o.templateId},o.templateId))]}),e("button",{className:"tcp-btn inline-flex h-10 items-center gap-2 px-3 text-sm",disabled:!U,onClick:it,children:[e("i",{"data-lucide":"download"}),"Load Template"]})]}),e("div",{className:"mt-2 text-xs text-slate-400",children:ne?.repairedAgentIds.includes(F.agentId)?"This agent had a missing shared template link. Studio repaired it into a workflow-local prompt.":F.linkedTemplateId?O.has(F.linkedTemplateId)?`Linked template: ${F.linkedTemplateId}`:`Missing template link repaired locally: ${F.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:F.modelProvider,disabled:I.useSharedModel,onInput:o=>nt(F.agentId,(()=>{const b=o.target.value,T=sn(k,b);return{modelProvider:b,modelId:T.includes(F.modelId)?F.modelId:T[0]||F.modelId}})()),children:[e("option",{value:"",children:"Select provider..."}),k.map(o=>e("option",{value:o.id,children:o.id},o.id))]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Model ID"}),sn(k,F.modelProvider).length?e("select",{className:"tcp-input text-sm",value:F.modelId,disabled:I.useSharedModel,onInput:o=>nt(F.agentId,{modelId:o.target.value}),children:sn(k,F.modelProvider).map(o=>e("option",{value:o,children:o},o))}):e("input",{className:"tcp-input text-sm",value:F.modelId,disabled:I.useSharedModel,onInput:o=>nt(F.agentId,{modelId:o.target.value}),placeholder:"provider-specific model id"})]}),I.useSharedModel?e("div",{className:"text-xs text-amber-200 md:col-span-2",children:"Per-agent model controls are locked because this workflow is using one shared model for all agents."}):null,e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Tool Allowlist"}),e("input",{className:"tcp-input text-sm",value:yn(F.toolAllowlist),onInput:o=>nt(F.agentId,{toolAllowlist:vn(o.target.value)})})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Tool Denylist"}),e("input",{className:"tcp-input text-sm",value:yn(F.toolDenylist),onInput:o=>nt(F.agentId,{toolDenylist:vn(o.target.value)})})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Allowed MCP Servers"}),e("input",{className:"tcp-input text-sm",value:yn(F.mcpAllowedServers),onInput:o=>nt(F.agentId,{mcpAllowedServers:vn(o.target.value)}),placeholder:S.join(", ")||"No MCP servers detected"})]})]}),e("div",{className:"grid gap-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Role Prompt"}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Role"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:F.prompt.role,onInput:o=>nt(F.agentId,{prompt:{...F.prompt,role:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Mission"}),e("textarea",{className:"tcp-input min-h-[92px] text-sm",value:F.prompt.mission,onInput:o=>nt(F.agentId,{prompt:{...F.prompt,mission:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Inputs"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:F.prompt.inputs,onInput:o=>nt(F.agentId,{prompt:{...F.prompt,inputs:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Contract"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:F.prompt.outputContract,onInput:o=>nt(F.agentId,{prompt:{...F.prompt,outputContract:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Guardrails"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:F.prompt.guardrails,onInput:o=>nt(F.agentId,{prompt:{...F.prompt,guardrails:o.target.value}})})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/40 p-3",children:[e("div",{className:"mb-2 text-xs uppercase tracking-wide text-slate-500",children:"Composed System Prompt"}),e("pre",{className:"whitespace-pre-wrap break-words text-xs text-slate-200",children:tr(F.prompt)||"Prompt preview will appear here."})]})]}):e(We,{text:"Select or add an agent to edit it."})})]})]})})})}const Wd=`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 yi(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 zd(a){const t={};for(const n of Array.isArray(a)?a:[]){const r=String(n?.step_id||n?.payload?.task_id||"").trim();if(!r)continue;const s=n?.payload&&typeof n.payload=="object"?n.payload:{},l=t[r]||{assignedRole:"",errorMessage:"",runtimeDetail:"",runtimeStatus:"",sessionId:""};t[r]={assignedRole:String(s?.assigned_agent||s?.agent_id||l.assignedRole||""),errorMessage:String(s?.error||l.errorMessage||""),runtimeDetail:String(s?.why_next_step||l.runtimeDetail||""),runtimeStatus:String(s?.step_status||l.runtimeStatus||""),sessionId:String(s?.session_id||l.sessionId||"")}}return t}function Jd(a,t){const n=yi(a?.status),r=a?.payload&&typeof a.payload=="object"?a.payload:{},s=Number(a?.lease_expires_at_ms||0)||0,l=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:l||void 0,max_attempts:Number(a?.max_attempts||0)||void 0,is_stale:n==="in_progress"&&s>0&&s<=d}}function Qd(a,t){const n=yi(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 wi(a){const t=zd(a?.events),n=Array.isArray(a?.run?.tasks)?a.run.tasks:[],r=n.length?n:Array.isArray(a?.blackboard?.tasks)?a.blackboard.tasks:[],s=Array.isArray(a?.tasks)?a.tasks:[],l=r.map(x=>Jd(x,t[String(x?.id||"").trim()])).filter(x=>x.id),d=s.map(x=>Qd(x,t[String(x?.taskId||x?.step_id||"").trim()])).filter(x=>x.id),u=new Map;for(const x of l)u.set(x.id,x);for(const x of d){if(!u.has(x.id)){u.set(x.id,x);continue}const P=u.get(x.id);P&&u.set(x.id,{...P,session_id:P.session_id||x.session_id,runtime_status:P.runtime_status||x.runtime_status,runtime_detail:P.runtime_detail||x.runtime_detail,assigned_role:P.assigned_role||x.assigned_role,error_message:P.error_message||x.error_message})}const p=[...u.values()],_=String(a?.run?.current_step_id||"").trim()||p.find(x=>x.state==="in_progress"||x.state==="assigned")?.id||"",D=l.length?d.length?"hybrid":(n.length,"blackboard"):d.length?"context_steps":"empty";return{currentTaskId:_,taskSource:D,tasks:p}}const Gd={created:"Created",pending:"Pending",runnable:"Runnable",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"};function Hd(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 Vd(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 Yd(a){return a==="in_progress"||a==="assigned"?e("i",{"data-lucide":"loader-circle",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null}function bs({task:a,isCurrent:t,isSelected:n,workflowSummary:r,onTaskSelect:s,onRetryTask:l}){const[d,u]=w(!1),p=a.state==="failed"||a.state==="blocked"?String(a.error_message||"").trim():"";return e("div",{className:`cursor-pointer rounded-lg border p-2 ${Vd(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:`${Hd(a.state)} inline-flex shrink-0 items-center gap-1`,children:[Yd(a.state),e("span",{children:Gd[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(_=>!_),children:d?"Less":"More"}):null]}):null,e("div",{className:"mt-2 flex flex-wrap gap-1",children:[a.dependencies.slice(0,2).map(_=>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?e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["+",a.dependencies.length-2," more"]}):null]}),e("div",{className:"mt-2 tcp-subtle text-[10px]",children:"Details"}),a.state==="failed"&&l?e("button",{className:"tcp-btn mt-2 h-7 px-2 text-xs",onClick:_=>{_.stopPropagation(),l(a)},children:"Retry Task"}):null]})}function xi({tasks:a,currentTaskId:t,selectedTaskId:n,workflowSummaryByTaskId:r,onTaskSelect:s,onRetryTask:l}){const[d,u]=w("runnable"),p=Pt(null),_=Pt({}),D=L(()=>{const A={created:[],pending:[],runnable:[],assigned:[],in_progress:[],blocked:[],done:[],failed:[],validated:[]};for(const S of a)A[S.state].push(S);const G=new Set([...A.done,...A.validated].map(S=>S.id)),ee=[...A.runnable],de=[];for(const S of[...A.created,...A.pending])S.dependencies.length===0||S.dependencies.every(Q=>G.has(Q))?ee.push(S):de.push(S);return{runnable:ee,waiting:de,assigned:A.assigned,in_progress:A.in_progress,blocked:A.blocked,done:[...A.done,...A.validated],failed:A.failed}},[a]),x=[{key:"runnable",label:"Ready",tasks: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}],P=L(()=>{const A=x.find(G=>G.tasks.some(ee=>ee.id===t));return A?A.key:x.find(G=>G.tasks.length>0)?.key||"runnable"},[x,t]),O=P;be(()=>{u(A=>x.some(G=>G.key===A)?A:P)},[x,P]);const k=A=>{const G=_.current[A];G&&G.scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"})},J=()=>{O&&k(O)};return a.length?e(ta,{children:[e("div",{className:"grid gap-3 xl:hidden",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:t?e("button",{type:"button",className:"rounded-full border border-emerald-400/60 bg-emerald-400/10 px-3 py-1.5 text-[11px] font-medium text-emerald-200",onClick:()=>u(O),children:"Jump to active task"}):null}),e("div",{className:"flex gap-2 overflow-x-auto pb-1",children:x.map(A=>{const G=A.key===d;return e("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[11px] font-medium ${G?"border-emerald-400/60 bg-emerald-400/10 text-emerald-200":"border-slate-700/60 bg-slate-900/20 text-slate-300"}`,onClick:()=>u(A.key),children:[A.label," (",A.tasks.length,")"]},A.key)})}),x.filter(A=>A.key===d).map(A=>e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-2",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:A.label}),e("div",{className:"tcp-subtle text-xs",children:A.tasks.length})]}),e("div",{className:"grid gap-2",children:[A.tasks.map(G=>e(bs,{task:G,isCurrent:G.id===t,isSelected:G.id===n,workflowSummary:r?.[G.id],onTaskSelect:s,onRetryTask:l},G.id)),A.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},A.key))]}),e("div",{className:"hidden gap-3 xl:grid",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[t?e("button",{type:"button",className:"rounded-full border border-emerald-400/60 bg-emerald-400/10 px-3 py-1.5 text-[11px] font-medium text-emerald-200",onClick:J,children:"Jump to active task"}):null,e("div",{className:"flex flex-wrap gap-2",children:x.map(A=>{const G=A.key===O;return e("button",{type:"button",className:`rounded-full border px-3 py-1.5 text-[11px] font-medium ${G?"border-emerald-400/60 bg-emerald-400/10 text-emerald-200":"border-slate-700/60 bg-slate-900/20 text-slate-300"}`,onClick:()=>k(A.key),children:[A.label," (",A.tasks.length,")"]},`desktop-tab-${A.key}`)})})]}),e("div",{ref:p,className:"overflow-x-auto pb-2",children:e("div",{className:"flex min-w-max gap-3",children:x.map(A=>e("div",{ref:G=>{_.current[A.key]=G},className:`min-h-[16rem] w-[320px] shrink-0 rounded-xl border p-2 ${A.key===O?"border-emerald-400/60 bg-emerald-400/5":"border-slate-700/60 bg-slate-900/20"}`,children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:A.label}),e("div",{className:"tcp-subtle text-xs",children:A.tasks.length})]}),e("div",{className:"grid gap-2",children:[A.tasks.map(G=>e(bs,{task:G,isCurrent:G.id===t,isSelected:G.id===n,workflowSummary:r?.[G.id],onTaskSelect:s,onRetryTask:l},G.id)),A.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},A.key))})})]})]}):e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-4",children:"No tasks yet."})}function Va(a,t,n={}){be(()=>{if(!(!n.enabled||!a))return Mr(a,t,{withCredentials:n.withCredentials})},[t,n.enabled,n.withCredentials,a])}const Xd=`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
|
+
`,Zd=`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
|
+
`,eu=`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
|
+
`,tu=`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
|
+
`,au={"ai-opportunity":"sparkles","workflow-audit":"workflow","agentic-design":"bot","automation-rollout":"arrow-up-circle"},nu=Object.assign({"../presets/mission-builder/agentic-design.yaml":Xd,"../presets/mission-builder/ai-opportunity.yaml":Zd,"../presets/mission-builder/automation-rollout.yaml":eu,"../presets/mission-builder/workflow-audit.yaml":tu});function ru(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 Ta(a){return String(a||"").split(",").map(t=>t.trim()).filter(Boolean)}function ur(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 mr(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 vs(a,t,n){const r={type:"run_once"};return a==="cron"?{type:"cron",cron_expression:String(n||"").trim(),timezone:"UTC",misfire_policy:r}:a==="interval"?{type:"interval",interval_seconds:Math.max(1,Number.parseInt(String(t||"3600"),10)||3600),timezone:"UTC",misfire_policy:r}:{type:"manual",timezone:"UTC",misfire_policy:r}}function Ha(a){return{mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,title:"",goal:"",success_criteria:[],shared_context:"",workspace_root:a,orchestrator_template_id:"",phases:[{phase_id:"phase_1",title:"Phase 1",description:"",execution_mode:"soft"}],milestones:[],team:{allowed_template_ids:[],default_model_policy:null,allowed_mcp_servers:[],max_parallel_agents:4,mission_budget:{},orchestrator_only_tool_calls:!1},workstreams:[{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:"Workstream 1",objective:"",role:"worker",prompt:"",priority:1,phase_id:"phase_1",lane:"lane_1",milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}],review_stages:[],metadata:null}}function su(a,t){const n=nr.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(),l=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(!l)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:l,description:d,blueprint:u}}const ys=Object.entries(nu).map(([a,t])=>su(t,a)).sort((a,t)=>a.label.localeCompare(t.label,void 0,{sensitivity:"base"}));function ki(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function iu(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=ki(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 ou(a,t){const n=a?.metadata&&typeof a.metadata=="object"?a.metadata:{},r=n.mission_blueprint||n.missionBlueprint||n.mission_blueprint_v1;if(!r||typeof r!="object")return null;const s=r;return{...Ha(t),...s,workspace_root:String(s.workspace_root||t||"").trim(),phases:Array.isArray(s.phases)&&s.phases.length?s.phases:Ha(t).phases,milestones:Array.isArray(s.milestones)?s.milestones:[],workstreams:Array.isArray(s.workstreams)?s.workstreams:[],review_stages:Array.isArray(s.review_stages)?s.review_stages:[]}}function Ra({title:a,subtitle:t,icon:n,children:r}){return e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-3",children:[e("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-100",children:[n?e("i",{"data-lucide":n}):null,e("span",{children:a})]}),t?e("div",{className:"tcp-subtle mt-1 text-xs",children:t}):null]}),e("div",{className:"grid gap-3",children:r})]})}function gt({label:a,value:t,onInput:n,placeholder:r,type:s="text"}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("input",{type:s,value:t,placeholder:r,onInput:l=>n(l.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function xn({label:a,value:t,onInput:n,placeholder:r,rows:s=5}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("textarea",{rows:s,value:t,placeholder:r,onInput:l=>n(l.target.value),className:"min-h-[108px] w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function lu({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 Gt({children:a}){return e("div",{className:"tcp-subtle -mt-1 text-xs",children:a})}function cu({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 du({value:a,error:t,open:n,browseDir:r,search:s,parentDir:l,currentDir:d,directories:u,onOpen:p,onClose:_,onClear:D,onSearchChange:x,onBrowseParent:P,onBrowseDirectory:O,onSelectDirectory:k}){const J=String(s||"").trim().toLowerCase();return e(ta,{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:_}),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:P,disabled:!l,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:k,disabled:!d,children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",type:"button",onClick:_,children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:s,onInput:A=>x(A.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:u.length?u.map(A=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>O(String(A?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(A?.name||A?.path||"")})]})},String(A?.path||A?.name))):e(cu,{text:J?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null]})}function pr({providerLabel:a,modelLabel:t,draft:n,providers:r,onChange:s,inheritLabel:l="Inherit team default"}){const d=r.find(u=>u.id===n.provider)?.models||[];return e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"cpu"}),e("span",{children:a})]}),e("select",{value:n.provider,onInput:u=>{const p=u.target.value,_=r.find(D=>D.id===p)?.models||[];s({provider:p,model:_[0]||""})},className:"tcp-select h-10 w-full",children:[e("option",{value:"",children:l}),r.map(u=>e("option",{value:u.id,children:[u.id,u.configured===!1?" (not configured)":""]},u.id))]})]}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"sparkles"}),e("span",{children:t})]}),e("select",{value:n.model,onInput:u=>s({...n,model:u.target.value}),className:"tcp-select h-10 w-full",disabled:!n.provider,children:[e("option",{value:"",children:n.provider?"Select a model":l}),d.map(u=>e("option",{value:u,children:u},u))]})]})]})}function uu({client:a,api:t,toast:n,defaultProvider:r,defaultModel:s,editingAutomation:l=null,onShowAutomations:d,onShowRuns:u,onClearEditing:p}){const _=aa(),D=Pt(null),[x,P]=w("mission"),[O,k]=w("manual"),[J,A]=w("3600"),[G,ee]=w(""),[de,S]=w(!0),[I,Q]=w(""),[R,we]=w(""),[y,v]=w(null),[U,pe]=w(""),[X,$e]=w(Ha("")),[Oe,Ke]=w({provider:r,model:s}),[ae,ue]=w({}),[M,he]=w({}),[Te,Re]=w(!1),[re,Ue]=w(!1),[qe,ze]=w(""),[V,He]=w(""),ne=Z({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),Ie=Z({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),ht=Z({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),se=Z({queryKey:["tool","ids"],queryFn:()=>a.listToolIds().catch(()=>[]),refetchInterval:3e4}),F=Z({queryKey:["agent-team","templates"],queryFn:async()=>{const o=await a.agentTeams.listTemplates().catch(()=>({templates:[]}));return Array.isArray(o?.templates)?o.templates:[]},refetchInterval:3e4}),rt=Z({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),mt=Z({queryKey:["advanced-mission-builder","workspace-browser",qe],enabled:re&&!!qe,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(qe)}`,{method:"GET"})});be(()=>{const o=String(rt.data?.workspaceRoot||rt.data?.workspace_root||"").trim();o&&(pe(o),$e(b=>b.workspace_root?b:{...Ha(o),workspace_root:o}))},[rt.data]),be(()=>{const o=U||String(rt.data?.workspaceRoot||rt.data?.workspace_root||"").trim();if(!l){$e(Ha(o)),v(null),Q(""),S(!0),k("manual"),A("3600"),ee(""),Ke({provider:r,model:s}),ue({}),he({});return}const b=ou(l,o);if(!b)return;$e(b),Ke(mr(b.team.default_model_policy));const T={};for(const Ze of b.workstreams)T[Ze.workstream_id]=mr(Ze.model_override);ue(T);const C={};for(const Ze of b.review_stages)C[Ze.stage_id]=mr(Ze.model_override);he(C);const $=l?.schedule||{},Ye=String($?.type||"").trim().toLowerCase();Ye==="cron"?(k("cron"),ee(String($?.cron_expression||"").trim())):Ye==="interval"?(k("interval"),A(String($?.interval_seconds||3600))):(k("manual"),ee(""),A("3600")),S(!1),v(null),Q("")},[l?.automation_id,U,r,s,rt.data]);const ot=L(()=>{const o=Array.isArray(ne.data?.all)?ne.data.all:[],b=Ie.data?.providers||{},T=o.map(C=>({id:String(C?.id||"").trim(),models:Object.keys(C?.models||{}),configured:!!b[String(C?.id||"").trim()]})).filter(C=>C.id).sort((C,$)=>C.id.localeCompare($.id));return r&&!T.some(C=>C.id===r)&&T.unshift({id:r,models:s?[s]:[],configured:!0}),T},[s,r,ne.data,Ie.data]),St=L(()=>ru(ht.data),[ht.data]),Ee=L(()=>(Array.isArray(se.data)?se.data:[]).map(o=>String(o||"").trim()).filter(Boolean).sort(),[se.data]),Rt=L(()=>(Array.isArray(F.data)?F.data:[]).map(o=>({template_id:String(o?.template_id||o?.templateId||"").trim(),role:String(o?.role||"").trim()})).filter(o=>o.template_id),[F.data]),yt=Array.isArray(mt.data?.directories)?mt.data.directories:[],Ot=String(mt.data?.parent||"").trim(),Je=String(mt.data?.dir||qe||"").trim(),Qe=L(()=>{const o=String(V||"").trim().toLowerCase();return o?yt.filter(b=>String(b?.name||b?.path||"").trim().toLowerCase().includes(o)):yt},[V,yt]),nt=ki(X.workspace_root||U);be(()=>{try{D.current?ya(D.current):ya()}catch{}},[x,Te,y,R,X,Oe,ae,M]);const ye=L(()=>({...X,workspace_root:X.workspace_root||U,team:{...X.team,default_model_policy:ur(Oe)},workstreams:X.workstreams.map(o=>({...o,model_override:ur(ae[o.workstream_id]||{provider:"",model:""})})),review_stages:X.review_stages.map(o=>({...o,model_override:ur(M[o.stage_id]||{provider:"",model:""})}))}),[X,U,Oe,ae,M]),Ne=L(()=>iu(ye),[ye]),Ve=L(()=>[...ye.workstreams.map(o=>o.workstream_id),...ye.review_stages.map(o=>o.stage_id)],[ye]);function le(o){$e(b=>({...b,...o})),v(null)}function it(){$e(o=>({...o,workstreams:[...o.workstreams,{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:`Workstream ${o.workstreams.length+1}`,objective:"",role:"worker",prompt:"",priority:o.workstreams.length+1,phase_id:o.phases[0]?.phase_id||"",lane:`lane_${o.workstreams.length+1}`,milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}]})),v(null)}function N(){$e(o=>({...o,review_stages:[...o.review_stages,{stage_id:`review_${crypto.randomUUID().slice(0,8)}`,stage_kind:"approval",title:`Gate ${o.review_stages.length+1}`,target_ids:[],role:"reviewer",prompt:"",checklist:[],priority:o.review_stages.length+1,phase_id:o.phases[0]?.phase_id||"",lane:"review",milestone:"",tool_allowlist_override:[],mcp_servers_override:[],gate:{required:!0,decisions:["approve","rework","cancel"],rework_targets:[],instructions:""}}]})),v(null)}function W(o){const b=ys.find(C=>C.id===o);if(!b)return;const T={...Ha(X.workspace_root||U),...b.blueprint,mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,workspace_root:X.workspace_root||U};$e(T),v(null),Q(""),P("mission"),Ke({provider:r,model:s}),ue({}),he({}),n("info",`Loaded ${b.label}. Review the prompts and adapt them to your mission.`)}async function ve(){if(Ne.length){const o=Ne.join(" ");Q(o),n("err",o),P("mission");return}we("preview"),Q("");try{const o=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:ye,schedule:vs(O,J,G)})});v(o),P("compile")}catch(o){const b=o instanceof Error?o.message:String(o||""),T=b==="mission blueprint validation failed"&&Ne.length?Ne.join(" "):b;Q(T),n("err",T)}finally{we("")}}async function De(){if(Ne.length){const o=Ne.join(" ");Q(o),n("err",o),P("mission");return}we("apply"),Q("");try{const o=vs(O,J,G);if(l?.automation_id){const C=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:ye,schedule:o})});await a.automationsV2.update(l.automation_id,{name:C?.automation?.name,description:C?.automation?.description||null,schedule:C?.automation?.schedule,agents:C?.automation?.agents,flow:C?.automation?.flow,execution:C?.automation?.execution,workspace_root:C?.automation?.workspace_root,metadata:C?.automation?.metadata}),await Promise.all([_.invalidateQueries({queryKey:["automations"]}),_.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:ye,creator_id:"control-panel",schedule:o})});await Promise.all([_.invalidateQueries({queryKey:["automations"]}),_.invalidateQueries({queryKey:["automations","v2","list"]})]);const T=String(b?.automation?.automation_id||"").trim();de&&T?(await a.automationsV2.runNow(T),n("ok","Advanced mission created and started."),u()):(n("ok","Advanced mission created."),d()),$e(Ha(U)),v(null),S(!0)}catch(o){const b=o instanceof Error?o.message:String(o||""),T=b==="mission blueprint validation failed"&&Ne.length?Ne.join(" "):b;Q(T),n("err",T)}finally{we("")}}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:"}),ys.map(o=>e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>W(o.id),children:[e("i",{"data-lucide":au[o.id]||"sparkles"}),o.label]},o.id))]}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[["mission","clipboard-list"],["team","users"],["workstreams","workflow"],["review","shield-check"],["compile","binary"]].map(([o,b])=>e(lu,{active:x===o,label:o==="workstreams"?"workstreams":o,icon:b,onClick:()=>P(o)},o))})]}),I?e("div",{className:"rounded-xl border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-200",children:I}):null,l?e("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:["Editing advanced mission:"," ",e("strong",{children:String(l?.name||l?.automation_id||"")})]}):null,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(Ra,{title:"What goes where",subtitle:"Use the right field for the right level of instruction.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"Mission goal:"})," the one shared outcome for the whole operation."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Success criteria:"})," concrete checks for whether the mission is done well."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Shared context:"})," facts, constraints, tone, audience, deadlines, approved sources."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream objective:"})," the local assignment for that lane."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream prompt:"})," the operating instructions for how that lane should work."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Output contract:"})," the artifact that downstream work expects to receive."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Review / gate prompt:"})," what a reviewer or approver must check before promotion."]})]})}),e(Ra,{title:"How to get good results",subtitle:"The builder works best when each stage is explicit.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:"Keep the mission goal outcome-based, not a long checklist."}),e("div",{children:"Make success criteria measurable."}),e("div",{children:"Give each workstream one clear responsibility."}),e("div",{children:"Use dependencies only for real handoffs."}),e("div",{children:"Define outputs as concrete artifacts, not vague intentions."}),e("div",{children:"Use review gates for quality and promotion, not for every step."}),e("div",{children:"Prefer prompts that say what evidence, format, and audience the step should target."})]})}),e(Ra,{title:"Prompt pattern",subtitle:"A reliable starting scaffold for most workstreams.",children:e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3 text-xs text-slate-300",children:[e("div",{children:e("strong",{className:"text-slate-100",children:"Mission goal"})}),e("div",{className:"mt-1",children:"Produce a coordinated launch plan for Product X for the next 30 days."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Shared context"})}),e("div",{className:"mt-1",children:"Audience is SMB owners. Tone is clear and practical. Use approved workspace and MCP sources only. Avoid speculative claims."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream objective"})}),e("div",{className:"mt-1",children:"Analyze the target workflow and identify the 3 highest-value AI opportunities for a near-term pilot."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream prompt"})}),e("div",{className:"mt-1",children:"Act as an AI workflow strategist. Map the current process, identify repeated manual work, decision bottlenecks, and coordination pain, then recommend realistic AI patterns with evidence and operational caveats."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Output contract"})}),e("div",{className:"mt-1",children:"A markdown memo with sections: workflow summary, AI opportunities, feasibility constraints, risks, and recommended pilots."})]})}),e(Ra,{title:"Starter examples",subtitle:"Use these when you do not want to begin from a blank blueprint.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"AI Opportunities:"})," workflow analysis and capability mapping feeding a ranked pilot brief."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workflow Audit:"})," current-state mapping and failure analysis feeding an automation design review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Agentic Design:"})," role design and flow design feeding governance and safety review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Rollout:"})," process readiness and platform readiness feeding a launch plan and approval gate."]})]})})]})]})}):null,x==="mission"?e(Ra,{title:"Mission",subtitle:"Global brief, success criteria, and schedule.",icon:"clipboard-list",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(gt,{label:"Mission title",value:X.title,onInput:o=>le({title:o})}),e(gt,{label:"Mission ID",value:X.mission_id,onInput:o=>le({mission_id:o})})]}),e(Gt,{children:"Use a short title a human operator would recognize later in the automation list."}),e(du,{value:X.workspace_root,error:nt,open:re,browseDir:qe,search:V,parentDir:Ot,currentDir:Je,directories:Qe,onOpen:()=>{const o=String(X.workspace_root||U||"/").trim();ze(o||"/"),He(""),Ue(!0)},onClose:()=>{Ue(!1),He("")},onClear:()=>le({workspace_root:""}),onSearchChange:He,onBrowseParent:()=>{Ot&&ze(Ot)},onBrowseDirectory:o=>ze(o),onSelectDirectory:()=>{Je&&(le({workspace_root:Je}),Ue(!1),He(""),n("ok",`Workspace selected: ${Je}`))}}),e(Gt,{children:"This is the shared working directory the mission can use for files and artifacts."}),nt?e("div",{className:"text-xs text-red-300",children:nt}):null,e(xn,{label:"Mission goal",value:X.goal,onInput:o=>le({goal:o}),placeholder:"Describe the shared objective all participants are working toward."}),e(Gt,{children:"Write the one shared outcome for the whole swarm, not a list of steps."}),e(xn,{label:"Shared context",value:X.shared_context||"",onInput:o=>le({shared_context:o}),placeholder:"Shared constraints, references, context, and operator guidance."}),e(Gt,{children:"Put the facts every lane should inherit here: audience, constraints, tone, deadlines, approved sources, and things to avoid."}),e(gt,{label:"Success criteria",value:X.success_criteria.join(", "),onInput:o=>le({success_criteria:Ta(o)}),placeholder:"comma-separated"}),e(Gt,{children:"These should be measurable checks like “brief includes 5 competitors” or “plan contains owner, timeline, and risks”."}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Schedule"}),e("select",{value:O,onInput:o=>k(o.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"manual",children:"Manual"}),e("option",{value:"interval",children:"Interval"}),e("option",{value:"cron",children:"Cron"})]})]}),O==="interval"?e(gt,{label:"Interval seconds",value:J,onInput:A}):null,O==="cron"?e(gt,{label:"Cron expression",value:G,onInput:ee}):null]})]}):null,x==="team"?e(Ra,{title:"Team",subtitle:"Templates, default model, concurrency, and mission limits.",icon:"users",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Orchestrator template"}),e("select",{value:X.orchestrator_template_id||"",onInput:o=>le({orchestrator_template_id:o.target.value}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"",children:"None"}),Rt.map(o=>e("option",{value:o.template_id,children:[o.template_id," (",o.role||"role",")"]},o.template_id))]})]}),e(gt,{label:"Allowed templates",value:(X.team.allowed_template_ids||[]).join(", "),onInput:o=>le({team:{...X.team,allowed_template_ids:Ta(o)}}),placeholder:"comma-separated"})]}),e(Gt,{children:"The orchestrator keeps the mission coherent. Allowed templates restrict which reusable agent profiles lanes are permitted to use."}),e(pr,{providerLabel:"Default model provider",modelLabel:"Default model",draft:Oe,providers:ot,inheritLabel:"No team default",onChange:Ke}),e("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-4",children:[e(gt,{label:"Max parallel agents",value:String(X.team.max_parallel_agents||4),onInput:o=>le({team:{...X.team,max_parallel_agents:Math.max(1,Number.parseInt(String(o||"4"),10)||4)}}),type:"number"}),e(gt,{label:"Token ceiling",value:String(X.team.mission_budget?.max_total_tokens||""),onInput:o=>le({team:{...X.team,mission_budget:{...X.team.mission_budget||{},max_total_tokens:o?Number(o):void 0}}}),type:"number"}),e(gt,{label:"Cost ceiling USD",value:String(X.team.mission_budget?.max_total_cost_usd||""),onInput:o=>le({team:{...X.team,mission_budget:{...X.team.mission_budget||{},max_total_cost_usd:o?Number(o):void 0}}}),type:"number"}),e(gt,{label:"Tool-call ceiling",value:String(X.team.mission_budget?.max_total_tool_calls||""),onInput:o=>le({team:{...X.team,mission_budget:{...X.team.mission_budget||{},max_total_tool_calls:o?Number(o):void 0}}}),type:"number"})]}),e(gt,{label:"Allowed MCP servers",value:(X.team.allowed_mcp_servers||[]).join(", "),onInput:o=>le({team:{...X.team,allowed_mcp_servers:Ta(o)}}),placeholder:St.map(o=>o.name).join(", ")}),e(Gt,{children:"Team defaults apply everywhere unless a workstream or review stage overrides its own tool or MCP scope."})]}):null,x==="workstreams"?e(Ra,{title:"Workstreams",subtitle:"Scoped sub-objectives, dependencies, tools, MCP, and output contracts.",icon:"workflow",children:[e(Gt,{children:"A workstream is one scoped lane of work. Give it one responsibility, one artifact to produce, and only the dependencies it truly needs."}),e("div",{className:"flex justify-end",children:e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:it,children:[e("i",{"data-lucide":"plus"}),"Add workstream"]})}),ye.workstreams.map((o,b)=>{const T=ae[o.workstream_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:o.title||`Workstream ${b+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>le({workstreams:ye.workstreams.filter(C=>C.workstream_id!==o.workstream_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(gt,{label:"Title",value:o.title,onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,title:C}:$)})}),e(gt,{label:"Role",value:o.role,onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,role:C}:$)})})]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e(gt,{label:"Phase",value:o.phase_id||"",onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,phase_id:C}:$)})}),e(gt,{label:"Lane",value:o.lane||"",onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,lane:C}:$)})}),e(gt,{label:"Priority",value:String(o.priority||0),onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,priority:Number(C)||0}:$)}),type:"number"})]}),e(Gt,{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(xn,{label:"Objective",value:o.objective,onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,objective:C}:$)}),rows:3}),e(Gt,{children:"Objective is the local assignment. Keep it crisp: what this lane must accomplish."}),e(xn,{label:"Prompt",value:o.prompt,onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,prompt:C}:$)}),rows:5}),e(Gt,{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(gt,{label:"Depends on",value:o.depends_on.join(", "),onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,depends_on:Ta(C)}:$)}),placeholder:"comma-separated stage ids"}),e(gt,{label:"Output contract kind",value:o.output_contract.kind,onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,output_contract:{...$.output_contract,kind:C}}:$)})})]}),e(Gt,{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(gt,{label:"Tool allowlist override",value:(o.tool_allowlist_override||[]).join(", "),onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,tool_allowlist_override:Ta(C)}:$)}),placeholder:Ee.join(", ")}),e(gt,{label:"MCP servers override",value:(o.mcp_servers_override||[]).join(", "),onInput:C=>le({workstreams:ye.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,mcp_servers_override:Ta(C)}:$)}),placeholder:St.map(C=>C.name).join(", ")})]}),e(Gt,{children:"Leave tool and MCP overrides empty to inherit team defaults. Override only when this lane needs a narrower or different scope."}),e(pr,{providerLabel:"Model provider",modelLabel:"Model",draft:T,providers:ot,onChange:C=>ue($=>({...$,[o.workstream_id]:C}))})]},o.workstream_id)})]}):null,x==="review"?e(Ra,{title:"Review & Gates",subtitle:"Reviewer, tester, and approval stages.",icon:"shield-check",children:[e(Gt,{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:N,children:[e("i",{"data-lucide":"plus"}),"Add review stage"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>le({phases:[...ye.phases,{phase_id:`phase_${ye.phases.length+1}`,title:`Phase ${ye.phases.length+1}`,description:"",execution_mode:"soft"}]}),children:[e("i",{"data-lucide":"copy-plus"}),"Add phase"]})]}),e("div",{className:"grid gap-2",children:ye.phases.map((o,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(gt,{label:"Phase ID",value:o.phase_id,onInput:T=>le({phases:ye.phases.map((C,$)=>$===b?{...C,phase_id:T}:C)})}),e(gt,{label:"Title",value:o.title,onInput:T=>le({phases:ye.phases.map((C,$)=>$===b?{...C,title:T}:C)})}),e(gt,{label:"Description",value:o.description||"",onInput:T=>le({phases:ye.phases.map((C,$)=>$===b?{...C,description:T}:C)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Execution mode"}),e("select",{value:o.execution_mode||"soft",onInput:T=>le({phases:ye.phases.map((C,$)=>$===b?{...C,execution_mode:T.target.value}:C)}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"soft",children:"soft"}),e("option",{value:"barrier",children:"barrier"})]})]})]})},o.phase_id))}),e(Gt,{children:"`soft` phases prefer the current open phase first. `barrier` phases hold later phases closed until earlier required work is complete."}),ye.review_stages.map((o,b)=>{const T=M[o.stage_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:o.title||`Review stage ${b+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>le({review_stages:ye.review_stages.filter(C=>C.stage_id!==o.stage_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(gt,{label:"Title",value:o.title,onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,title:C}:$)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Stage kind"}),e("select",{value:o.stage_kind,onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,stage_kind: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",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(gt,{label:"Targets",value:o.target_ids.join(", "),onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,target_ids:Ta(C)}:$)}),placeholder:Ve.join(", ")}),e(gt,{label:"Phase",value:o.phase_id||"",onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,phase_id:C}:$)})}),e(gt,{label:"Lane",value:o.lane||"",onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,lane:C}:$)})})]}),e(Gt,{children:"Targets are the stages this review or gate is checking. Put the review in the phase where that checkpoint should happen."}),e(xn,{label:"Prompt",value:o.prompt,onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,prompt:C}:$)}),rows:4}),e(Gt,{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(gt,{label:"Checklist",value:(o.checklist||[]).join(", "),onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,checklist:Ta(C)}:$)}),placeholder:"comma-separated"}),e(gt,{label:"MCP servers override",value:(o.mcp_servers_override||[]).join(", "),onInput:C=>le({review_stages:ye.review_stages.map($=>$.stage_id===o.stage_id?{...$,mcp_servers_override:Ta(C)}:$)}),placeholder:St.map(C=>C.name).join(", ")})]}),e(Gt,{children:"Checklist items should be concrete pass/fail checks, not broad wishes."}),e(pr,{providerLabel:"Model provider",modelLabel:"Model",draft:T,providers:ot,onChange:C=>he($=>({...$,[o.stage_id]:C}))})]},o.stage_id)})]}):null,x==="compile"?e(Ra,{title:"Compile & Run",subtitle:"Validate the mission graph before launch.",icon:"binary",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",disabled:R==="preview",onClick:()=>{ve()},children:[e("i",{"data-lucide":"refresh-cw"}),R==="preview"?"Compiling...":"Compile preview"]}),e("button",{className:"tcp-btn-primary h-8 px-3 text-xs",disabled:R==="apply",onClick:()=>{De()},children:[e("i",{"data-lucide":l?"save":"arrow-up-circle"}),R==="apply"?"Saving...":l?"Save automation":de?"Create and run":"Create draft"]}),l?null:e("label",{className:"ml-2 inline-flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:de,onChange:o=>S(o.target.checked)}),"Run immediately after create"]}),l&&p?e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>p(),children:"Cancel edit"}):null]}),y?e(ta,{children:[e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Validation"}),Array.isArray(y?.validation)&&y.validation.length?e("div",{className:"grid gap-2",children:y.validation.map((o,b)=>e("div",{className:`rounded-lg border px-3 py-2 text-xs ${String(o?.severity||"").toLowerCase()==="warning"?"border-amber-500/40 bg-amber-500/10 text-amber-200":"border-slate-700 bg-slate-950/60 text-slate-200"}`,children:[e("div",{className:"font-medium",children:String(o?.code||o?.severity||"validation")}),e("div",{className:"mt-1",children:String(o?.message||"")})]},`${o?.code||"message"}-${b}`))}):e("div",{className:"tcp-subtle text-xs",children:"No validation warnings."})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Compiled automation"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:[e("div",{children:["name: ",String(y?.automation?.name||"—")]}),e("div",{children:["nodes:"," ",Array.isArray(y?.automation?.flow?.nodes)?y.automation.flow.nodes.length:0]}),e("div",{children:["agents:"," ",Array.isArray(y?.automation?.agents)?y.automation.agents.length:0]}),e("div",{children:["max parallel:"," ",String(y?.automation?.execution?.max_parallel_agents??"—")]})]})]})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Node preview"}),e("div",{className:"grid gap-2",children:(Array.isArray(y?.node_previews)?y.node_previews:[]).map(o=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/70 p-3 text-xs text-slate-300",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-slate-100",children:String(o?.title||o?.node_id||"node")}),e("span",{className:"tcp-subtle",children:String(o?.node_id||"")}),e("span",{className:"tcp-subtle",children:["phase: ",String(o?.phase_id||"—")]}),e("span",{className:"tcp-subtle",children:["lane: ",String(o?.lane||"—")]}),e("span",{className:"tcp-subtle",children:["priority: ",String(o?.priority??"—")]})]}),e("div",{className:"mt-1",children:["depends on:"," ",Array.isArray(o?.depends_on)&&o.depends_on.length?o.depends_on.join(", "):"none"]}),e("div",{className:"mt-1",children:["tools:"," ",Array.isArray(o?.tool_allowlist)&&o.tool_allowlist.length?o.tool_allowlist.join(", "):"default"]}),e("div",{className:"mt-1",children:["MCP:"," ",Array.isArray(o?.mcp_servers)&&o.mcp_servers.length?o.mcp_servers.join(", "):"default"]})]},String(o?.node_id||"")))})]})]}):e("div",{className:"tcp-subtle text-xs",children:"Compile the mission to inspect validation, compiled nodes, and execution shape."})]}):null]})}const mu=`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
|
+
`,pu=`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 hr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function ws(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 Bn(a){const t=Number(a);return Number.isFinite(t)?t.toFixed(3):"n/a"}const hu=Object.assign({"./smoke-workflows/extract-format.yaml":mu,"./smoke-workflows/summary.yaml":pu}),gu=Object.entries(hu).map(([a,t])=>{const n=nr.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 fu(a,t){const n=gu.find(d=>d.kind===a);if(!n)throw new Error("Unknown smoke workflow kind: "+a);const r=structuredClone(n.payload),{kind:s,...l}=r;return l.workspace_root=String(t||"").trim(),l}function bu({client:a,toast:t}){const n=aa(),[r,s]=w(""),[l,d]=w({name:"",sourceWorkflowId:"",smokeWorkspaceRoot:"",objectiveRef:"objective.md",evalRef:"eval.yaml",mutationPolicyRef:"mutation_policy.yaml",scopeRef:"scope.yaml",budgetRef:"budget.yaml",modelProvider:"",modelId:"",startImmediately:!0}),u=Z({queryKey:["optimizations","workflows","automations-v2"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]})}),p=Z({queryKey:["optimizations","list"],queryFn:()=>a?.optimizations?.list?.().catch(()=>({optimizations:[]}))??Promise.resolve({optimizations:[]})}),_=Z({queryKey:["optimizations","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),D=Z({queryKey:["optimizations","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),x=Z({queryKey:["optimizations","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),P=L(()=>hr(p.data,"optimizations"),[p.data]),O=L(()=>{const v=Array.isArray(D.data?.all)?D.data.all:[],U=x.data?.providers||{};return v.map(pe=>({id:String(pe?.id||"").trim(),models:Object.keys(pe?.models||{}).sort(),configured:!!U[String(pe?.id||"").trim()]})).filter(pe=>pe.id).sort((pe,X)=>pe.id.localeCompare(X.id))},[D.data,x.data]),k=L(()=>{const v=O.find(U=>U.id===String(l.modelProvider||"").trim());return Array.isArray(v?.models)?v.models:[]},[l.modelProvider,O]);be(()=>{const v=String(_.data?.workspaceRoot||_.data?.workspace_root||"").trim();v&&d(U=>String(U.smokeWorkspaceRoot||"").trim()?U:{...U,smokeWorkspaceRoot:`${v}/docs/internal/optimization-smoke-pack`})},[_.data]);const J=r||String(P[0]?.optimization_id||"").trim(),A=Z({queryKey:["optimizations","detail",J],enabled:!!J,queryFn:()=>a.optimizations.get(J)}),G=Z({queryKey:["optimizations","experiments",J],enabled:!!J,queryFn:()=>a.optimizations.listExperiments(J)}),ee=xe({mutationFn:async()=>{const v=String(l.sourceWorkflowId||"").trim();if(!v)throw new Error("Source workflow is required.");const U={name:String(l.name||"").trim()||void 0,source_workflow_id:v,artifacts:{objective_ref:String(l.objectiveRef||"").trim(),eval_ref:String(l.evalRef||"").trim(),mutation_policy_ref:String(l.mutationPolicyRef||"").trim(),scope_ref:String(l.scopeRef||"").trim(),budget_ref:String(l.budgetRef||"").trim()},execution_override:String(l.modelProvider||"").trim()&&String(l.modelId||"").trim()?{provider_id:String(l.modelProvider||"").trim(),model_id:String(l.modelId||"").trim()}:void 0},pe=await a.optimizations.create(U);if(l.startImmediately){const X=String(pe?.optimization?.optimization_id||"").trim();X&&await a.optimizations.action(X,{action:"start"})}return pe},onSuccess:async v=>{const U=String(v?.optimization?.optimization_id||"").trim();t("ok","Optimization campaign created."),U&&s(U),await n.invalidateQueries({queryKey:["optimizations"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),de=xe({mutationFn:async v=>{const U=String(l.smokeWorkspaceRoot||"").trim();if(!U)throw new Error("Smoke workflow workspace root is required.");if(!a?.automationsV2?.create)throw new Error("Workflow creation client is unavailable.");const pe=fu(v,U);return a.automationsV2.create(pe)},onSuccess:async(v,U)=>{const pe=String(v?.automation?.automation_id||v?.automation?.automationId||"").trim();d(X=>({...X,sourceWorkflowId:pe||X.sourceWorkflowId,name:pe&&!String(X.name||"").trim()?`Optimize ${String(v?.automation?.name||pe).trim()}`:X.name})),t("ok",U==="summary"?"Smoke summary workflow created and selected.":"Smoke extract-format workflow created and selected."),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),S=xe({mutationFn:async({optimizationId:v,action:U,experimentId:pe})=>a.optimizations.action(v,{action:U,experiment_id:pe}),onSuccess:async()=>{t("ok","Optimization action applied."),await n.invalidateQueries({queryKey:["optimizations"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),I=xe({mutationFn:async({optimizationId:v,experimentId:U})=>a.optimizations.applyWinner(v,U),onSuccess:async()=>{t("ok","Approved winner applied to the live workflow."),await n.invalidateQueries({queryKey:["optimizations"]}),await n.invalidateQueries({queryKey:["optimizations","detail",J]}),await n.invalidateQueries({queryKey:["optimizations","experiments",J]}),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),Q=hr(u.data,"automations").map(v=>({id:String(v?.automation_id||v?.automationId||v?.id||"").trim(),name:String(v?.name||v?.automation_id||"Workflow").trim()})),R=A.data?.optimization||null,we=hr(G.data,"experiments"),y=R?.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:l.name,onChange:v=>d(U=>({...U,name:v.target.value})),placeholder:"Optimize research brief workflow"})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Source workflow"}),e("select",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:l.sourceWorkflowId,onChange:v=>d(U=>({...U,sourceWorkflowId:v.target.value})),children:[e("option",{value:"",children:"Select a workflow"}),Q.map(v=>e("option",{value:v.id,children:v.name},v.id))]})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/50 p-3",children:[e("div",{className:"text-xs font-medium text-slate-200",children:"Need a cheap target first?"}),e("div",{className:"mt-1 text-[11px] text-slate-500",children:"Create a tiny validator-backed workflow in the smoke-pack workspace, then use it as the optimization source."}),e("label",{className:"mt-3 grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Smoke workspace root"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:l.smokeWorkspaceRoot,onChange:v=>d(U=>({...U,smokeWorkspaceRoot:v.target.value})),placeholder:"/abs/path/to/docs/internal/optimization-smoke-pack"})]}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-9 px-3 text-xs",onClick:()=>de.mutate("summary"),disabled:de.isPending,children:"Create Smoke Summary"}),e("button",{className:"tcp-btn h-9 px-3 text-xs",onClick:()=>de.mutate("extract_format"),disabled:de.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:l.modelProvider,onChange:v=>d(U=>({...U,modelProvider:v.target.value,modelId:v.target.value&&U.modelProvider!==v.target.value?"":U.modelId})),children:[e("option",{value:"",children:"Use workflow/default model"}),O.map(v=>e("option",{value:v.id,children:[v.id,v.configured?"":" (catalog only)"]},v.id))]})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Model id"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:l.modelId,onChange:v=>d(U=>({...U,modelId:v.target.value})),placeholder:l.modelProvider?"Pick a cheaper model for this campaign":"Optional",list:"optimization-model-ids"}),e("datalist",{id:"optimization-model-ids",children:k.map(v=>e("option",{value:v},v))}),e("span",{className:"tcp-subtle text-[11px]",children:"Fixed for the whole campaign. Leave blank to use the workflow's existing model settings."})]}),[["Objective ref","objectiveRef"],["Eval ref","evalRef"],["Mutation policy ref","mutationPolicyRef"],["Scope ref","scopeRef"],["Budget ref","budgetRef"]].map(([v,U])=>e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:v}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:l[U],onChange:pe=>d(X=>({...X,[U]:pe.target.value}))})]},U)),e("label",{className:"flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:l.startImmediately,onChange:v=>d(U=>({...U,startImmediately:v.target.checked}))}),"Start immediately after create"]}),e("button",{className:"tcp-btn h-10 px-3 text-sm",onClick:()=>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:P.length})]}),e("div",{className:"grid gap-2",children:P.length?P.map(v=>{const U=String(v?.optimization_id||"").trim();return e("button",{type:"button",className:`rounded-xl border px-3 py-3 text-left transition ${J===U?"border-amber-400/60 bg-amber-400/10":"border-slate-700/50 bg-slate-950/40 hover:border-slate-600"}`,onClick:()=>s(U),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium text-slate-100",children:String(v?.name||U||"Optimization")}),e("span",{className:ws(v?.status),children:String(v?.status||"draft")})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:["workflow:"," ",String(v?.source_workflow_name||v?.source_workflow_id||"unknown")]})]},U)}):e(We,{text:"No optimization campaigns yet."})})]})]}),e("div",{className:"grid gap-4",children:R?e(ta,{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(R?.name||R?.optimization_id||"Optimization")}),e("div",{className:"mt-1 text-sm text-slate-400",children:["Source workflow:"," ",String(R?.source_workflow_name||R?.source_workflow_id||"unknown")]}),e("div",{className:"mt-1 text-xs text-slate-500",children:["baseline: ",String(R?.baseline_snapshot_hash||"").slice(0,12)]}),R?.execution_override?e("div",{className:"mt-1 text-xs text-slate-500",children:["model: ",String(R.execution_override.provider_id||"").trim(),"/",String(R.execution_override.model_id||"").trim()]}):null]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>S.mutate({optimizationId:J,action:"start"}),disabled:S.isPending,children:"Start"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>S.mutate({optimizationId:J,action:"pause"}),disabled:S.isPending,children:"Pause"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>S.mutate({optimizationId:J,action:"resume"}),disabled:S.isPending,children:"Resume"})]})]}),e("div",{className:"mt-4 grid gap-3 md:grid-cols-4",children:[e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Status"}),e("div",{className:"mt-1 text-sm text-slate-100",children:String(R?.status||"draft")})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Pass Rate"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?Bn(y.artifact_validator_pass_rate):"n/a"})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Unmet Reqs"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?Bn(y.unmet_requirement_count):"n/a"})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Blocked Rate"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?Bn(y.blocked_node_rate):"n/a"})]})]}),R?.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(R.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:we.length})]}),we.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:we.map(v=>{const U=String(v?.experiment_id||"").trim(),pe=v?.phase1_metrics||{};return e("tr",{className:"border-t border-slate-800",children:[e("td",{className:"px-2 py-3 text-slate-200",children:U||"unknown"}),e("td",{className:"px-2 py-3",children:e("span",{className:ws(v?.status),children:String(v?.status||"draft")})}),e("td",{className:"px-2 py-3 text-slate-300",children:String(v?.mutation_summary||"pending")}),e("td",{className:"px-2 py-3 text-slate-300",children:pe?Bn(pe.artifact_validator_pass_rate):"n/a"}),e("td",{className:"px-2 py-3 text-slate-300",children:String(v?.promotion_recommendation||"n/a")}),e("td",{className:"px-2 py-3",children:e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>S.mutate({optimizationId:J,action:"approve_winner",experimentId:U}),disabled:!U||S.isPending,children:"Approve"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>S.mutate({optimizationId:J,action:"reject_winner",experimentId:U}),disabled:!U||S.isPending,children:"Reject"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>I.mutate({optimizationId:J,experimentId:U}),disabled:!U||I.isPending||String(v?.status||"").trim().toLowerCase()!=="promotion_approved",children:"Apply"})]})})]},U)})})]})}):e(We,{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(We,{text:"Select or create an optimization campaign to inspect it."})})})]})}const vu=Object.assign({"./automation-wizard.yaml":Wd});function yu(a){const t=nr.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,l=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(l)||!l.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:l.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 pa=yu(Object.values(vu)[0]||""),xs="tandem.automations.plannerSeed",ks="tandem.automations.studioHandoff";function Ns(a,t,n=""){return{goal:"",workspaceRoot:n,schedulePreset:pa.defaults.schedulePreset,cron:"",mode:pa.defaults.mode,maxAgents:pa.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 Ma(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Ni(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 wu(a){const t=String(a.cron||"").trim();if(t)return{cron:{expression:t}};const n=pa.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 _i(a){const t=String(a?.type||"").trim().toLowerCase();if(t==="cron")return String(a?.cron_expression||a?.cronExpression||"cron");if(t==="interval"){const n=Number(a?.interval_seconds||a?.intervalSeconds||0);return!Number.isFinite(n)||n<=0?"interval":n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`}return"manual"}function _n(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Vn(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 gr(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 ku(a){let t;const n=String(a.roleModelsJson||"").trim();if(n)try{const u=JSON.parse(n);u&&typeof u=="object"&&!Array.isArray(u)&&(t=u)}catch{t=void 0}const r=String(a.plannerModelProvider||"").trim(),s=String(a.plannerModelId||"").trim();r&&s&&(t={...t||{}},t.planner={provider_id:r,model_id:s});const l=a.mode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(a.maxAgents||"4"),10)||4)):1,d={execution_mode:a.mode,max_parallel_agents:l};return String(a.modelProvider||"").trim()&&(d.model_provider=String(a.modelProvider).trim()),String(a.modelId||"").trim()&&(d.model_id=String(a.modelId).trim()),t&&Object.keys(t).length&&(d.role_models=t),d}function Nu(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 Si(a){const t=String(a?.type||"").trim().toLowerCase(),n=String(a?.cron?.expression||a?.cron_expression||a?.cron||"").trim(),r=Number(a?.interval_seconds?.seconds||a?.interval_seconds||a?.intervalSeconds||3600),s=Number.isFinite(r)&&r>0?Math.round(r):3600;return{scheduleKind:t==="manual"?"manual":n?"cron":"interval",cronExpression:n,intervalSeconds:s}}function _u(a){let t="",n=!1;for(const r of String(a||"").trim())/^[a-z0-9]$/i.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="_",n=!0);return t.replace(/^_+|_+$/g,"")||"mcp"}function On(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 Fn(a,t){const n=new Set,r=[];for(const s of[t,...a]){const l=String(s||"").trim();!l||n.has(l)||(n.add(l),r.push(l))}return r}function Lr(a){return On(String(a||"").split(/[\n,]/g).map(t=>String(t||"").trim()).filter(Boolean))}function Su(a){return On(a).join(`
|
|
2432
|
+
`)}function Iu(a,t,n){return t==="all"?["*"]:On([...Lr(n),...a.map(r=>`mcp.${_u(r)}.*`)])}function Cu(a){const t=a?.metadata?.operator_preferences||a?.metadata?.operatorPreferences;if(t&&typeof t=="object")return t;const n=Array.isArray(a?.agents)?a.agents[0]:null,r=n?.model_policy?.default_model||n?.modelPolicy?.defaultModel||null,s=n?.model_policy?.role_models||n?.modelPolicy?.roleModels||null,l={};return(r?.provider_id||r?.providerId)&&(l.model_provider=r.provider_id||r.providerId),(r?.model_id||r?.modelId)&&(l.model_id=r.model_id||r.modelId),s&&typeof s=="object"&&(l.role_models=s),(a?.execution?.max_parallel_agents||a?.execution?.maxParallelAgents)&&(l.max_parallel_agents=a.execution.max_parallel_agents||a.execution.maxParallelAgents),l}function Au(a){const t=On((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:Su(n)}}function Pu(a){const t=String(a?.automation_id||a?.automationId||a?.id||"").trim();if(!t)return null;const n=Si(a?.schedule),r=Cu(a),s=r?.role_models?.planner||r?.roleModels?.planner||{},l=Number(r?.max_parallel_agents??r?.maxParallelAgents??a?.execution?.max_parallel_agents??a?.execution?.maxParallelAgents??1),d=String(r?.execution_mode||r?.executionMode||"").trim(),u=Array.isArray(a?.metadata?.allowed_mcp_servers)?a.metadata.allowed_mcp_servers:Array.isArray(a?.agents?.[0]?.mcp_policy?.allowed_servers)?a.agents[0].mcp_policy.allowed_servers:[],p=Au(a),_=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:l>1?"swarm":"team",maxParallelAgents:String(Number.isFinite(l)&&l>0?Math.round(l):1),modelProvider:String(r?.model_provider||r?.modelProvider||"").trim(),modelId:String(r?.model_id||r?.modelId||"").trim(),plannerModelProvider:String(s?.provider_id||s?.providerId||"").trim(),plannerModelId:String(s?.model_id||s?.modelId||"").trim(),toolAccessMode:p.toolAccessMode,customToolsText:p.customToolsText,selectedMcpServers:u.map(D=>String(D||"").trim()).filter(Boolean),nodes:_}}function Tu(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 Ru(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 qu(a){return String(a?.metadata?.feature||"").trim()==="agent_standup"}function Mu(a){const t={execution_mode:a.executionMode,max_parallel_agents:a.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(a.maxParallelAgents||"4"),10)||4)):1},n=String(a.modelProvider||"").trim(),r=String(a.modelId||"").trim();n&&(t.model_provider=n),r&&(t.model_id=r);const s=String(a.plannerModelProvider||"").trim(),l=String(a.plannerModelId||"").trim();return s&&l&&(t.role_models={planner:{provider_id:s,model_id:l}}),t.tool_access_mode=a.toolAccessMode,a.toolAccessMode==="custom"&&(t.tool_allowlist=Lr(a.customToolsText)),t}function $u(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 Da(a){const t=String(a||"").trim().toLowerCase();return["queued","running","in_progress","executing","pending_approval","awaiting_approval"].includes(t)}function _s(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 Ou(a,t){const n=[],r=Ua(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 ar(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?Date.now():t<1e12?t*1e3:t}function Ii(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function Ss(a){const t=Ii(a);return t?new Date(t).toLocaleTimeString():"time unavailable"}function Yn(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 Pn(a,t=88){const n=String(a||"").replace(/\s+/g," ").trim();return n?n.length>t?`${n.slice(0,t-1).trimEnd()}…`:n:""}function Ga(a){return String(a?.mission_snapshot?.objective||a?.mission?.objective||a?.objective||a?.name||"").replace(/\s+/g," ").trim()}function fr(a){const t=String(a?.name||"").trim();if(t)return t;const n=Ga(a);if(n)return Pn(n,96);const r=String(a?.automation_id||a?.routine_id||"").trim();return r||"Run"}function ja(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"":new Date(ar(t)).toLocaleString()}function Kn(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 Eu(a){const t=String(a||"").trim();return t?t.includes("/")||t.includes("\\")?!0:/\.[a-z0-9]{1,8}$/i.test(t):!1}function Tn(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)||Eu(r)?[r]:[]:[]}return Array.isArray(a)?a.flatMap(r=>Tn(r,t,n+1)):typeof a=="object"?Object.entries(a).flatMap(([r,s])=>Tn(s,r,n+1)):[]}function Wr(a){return(Array.isArray(a?.parts)?a.parts:[]).map(r=>{const s=String(r?.type||"").trim();if(s==="text"||s==="reasoning")return String(r?.text||"").trim();if(s==="tool"){const l=String(r?.tool||"tool").trim(),d=String(r?.error||"").trim(),u=r?.result?Ht(r.result):"";return[`tool: ${l}`,d?`error: ${d}`:"",u].filter(Boolean).join(`
|
|
2433
|
+
`)}return String(r?.text||"").trim()}).filter(Boolean).join(`
|
|
2434
|
+
|
|
2435
|
+
`).trim()}function Du(a){const t=String(a?.info?.role||"").trim().toLowerCase();if(t==="user")return"user";if(t==="assistant")return"assistant";const n=Wr(a).toLowerCase();return n.includes("engine_error")||n.includes("error")?"error":"system"}function ju(a){return Array.isArray(a?.parts)?a.parts:[]}function Uu(a){return ar(a?.info?.time?.created||a?.info?.created_at_ms||a?.created_at_ms||0)}function Bu(a,t){return String(a?.info?.id||a?.id||`message-${t}`).trim()||`message-${t}`}function kn(a){const t=String(a||"").trim();return t?`session ${Yn(t,18)}`:"session"}function Ci(a){const t=String(a||"").trim();return t?t.startsWith("node-")?t:`node-${t}`:""}function Is(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 Ci(r[1])}return""}function Fu(a,t){const n=String(t||"").trim();if(!n)return[];const r=new Set([n]);let s=!0;for(;s;){s=!1;for(const l of Array.isArray(a)?a:[]){const d=String(l?.id||"").trim();if(!d||r.has(d))continue;(Array.isArray(l?.dependencies)?l.dependencies.map(p=>String(p||"").trim()).filter(Boolean):[]).some(p=>r.has(p))&&(r.add(d),s=!0)}}return Array.from(r)}function Ku(a,t,n){const r=String(a?.status||"").trim().toLowerCase();if(!["running","pausing","paused"].includes(r))return"";const s=ad(a);if(s)return s;for(let l=n.length-1;l>=0;l-=1){const d=n[l]?.event?.properties||n[l]?.event||{},u=Ci(String(d?.task_id||d?.step_id||d?.node_id||"").trim());if(u)return u;const p=Is(String(d?.message||d?.detail||d?.reason||""));if(p)return p}for(let l=t.length-1;l>=0;l-=1){const d=Is(Wr(t[l]?.message));if(d)return d}return Xc(a)}function Ai(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 Lu(a,t,n){const r=[],s=(l,d,u,p,_)=>{u.trim()&&(r.some(D=>D.key===l)||r.push({key:l,title:d,reason:u,source:p,at:_}))};if((a?.requires_approval===!0||String(a?.status||"").trim()==="pending_approval")&&s("approval-required","Approval required",String(a?.approval_reason||"Manual approval required before external side effects.").trim(),"policy"),String(a?.denial_reason||"").trim()&&s("denied","Run denied",String(a.denial_reason).trim(),"run"),String(a?.paused_reason||"").trim()&&s("paused","Run paused",String(a.paused_reason).trim(),"run"),String(a?.detail||"").trim()){const l=String(a.detail).trim();(l.toLowerCase().includes("tool")||l.toLowerCase().includes("bash_command_missing")||l.toLowerCase().includes("command_missing")||l.toLowerCase().includes("permission")||l.toLowerCase().includes("approval")||l.toLowerCase().includes("mcp")||l.toLowerCase().includes("auth")||l.toLowerCase().includes("failed after"))&&s("detail","Failure reason",Ai(a),"run")}pi(a).length||s("missing-session","No linked session transcript","This run does not expose a linked session transcript, so only telemetry/history are available.","run");for(const l of Dr(a)){const d=rd(l.value),u=Ur(l.value),p=$n(l.value);if(String(l?.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-${l.nodeId}`,`Node blocked: ${l.nodeId}`,[String(l?.value?.blocked_reason||l?.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
|
+
`),l.nodeId)}if(!d)continue;const _=d.toLowerCase();(_.includes("could not complete")||_.includes("invalid attachment")||_.includes("timed out")||_.includes("blocked")||_.includes("no email delivery tool")||_.includes("auth was not approved"))&&s(`node-output-${l.nodeId}`,`Node issue: ${l.nodeId}`,Pn(d,360),l.nodeId,Number(l.value?.created_at_ms||l.value?.createdAtMs||0))}return md([...t,...n]).forEach(l=>{s(l.key,l.title,l.reason,l.source,l.at)}),r.sort((l,d)=>(d.at||0)-(l.at||0))}function Wu({value:a,onChange:t,routedSkill:n,routingConfidence:r,validationBadge:s,generatedSkill:l,advancedMode:d,customSkillName:u,customSkillDescription:p,customWorkflowKind:_,onToggleAdvancedMode:D,onChangeCustomSkillName:x,onChangeCustomSkillDescription:P,onChangeCustomWorkflowKind:O,showArtifactPreview:k,onToggleArtifactPreview:J,artifactPreviewKey:A,onSelectArtifactPreviewKey:G,onGenerateSkill:ee,onInstallGeneratedSkill:de,isGeneratingSkill:S,isInstallingSkill:I,installStatus:Q,topMatches:R,isMatching:we}){const y=Object.keys(l?.artifacts||{});return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"Describe what you want the AI to do — in plain English. No technical knowledge needed."}),e("textarea",{className:"tcp-input min-h-[120px] text-base",placeholder:`e.g. "${pa.goalExamples[0]}"`,value:a,onInput:v=>t(v.target.value),autoFocus:!0}),e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500",children:"Need inspiration? Try one of these:"}),e("div",{className:"flex flex-wrap gap-2",children:pa.goalExamples.slice(1).map(v=>e("button",{className:"tcp-btn truncate text-left text-xs",style:{maxWidth:"280px"},onClick:()=>t(v),children:v},v))})]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Reusable Flows"}),e("span",{className:"text-slate-500",children:we?"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."}),R.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:R.slice(0,3).map((v,U)=>e("span",{className:"tcp-badge-info",children:[String(v?.skill_name||"unknown")," ",typeof v?.confidence=="number"?`${Math.round(v.confidence*100)}%`:""]},`${String(v?.skill_name||"match")}-${U}`))}):null]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Optional: Reusable Skill Export"}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick: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()||S,children:S?"Generating…":"Generate Reusable Skill Draft"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:de,disabled:!l?.artifacts||I,children:I?"Installing…":"Save Reusable Skill"})]})]}),e("p",{className:"mt-1 text-slate-400",children:"This is a secondary prompt-based export path. It does not power the default automation flow, and it does not automatically track planner-chat revisions to the workflow plan."}),e("div",{className:"mt-2 rounded-lg border border-slate-800/70 bg-slate-950/30 px-3 py-2 text-xs text-slate-400",children:"Recommended flow: review and finalize the workflow plan first, then generate or regenerate the reusable skill draft if you want a reusable export from the current prompt."}),d?e("div",{className:"mt-2 grid gap-2",children:[e("input",{className:"tcp-input text-xs",placeholder:"skill-name",value:u,onInput:v=>x(v.target.value)}),e("input",{className:"tcp-input text-xs",placeholder:"Short skill description",value:p,onInput:v=>P(v.target.value)}),e("select",{className:"tcp-input text-xs",value:_,onInput:v=>O(v.target.value),children:[e("option",{value:"pack_builder_recipe",children:"pack_builder_recipe"}),e("option",{value:"automation_v2_dag",children:"automation_v2_dag"})]})]}):null,l?e("div",{className:"mt-2 grid gap-1",children:[e("p",{children:["Optional scaffold status:"," ",e("strong",{children:String(l?.status||"generated")})]}),e("p",{className:"text-amber-200",children:"This draft was generated from the prompt and export options. If you revise the workflow plan later in review, regenerate this draft before saving it."}),e("p",{children:["Suggested skill:"," ",e("strong",{children:String(l?.router?.skill_name||"new optional skill")})]}),e("p",{className:"text-slate-400",children:["Artifacts:"," ",y.join(", ")||"SKILL.md, workflow.yaml, automation.example.yaml"]}),e("div",{className:"mt-1 flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:J,children:k?"Hide Raw":"Show Raw"}),k?e("select",{className:"tcp-input h-7 text-xs",value:A,onInput:v=>G(v.target.value),children:Object.keys(l?.artifacts||{}).map(v=>e("option",{value:v,children:v},v))}):null]}),k?e("textarea",{className:"tcp-input min-h-[140px] font-mono text-[11px]",readOnly:!0,value:String(l?.artifacts?.[A]||"")}):null]}):e("p",{className:"mt-1 text-slate-400",children:"Generate a reusable skill draft from this prompt if you want to save it for later reuse."}),Q?e("p",{className:"mt-2 text-slate-300",children:Q}):null]})]})}function zu({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:pa.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 Ju({selected:a,onSelect:t,maxAgents:n,onMaxAgents:r,workspaceRoot:s,onWorkspaceRootChange:l,providerOptions:d,providerId:u,modelId:p,plannerProviderId:_,plannerModelId:D,onProviderChange:x,onModelChange:P,onPlannerProviderChange:O,onPlannerModelChange:k,roleModelsJson:J,onRoleModelsChange:A,roleModelsError:G,toolAccessMode:ee,customToolsText:de,onToolAccessModeChange:S,onCustomToolsTextChange:I,mcpServers:Q,selectedMcpServers:R,onToggleMcpServer:we,onOpenMcpSettings:y,workspaceRootError:v,plannerModelError:U,workspaceBrowserOpen:pe,workspaceBrowserDir:X,workspaceBrowserSearch:$e,onWorkspaceBrowserSearchChange:Oe,onOpenWorkspaceBrowser:Ke,onCloseWorkspaceBrowser:ae,onBrowseWorkspaceParent:ue,onBrowseWorkspaceDirectory:M,onSelectWorkspaceDirectory:he,workspaceBrowserParentDir:Te,workspaceCurrentBrowseDir:Re,filteredWorkspaceDirectories:re}){const Ue=d.find(V=>V.id===u)?.models||[],qe=d.find(V=>V.id===_)?.models||[],ze=String($e||"").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:pa.executionModes.map(V=>e("button",{onClick:()=>t(V.id),className:`tcp-list-item flex items-start gap-4 text-left transition-all ${a===V.id?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("span",{className:"mt-0.5 text-2xl",children:V.icon}),e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{className:"font-semibold",children:V.label}),V.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:V.desc}),e("span",{className:"tcp-subtle text-xs",children:["Best for: ",V.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===V.id?!0:void 0})]},V.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:V=>r(V.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:Ke,children:"Browse"}),e("input",{className:`tcp-input text-sm ${v?"border-red-500/70 text-red-100":""}`,value:s,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>l(""),disabled:!s,children:"Clear"})]}),e("div",{className:"text-xs text-slate-500",children:"Tandem will run this automation from this workspace directory."}),v?e("div",{className:"text-xs text-red-300",children:v}):null]})]}),e(Tt,{children:pe?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:ae}),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:ue,disabled:!Te,children:"Up"}),e("button",{className:"tcp-btn-primary",type:"button",onClick:he,disabled:!Re,children:"Select This Folder"}),e("button",{className:"tcp-btn",type:"button",onClick:ae,children:"Close"})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:$e,onInput:V=>Oe(V.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:re.length?re.map(V=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>M(String(V?.path||"")),children:String(V?.name||V?.path||"")},String(V?.path||V?.name))):e(We,{text:ze?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Model Selection"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Provider"}),e("select",{className:"tcp-input text-sm",value:u,onInput:V=>x(V.target.value),children:[e("option",{value:"",children:"Use workspace default"}),d.map(V=>e("option",{value:V.id,children:V.id},V.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:V=>P(V.target.value),placeholder:"Use workspace default model"}),u?e("datalist",{id:`models-${u}`,children:Ue.map(V=>e("option",{value:V},V))}):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:_,onInput:V=>O(V.target.value),children:[e("option",{value:"",children:"Disabled"}),d.map(V=>e("option",{value:V.id,children:V.id},`planner-${V.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:_?`planner-models-${_}`:void 0,onInput:V=>k(V.target.value),placeholder:"Disabled unless provider and model are set"}),_?e("datalist",{id:`planner-models-${_}`,children:qe.map(V=>e("option",{value:V},V))}):null]})]}),U?e("div",{className:"text-xs text-red-300",children:U}):null]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Role model overrides (advanced JSON)"}),e("textarea",{className:`tcp-input min-h-[72px] font-mono text-xs ${G?"border-red-500/70 text-red-100":""}`,value:J,onInput:V=>A(V.target.value),placeholder:'{"planner":{"provider_id":"openai","model_id":"gpt-5"},"worker":{"provider_id":"anthropic","model_id":"claude-sonnet-4"}}'}),G?e("div",{className:"text-xs text-red-300",children:G}):null]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Tool Access"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{type:"button",className:`tcp-list-item text-left ${ee==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>S("all"),children:[e("div",{className:"font-medium",children:"All tools"}),e("div",{className:"tcp-subtle text-xs",children:"Grant full built-in tool access. Use this for autonomous coding and file operations."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${ee==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>S("custom"),children:[e("div",{className:"font-medium",children:"Custom allowlist"}),e("div",{className:"tcp-subtle text-xs",children:"Restrict built-in tools manually. MCP tools still come from the selected servers below."})]})]}),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:de,onInput:V=>I(V.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:y,children:"Add MCP Server"})]}),Q.length?e("div",{className:"flex flex-wrap gap-2",children:Q.map(V=>{const He=R.includes(V.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${He?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>we(V.name),children:[V.name," ",V.connected?"• connected":"• disconnected"]},V.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 Qu({wizard:a,onToggleExportPackDraft:t,onSubmit:n,isPending:r,planPreview:s,isPreviewing:l,planningConversation:d,planningChangeSummary:u,onSendPlanningMessage:p,isSendingPlanningMessage:_,onResetPlanningChat:D,isResettingPlanningChat:x,plannerError:P,plannerDiagnostics:O,generatedSkill:k,installStatus:J}){const[A,G]=w(""),[ee,de]=w(!1),[S,I]=w(!1),[Q,R]=w({}),we=a.cron?a.cron:pa.schedulePresets.find(ne=>ne.label===a.schedulePreset)?.intervalSeconds?`Every ${pa.schedulePresets.find(ne=>ne.label===a.schedulePreset).intervalSeconds/3600}h`:a.schedulePreset||"Manual",y=s&&typeof s=="object"?s.operator_preferences||s.operatorPreferences||{}:{},v=String(y?.execution_mode||a.mode||"team").trim(),U=pa.executionModes.find(ne=>ne.id===v),pe=Number(y?.max_parallel_agents??y?.maxParallelAgents??(v==="swarm"?a.maxAgents:1)),X=!!s,$e=String(X?y?.model_provider||y?.modelProvider||"":a.modelProvider||"").trim(),Oe=String(X?y?.model_id||y?.modelId||"":a.modelId||"").trim(),Ke=y&&typeof y=="object"&&(y?.role_models?.planner||y?.roleModels?.planner),ae=String(X?Ke?.provider_id||Ke?.providerId||"":a.plannerModelProvider||"").trim(),ue=String(X?Ke?.model_id||Ke?.modelId||"":a.plannerModelId||"").trim(),M=!!(ae&&ue||$e&&Oe),he=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(X?y?.tool_access_mode||y?.toolAccessMode||"all":a.toolAccessMode||"all").trim(),re=X?On((y?.tool_allowlist||y?.toolAllowlist||[]).map(ne=>String(ne||"").trim())):Lr(a.customToolsText),Ue=s?.schedule?_i(s.schedule):we,qe=String(s?.title||"").trim(),ze=String(O?.fallback_reason||O?.fallbackReason||"").trim(),V=String(O?.detail||"").trim(),He=ne=>R(Ie=>({...Ie,[ne]:!Ie[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:()=>de(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:cn(a.goal||"")}})})]})]}),e("div",{className:"grid grid-cols-2 gap-3",children:[e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Schedule"}),e("span",{className:"text-sm font-medium text-slate-200",children:Ue})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Execution Mode"}),e("span",{className:"text-sm font-medium text-slate-200",children:[U?.icon," ",U?.label||v,Number.isFinite(pe)&&pe>1?` · ${pe} agents`:""]})]})]}),X||$e||Oe?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:$e||Oe?`${$e||"default provider"} / ${Oe||"default model"}`:"Workspace default"})]}):null,X||ae||ue?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:ae||ue?`${ae||"default provider"} / ${ue||"default model"}`:$e||Oe?`Using model override: ${$e||"default provider"} / ${Oe||"default model"}`:"Workspace default"})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Broader Planner Revisions"}),e("span",{className:"text-sm font-medium text-slate-200",children:M?"Enabled. Tandem will use the planner model if set, otherwise it falls back to the selected model override.":"Disabled unless a planner model, model override, or workspace default model is configured"})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Workspace Root"}),e("code",{className:"rounded bg-slate-800/60 px-2 py-1 text-xs text-slate-300",children:he||"engine workspace root"})]}),X||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"?re.length?e("div",{className:"flex flex-wrap gap-1",children:re.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"}),l?e("span",{className:"text-sm text-slate-300",children:"Planning workflow…"}):s?e("div",{className:"grid gap-1 text-sm text-slate-300",children:[e("span",{children:["Confidence: ",e("strong",{children:String(s?.confidence||"unknown")})]}),e("span",{children:["Execution target:"," ",e("strong",{children:String(s?.execution_target||"automation_v2")})]}),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,Ie)=>(()=>{const ht=String(ne?.step_id||ne?.stepId||`step-${Ie+1}`),se=!!Q[ht];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:()=>He(ht),children:[e("div",{className:"min-w-0",children:[e("div",{className:"text-xs font-medium text-slate-200",children:[ht,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:se?"Hide":"Details"})]}),se&&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:cn(ne.objective||"")}})}):null]},`${ht}-${Ie}`)})())}):null,typeof s?.description=="string"&&s.description.trim()?e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>I(ne=>!ne),children:[e("span",{className:"text-sm text-slate-200",children:"Plan description"}),e("span",{className:"tcp-subtle text-xs",children:S?"Collapse":"Expand"})]}),e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:`tcp-markdown tcp-markdown-ai text-sm ${S?"":"max-h-24 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:cn(String(s.description||""))}})})]}):null]}):e("span",{className:"text-sm text-slate-400",children:"Workflow preview has not been generated yet."})]})]}),P?e("div",{className:"rounded-xl border border-red-500/40 bg-red-950/30 p-3 text-sm text-red-200",children:P}):null,ze?e("div",{className:"rounded-xl border border-amber-500/40 bg-amber-950/30 p-3 text-sm text-amber-100",children:[e("div",{className:"font-medium text-amber-200",children:"Planner fallback"}),e("div",{className:"mt-1",children:["Reason: ",e("code",{className:"text-xs",children:ze})]}),V?e("div",{className:"mt-2 text-xs text-amber-200/90 whitespace-pre-wrap",children:V}):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,Ie)=>e("span",{className:"tcp-badge-ok",children:ne},`${ne}-${Ie}`))})]}):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:M?"With a planner model or model override configured, planning chat can attempt broader natural-language workflow rewrites across the allowed fixed step ids. Deterministic edits still act as the safety net for schedule, workspace root, title, MCP servers, execution mode, model overrides, safe workflow shapes, small workflow-step changes, and terminal output-style changes. Custom step types are still not supported in this slice.":"Planning chat is currently limited to deterministic edits like schedule, workspace root, title, MCP servers, execution mode, model overrides, switching between safe workflow shapes, small workflow-step changes like adding or removing input collection, analysis, or notifications, and terminal output-style changes like JSON, markdown, summary, URLs, or citations. Broader workflow rewrites require a planner model or model override, and custom step types are still not supported in this slice."}),e("div",{className:"max-h-56 overflow-auto rounded-lg border border-slate-800 bg-slate-950/50 p-3",children:Array.isArray(d?.messages)&&d.messages.length?e("div",{className:"grid gap-3",children:d.messages.map((ne,Ie)=>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||Ie}-${Ie}`))}):e("div",{className:"text-sm text-slate-400",children:"Add planning notes here to revise the workflow before creating it."})}),e("textarea",{className:"tcp-input min-h-[84px] text-sm",value:A,onInput:ne=>G(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:_||!A.trim()||!s?.plan_id,onClick:()=>{const ne=A.trim();ne&&(p(ne),G(""))},children:_?"Updating plan…":"Update Plan"})})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:e("label",{className:"flex items-start gap-3 rounded-lg border border-slate-700/50 bg-slate-900/30 p-3 text-sm text-slate-300",children:[e("input",{type:"checkbox",className:"mt-0.5",checked:a.exportPackDraft,onChange:t}),e("span",{className:"grid gap-1",children:[e("span",{className:"font-medium text-slate-200",children:"Also export a reusable pack draft"}),e("span",{className:"text-xs text-slate-400",children:"After creating the automation, Tandem will also create a Pack Builder draft so this workflow can be saved and reused later."})]})]})}),k||J?e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Reusable Skill Export"}),e("div",{className:"mt-1 grid gap-1",children:[k?e(ta,{children:[e("span",{children:["Draft status:"," ",e("strong",{className:"text-slate-300",children:String(k?.status||"generated")})]}),e("span",{className:"text-amber-200",children:"This draft is prompt-based and may be stale if you changed the workflow plan in planning chat. Regenerate it from Step 1 before saving if you want it to reflect the latest plan direction."})]}):null,J?e("span",{children:J}):null]})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:["💡 Tandem will save this automation and schedule a"," ",e("strong",{className:"text-slate-300",children:U?.label||v})," that runs"," ",e("strong",{className:"text-slate-300",children:Ue}),". You can pause, edit or delete it anytime."]}),e("button",{className:"tcp-btn-primary",disabled:r||l||!a.goal.trim()||!s,onClick:n,children:r?"Creating automation…":"🚀 Create Automation"})]})}function Gu({client:a,api:t,toast:n,navigate:r,defaultProvider:s,defaultModel:l}){const d=aa(),[u,p]=w(1),[_,D]=w("automations_page"),[x,P]=w([]),[O,k]=w(null),[J,A]=w(null),[G,ee]=w([]),[de,S]=w(""),[I,Q]=w(null),[R,we]=w(!1),[y,v]=w(""),[U,pe]=w(""),[X,$e]=w(""),[Oe,Ke]=w(null),[ae,ue]=w(!1),[M,he]=w("SKILL.md"),[Te,Re]=w(""),[re,Ue]=w(()=>Ns(s,l)),qe=Z({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),ze=Z({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),V=Z({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),He=Z({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),ne=Z({queryKey:["automations","workspace-browser",y],enabled:R&&!!y,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(y)}`,{method:"GET"})}),Ie=L(()=>(Array.isArray(qe.data?.all)?qe.data.all:[]).map(W=>({id:String(W?.id||"").trim(),models:Object.keys(W?.models||{})})).filter(W=>!!W.id).sort((W,ve)=>W.id.localeCompare(ve.id)),[qe.data]),ht=L(()=>Ni(V.data),[V.data]),se=Array.isArray(ne.data?.directories)?ne.data.directories:[],F=String(ne.data?.parent||"").trim(),rt=String(ne.data?.dir||y||"").trim(),mt=String(U||"").trim().toLowerCase(),ot=L(()=>mt?se.filter(N=>String(N?.name||N?.path||"").trim().toLowerCase().includes(mt)):se,[se,mt]);be(()=>{const N=String(ze.data?.default||s||"").trim();if(!N)return;const W=Ie.find(De=>De.id===N)?.models||[],ve=String(ze.data?.providers?.[N]?.default_model||l||W[0]||"").trim();Ue(De=>De.modelProvider&&De.modelId?De:{...De,modelProvider:De.modelProvider||N,modelId:De.modelId||ve})},[l,s,Ie,ze.data]),be(()=>{const N=String(He.data?.workspaceRoot||He.data?.workspace_root||"").trim();N&&Ue(W=>String(W.workspaceRoot||"").trim()?W:{...W,workspaceRoot:N})},[He.data]);const St=xe({mutationFn:async N=>!N.trim()||!a?.skills?.match?null:a.skills.match({goal:N,maxMatches:3,threshold:.35}),onError:()=>{}}),Ee=xe({mutationFn:async()=>{if(!a?.workflowPlans?.chatStart)throw new Error("This control panel build is missing workflow planner client support. Rebuild the control panel against the local tandem client package.");return await a.workflowPlans.chatStart({prompt:re.goal,schedule:wu(re),plan_source:_,allowed_mcp_servers:re.selectedMcpServers,workspace_root:re.workspaceRoot,operator_preferences:ku(re)})||null},onSuccess:N=>{k(N?.plan||null),A(N?.conversation||null),ee([]),S(""),Q(N?.planner_diagnostics||N?.plannerDiagnostics||null)},onError:N=>{k(null),A(null),ee([]),S(N instanceof Error?N.message:String(N)),Q(null)}}),Rt=xe({mutationFn:async N=>!a?.workflowPlans?.chatMessage||!O?.plan_id?null:a.workflowPlans.chatMessage({plan_id:O.plan_id,message:N}),onSuccess:N=>{k(N?.plan||null),A(N?.conversation||null),ee(Array.isArray(N?.change_summary)?N.change_summary.map(W=>String(W||"").trim()).filter(Boolean):[]),S(typeof N?.clarifier?.question=="string"?String(N.clarifier.question):""),Q(N?.planner_diagnostics||N?.plannerDiagnostics||null)},onError:N=>{const W=N instanceof Error?N.message:String(N);S(W),n("err",W)}}),yt=xe({mutationFn:async()=>!a?.workflowPlans?.chatReset||!O?.plan_id?null:a.workflowPlans.chatReset({plan_id:O.plan_id}),onSuccess:N=>{k(N?.plan||null),A(N?.conversation||null),ee([]),S(""),Q(N?.planner_diagnostics||N?.plannerDiagnostics||null)},onError:N=>{const W=N instanceof Error?N.message:String(N);S(W),n("err",W)}}),Ot=xe({mutationFn:async N=>{if(!a?.skills?.get||!a?.skills?.validate)return null;const ve=(await a.skills.get(N))?.content;return ve?a.skills.validate({content:ve}):null},onSuccess:N=>{if(!N){$e("");return}$e(N.invalid>0?"not_validated":"validated")},onError:()=>$e("not_validated")}),Je=xe({mutationFn:async()=>{if(!a?.skills?.generate||!re.goal.trim())return null;const N=re.advancedMode?[re.goal.trim(),re.customSkillName?`Skill name: ${re.customSkillName}`:"",re.customSkillDescription?`Description: ${re.customSkillDescription}`:"",`Workflow kind: ${re.customWorkflowKind}`].filter(Boolean).join(`
|
|
2443
|
+
`):re.goal;return a.skills.generate({prompt:N})},onSuccess:N=>{Ke(N);const W=Object.keys(N?.artifacts||{})[0];he(W||"SKILL.md"),ue(!1),Re("")},onError:()=>{Ke(null),ue(!1),Re("Optional skill generation failed.")}}),Qe=xe({mutationFn:async()=>{if(!a?.skills?.generateInstall)return null;const N=Oe?.artifacts;if(!N||!N["SKILL.md"])throw new Error("No generated artifacts available to install.");return a.skills.generateInstall({location:"project",conflictPolicy:"rename",artifacts:{"SKILL.md":N["SKILL.md"],"workflow.yaml":N["workflow.yaml"],"automation.example.yaml":N["automation.example.yaml"]}})},onSuccess:N=>{const W=N?.skill?.name;Re(W?`Installed optional skill as '${String(W)}' in project skills.`:"Installed optional skill in project skills."),d.invalidateQueries({queryKey:["automations"]})},onError:N=>Re(`Install failed: ${N instanceof Error?N.message:String(N)}`)}),nt=xe({mutationFn:async()=>{if(!re.goal.trim())throw new Error("Please describe your goal first.");const N=O||await Ee.mutateAsync().catch(ve=>{throw ve instanceof Error?ve:new Error(String(ve))}),W=N?.plan||N;if(!W)throw new Error("Workflow plan preview failed.");return a.workflowPlans.apply({plan:W,creator_id:"control-panel",...re.exportPackDraft?{pack_builder_export:{enabled:!0,auto_apply:!1}}:{}})},onSuccess:async N=>{N?.pack_builder_export?.status==="preview_pending"?n("ok","🎉 Automation created and reusable pack draft exported. Check Pack Builder to continue."):n("ok","🎉 Automation created! Check 'My Automations' to see it running."),await Promise.all([d.invalidateQueries({queryKey:["automations"]}),d.invalidateQueries({queryKey:["mcp"]})]),Ue(Ns(s,l,String(He.data?.workspaceRoot||He.data?.workspace_root||"").trim())),P([]),D("automations_page"),k(null),A(null),ee([]),S(""),$e(""),Ke(null),ue(!1),he("SKILL.md"),Re(""),p(1)},onError:N=>{const W=N instanceof Error?N.message:String(N);S(W),n("err",W)}}),ye=_n(re.workspaceRoot),Ne=Vn(re.plannerModelProvider,re.plannerModelId),Ve=Nu(re.roleModelsJson),le=u===1?re.goal.trim().length>8:u===2?!!re.schedulePreset||!!re.cron.trim():u===3?!!re.mode&&!ye&&!Ne&&!Ve:!0,it=async()=>{if(u===1){const W=await St.mutateAsync(re.goal);W&&W.decision==="match"&&W.skill_name?(Ot.mutateAsync(String(W.skill_name)),Ue(De=>({...De,routedSkill:String(W.skill_name),routingConfidence:typeof W.confidence=="number"?`${Math.round(W.confidence*100)}%`:""}))):($e(""),Ue(De=>({...De,routedSkill:"",routingConfidence:""})));const ve=Array.isArray(W?.top_matches)?W.top_matches:[];P(ve)}const N=u+1;if(N===4){S(""),k(null),A(null),ee([]);try{await Ee.mutateAsync()}catch{return}}p(N)};return be(()=>{if(u===1)try{const N=sessionStorage.getItem(xs);if(!N)return;sessionStorage.removeItem(xs);const W=JSON.parse(N),ve=String(W?.prompt||"").trim();if(!ve)return;const De=String(W?.plan_source||"chat_setup").trim()||"chat_setup";D(De),Ue(o=>({...o,goal:ve}))}catch{}},[u]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex items-center gap-2",children:pa.steps.map((N,W)=>{const ve=W+1,De=ve===u,o=ve<u;return e("div",{className:"flex-1",children:[e("button",{className:`mb-1 flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-xs font-medium transition-all ${De?"bg-amber-500/20 text-amber-300":o?"text-slate-400":"text-slate-600"}`,onClick:()=>o&&p(ve),children:[e("span",{className:`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${De?"bg-amber-500 text-black":o?"bg-slate-600 text-white":"bg-slate-800 text-slate-500"}`,children:o?"✓":ve}),N]}),e("div",{className:"h-0.5 w-full rounded-full bg-slate-800",children:e("div",{className:"h-full rounded-full bg-amber-500 transition-all",style:{width:o?"100%":De?"50%":"0%"}})})]},N)})}),e(Tt,{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(Wu,{value:re.goal,onChange:N=>Ue(W=>({...W,goal:N})),routedSkill:re.routedSkill,routingConfidence:re.routingConfidence,validationBadge:X,generatedSkill:Oe,advancedMode:re.advancedMode,customSkillName:re.customSkillName,customSkillDescription:re.customSkillDescription,customWorkflowKind:re.customWorkflowKind,onToggleAdvancedMode:()=>Ue(N=>({...N,advancedMode:!N.advancedMode})),onChangeCustomSkillName:N=>Ue(W=>({...W,customSkillName:N})),onChangeCustomSkillDescription:N=>Ue(W=>({...W,customSkillDescription:N})),onChangeCustomWorkflowKind:N=>Ue(W=>({...W,customWorkflowKind:N})),showArtifactPreview:ae,onToggleArtifactPreview:()=>ue(N=>!N),artifactPreviewKey:M,onSelectArtifactPreviewKey:N=>he(N),onGenerateSkill:()=>{Je.mutateAsync()},onInstallGeneratedSkill:()=>{Qe.mutateAsync()},isGeneratingSkill:Je.isPending,isInstallingSkill:Qe.isPending,installStatus:Te,topMatches:x,isMatching:St.isPending}):u===2?e(zu,{selected:re.schedulePreset,onSelect:N=>Ue(W=>({...W,schedulePreset:N.label,cron:N.cron})),customCron:re.cron,onCustomCron:N=>Ue(W=>({...W,cron:N,schedulePreset:""}))}):u===3?e(Ju,{selected:re.mode,onSelect:N=>Ue(W=>({...W,mode:N})),maxAgents:re.maxAgents,onMaxAgents:N=>Ue(W=>({...W,maxAgents:N})),workspaceRoot:re.workspaceRoot,onWorkspaceRootChange:N=>Ue(W=>({...W,workspaceRoot:N})),providerOptions:Ie,providerId:re.modelProvider,modelId:re.modelId,plannerProviderId:re.plannerModelProvider,plannerModelId:re.plannerModelId,onProviderChange:N=>Ue(W=>({...W,modelProvider:N,modelId:N===W.modelProvider?W.modelId:""})),onModelChange:N=>Ue(W=>({...W,modelId:N})),onPlannerProviderChange:N=>Ue(W=>({...W,plannerModelProvider:N,plannerModelId:N===W.plannerModelProvider?W.plannerModelId:""})),onPlannerModelChange:N=>Ue(W=>({...W,plannerModelId:N})),roleModelsJson:re.roleModelsJson,onRoleModelsChange:N=>Ue(W=>({...W,roleModelsJson:N})),roleModelsError:Ve,toolAccessMode:re.toolAccessMode,customToolsText:re.customToolsText,onToolAccessModeChange:N=>Ue(W=>({...W,toolAccessMode:N})),onCustomToolsTextChange:N=>Ue(W=>({...W,customToolsText:N})),mcpServers:ht,selectedMcpServers:re.selectedMcpServers,onToggleMcpServer:N=>Ue(W=>({...W,selectedMcpServers:W.selectedMcpServers.includes(N)?W.selectedMcpServers.filter(ve=>ve!==N):[...W.selectedMcpServers,N]})),onOpenMcpSettings:()=>r("mcp"),workspaceRootError:ye,plannerModelError:Ne,workspaceBrowserOpen:R,workspaceBrowserDir:y,workspaceBrowserSearch:U,onWorkspaceBrowserSearchChange:pe,onOpenWorkspaceBrowser:()=>{const N=String(re.workspaceRoot||He.data?.workspaceRoot||He.data?.workspace_root||"/").trim();v(N||"/"),pe(""),we(!0)},onCloseWorkspaceBrowser:()=>{we(!1),pe("")},onBrowseWorkspaceParent:()=>{F&&v(F)},onBrowseWorkspaceDirectory:N=>v(N),onSelectWorkspaceDirectory:()=>{rt&&(Ue(N=>({...N,workspaceRoot:rt})),we(!1),pe(""),n("ok",`Workspace selected: ${rt}`))},workspaceBrowserParentDir:F,workspaceCurrentBrowseDir:rt,filteredWorkspaceDirectories:ot}):e(Qu,{wizard:re,onToggleExportPackDraft:()=>Ue(N=>({...N,exportPackDraft:!N.exportPackDraft})),onSubmit:()=>nt.mutate(),isPending:nt.isPending,planPreview:O,isPreviewing:Ee.isPending,planningConversation:J,planningChangeSummary:G,onSendPlanningMessage:N=>{Rt.mutateAsync(N)},isSendingPlanningMessage:Rt.isPending,onResetPlanningChat:()=>{yt.mutateAsync()},isResettingPlanningChat:yt.isPending,plannerError:de,plannerDiagnostics:I,generatedSkill:Oe,installStatus:Te})},u)}),u<4?e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn",disabled:u===1||Ee.isPending,onClick:()=>p(N=>N-1),children:"← Back"}),e("button",{className:"tcp-btn-primary",disabled:!le||Ee.isPending,onClick:()=>{it()},children:Ee.isPending?"Generating Plan...":"Next →"})]}):null]})}function Cs({client:a,toast:t,navigate:n,viewMode:r,selectedRunId:s,onSelectRunId:l,onOpenRunningView:d,onOpenAdvancedEdit:u}){const p=aa(),_=Pt(null),[D,x]=w(null),[P,O]=w(null),[k,J]=w("all"),[A,G]=w([]),[ee,de]=w(""),[S,I]=w("all"),[Q,R]=w(""),[we,y]=w(""),[v,U]=w([]),pe=Pt(null),X=Pt(null),$e=Pt(null),[Oe,Ke]=w(!0),[ae,ue]=w(null),M=s.startsWith("automation-v2-run-"),he=Z({queryKey:["automations","list"],queryFn:()=>a?.automations?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Te=Z({queryKey:["automations","v2","list"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Re=L(()=>{const i=Ma(Te.data,"automations"),m=new Map;for(const E of i){const Y=String(E?.automation_id||E?.automationId||E?.id||"").trim();Y&&(m.has(Y)||m.set(Y,E))}return Array.from(m.values())},[Te.data]),re=Z({queryKey:["providers","catalog","workflow-edit"],queryFn:()=>a?.providers?.catalog?.().catch(()=>({providers:[]}))??Promise.resolve({providers:[]}),refetchInterval:3e4}),Ue=Z({queryKey:["mcp","servers","workflow-edit"],queryFn:()=>a?.mcp?.list?.().catch(()=>({servers:[]}))??Promise.resolve({servers:[]}),refetchInterval:15e3}),qe=Z({queryKey:["automations","runs"],queryFn:()=>a?.automations?.listRuns?.({limit:20}).catch(()=>({runs:[]}))??Promise.resolve({runs:[]}),refetchInterval:9e3}),ze=Z({queryKey:["automations","v2","runs","all"],queryFn:()=>Lt("/api/engine/automations/v2/runs?limit=40").catch(()=>({runs:[]})),refetchInterval:9e3}),V=Z({queryKey:["automations","run",s],enabled:!!s,queryFn:()=>(M?a?.automationsV2?.getRun?.(s):a?.automations?.getRun?.(s))?.catch(()=>({run:null}))??Promise.resolve({run:null}),refetchInterval:s?5e3:!1}),He=Z({queryKey:["automations","run","artifacts",s],enabled:!!s&&!M,queryFn:()=>a?.automations?.listArtifacts?.(s).catch(()=>({artifacts:[]})),refetchInterval:s?8e3:!1}),ne=Z({queryKey:["automations","run","task-reset-preview",s,Q],enabled:!!s&&M&&String(Q||"").startsWith("node-")&&!!String(Q||"").trim()&&!!a?.automationsV2?.previewTaskReset,queryFn:()=>a?.automationsV2?.previewTaskReset(s,String(Q||"").replace(/^node-/,"").trim()).catch(()=>({preview:null}))??Promise.resolve({preview:null}),refetchInterval:!1}),Ie=L(()=>pi(V.data?.run),[V.data]),ht=Bi({queries:Ie.map(i=>({queryKey:["automations","run","session",s,i,"messages"],enabled:!!s&&!!i,queryFn:()=>a?.sessions?.messages?.(i).catch(()=>[])??Promise.resolve([]),refetchInterval:s&&i&&Da(V.data?.run?.status)?4e3:!1}))}),se=String(V.data?.run?.automation_id||V.data?.run?.routine_id||"").trim(),F=String(V.data?.contextRunID||(M&&s?`automation-v2-${s}`:"")).trim(),rt=Z({queryKey:["automations","history",se],enabled:!!se&&!M,queryFn:()=>a?.automations?.history?.(se,80).catch(()=>({events:[]})),refetchInterval:s?1e4:!1}),mt=Z({queryKey:["automations","run","events",s],enabled:!!s&&!!a?.runEvents,queryFn:()=>a.runEvents(s,{tail:400}).catch(()=>[]),refetchInterval:s&&Da(V.data?.run?.status)?5e3:!1}),ot=Z({queryKey:["automations","run","context",F],enabled:!!F,queryFn:()=>Lt(`/api/engine/context/runs/${encodeURIComponent(F)}`).catch(()=>({run:null})),refetchInterval:F&&Da(V.data?.run?.status)?5e3:!1}),St=Z({queryKey:["automations","run","context",F,"blackboard"],enabled:!!F,queryFn:()=>Lt(`/api/engine/context/runs/${encodeURIComponent(F)}/blackboard`).catch(()=>({blackboard:null})),refetchInterval:F&&Da(V.data?.run?.status)?5e3:!1}),Ee=Z({queryKey:["automations","run","context",F,"events"],enabled:!!F,queryFn:()=>Lt(`/api/engine/context/runs/${encodeURIComponent(F)}/events`).catch(()=>({events:[]})),refetchInterval:F&&Da(V.data?.run?.status)?5e3:!1}),Rt=Z({queryKey:["automations","run","context",F,"patches"],enabled:!!F,queryFn:()=>Lt(`/api/engine/context/runs/${encodeURIComponent(F)}/blackboard/patches`).catch(()=>({patches:[]})),refetchInterval:F&&Da(V.data?.run?.status)?5e3:!1}),yt=Z({queryKey:["automations","packs"],queryFn:()=>a?.packs?.list?.().catch(()=>({packs:[]}))??Promise.resolve({packs:[]}),refetchInterval:3e4}),Ot=xe({mutationFn:i=>a?.automations?.runNow?.(i),onSuccess:async()=>{t("ok","Automation triggered."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Je=xe({mutationFn:i=>a?.automationsV2?.runNow?.(i),onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||"").trim();t("ok","Workflow automation triggered."),await p.invalidateQueries({queryKey:["automations"]}),m&&(l(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Qe=xe({mutationFn:async({action:i,runId:m,family:E,reason:Y})=>E==="v2"?i==="pause"?a.automationsV2.pauseRun(m,Y):a.automationsV2.resumeRun(m,Y):i==="pause"?a.automations.pauseRun(m,Y):a.automations.resumeRun(m,Y),onSuccess:async()=>{t("ok","Run action applied."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),nt=xe({mutationFn:async({runId:i,nodeId:m,reason:E})=>{if(!a?.automationsV2?.repairRun)throw new Error("Workflow repair is not available in this client.");return a.automationsV2.repairRun(i,{node_id:m,reason:E??""})},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&&(l(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),ye=xe({mutationFn:async({runId:i,reason:m})=>{if(!a?.automationsV2?.recoverRun)throw new Error("Workflow retry is not available in this client.");return a.automationsV2.recoverRun(i,m)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Workflow run queued again."),await p.invalidateQueries({queryKey:["automations"]}),m&&(l(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Ne=xe({mutationFn:async({runId:i,nodeId:m,reason:E})=>{if(!a?.automationsV2?.retryTask)throw new Error("Task retry is not available in this client.");return a.automationsV2.retryTask(i,m,E)},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&&(l(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Ve=xe({mutationFn:async({runId:i,nodeId:m,reason:E})=>{if(!a?.automationsV2?.continueTask)throw new Error("Task continue is not available in this client.");return a.automationsV2.continueTask(i,m,E)},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&&(l(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),le=xe({mutationFn:async({runId:i,nodeId:m,reason:E})=>{if(!a?.automationsV2?.requeueTask)throw new Error("Task requeue is not available in this client.");return a.automationsV2.requeueTask(i,m,E)},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&&(l(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),it=xe({mutationFn:async({runId:i,taskId:m,agentId:E,reason:Y})=>{if(!a?.automationsV2?.claimBacklogTask)throw new Error("Backlog task claim is not available in this client.");return a.automationsV2.claimBacklogTask(i,m,{agent_id:E,reason:Y})},onSuccess:async()=>{t("ok","Backlog task claimed."),await p.invalidateQueries({queryKey:["automations"]}),s&&(l(s),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),N=xe({mutationFn:async({runId:i,taskId:m,reason:E})=>{if(!a?.automationsV2?.requeueBacklogTask)throw new Error("Backlog task requeue is not available in this client.");return a.automationsV2.requeueBacklogTask(i,m,E)},onSuccess:async()=>{t("ok","Backlog task requeued."),await p.invalidateQueries({queryKey:["automations"]}),s&&(l(s),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),W=xe({mutationFn:async i=>{const m=String(i.name||"").trim(),E=String(i.objective||"").trim(),Y=String(i.cronExpression||"").trim(),ce=Number(i.intervalSeconds);if(!m)throw new Error("Automation name is required.");if(!E)throw new Error("Objective is required.");if(i.scheduleKind==="cron"&&!Y)throw new Error("Cron expression is required.");if(i.scheduleKind==="interval"&&(!Number.isFinite(ce)||ce<=0))throw new Error("Interval seconds must be greater than zero.");return a.automations.update(i.automationId,{name:m,mode:i.mode,mission:{objective:E},policy:{approval:{requires_approval:!!i.requiresApproval}},schedule:i.scheduleKind==="cron"?{cron:{expression:Y}}:{interval_seconds:{seconds:Math.round(ce)}}})},onSuccess:async()=>{t("ok","Automation updated."),O(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),ve=xe({mutationFn:async i=>{const m=String(i.name||"").trim(),E=String(i.description||"").trim(),Y=String(i.workspaceRoot||"").trim(),ce=gr(i.modelProvider,i.modelId),st=Vn(i.plannerModelProvider,i.plannerModelId),Dt=_n(Y);if(!m)throw new Error("Automation name is required.");if(Dt)throw new Error(Dt);if(ce)throw new Error(ce);if(st)throw new Error(st);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 oa=Mu(i),xa=$u(oa),la=i.selectedMcpServers.map(oe=>String(oe||"").trim()).filter(Boolean),Pa=Iu(la,i.toolAccessMode,i.customToolsText),Zt=Re.find(oe=>String(oe?.automation_id||oe?.automationId||oe?.id||"").trim()===i.automationId),Ea=Array.isArray(Zt?.agents)?Zt.agents.map(oe=>({...oe,model_policy:xa,modelPolicy:void 0,tool_policy:{...oe?.tool_policy||{},allowlist:Pa,denylist:Array.isArray(oe?.tool_policy?.denylist)?oe.tool_policy.denylist:[]},mcp_policy:{...oe?.mcp_policy||{},allowed_servers:la,allowed_tools:null}})):[],c=Array.isArray(Zt?.flow?.nodes)?Zt.flow.nodes.map((oe,at)=>{const At=String(oe?.node_id||oe?.nodeId||oe?.id||`node-${at}`).trim(),na=i.nodes.find(Bt=>Bt.nodeId===At);return na?{...oe,objective:String(na.objective||"").trim()}:oe}):[],q=Zt?.metadata&&typeof Zt.metadata=="object"?Zt.metadata:{};return a.automationsV2.update(i.automationId,{name:m,description:E||null,schedule:Ru(i),workspace_root:Y,execution:{...Zt?.execution||{},max_parallel_agents:i.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(i.maxParallelAgents||"4"),10)||4)):1},flow:Zt?.flow?{...Zt.flow,nodes:c}:Zt?.flow,agents:Ea,metadata:{...q,workspace_root:Y,operator_preferences:oa,allowed_mcp_servers:la}})},onSuccess:async()=>{t("ok","Workflow automation updated."),ue(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),De=xe({mutationFn:async({action:i,automationId:m,family:E})=>E==="v2"?i==="delete"?a.automationsV2.delete(m):i==="pause"?a.automationsV2.pause(m):a.automationsV2.resume(m):i==="delete"?a.automations.delete(m):a.automations.update(m,{status:i==="pause"?"paused":"enabled"}),onSuccess:async(i,m)=>{m.action==="delete"&&t("ok","Automation removed."),m.action==="pause"&&t("ok","Automation paused."),m.action==="resume"&&t("ok","Automation resumed."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),o=L(()=>{const i=[...Ma(he.data,"automations"),...Ma(he.data,"routines")],m=new Map;for(const E of i){const Y=String(E?.automation_id||E?.routine_id||E?.id||"").trim();Y&&(m.has(Y)||m.set(Y,E))}return Array.from(m.values())},[he.data]),b=Ma(qe.data,"runs"),T=L(()=>(Array.isArray(re.data?.providers)?re.data.providers:[]).map(m=>({id:String(m?.id||"").trim(),models:Array.isArray(m?.models)?m.models.map(E=>String(E||"").trim()).filter(Boolean):[]})).filter(m=>m.id).sort((m,E)=>m.id.localeCompare(E.id)),[re.data]),C=L(()=>Ni(Ue.data),[Ue.data]),$=Ma(ze.data,"runs"),Ye=L(()=>{const i=[...b,...$],m=new Map;for(const E of i){const Y=String(E?.run_id||E?.runId||E?.id||"").trim();Y&&(m.has(Y)||m.set(Y,E))}return Array.from(m.values()).sort((E,Y)=>{const ce=ar(E?.started_at_ms||E?.startedAtMs||E?.created_at_ms||E?.createdAtMs||0);return ar(Y?.started_at_ms||Y?.startedAtMs||Y?.created_at_ms||Y?.createdAtMs||0)-ce})},[b,$]),Ze=Ma(yt.data,"packs"),bt=Ye.filter(i=>Da(Ua(i))),qt=Ye.filter(i=>{const m=Ua(i);return m==="failed"||m==="error"||m==="blocked"}),Ae=V.data?.run||null,wt=St.data?.blackboard||null,It=Array.isArray(Ee.data?.events)?Ee.data.events:[],te=Array.isArray(Rt.data?.patches)?Rt.data.patches:[],_e=L(()=>{if(!M)return{tasks:[],currentTaskId:"",taskSource:"empty"};const i=Ku(Ae,[],v),m=wi({run:ot.data?.run||null,tasks:Array.isArray(ot.data?.run?.steps)?ot.data?.run.steps:[],blackboard:wt,events:It});if(m.tasks.length){const E=i?m.tasks.map(Y=>Y.id===i&&["pending","runnable","assigned"].includes(Y.state)?{...Y,state:"in_progress"}:Y):m.tasks;return{...m,tasks:E,currentTaskId:m.currentTaskId||i}}return Zc(Ae,i)},[M,Ae,v,wt,It,ot.data]),h=L(()=>_e.tasks.find(i=>i.id===Q)||null,[Q,_e.tasks]),j=L(()=>_e.tasks.find(i=>String(i.state||"").toLowerCase()==="blocked")||null,[_e.tasks]),z=L(()=>{if(!h)return null;const i=String(h.id||"").replace(/^node-/,"");return ir(Ae,i)},[h,Ae]),K=L(()=>Ur(z),[z]),H=L(()=>$n(z),[z]),fe=L(()=>hd(h,z),[h,z]),Be=fe.touchedFiles,pt=fe.undeclaredFiles,lt=fe.researchReadPaths,xt=fe.discoveredRelevantPaths,et=fe.reviewedPathsBackedByRead,kt=fe.unreviewedRelevantPaths,Et=fe.unmetResearchRequirements,Wt=String(h?.state||"").toLowerCase()==="blocked"?h:j,vt=String(Wt?.id||"").replace(/^node-/,"").trim(),ct=String(Ae?.status||"").trim().toLowerCase(),Se=Ua(Ae),Pe=ct!==Se&&(ct==="completed"||ct==="done")&&Qn(Ae)>0,ga=M&&["failed","paused"].includes(Se)&&!!s,ke=M&&!!s&&!!vt,ge=L(()=>{const i=Ae?.nodeRepairGuidance,m=i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).map(([Y,ce])=>({nodeId:String(Y||"").trim(),guidance:ce||{}})).filter(Y=>Y.nodeId):[];if(m.length)return m;const E=Ae?.checkpoint?.node_outputs||Ae?.checkpoint?.nodeOutputs||{};return Object.entries(E).map(([Y,ce])=>{const st=ce?.artifact_validation||ce?.artifactValidation||{},Dt=ce?.validator_summary||ce?.validatorSummary||{},oa=Array.isArray(st?.required_next_tool_actions||st?.requiredNextToolActions)?st.required_next_tool_actions||st.requiredNextToolActions:[],xa=Array.isArray(Dt?.unmet_requirements||Dt?.unmetRequirements)?Dt.unmet_requirements||Dt.unmetRequirements:[],la=String(Dt?.reason||ce?.blocked_reason||ce?.blockedReason||"").trim(),Pa=String(st?.blocking_classification||st?.blockingClassification||"").trim();return!oa.length&&!xa.length&&!la&&!Pa?null:{nodeId:String(Y||"").trim(),guidance:{status:ce?.status||"",failureKind:ce?.failure_kind||ce?.failureKind||"",reason:la,unmetRequirements:xa,blockingClassification:Pa,requiredNextToolActions:oa,repairAttempt:st?.repair_attempt??st?.repairAttempt??null,repairAttemptsRemaining:st?.repair_attempts_remaining??st?.repairAttemptsRemaining??null}}}).filter(Boolean)},[Ae]);be(()=>{!h||!pe.current||pe.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[h]),be(()=>{y("")},[s,Q]);const dt=M?Array.isArray(wt?.artifacts)?wt.artifacts:[]:Ma(He.data,"artifacts"),Ge=L(()=>dt.map((i,m)=>{const E=String(i?.id||i?.artifact_id||`artifact-${m+1}`).trim(),Y=String(i?.name||i?.label||i?.kind||i?.type||i?.path||E).trim(),ce=String(i?.kind||i?.type||i?.path||"").trim(),st=Kn(Tn(i));return{key:E,name:Y||E,kind:ce,artifact:i,paths:st}}),[dt]),Nt=L(()=>h?Kn([...Tn(z),...Tn(H),String(h.output_path||"").trim()]):[],[h,H,z]),Ut=L(()=>Nt.length?Ge.filter(i=>i.paths.some(m=>Nt.includes(m))):[],[Ge,Nt]),ra=fe.verificationOutcome,Mt=fe.verificationPassed,zt=fe.verificationResults,Ct=L(()=>String(h?.id||"").startsWith("node-")?String(h?.id||"").replace(/^node-/,"").trim():"",[h]),Vt=L(()=>String(h?.id||"").startsWith("node-"),[h]),Yt=L(()=>String(h?.task_type||"").trim()==="automation_backlog_item",[h]),ua=L(()=>String(h?.state||"").trim().toLowerCase(),[h]),Na=L(()=>Number(h?.lease_expires_at_ms||0)||0,[h]),f=L(()=>!!h?.is_stale||ua==="in_progress"&&Na>0&&Na<=Date.now(),[h,Na,ua]),B=fe.failureDetail,me=fe.workflowClass,Le=fe.phase,Fe=fe.failureKind,tt=fe.artifactCandidates,_t=L(()=>td(Ae,Ct,8),[Ct,Ae]),Jt=L(()=>Fu(_e.tasks,h?.id||""),[h,_e.tasks]),sa=L(()=>Jt.map(i=>_e.tasks.find(m=>m.id===i)||null).filter(Boolean),[Jt,_e.tasks]),Qt=L(()=>{const i=ne.data?.preview,m=Array.isArray(i?.reset_nodes)?i.reset_nodes.map(E=>String(E||"").trim()).filter(Boolean):[];return m.length?m:Jt.map(E=>E.replace(/^node-/,"").trim()).filter(Boolean)},[Jt,ne.data]),Xt=L(()=>{const i=ne.data?.preview,m=Array.isArray(i?.cleared_outputs)?i.cleared_outputs.map(E=>String(E||"").trim()).filter(Boolean):[];return m.length?Kn(m):Kn(sa.map(E=>String(E?.output_path||"").trim()))},[sa,ne.data]),wa=i=>{const m=String(i||"").trim(),E=Ge.find(Y=>Y.paths.includes(m));y(E?.key||""),X.current&&X.current.scrollIntoView({block:"nearest",behavior:"smooth"})},Ka=M&&!!s&&Vt&&!!Ct&&["blocked","failed"].includes(ua),Xa=M&&!!s&&Vt&&!!Ct&&ua==="blocked",hn=M&&!!s&&Vt&&!!Ct&&!["in_progress","done","blocked","failed"].includes(ua),Za=M&&!!s&&Yt&&!Vt&&["pending","runnable"].includes(ua),ia=M&&!!s&&Yt&&!Vt&&(["blocked","failed"].includes(ua)||f),ma=L(()=>{const i=ne.data?.preview,m=String(h?.title||Ct||"task").trim(),E=Qt.length,Y=Math.max(0,E-(Ct?1:0)),ce=Xt.length;return{rootTitle:m,subtreeCount:E,descendantCount:Y,outputCount:ce,previewBacked:!!ne.data?.preview,preservesUpstreamOutputs:typeof i?.preserves_upstream_outputs=="boolean"?i.preserves_upstream_outputs:!0}},[h,Ct,Qt.length,Xt.length,ne.data]),En=Ou(Ae,dt),_a=M?(()=>{const i=ld(It,te);return i.length?i:cd(Array.isArray(mt.data)?mt.data:[],Ca)})():Array.isArray(rt.data?.events)?rt.data.events:Array.isArray(rt.data?.history)?rt.data.history:[],fa=L(()=>dd(Array.isArray(mt.data)?mt.data:[],It,M,Ca),[M,mt.data,s,It]),La=L(()=>{const i=[...fa,...A],m=new Set;return i.filter(E=>!E?.id||m.has(E.id)?!1:(m.add(E.id),!0)).sort((E,Y)=>Number(E.at||0)-Number(Y.at||0))},[fa,A]),$a=La.filter(i=>k==="all"?!0:i.source===k),Dn=L(()=>pd($a),[$a]),en=L(()=>ht.flatMap((i,m)=>{const E=Ie[m]||"";return(Array.isArray(i.data)?i.data:[]).map(ce=>({sessionId:E,message:ce}))}),[Ie,ht]),gn=L(()=>{const i=[];return i.push({label:"status",value:Se||"unknown"}),Pe&&i.push({label:"status note",value:"derived from blocked nodes"}),i.push({label:"artifacts",value:String(dt.length)}),M&&(i.push({label:"tasks",value:String(_e.tasks.length)}),i.push({label:"context events",value:String(It.length)}),i.push({label:"blackboard patches",value:String(te.length)}),i.push({label:"completed nodes",value:String(os(Ae))}),i.push({label:"pending nodes",value:String(Qc(Ae))}),i.push({label:"blocked nodes",value:String(Qn(Ae))})),String(Ae?.detail||"").trim()&&i.push({label:"detail",value:String(Ae.detail).trim()}),Ae?.requires_approval!==void 0&&i.push({label:"requires approval",value:String(!!Ae?.requires_approval)}),String(Ae?.approval_reason||"").trim()&&i.push({label:"approval reason",value:String(Ae.approval_reason).trim()}),String(Ae?.denial_reason||"").trim()&&i.push({label:"denial reason",value:String(Ae.denial_reason).trim()}),String(Ae?.paused_reason||"").trim()&&i.push({label:"paused reason",value:String(Ae.paused_reason).trim()}),i},[M,dt.length,Se,Pe,Ae,It.length,te.length,_e.tasks.length]);L(()=>Ai(Ae),[Ae]),be(()=>{de(i=>i&&Ie.includes(i)?i:Ie[0]||"")},[Ie]),be(()=>{I(i=>i==="all"||i&&Ie.includes(i)?i:"all")},[Ie]),be(()=>{G([]),J("all"),R(""),U([]),Ke(!0)},[s,F]);const Ce=Pt("");be(()=>{!s||!_e.tasks.length||Ce.current!==s&&(Ce.current=s,R(_e.currentTaskId||_e.tasks.find(i=>["in_progress","blocked","assigned","runnable","pending"].includes(String(i.state||"").toLowerCase()))?.id||_e.tasks[0]?.id||""))},[s,_e.currentTaskId,_e.tasks]),Va(s?M?`/api/engine/automations/v2/events?run_id=${encodeURIComponent(s)}`:`/api/engine/automations/events?run_id=${encodeURIComponent(s)}`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m||m.status==="ready")return;const E=is(m);if(!E||E!==s)return;const Y=Ca(m),ce=dn(m),st=`automations:${E}:${Y}:${ce}:${Math.random().toString(16).slice(2,8)}`;G(Dt=>[...Dt.slice(-299),{id:st,source:"automations",at:ce,event:m}])}catch{return}},{enabled:!!s}),Va(F?`/api/engine/context/runs/${encodeURIComponent(F)}/events/stream?tail=50`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m||m.status==="ready")return;const E=`context:${String(m?.seq||"")}:${String(m?.event_type||"")}`,Y=Ii(m?.created_at_ms||m?.timestamp_ms||m?.timestampMs)||Date.now();G(ce=>ce.some(st=>st.id===E)?ce:[...ce.slice(-399),{id:E,source:"context",at:Y,event:m}])}catch{return}},{enabled:!!F}),Va(s&&ee?`/event?sessionID=${encodeURIComponent(ee)}&runID=${encodeURIComponent(s)}`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m)return;const E=Ca(m),Y=dn(m),ce=[E||"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||Y)].join(":");U(st=>st.some(Dt=>Dt.id===ce)?st:[...st.slice(-499),{id:ce,at:Y,event:m}])}catch{return}},{enabled:!!s&&!!ee}),Va(s?"/api/global/event":"",i=>{try{const m=JSON.parse(String(i?.data||"{}")),E=is(m);if(!E||E!==s)return;const Y=Ca(m);if(!Y||Y==="server.connected"||Y==="engine.lifecycle.ready")return;const ce=dn(m),st=`global:${E}:${Y}:${ce}:${Math.random().toString(16).slice(2,8)}`;G(Dt=>[...Dt.slice(-299),{id:st,source:"global",at:ce,event:m}])}catch{return}},{enabled:!!s}),be(()=>{const i=_.current;i&&ya(i)},[o.length,Re.length,Ye.length,$.length,Ze.length,bt.length,qt.length,!!P,!!s,!!ee,!!h,A.length,v.length,W.isPending,Qe.isPending,Ot.isPending,Je.isPending]);const Sa=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"},fn=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 E=Si(i?.schedule);O({automationId:m,name:String(i?.name||m||"").trim(),objective:String(i?.mission?.objective||i?.mission_snapshot?.objective||"").trim(),mode:String(i?.mode||"").toLowerCase()==="standalone"?"standalone":"orchestrated",requiresApproval:i?.requires_approval===!0||i?.policy?.approval?.requires_approval===!0,scheduleKind:E.scheduleKind==="cron"?"cron":"interval",cronExpression:E.cronExpression,intervalSeconds:String(E.intervalSeconds)})},tn=i=>{const m=String(i?.status||"").trim().toLowerCase();return m==="paused"||m==="disabled"},ba=o.length,Wa=Re.length,an=ba+Wa,za=L(()=>Lu(Ae,v,A),[Ae,v,A]),Oa=L(()=>{const i=en.map(({sessionId:Y,message:ce},st)=>({id:`message:${Y}:${Bu(ce,st)}`,kind:"message",sessionId:Y,at:Uu(ce),variant:Du(ce),label:String(ce?.info?.role||"session").trim()||"session",body:Wr(ce),raw:ce,parts:ju(ce),sessionLabel:kn(Y)})),m=ud(v,ee).map(Y=>({...Y,sessionLabel:kn(ii(Y.raw,ee))})),E=[...i,...m].sort((Y,ce)=>Y.at-ce.at);return S==="all"?E:E.filter(Y=>Y.sessionId===S)},[S,ee,en,v]);return be(()=>{const i=$e.current;!i||!Oe||(i.scrollTop=i.scrollHeight)},[Oa,Oe]),e("div",{ref:_,className:"grid gap-4",children:[r==="list"&&Ze.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"}),Ze.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:[an," 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:[ba," items"]})]}),o.length>0?o.map(i=>{const m=String(i?.automation_id||i?.id||i?.routine_id||"");return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"⏰"}),e("strong",{children:String(i?.name||m||"Automation")})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>fn(i),children:e("i",{"data-lucide":"pencil"})}),e("span",{className:Sa(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:()=>Ot.mutate(m),children:[e("i",{"data-lucide":"play"}),"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>De.mutate({action:tn(i)?"resume":"pause",automationId:m,family:"legacy"}),disabled:!m||De.isPending,children:[e("i",{"data-lucide":tn(i)?"play":"pause"}),tn(i)?"Resume":"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{const E=Ye.find(ce=>String(ce?.automation_id||ce?.routine_id||ce?.id||"").trim()===m),Y=String(E?.run_id||E?.id||"").trim();Y?(l(Y),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||De.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:[Wa," items"]})]}),Re.length>0?Re.map(i=>{const m=String(i?.automation_id||i?.automationId||"").trim(),E=String(i?.status||"draft").trim(),Y=E.toLowerCase()==="paused",ce=qu(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")}),ce?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(Tu(i)){u(i);return}ue(Pu(i))},disabled:!m,title:"Edit workflow automation","aria-label":"Edit workflow automation",children:e("i",{"data-lucide":"pencil"})}),e("span",{className:Sa(E),children:E})]})]}),String(i?.description||"").trim()?e("div",{className:"tcp-subtle text-xs",children:String(i.description)}):null,ce?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:_i(i?.schedule)}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Je.mutate(m),disabled:!m||Je.isPending,children:[e("i",{"data-lucide":"play"}),Je.isPending?"Starting...":"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>De.mutate({action:Y?"resume":"pause",automationId:m,family:"v2"}),disabled:!m||De.isPending,children:[e("i",{"data-lucide":Y?"play":"pause"}),Y?"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||De.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},m)}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"No workflow automations saved yet"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"This section is separate from run history and only shows workflow automation definitions."})]})]}):null,r==="running"?bt.length>0?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs font-medium uppercase tracking-wide text-slate-500",children:"Active Running Tasks"}),e("span",{className:"tcp-badge-warn",children:[bt.length," active"]})]}),bt.slice(0,14).map((i,m)=>{const E=String(i?.run_id||i?.id||m).trim(),Y=Ua(i),ce=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:fr(i)}),e("span",{className:"tcp-subtle text-xs",children:[E||"unknown run"," · running for ",_s(i)]}),ja(ce)?e("span",{className:"tcp-subtle text-xs",children:["Started: ",ja(ce)]}):null,Ga(i)?e("span",{className:"text-xs text-slate-400",children:Pn(Ga(i),160)}):null]}),e("span",{className:Sa(Y),children:Y||"unknown"})]}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l(E),children:[e("i",{"data-lucide":"bug"}),"Inspect"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Qe.mutate({action:"pause",runId:E,family:E.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!E||Qe.isPending,children:[e("i",{"data-lucide":"pause"}),"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Qe.mutate({action:"resume",runId:E,family:E.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!E||Qe.isPending,children:[e("i",{"data-lucide":"play"}),"Resume"]})]})]},E||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"&&qt.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:[qt.length," issues"]})]}),qt.slice(0,10).map((i,m)=>{const E=String(i?.run_id||i?.id||m).trim(),Y=Ua(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:fr(i)}),e("span",{className:"tcp-subtle text-xs",children:E||"unknown run"}),ja(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Finished:"," ",ja(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)]}):null,Ga(i)?e("span",{className:"text-xs text-slate-400",children:Pn(Ga(i),160)}):null]}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:Sa(Y),children:Y||"failed"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l(E),children:[e("i",{"data-lucide":"bug"}),"Inspect"]})]})]})},`failed-${E||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:fr(i)}),e("span",{className:Sa(Ua(i)),children:Ua(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||"")}),ja(i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Started:"," ",ja(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: ",ja(i?.finished_at_ms||i?.finishedAtMs)]}):null,Ga(i)?e("span",{className:"text-xs text-slate-400",children:Pn(Ga(i),160)}):null]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{l(String(i?.run_id||i?.id||"").trim()),d()},children:[e("i",{"data-lucide":"info"}),r==="running"?"Logs":"Details"]})]})]},String(i?.run_id||i?.id||m)))]}):null,!Ye.length&&r==="running"?e(We,{text:"Run one automation, then use Logs to inspect full execution events."}):null,!an&&!Ze.length&&!Ye.length&&r==="list"?e(We,{text:"No automations yet. Create your first one with the wizard!"}):null,e(Tt,{children:[s?e(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>l(""),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(Ae?.automation_id||Ae?.routine_id||"unknown")," · ","run: ",s," · ","running for ",_s(Ae)]}),M?e("div",{className:"tcp-subtle text-xs",children:["completed nodes: ",os(Ae)," · ","blocked nodes: ",Qn(Ae)," · ","active sessions: ",ls(Ae)]}):null]}),e("div",{className:"flex w-full flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center lg:w-auto",children:[e("span",{className:Sa(Se),children:Se||"unknown"}),Pe?e("span",{className:"tcp-subtle",children:"derived from blocked nodes"}):null,ke?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>Ve.mutate({runId:s,nodeId:vt,reason:`continued blocked task ${vt} from run debugger`}),disabled:!vt||Ve.isPending||Qe.isPending,title:vt?`Continue blocked task ${vt} with minimal reset`:"Select a blocked node to continue",children:[e("i",{"data-lucide":"skip-forward"}),Ve.isPending?"Continuing...":"Continue"]}):null,ga?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>ye.mutate({runId:s,reason:"retried from run debugger"}),disabled:!s||ye.isPending||Qe.isPending,children:[e("i",{"data-lucide":"rotate-ccw"}),ye.isPending?"Retrying...":"Retry"]}):null,s?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>Qe.mutate({action:Se==="paused"?"resume":"pause",runId:s,family:M?"v2":"legacy"}),disabled:!s||Qe.isPending||!(Se==="paused"||Da(Se)),children:[e("i",{"data-lucide":Se==="paused"?"play":"pause"}),Se==="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]}),F?p.invalidateQueries({queryKey:["automations","run","context",F]}):Promise.resolve(),F?p.invalidateQueries({queryKey:["automations","run","context",F,"blackboard"]}):Promise.resolve(),F?p.invalidateQueries({queryKey:["automations","run","context",F,"events"]}):Promise.resolve(),F?p.invalidateQueries({queryKey:["automations","run","context",F,"patches"]}):Promise.resolve(),s?p.invalidateQueries({queryKey:["automations","run","session",s]}):Promise.resolve()])},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>l(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]}),e("div",{className:"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:gn.map(i=>e("div",{className:"break-words",children:[i.label,": ",i.value]},i.label))})]}),M?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:"Workflow Board"}),e("div",{className:"tcp-subtle text-xs",children:["context run: ",Yn(F||"unlinked",44)," · ","tasks: ",_e.tasks.length," · ","artifacts: ",dt.length]})]}),e("span",{className:"tcp-badge-info",children:_e.taskSource==="hybrid"?"blackboard + context":_e.taskSource==="checkpoint"?"run checkpoint":_e.taskSource})]}),e(xi,{tasks:_e.tasks,currentTaskId:_e.currentTaskId,selectedTaskId:Q,onTaskSelect:i=>R(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:pe,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:()=>R(""),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:kn(h.session_id)}):null]}),z?e("div",{className:"flex flex-wrap gap-2 text-xs",children:[String(z?.status||"").trim()?e("span",{className:String(z?.status||"").trim().toLowerCase()==="blocked"?"tcp-badge-warn":"tcp-badge-ok",children:["status: ",String(z?.status||"").trim()]}):null,typeof z?.approved=="boolean"?e("span",{className:z.approved?"tcp-badge-ok":"tcp-badge-warn",children:["approved: ",String(z.approved)]}):null,K?.workspace_inspection_used?e("span",{className:"tcp-badge-info",children:"workspace inspected"}):null,K?.web_research_used?e("span",{className:"tcp-badge-info",children:"web research used"}):null,String(H?.rejected_artifact_reason||"").trim()?e("span",{className:"tcp-badge-warn",children:"artifact rejected"}):null]}):null,Vt?null:e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:Yt?"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,me||Le||Fe||tt.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:me||"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:Le||"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:Fe||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"artifact candidates"}),e("div",{className:"mt-1 font-medium text-slate-100",children:tt.length})]})]}),tt.length?e("div",{className:"mt-3 grid gap-2",children:tt.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:"," ",Na?ja(Na):"n/a"]}),e("div",{children:["stale lease: ",f?"yes":"no"]}),e("div",{children:["verification:"," ",String(h.verification_command||"").trim()||"n/a"]})]})]}):null,lt.length||xt.length||Et.length||H?.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:xt.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:lt.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:H?.web_research_attempted?H?.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:H?.repair_attempted?H?.repair_succeeded?"attempted and satisfied":H?.repair_exhausted?"attempted and exhausted":"attempted and still active":"not needed or not attempted"}),H?.repair_attempted?e("div",{className:"mt-1 tcp-subtle",children:["attempt"," ",Number(H?.repair_attempt||0)," ","of"," ",Number(H?.repair_attempt||0)+Number(H?.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:kt.length})]})]}),Et.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:Et.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,kt.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:kt.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,z||Nt.length||B?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:ra})]}),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 Mt=="boolean"?Mt?"yes":"no":"n/a"})]})]}),K?.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(K?.verification_completed||0)," ","/"," ",Number(K?.verification_total||0)," ","checks ran"]}),zt.length?e("div",{className:"grid gap-2",children:zt.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,B?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:B})]}):null,Nt.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:Nt.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:()=>wa(i),title:i,children:["Open ",Yn(i,44)]},i))}),Ut.length?e("div",{className:"mt-2 tcp-subtle",children:["matched run artifacts:"," ",Ut.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,(Xa||Ka||hn||Za||ia||ga)&&s?e("div",{className:"mt-3 space-y-3",children:[Vt?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...":ma.previewBacked?"Engine preview":"UI-estimated preview"}),e("div",{className:"mt-1",children:["Selected task: ",ma.rootTitle]}),e("div",{children:["Reset scope:"," ",Xa?"minimal reset of the blocked task":`${ma.subtreeCount} task${ma.subtreeCount===1?"":"s"}${ma.descendantCount>0?` (${ma.descendantCount} descendant${ma.descendantCount===1?"":"s"})`:""}`]}),e("div",{children:["Preserves:"," ",ma.preservesUpstreamOutputs?"completed upstream outputs outside this subtree":"n/a"]}),e("div",{children:["Clears: stale outputs for"," ",ma.outputCount," declared artifact",ma.outputCount===1?"":"s"]}),Xt.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:Xt.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]}):Yt?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:[Za?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>it.mutate({runId:s,taskId:String(h.id||""),agentId:String(h.task_owner||"").trim()||void 0,reason:`claimed backlog task ${String(h.id||"")} from debugger`}),disabled:it.isPending||N.isPending,children:it.isPending?"Claiming...":"Claim Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Assign this projected coding task and start its lease."})]}):null,ia?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>N.mutate({runId:s,taskId:String(h.id||""),reason:`requeued backlog task ${String(h.id||"")} from debugger`}),disabled:it.isPending||N.isPending,children:N.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,Xa?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:Ct,reason:`continued blocked task ${Ct} from debugger`}),disabled:Ve.isPending||Ne.isPending||le.isPending||it.isPending||N.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,Ka?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>Ne.mutate({runId:s,nodeId:Ct,reason:`retried task ${Ct} from debugger`}),disabled:Ve.isPending||Ne.isPending||le.isPending||it.isPending||N.isPending,children:Ne.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,hn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>le.mutate({runId:s,nodeId:Ct,reason:`requeued task ${Ct} from debugger`}),disabled:Ve.isPending||Ne.isPending||le.isPending||it.isPending||N.isPending,children:le.isPending?"Requeueing...":"Requeue Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Use when this task should go back onto the queue with its descendants reset."})]}):null,ua==="blocked"&&vt?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>nt.mutate({runId:s,nodeId:vt,reason:`continued from blocked node ${vt}`}),disabled:Ve.isPending||nt.isPending||!vt,children:nt.isPending?"Repairing...":"Repair Blocked Step"}),e("div",{className:"tcp-subtle text-[11px]",children:"Heavier reset/repair flow for blocked nodes when minimal continue is not enough."})]}):null,ga?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>ye.mutate({runId:s,reason:`retried from task ${String(h.id||"").replace(/^node-/,"")}`}),disabled:ye.isPending,children:ye.isPending?"Retrying...":"Retry Workflow"}),e("div",{className:"tcp-subtle text-[11px]",children:"Recover the whole run, not just this task subtree."})]}):null]})]}):null]}):null,H||K||Be.length||pt.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(H?.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(H?.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:K?.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:K?.web_research_used?"yes":"no"})]})]}),e("div",{className:"mt-3 space-y-2",children:[e("div",{children:[e("div",{className:"tcp-subtle mb-1",children:"touched files"}),Be.length?e("div",{className:"flex flex-wrap gap-1",children:Be.map(i=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:i},i))}):e("div",{className:"tcp-subtle",children:"none"})]}),e("div",{children:[e("div",{className:"tcp-subtle mb-1",children:"undeclared files"}),pt.length?e("div",{className:"flex flex-wrap gap-1",children:pt.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,K?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(K?.requested_tools)&&K.requested_tools.join(", ")||"n/a"]}),e("div",{children:["executed:"," ",Array.isArray(K?.executed_tools)&&K.executed_tools.join(", ")||"none"]}),e("div",{children:["workspace inspection:"," ",K?.workspace_inspection_used?"yes":"no"]}),e("div",{children:["web research:"," ",K?.web_research_used?"yes":"no"]})]})]}):null,H?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(H?.accepted_artifact_path||"").trim()||"n/a"]}),e("div",{children:["rejected reason:"," ",String(H?.rejected_artifact_reason||"").trim()||"none"]}),e("div",{children:["auto-cleaned:"," ",String(!!H?.auto_cleaned)]}),e("div",{children:["undeclared files:"," ",pt.length?pt.join(", "):"none"]}),e("div",{children:["execution policy:"," ",String(H?.execution_policy?.mode||"").trim()||"n/a"]}),e("div",{children:["touched files:"," ",Be.length?Be.join(", "):"none"]}),e("div",{children:["git diff:"," ",String(H?.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?S==="all"?`Merged timeline across ${Ie.length||1} session${Ie.length===1?"":"s"}`:`Filtered to ${S}`:"This run does not expose a session transcript."})]}),e("div",{className:"flex flex-wrap gap-2",children:[Ie.length>1?e("select",{className:"tcp-select h-7 min-w-[12rem] max-w-full shrink-0 text-xs sm:min-w-[14rem]",value:S,onInput:i=>I(i.target.value),children:[e("option",{value:"all",children:"All sessions"}),Ie.map(i=>e("option",{value:i,title:i,children:kn(i)},i))]}):ee?e("span",{className:"tcp-badge-info",title:ee,children:kn(ee)}):null,ee?e("span",{className:"tcp-badge-info",title:ee,children:["live: ",Yn(ee,24)]}):null,e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:!Oa.length,onClick:async()=>{try{await navigator.clipboard.writeText(Oa.map(i=>{const m=new Date(i.at).toLocaleTimeString(),E=i.sessionId?` · ${i.sessionLabel}`:"";return`[${m}] ${i.label}${E}
|
|
2444
|
+
${i.body||Ht(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:()=>{Ke(!0);const i=$e.current;i&&(i.scrollTop=i.scrollHeight)},children:[e("i",{"data-lucide":"arrow-down"}),"Jump to latest"]})]})]}),e("div",{ref:$e,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,E=m.scrollHeight-(m.scrollTop+m.clientHeight)<48;Ke(E)},children:Oa.length?Oa.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:Ht(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:Ht(i.raw)})]}):null]},i.id)):e("div",{className:"tcp-subtle text-xs",children:Ie.length?"Waiting for session transcript or live session events.":"This run does not expose a session transcript."})})]}),e("div",{className:"tcp-list-item min-h-0 xl:order-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Run Telemetry"}),e("div",{className:"flex w-full flex-wrap gap-1 sm:w-auto",children:[e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="all"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>J("all"),children:["all (",La.length,")"]}),e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="automations"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>J("automations"),children:"automations"}),M?e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="context"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>J("context"),children:"context"}):null,e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="global"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>J("global"),children:"global"})]})]}),Dn.length?e("div",{className:"grid gap-2 overflow-auto pr-1 sm:max-h-[12rem]",children:Dn.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:[Ss(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:Ht(i.raw)})]},i.id))}):e("div",{className:"tcp-subtle text-xs",children:M?"No workflow, context, or global telemetry has been captured for this run yet.":"No automation/global telemetry captured for this run yet."})]})]}),e("div",{className:"grid min-h-0 content-start gap-3 overflow-visible",children:[za.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:za.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,En.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:En.map(i=>e("div",{children:i},i))})]}):null,ge.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:[ge.length," node",ge.length===1?"":"s"]})]}),e("div",{className:"grid gap-2",children:ge.map(({nodeId:i,guidance:m})=>{const E=Array.isArray(m?.requiredNextToolActions)?m.requiredNextToolActions:[],Y=Array.isArray(m?.unmetRequirements)?m.unmetRequirements:[],ce=String(m?.reason||"").trim(),st=String(m?.blockingClassification||"").trim(),Dt=String(m?.failureKind||"").trim(),oa=String(m?.status||"").trim(),xa=oa.toLowerCase(),la=ls(Ae)>0,Pa=M&&!!s&&!la&&(["blocked","failed","needs_repair"].includes(xa)||xa==="completed"&&(E.length>0||Y.length>0)),Zt=M&&!!s&&!la&&["blocked","needs_repair"].includes(xa);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}),oa?e("span",{className:"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200 tcp-badge",children:oa}):null,st?e("span",{className:"tcp-subtle text-[11px]",children:st.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:()=>R(`node-${i}`),children:"Focus"}),Pa?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ne.mutate({runId:s,nodeId:i,reason:`retried task ${i} from repair guidance`}),disabled:Ne.isPending||Ve.isPending||le.isPending,children:Ne.isPending?"Retrying...":"Retry"}):null,Zt?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:Ne.isPending||Ve.isPending||le.isPending,children:Ve.isPending?"Continuing...":"Continue"}):null]}),ce?e("div",{className:"mb-2 whitespace-pre-wrap break-words text-sm text-emerald-100/90",children:ce}):null,E.length?e("div",{className:"grid gap-1",children:E.map((Ea,c)=>e("div",{className:"rounded-md border border-emerald-400/20 bg-black/20 px-2 py-1 text-xs text-emerald-50",children:String(Ea||"")},`${i}-action-${c}`))}):null,!E.length&&Y.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:Y.map(Ea=>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(Ea||"").replace(/_/g," ")},`${i}-${String(Ea)}`))}):null,Dt?e("div",{className:"tcp-subtle mt-2 text-[11px]",children:["failure kind: ",Dt]}):null]},i)})})]}):null,e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:"Mission Objective"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:String(Ae?.mission_snapshot?.objective||"n/a")})]}),e("div",{ref:X,className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:["Artifacts (",dt.length,")"]}),dt.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-40",children:Ge.map(i=>e("details",{open:we===i.key?!0:void 0,className:we===i.key?"rounded-lg border border-sky-500/40 bg-sky-950/10 p-2":"rounded-lg border border-slate-700/40 bg-slate-900/25 p-2",children:[e("summary",{className:"cursor-pointer list-none",onClick:()=>y(m=>m===i.key?"":i.key),children:e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:i.name}),e("span",{className:"tcp-subtle text-[11px]",children:i.kind||"artifact"})]})}),i.paths.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:i.paths.map(m=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:m},m))}):null,e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:Ht(i.artifact)})]},i.key))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:M?"No blackboard artifacts have been recorded for this workflow run yet.":"No run artifacts were persisted for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"font-medium",children:M?"Run History":"Persisted History"}),_a.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-[14rem]",children:_a.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:Ss(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:Ht(i)})]},`${String(i?.id||i?.event||i?.type||"history")}-${m}`))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:M?"No context-run history has been persisted for this workflow run yet.":"No persisted history rows returned for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Raw Run Payload"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(["=== RUN ===",Ht(Ae),"=== ARTIFACTS ===",Ht(dt),"=== TELEMETRY ===",Ht($a.map(i=>i.event)),"=== CONTEXT RUN ===",Ht(ot.data?.run||null),"=== BLACKBOARD ===",Ht(wt),"=== HISTORY ===",Ht(_a),"=== SESSION MESSAGES ===",Ht(en)].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:Ht({run:Ae,contextRun:ot.data?.run||null,blackboard:wt})})]})]})]})]})}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>n("feed"),children:[e("i",{"data-lucide":"radio"}),"Open Live Feed"]}),e("button",{className:"tcp-btn",onClick:()=>l(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]})}):null,P?e(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>O(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:P.name,onInput:i=>O(m=>m&&{...m,name:i.target.value})})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Objective"}),e("textarea",{className:"tcp-input min-h-[96px]",value:P.objective,onInput:i=>O(m=>m&&{...m,objective:i.target.value})})]}),e("div",{className:"grid gap-1 sm:grid-cols-2 sm:gap-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Mode"}),e("select",{className:"tcp-input",value:P.mode,onInput:i=>O(m=>m&&{...m,mode:i.target.value}),children:[e("option",{value:"standalone",children:"standalone"}),e("option",{value:"orchestrated",children:"orchestrated"})]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Approval policy"}),e("button",{className:`tcp-input flex h-10 items-center justify-between px-3 text-xs ${P.requiresApproval?"border-amber-400/60 bg-amber-400/10":""}`,role:"switch","aria-checked":P.requiresApproval,onClick:()=>O(i=>i&&{...i,requiresApproval:!i.requiresApproval}),children:[e("span",{className:"flex items-center gap-2",children:[e("i",{"data-lucide":P.requiresApproval?"shield-alert":"shield-check"}),P.requiresApproval?"Manual approvals enabled":"Fully automated enabled"]}),e("span",{className:`relative h-5 w-9 rounded-full transition ${P.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 ${P.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:P.scheduleKind,onInput:i=>O(m=>m&&{...m,scheduleKind:i.target.value}),children:[e("option",{value:"interval",children:"interval"}),e("option",{value:"cron",children:"cron"})]})]})}),P.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:P.cronExpression,onInput:i=>O(m=>m&&{...m,cronExpression:i.target.value}),placeholder:"0 9 * * *"})]}):e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Interval seconds"}),e("input",{type:"number",min:"1",className:"tcp-input",value:P.intervalSeconds,onInput:i=>O(m=>m&&{...m,intervalSeconds:i.target.value})})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>O(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>P&&W.mutate(P),disabled:W.isPending,children:[e("i",{"data-lucide":"check"}),"Save"]})]})]})}):null,ae?e(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>ue(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:()=>ue(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:ae.name,onInput:i=>ue(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:ae.description,onInput:i=>ue(m=>m&&{...m,description:i.target.value}),placeholder:"Add notes, delivery expectations, or operator guidance."})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Workspace root"}),e("input",{className:`tcp-input ${_n(ae.workspaceRoot)?"border-red-500/70 text-red-100":""}`,value:ae.workspaceRoot,onInput:i=>ue(m=>m&&{...m,workspaceRoot:i.target.value})}),_n(ae.workspaceRoot)?e("div",{className:"text-xs text-red-300",children:_n(ae.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:ae.scheduleKind,onInput:i=>ue(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:ae.executionMode,onInput:i=>ue(m=>m&&{...m,executionMode:i.target.value}),children:pa.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:ae.maxParallelAgents,onInput:i=>ue(m=>m&&{...m,maxParallelAgents:i.target.value}),disabled:ae.executionMode!=="swarm"})]})]}),ae.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:ae.cronExpression,onInput:i=>ue(m=>m&&{...m,cronExpression:i.target.value})})]}):ae.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:ae.intervalSeconds,onInput:i=>ue(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:ae.modelProvider,onInput:i=>ue(m=>m&&{...m,modelProvider:i.target.value,modelId:""}),children:[e("option",{value:"",children:"Workspace default"}),Fn(T.map(i=>i.id),ae.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:ae.modelId,onInput:i=>ue(m=>m&&{...m,modelId:i.target.value}),children:[e("option",{value:"",children:"Workspace default"}),Fn(T.find(i=>i.id===ae.modelProvider)?.models||[],ae.modelId).map(i=>e("option",{value:i,children:i},i))]}),gr(ae.modelProvider,ae.modelId)?e("div",{className:"text-xs text-red-300",children:gr(ae.modelProvider,ae.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:ae.plannerModelProvider,onInput:i=>ue(m=>m&&{...m,plannerModelProvider:i.target.value,plannerModelId:""}),children:[e("option",{value:"",children:"Use workflow model"}),Fn(T.map(i=>i.id),ae.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:ae.plannerModelId,onInput:i=>ue(m=>m&&{...m,plannerModelId:i.target.value}),children:[e("option",{value:"",children:"Use workflow model"}),Fn(T.find(i=>i.id===ae.plannerModelProvider)?.models||[],ae.plannerModelId).map(i=>e("option",{value:i,children:i},`planner-model-${i}`))]}),Vn(ae.plannerModelProvider,ae.plannerModelId)?e("div",{className:"text-xs text-red-300",children:Vn(ae.plannerModelProvider,ae.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 ${ae.toolAccessMode==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>ue(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 ${ae.toolAccessMode==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>ue(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."})]})]}),ae.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:ae.customToolsText,onInput:i=>ue(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"}),C.length?e("div",{className:"flex flex-wrap gap-2",children:C.map(i=>{const m=ae.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:()=>ue(E=>E&&{...E,selectedMcpServers:m?E.selectedMcpServers.filter(Y=>Y!==i.name):[...E.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."})]})}),ae.nodes.length?e("div",{className:"grid gap-3",children:ae.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:E=>ue(Y=>Y&&{...Y,nodes:Y.nodes.map(ce=>ce.nodeId===i.nodeId?{...ce,objective:E.target.value}:ce)}),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:()=>ue(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>ae&&ve.mutate(ae),disabled:ve.isPending,children:[e("i",{"data-lucide":"check"}),ve.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:De.isPending,onClick:()=>De.mutate({action:"delete",automationId:D.automationId,family:D.family},{onSettled:()=>x(null)}),children:[e("i",{"data-lucide":"trash-2"}),De.isPending?"Deleting...":"Delete automation"]})]})]})}):null]})]})}function Hu({client:a,toast:t}){const n=aa(),r=Z({queryKey:["automations","approvals"],queryFn:()=>a?.agentTeams?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),s=Z({queryKey:["automations","instances"],queryFn:()=>a?.agentTeams?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),l=xe({mutationFn:({requestId:p,decision:_})=>a?.agentTeams?.replyApproval?.(p,_),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["automations"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=Ma(r.data,"spawnApprovals"),u=Ma(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,_)=>{const D=String(p?.request_id||p?.id||`request-${_}`);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:()=>l.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:()=>l.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,_)=>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||_)))]}):null,!d.length&&!u.length?e(We,{text:"No pending approvals or active team instances."}):null]})}function Vu({client:a,api:t,toast:n,navigate:r,providerStatus:s}){const[l,d]=w("create"),[u,p]=w("simple"),[_,D]=w(""),[x,P]=w(null);return be(()=>{try{const k=sessionStorage.getItem(ks);if(!k)return;sessionStorage.removeItem(ks);const J=JSON.parse(k||"{}");J?.tab==="running"&&d("running");const A=String(J?.runId||"").trim();A&&D(A)}catch{}},[]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex gap-1 rounded-xl border border-slate-700/50 bg-slate-900/40 p-1",children:[{id:"create",label:"Create",icon:"sparkles"},{id:"list",label:"Automations",icon:"clipboard-list"},{id:"running",label:"Tasks",icon:"activity"},{id:"optimize",label:"Optimize",icon:"flask-conical"},{id:"approvals",label:"Teams",icon:"users"}].map(k=>e("button",{onClick:()=>d(k.id),className:`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-all ${l===k.id?"bg-amber-500/20 text-amber-300 shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[e("i",{"data-lucide":k.icon}),e("span",{children:k.label})]},k.id))}),e(Tt,{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:l==="create"?e(Kt,{title:"Create an Automation",subtitle:"Describe what you want, pick a schedule, and Tandem handles the rest",children:e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Builder Mode"}),e("div",{className:"tcp-subtle text-xs",children:"Keep the simple wizard for quick automations, or switch to the advanced swarm builder for orchestrated mission planning."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="simple"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>{p("simple"),P(null)},children:"Simple Wizard"}),e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="advanced"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>p("advanced"),children:"Advanced Swarm Builder"})]})]}),u==="advanced"?e(uu,{client:a,api:t,toast:n,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel,editingAutomation:x,onShowAutomations:()=>{P(null),d("list")},onShowRuns:()=>{P(null),d("running")},onClearEditing:()=>P(null)}):e(Gu,{client:a,api:t,toast:n,navigate:r,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel})]})}):l==="list"?e(Kt,{title:"My Automations",subtitle:"Installed packs, routines and run history",children:e(Cs,{client:a,toast:n,navigate:r,viewMode:"list",selectedRunId:_,onSelectRunId:D,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:k=>{P(k),p("advanced"),d("create")}})}):l==="running"?e(Kt,{title:"Live Running Tasks",subtitle:"Inspect active runs and open detailed event logs for each run",children:e(Cs,{client:a,toast:n,navigate:r,viewMode:"running",selectedRunId:_,onSelectRunId:D,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:k=>{P(k),p("advanced"),d("create")}})}):l==="optimize"?e(Kt,{title:"Workflow Optimization",subtitle:"Create and inspect overnight shadow-eval optimization campaigns",children:e(bu,{client:a,toast:n})}):e(Kt,{title:"Teams & Approvals",subtitle:"Active agent teams and pending spawn approvals",children:e(Hu,{client:a,toast:n})})},l)})]})}function Yu({client:a,toast:t}){const n=aa(),r=Z({queryKey:["channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),s=Z({queryKey:["channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),l=xe({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(Kt,{title:"Channels",subtitle:"Connector health and quick reconnect",children:e("div",{className:"grid gap-2",children:u.length?u.map(([p,_])=>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:_?.connected?"tcp-badge-ok":"tcp-badge-warn",children:_?.connected?"connected":"disconnected"})]}),e("div",{className:"tcp-subtle text-xs",children:String(_?.last_error||_?.error||"")||"No recent errors."}),e("div",{className:"mt-2",children:e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l.mutate(p),children:[e("i",{"data-lucide":"refresh-cw"}),"Reconnect"]})})]},p)):e(We,{text:"No channels configured."})})})})}function Ft(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Xe(a){return String(a||"").trim()}function br(a){try{return JSON.stringify(a,null,2)}catch{return"{}"}}function Xu(a){return a?"ok":"ghost"}function Zu(a){return Xe(a?.event_type||a?.type||a?.event||"workflow.event")}function em({api:a,toast:t}){const n=aa(),[r,s]=w(""),[l,d]=w(""),[u,p]=w(""),[_,D]=w("context.task.created"),[x,P]=w(`{
|
|
2455
|
+
"event_id": "demo-task-1"
|
|
2456
|
+
}`),[O,k]=w([]),J=Z({queryKey:["packs","list"],queryFn:()=>a("/api/engine/packs",{method:"GET"}).catch(()=>({packs:[]})),refetchInterval:15e3}),A=Z({queryKey:["workflows","list"],queryFn:()=>a("/api/engine/workflows",{method:"GET"}).catch(()=>({workflows:[]})),refetchInterval:15e3}),G=Z({queryKey:["workflows","hooks"],queryFn:()=>a("/api/engine/workflow-hooks",{method:"GET"}).catch(()=>({hooks:[]})),refetchInterval:15e3}),ee=Ft(J.data,"packs"),de=Ft(A.data,"workflows"),S=Ft(G.data,"hooks"),I=L(()=>l||Xe(ee[0]?.pack_id||ee[0]?.name),[ee,l]),Q=L(()=>u||Xe(de[0]?.workflow_id),[u,de]),R=Z({queryKey:["workflows","runs",Q],queryFn:()=>a(`/api/engine/workflows/runs${Q?`?workflow_id=${encodeURIComponent(Q)}&limit=20`:"?limit=20"}`,{method:"GET"}).catch(()=>({runs:[]})),refetchInterval:6e3}),we=Ft(R.data,"runs"),y=Z({queryKey:["packs","detail",I],enabled:!!I,queryFn:()=>a(`/api/engine/packs/${encodeURIComponent(I)}`,{method:"GET"})}),v=Z({queryKey:["workflows","detail",Q],enabled:!!Q,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(Q)}`,{method:"GET"})}),U=xe({mutationFn:()=>a("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:r,source:{kind:"control-panel"}})}),onSuccess:async()=>{t("ok","Pack installed."),s(""),await Promise.all([n.invalidateQueries({queryKey:["packs"]}),n.invalidateQueries({queryKey:["workflows"]})])},onError:M=>t("err",M instanceof Error?M.message:String(M))}),pe=xe({mutationFn:M=>a(`/api/engine/workflows/${encodeURIComponent(M)}/run`,{method:"POST"}),onSuccess:async M=>{t("ok",`Workflow ${Xe(M?.run?.workflow_id||Q)} started.`),await Promise.all([n.invalidateQueries({queryKey:["workflows"]}),n.invalidateQueries({queryKey:["workflows","runs"]})])},onError:M=>t("err",M instanceof Error?M.message:String(M))}),X=xe({mutationFn:async()=>{let M={};const he=Xe(x);return he&&(M=JSON.parse(he)),a("/api/engine/workflows/simulate",{method:"POST",body:JSON.stringify({event_type:_,properties:M})})},onError:M=>t("err",M instanceof Error?M.message:String(M))}),$e=xe({mutationFn:({bindingId:M,enabled:he})=>a(`/api/engine/workflow-hooks/${encodeURIComponent(M)}`,{method:"PATCH",body:JSON.stringify({enabled:he})}),onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:["workflows","hooks"]}),n.invalidateQueries({queryKey:["workflows","detail"]})])},onError:M=>t("err",M instanceof Error?M.message:String(M))}),Oe=y.data?.pack||null,Ke=v.data?.workflow||null,ae=Ft(v.data,"hooks"),ue=X.data?.simulation||null;return Va(`/api/engine/workflows/events${Q?`?workflow_id=${encodeURIComponent(Q)}`:""}`,M=>{try{const he=JSON.parse(M.data);if(he?.status==="ready")return;k(Te=>[...Te.slice(-59),{at:Date.now(),data:he}])}catch{}},{enabled:!0}),e(Mn,{className:"grid gap-4",children:[e(rc,{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(ta,{children:[e(je,{tone:"info",children:[ee.length," installed packs"]}),e(je,{tone:"warn",children:[de.length," workflows"]}),e(je,{tone:"ghost",children:[S.length," hooks"]})]})}),e(In,{main:e("div",{className:"grid gap-4",children:[e(ft,{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((M,he)=>{const Te=Xe(M?.pack_id||M?.name||he);return e("button",{type:"button",className:`tcp-list-item text-left ${Te===I?"border-amber-400/70":""}`,onClick:()=>d(Te),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Xe(M?.name||Te)}),e("span",{className:"tcp-badge-info",children:Xe(M?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-subtle",children:Xe(M?.pack_type||"pack")}),e("span",{className:"tcp-subtle",children:Xe(M?.install_path||"")})]})]},Te)}):e(We,{text:"No packs are installed yet."})})}),e(ft,{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:de.length?de.map(M=>{const he=Xe(M?.workflow_id),Te=he===Q,Re=Xe(M?.source?.kind||"unknown");return e("button",{type:"button",className:`tcp-list-item text-left ${Te?"border-amber-400/70":""}`,onClick:()=>p(he),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Xe(M?.name||he)}),e("span",{className:`tcp-badge-${Re==="pack"?"warn":"info"}`,children:Re})]}),e("div",{className:"tcp-subtle text-xs",children:[he," · ",Ft(M?.steps,"steps").length," steps"]})]},he)}):e(We,{text:"No workflows are currently registered."})})})]}),aside:e("div",{className:"grid gap-4",children:[e(ft,{title:"Install pack",subtitle:"Install a local pack path and reload workflow contributions automatically.",children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:r,onInput:M=>s(M.target.value),placeholder:"/path/to/pack.zip"}),e("button",{className:"tcp-btn-primary",disabled:!r.trim()||U.isPending,onClick:()=>U.mutate(),children:[e("i",{"data-lucide":"download"}),"Install from path"]})]})}),e(ft,{title:"Pack inspector",subtitle:"Shows which workflows and hooks a pack contributes, alongside its current capability surface.",children:Oe?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Xe(Oe?.installed?.name||I)}),e(je,{tone:"info",children:Xe(Oe?.installed?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e(je,{tone:"ghost",children:[Number(Oe?.workflow_extensions?.workflow_count||0)," ","workflows"]}),e(je,{tone:"ghost",children:[Number(Oe?.workflow_extensions?.workflow_hook_count||0)," ","hooks"]}),e(je,{tone:"ghost",children:[Number(Oe?.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"}),Ft(Oe?.workflow_extensions,"workflow_entrypoints").length?Ft(Oe?.workflow_extensions,"workflow_entrypoints").map((M,he)=>e("div",{className:"tcp-list-item text-sm",children:Xe(M)},`${Xe(M)}-${he}`)):e(We,{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:br(Oe?.manifest||{})})]})]}):e(We,{text:"Select an installed pack to inspect workflow extensions."})})]})}),e(In,{main:e(ft,{title:"Workflow viewer",subtitle:"Structured view of workflow steps and source provenance for the selected workflow.",actions:e("button",{className:"tcp-btn",disabled:!Q||pe.isPending,onClick:()=>Q&&pe.mutate(Q),children:[e("i",{"data-lucide":"play"}),"Run workflow"]}),children:Ke?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:Xe(Ke?.name||Q)}),e(je,{tone:"info",children:Xe(Ke?.source?.kind||"unknown")})]}),e("div",{className:"tcp-subtle text-sm",children:Xe(Ke?.description||"No description provided.")})]}),e("div",{className:"grid gap-2",children:Ft(Ke,"steps").length?Ft(Ke,"steps").map((M,he)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 text-xs uppercase tracking-[0.24em] text-slate-400",children:["Step ",he+1]}),e("div",{className:"font-medium",children:Xe(M?.action||"unknown")}),M?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:br(M.with)}):null]},Xe(M?.step_id||he))):e(We,{text:"This workflow does not define any linear steps."})})]}):e(We,{text:"Select a workflow to inspect its current resolved definition."})}),aside:e("div",{className:"grid gap-4",children:[e(ft,{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:ae.length?ae.map(M=>{const he=Xe(M?.binding_id),Te=!!M?.enabled;return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:Xe(M?.event||he)}),e("div",{className:"tcp-subtle text-xs",children:he})]}),e("button",{className:"tcp-btn",disabled:$e.isPending,onClick:()=>$e.mutate({bindingId:he,enabled:!Te}),children:Te?"Disable":"Enable"})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e(je,{tone:Xu(Te),children:Te?"Enabled":"Disabled"}),e(je,{tone:"ghost",children:[Ft(M,"actions").length," actions"]})]}),e("div",{className:"grid gap-1",children:Ft(M,"actions").map((Re,re)=>e("div",{className:"tcp-subtle text-xs",children:Xe(Re?.action||Re)},`${he}-${re}`))})]},he)}):e(We,{text:"The selected workflow has no registered hooks."})})}),e(ft,{title:"Recent workflow runs",subtitle:"Latest workflow executions for the selected workflow, including hook-triggered runs.",children:e("div",{className:"grid gap-2",children:we.length?we.map((M,he)=>{const Te=Xe(M?.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:Xe(M?.run_id||`run-${he+1}`)}),e(je,{tone:Re,children:Te})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger: ",Xe(M?.trigger_event||"manual")]}),e("div",{className:"tcp-subtle text-xs",children:["actions: ",Ft(M,"actions").length]})]},Xe(M?.run_id||he))}):e(We,{text:"No workflow runs have been recorded yet."})})})]})}),e(In,{main:e(ft,{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:!_.trim()||X.isPending,onClick:()=>X.mutate(),children:[e("i",{"data-lucide":"flask-conical"}),"Simulate"]}),children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:_,onInput:M=>D(M.target.value),placeholder:"context.task.created"}),e("textarea",{className:"tcp-input min-h-[180px] font-mono text-xs",value:x,onInput:M=>P(M.target.value),spellCheck:!1}),ue?e("div",{className:"grid gap-3",children:[e("div",{className:"flex flex-wrap gap-2",children:Ft(ue,"canonical_events").map((M,he)=>e(je,{tone:"info",children:Xe(M)},`${Xe(M)}-${he}`))}),e("div",{className:"grid gap-2",children:Ft(ue,"matched_bindings").length?Ft(ue,"matched_bindings").map(M=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:Xe(M?.binding_id)}),e("div",{className:"tcp-subtle text-xs",children:[Xe(M?.event)," · ",Ft(M,"actions").length," ","actions"]})]},Xe(M?.binding_id))):e(We,{text:"No workflow hooks matched this event."})})]}):e(We,{text:"Run a simulation to inspect canonical events, matched bindings, and planned actions."})]})}),aside:e(ft,{title:"Triggered actions",subtitle:"Preview of actions the engine plans to execute for the simulated event.",children:e("div",{className:"grid gap-2",children:Ft(ue,"planned_actions").length?Ft(ue,"planned_actions").map((M,he)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:Xe(M?.action||M)}),M?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:br(M.with)}):null]},`${Xe(M?.action||M)}-${he}`)):e(We,{text:"No planned actions yet."})})})}),e(ft,{title:"Live workflow events",subtitle:"Real-time `workflow.*` events for the selected workflow, including run start, action completion, and failures.",actions:e("button",{className:"tcp-btn",onClick:()=>k([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear stream"]}),children:e("div",{className:"grid max-h-[28rem] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:O.length?[...O].reverse().map((M,he)=>{const Te=Zu(M.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(je,{tone:Re,children:new Date(M.at).toLocaleTimeString()})]}),e("div",{className:"tcp-subtle text-xs",children:["run: ",Xe(M.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle text-xs",children:["action:"," ",Xe(M.data?.properties?.action||M.data?.properties?.actionID||"-")]})]},`${M.at}-${he}`)}):e(We,{text:"Run a workflow or trigger a hook to watch live workflow events here."})})})]})}function Pi(a){return a>=1?"bg-rose-500":a>=.8?"bg-amber-500":"bg-emerald-500"}function Sn(a,t){return!t||t<=0?0:Math.min(a/t,1)}function Ln({label:a,used:t,max:n,unit:r,advisory:s=!1}){const l=Sn(t,n),d=s?l>=.8?"bg-sky-400":"bg-cyan-500":Pi(l);return e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center justify-between text-xs",children:[e("span",{className:"tcp-subtle",children:a}),e("span",{className:"font-mono text-[11px] text-slate-200",children:[t.toLocaleString(),r||""," / ",n.toLocaleString(),r||""]})]}),e("div",{className:"h-1.5 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${d}`,style:{width:`${l*100}%`}})})]})}function tm({budget:a}){const[t,n]=w(!1),r=a.limits_enforced===!1,s=Math.max(Sn(a.iterations_used,a.max_iterations),Sn(a.tokens_used,a.max_tokens),Sn(a.wall_time_secs,a.max_wall_time_secs),Sn(a.subagent_runs_used,a.max_subagent_runs));return e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/25 p-3",children:[e("button",{className:"flex w-full items-center justify-between",onClick:()=>n(l=>!l),children:[e("div",{className:"text-sm font-medium",children:"Budget + Tokens"}),e("div",{className:"flex items-center gap-2",children:[e("div",{className:"h-2 w-24 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${r?s>=.8?"bg-sky-400":"bg-cyan-500":Pi(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(Ln,{label:"Iterations",used:a.iterations_used,max:a.max_iterations,advisory:r}),e(Ln,{label:"Tokens",used:a.tokens_used,max:a.max_tokens,advisory:r}),e(Ln,{label:"Wall time",used:a.wall_time_secs,max:a.max_wall_time_secs,unit:"s",advisory:r}),e(Ln,{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 Ar(a,t=0){return String(a?.run_id||a?.runId||`run-${t}`).trim()}function As(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 am(a,t=""){const n=String(t||"").trim(),r=[...Array.isArray(a)?a:[]].sort((d,u)=>As(u)-As(d));if(n){const d=r.find((u,p)=>Ar(u,p)===n);if(d){const u=String(d?.status||"").trim().toLowerCase();if(!["completed","failed","cancelled"].includes(u))return n}}const l=r.find(d=>{const u=String(d?.status||"").trim().toLowerCase();return!["completed","failed","cancelled"].includes(u)})||r[0];return l?Ar(l):""}function nm(a,t){if(t.type==="sync_runs"){const n={},r=[];for(let l=0;l<t.runs.length;l+=1){const d=t.runs[l],u=Ar(d,l);u&&(n[u]=d,r.push(u))}let s=a.selectedRunId;return s||(s=am(t.runs,t.preferredRunId)),{runsById:n,orderedRunIds:r,selectedRunId:s,cursorsByRunId:a.cursorsByRunId}}if(t.type==="select_run")return{...a,selectedRunId:String(t.runId||"").trim()};if(t.type==="clear_selection")return{...a,selectedRunId:""};if(t.type==="advance_cursor"){const n=String(t.runId||"").trim();if(!n)return a;const r=Number(t.seq||0);if(!Number.isFinite(r)||r<=0)return a;const s=String(t.kind||"").trim().toLowerCase(),l=a.cursorsByRunId[n]||{eventSeq:0,patchSeq:0},d={eventSeq:s==="context_run_event"?Math.max(l.eventSeq,r):l.eventSeq,patchSeq:s==="blackboard_patch"?Math.max(l.patchSeq,r):l.patchSeq};return d.eventSeq===l.eventSeq&&d.patchSeq===l.patchSeq?a:{...a,cursorsByRunId:{...a.cursorsByRunId,[n]:d}}}return a}function rm(a,t=""){const[n,r]=Di(nm,{runsById:{},orderedRunIds:[],selectedRunId:"",cursorsByRunId:{}});be(()=>{r({type:"sync_runs",runs:Array.isArray(a)?a:[],preferredRunId:t})},[a,t]);const s=L(()=>n.orderedRunIds.map(l=>n.runsById[l]).filter(Boolean),[n.orderedRunIds,n.runsById]);return{runsById:n.runsById,orderedRunIds:n.orderedRunIds,orderedRuns:s,selectedRunId:n.selectedRunId,cursorsByRunId:n.cursorsByRunId,setSelectedRunId:l=>r({type:"select_run",runId:l}),clearSelectedRunId:()=>r({type:"clear_selection"}),advanceCursor:(l,d,u)=>r({type:"advance_cursor",runId:l,kind:d,seq:u})}}function sm(a){const t={},n={};for(const[l,d]of Object.entries(a||{})){const u=Number(d?.eventSeq||0),p=Number(d?.patchSeq||0);u>0&&(t[l]=u),p>0&&(n[l]=p)}const s=JSON.stringify({events:t,patches:n});return!s||s==='{"events":{},"patches":{}}'?"":btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function im({workspace:a,runIds:t,cursorToken:n,onEnvelope:r,onError:s}){const l=L(()=>[...new Set((t||[]).map(u=>String(u||"").trim()).filter(Boolean))],[t]),d=L(()=>{const u=String(a||"").trim();if(!u||!l.length)return"";const p=new URLSearchParams;return p.set("workspace",u),p.set("runIds",l.join(",")),n&&p.set("cursor",n),`/api/orchestrator/events?${p.toString()}`},[n,l,a]);be(()=>{if(!d)return;const u=Mr(d,p=>{let _=null;try{_=JSON.parse(String(p?.data||"{}"))}catch{return}!_||typeof _!="object"||r(_)},{onError:p=>{s&&s(p)}});return()=>u()},[r,s,d])}const om={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 Ia(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 lm(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 Ps(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"Run":`Run ${new Date(t).toLocaleTimeString()}`}function cm(a){return Number(a?.updated_at_ms||a?.created_at_ms||0)}function Ba(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"--:--:--":new Date(t).toLocaleTimeString()}function dm(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 um(a){const t=String(a||"").trim(),n=t.lastIndexOf(".");return n<0?"":t.slice(n+1).toLowerCase()}function Rn(a){const t=String(a||"").trim().replace(/\\/g,"/");return t?t.startsWith("/")?t.replace(/\/{2,}/g,"/"):t:""}function mm(a,t){const n=Rn(a).replace(/\/+$/,""),r=Rn(t).replace(/^\/+/,"");return n?r?`${n}/${r}`:n:r}function Ts(a,t){const n=Rn(a).replace(/\/+$/,""),r=Rn(t);return!n||!r?!1:r===n?!0:r.startsWith(`${n}/`)}function Rs(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=Rn(String(n||""));if(r.startsWith("/"))return r}return""}function qs(a){const t={};for(const n of a){const r=String(n?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(r))continue;const s=String(n?.step_id||"").trim();if(!s)continue;const l=Number(n?.seq||0);!Number.isFinite(l)||l<=0||(t[s]=Math.max(Number(t[s]||0),l))}return t}function pm(a){return String(a?.event_type||a?.type||a?.event||"workflow.event").trim().toLowerCase()}function Ms(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: ${Ba(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 on(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 hm({api:a,toast:t,navigate:n}){const r=aa(),s=!!Fs(),l=Pt(null),[d,u]=w(!0),[p,_]=w(!1),[D,x]=w(""),[P,O]=w(""),[k,J]=w(!1),[A,G]=w(""),[ee,de]=w(""),[S,I]=w(!1),[Q,R]=w("4"),[we,y]=w("3"),[v,U]=w("swarm.blackboard.default"),[pe,X]=w(""),[$e,Oe]=w(""),[Ke,ae]=w(""),[ue,M]=w(""),[he,Te]=w([]),[Re,re]=w(""),[Ue,qe]=w(""),[ze,V]=w(""),[He,ne]=w(!1);be(()=>{u(!0),ot()},[]);const Ie=Z({queryKey:["swarm","status"],queryFn:()=>a("/api/orchestrator/status"),refetchInterval:5e3}),ht=Z({queryKey:["swarm","runs",P],queryFn:()=>a(`/api/orchestrator/runs?workspace=${encodeURIComponent(P||"")}`),refetchInterval:6e3,enabled:!!Ie.data}),se=Array.isArray(ht.data?.runs)?ht.data.runs:[],F=rm(se,String(Ie.data?.runId||"").trim()),rt=F.selectedRunId,mt=F.setSelectedRunId,ot=F.clearSelectedRunId,St=F.advanceCursor,Ee=d?"":String(rt||"").trim(),Rt=F.orderedRuns,yt=L(()=>{if(!Ee)return null;for(const f of Rt)if(String(f?.run_id||f?.runId||"").trim()===Ee)return f;return null},[Rt,Ee]),Ot=L(()=>sm(F.cursorsByRunId),[F.cursorsByRunId]),Je=String(P||Ie.data?.workspaceRoot||"").trim(),Qe=L(()=>{const f=String(Ee||"").trim();return f?[f]:[]},[Ee]),nt=Pt(0),ye=ut(f=>{const B=String(f?.kind||"").trim().toLowerCase(),me=String(f?.run_id||f?.runId||"").trim();if(Ee&&me&&me!==Ee)return;const Le=Number(f?.seq||0);me&&Le>0&&(B==="context_run_event"||B==="blackboard_patch")&&St(me,B,Le);const Fe=Date.now();Fe-nt.current<900||(nt.current=Fe,r.invalidateQueries({queryKey:["swarm","runs"]}),Ee&&r.invalidateQueries({queryKey:["swarm","run",Ee]}))},[St,r,Ee]);im({workspace:Je,runIds:Qe,cursorToken:Ot,onEnvelope:ye});const Ne=Z({queryKey:["swarm","run",Ee],queryFn:()=>a(`/api/orchestrator/run/${encodeURIComponent(Ee)}`),refetchInterval:4e3,enabled:!!Ee}),Ve=Z({queryKey:["swarm","workspace-browser",A],enabled:k&&!!A,queryFn:()=>a(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(A)}`)}),le=String(Ne.data?.runStatus||Ne.data?.run?.status||Ie.data?.status||"idle").trim().toLowerCase(),it=L(()=>wi(Ne.data),[Ne.data]),N=it.tasks,W=L(()=>({...om,...Ne.data?.budget||{}}),[Ne.data?.budget]),ve=String(Rs(Ne.data?.run)||Rs(yt)||(Ee?"":String(Ie.data?.workspaceRoot||P||""))).trim();be(()=>{ve&&(Oe(f=>!f||!Ts(ve,f)?ve:f),ae(f=>Ts(ve,f)?f:""))},[ve]);const De=Array.isArray(Ve.data?.directories)?Ve.data.directories:[],o=String(ee||"").trim().toLowerCase(),b=L(()=>o?De.filter(f=>String(f?.name||f?.path||"").trim().toLowerCase().includes(o)):De,[De,o]),T=String(Ve.data?.parent||"").trim(),C=String(Ve.data?.dir||A||"").trim(),$=Z({queryKey:["swarm","workspace-files",ve,$e],enabled:!!ve&&!!$e,queryFn:async()=>{const f=await a(`/api/orchestrator/workspaces/files?workspaceRoot=${encodeURIComponent(ve)}&dir=${encodeURIComponent($e)}`).catch(()=>({directories:[],files:[],parent:null,dir:$e})),B=Array.isArray(f?.directories)?f.directories:[],Le=(Array.isArray(f?.files)?f.files:[]).map(Fe=>{const tt=String(Fe?.path||"").trim();return{...Fe,name:String(Fe?.name||tt||"file"),path:tt||mm(ve,String(Fe?.name||""))}});return{ok:!0,dir:String(f?.dir||$e),parent:f?.parent||null,directories:B,files:Le,fileAccessAllowed:!0}},refetchInterval:1e4}),Ye=Z({queryKey:["swarm","workspace-file",ve,Ke],enabled:!!ve&&!!Ke,queryFn:async()=>a(`/api/orchestrator/workspaces/read?workspaceRoot=${encodeURIComponent(ve)}&path=${encodeURIComponent(Ke)}`)}),Ze=Array.isArray($.data?.directories)?$.data.directories:[],bt=Array.isArray($.data?.files)?$.data.files:[],qt=String($.data?.parent||"").trim(),Ae=$.data?.fileAccessAllowed!==!1,wt=String(Ye.data?.text||""),It=um(Ke),te=["md","markdown","mdx"].includes(It),_e=["html","htm"].includes(It);be(()=>{He&&!_e&&ne(!1)},[_e,He]);const h=L(()=>N.map(f=>`${f.id}:${f.state}:${f.error_message||""}`).join("|"),[N]),j=L(()=>N.find(f=>f.id===Ue)||null,[Ue,N]),z=L(()=>{const f=Array.isArray(Ne.data?.events)?Ne.data.events:[];let B=null,me=0;for(const Le of f){const Fe=String(Le?.type||"").trim().toLowerCase();if(!["step_completed","task_completed"].includes(Fe))continue;const tt=Le?.payload&&typeof Le.payload=="object"?Le.payload:{},_t=String(tt?.session_id||"").trim();if(!_t)continue;const Jt=Number(Le?.ts_ms||0);(!B||Jt>=me)&&(B={sessionId:_t,event:Le},me=Jt)}return B},[Ne.data?.events]),K=L(()=>{const f=Array.isArray(Ne.data?.events)?Ne.data.events:[];for(let B=f.length-1;B>=0;B-=1){const me=f[B],Le=String(me?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(Le))continue;const Fe=me?.payload&&typeof me.payload=="object"?me.payload:{},tt=String(Fe?.session_id||"").trim();if(tt)return tt}return String(z?.sessionId||"").trim()},[z?.sessionId,Ne.data?.events]),H=L(()=>{const f=Array.isArray(Ne.data?.events)?Ne.data.events:[],B=qs(f),me=[];for(let Le=f.length-1;Le>=0;Le-=1){const Fe=f[Le],tt=String(Fe?.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(tt))continue;const _t=Fe?.payload&&typeof Fe.payload=="object"?Fe.payload:{},Jt=String(Fe?.step_id||"").trim(),sa=Number(Fe?.seq||0);if((tt==="task_failed"||tt==="step_failed")&&Jt&&Number.isFinite(sa)&&sa>0&&Number(B[Jt]||0)>sa)continue;const Xt=String(_t?.step_title||Fe?.step_id||tt).trim(),wa=String(_t?.why_next_step||_t?.error||"").trim();if(me.push({id:`${String(Fe?.seq||Le)}-${tt}`,type:tt,title:Xt||tt,detail:wa,at:Number(Fe?.ts_ms||0)}),me.length>=12)break}return me},[Ne.data?.events]),fe=L(()=>{const f=Array.isArray(Ne.data?.events)?Ne.data.events:[];for(let B=f.length-1;B>=0;B-=1){const me=f[B],Le=String(me?.type||"").trim().toLowerCase();if(Le==="plan_seeded_llm")return"llm";if(Le==="plan_seeded_local")return"fallback_local";if(Le==="plan_failed_llm_required")return"llm_failed"}return"unknown"},[Ne.data?.events]),Be=Z({queryKey:["swarm","run-output-session",String(K||"")],queryFn:()=>a(`/api/engine/session/${encodeURIComponent(String(K||""))}`),refetchInterval:6e3,enabled:!!K}),pt=L(()=>{const f=ai(Be.data,"Assistant");for(let B=f.length-1;B>=0;B-=1)if(f[B]?.role==="assistant"&&String(f[B]?.text||"").trim())return String(f[B]?.text||"").trim();return""},[Be.data]),lt=L(()=>{const f=Array.isArray(Be.data)?Be.data:Array.isArray(Be.data?.messages)?Be.data.messages:[],B=[];for(let me=f.length-1;me>=0;me-=1){const Le=f[me],Fe=Array.isArray(Le?.parts)?Le.parts:[];for(let tt=Fe.length-1;tt>=0;tt-=1){const _t=Fe[tt];if(!String(_t?.type||_t?.part_type||"").trim().toLowerCase().includes("tool"))continue;const sa=String(_t?.tool||_t?.name||"").trim(),Qt=String(_t?.state||_t?.status||"").trim(),Xt=String(_t?.error||"").trim(),wa=[sa||"tool",Qt||null,Xt?`err=${Xt}`:null].filter(Boolean).join(" · ");if(B.push(wa),B.length>=10)return B}}return B},[Be.data]),xt=L(()=>{const f=Array.isArray(Ne.data?.events)?Ne.data.events:[],B=qs(f),me=[];for(let Le=f.length-1;Le>=0;Le-=1){const Fe=f[Le],tt=String(Fe?.type||"").trim().toLowerCase();if(!["task_failed","step_failed","task_completed","step_completed"].includes(tt))continue;const _t=Fe?.payload&&typeof Fe.payload=="object"?Fe.payload:{},Jt=String(Fe?.step_id||"").trim(),sa=Number(Fe?.seq||0);if((tt==="task_failed"||tt==="step_failed")&&Jt&&Number.isFinite(sa)&&sa>0&&Number(B[Jt]||0)>sa)continue;const Xt=_t?.verification&&typeof _t.verification=="object"?_t.verification:{},wa=String(Xt?.reason||_t?.error||"").trim(),Ka=String(Xt?.mode||"strict").trim()||"strict";if(me.push({id:`${String(Fe?.seq||Le)}-${tt}`,taskId:Jt,title:String(_t?.step_title||Fe?.step_id||tt),type:tt,reason:wa,mode:Ka,at:Number(Fe?.ts_ms||0),verification:Xt}),me.length>=8)break}return me},[Ne.data?.events]),et=L(()=>xt.find(f=>f.id===ze)||null,[ze,xt]);be(()=>{if(!et&&!j&&!He||typeof document>"u")return;const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=f}},[et,j,He]);const kt=String(Ne.data?.run?.workflowId||Ne.data?.run?.workflow_id||yt?.workflowId||yt?.workflow_id||v||"").trim(),Et=Z({queryKey:["workflow","detail",kt],enabled:!!kt,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(kt)}`),refetchInterval:15e3}),Wt=Z({queryKey:["workflow","runs",kt],enabled:!!kt,queryFn:()=>a(`/api/engine/workflows/runs?workflow_id=${encodeURIComponent(kt)}&limit=12`).catch(()=>({runs:[]})),refetchInterval:5e3}),vt=Array.isArray(Wt.data?.runs)?Wt.data.runs:[],ct=L(()=>{const f={};for(const B of vt){const me=on(B);if(!me)continue;const Le=f[me]||{runs:0,failed:0};Le.runs+=1,String(B?.status||"").trim().toLowerCase()==="failed"&&(Le.failed+=1),f[me]=Le}return f},[vt]),Se=L(()=>Re?vt.filter(f=>on(f)===Re):vt,[Re,vt]),Pe=L(()=>{const f=[];for(const B of Se){const me=String(B?.run_id||"").trim(),Le=on(B);for(const Fe of Array.isArray(B?.actions)?B.actions:[])f.push({id:`${me}:${String(Fe?.action_id||Fe?.action||f.length)}`,runId:me,action:String(Fe?.action||"unknown action"),status:String(Fe?.status||"unknown"),detail:String(Fe?.detail||""),output:Fe?.output,updatedAt:Number(Fe?.updated_at_ms||B?.updated_at_ms||0),taskId:String(Fe?.task_id||Le||"").trim()})}return f.sort((B,me)=>me.updatedAt-B.updatedAt),f},[Se]);be(()=>{const f=Se;if(!f.length){M("");return}f.some(me=>{const Le=String(me?.run_id||"").trim();return Le&&Le===ue})||M(String(f[0]?.run_id||"").trim())},[Se,ue]);const ke=Z({queryKey:["workflow","run",ue],enabled:!!ue,queryFn:()=>a(`/api/engine/workflows/runs/${encodeURIComponent(ue)}`),refetchInterval:5e3}).data?.run||null;be(()=>{const f=on(ke);f&&re(f)},[ke?.run_id,ke?.source_event_id]),be(()=>{Te([])},[kt]),Va(`/api/engine/workflows/events${kt?`?workflow_id=${encodeURIComponent(kt)}`:""}`,f=>{try{const B=JSON.parse(f.data);if(B?.status==="ready")return;Te(me=>[...me.slice(-79),{at:Date.now(),data:B}])}catch{}},{enabled:!!kt});const ge=xe({mutationFn:()=>{const f=String(D||"").trim(),B=String(P||"").trim();if(!f)throw new Error("Enter a prompt first.");if(!B)throw new Error("Set workspace path first.");return a("/api/orchestrator/start",{method:"POST",body:JSON.stringify({objective:f,workspaceRoot:B,maxTasks:Number(Q||4),maxAgents:Number(we||3),workflowId:String(v||"swarm.blackboard.default").trim(),requireLlmPlan:!0,allowLocalPlannerFallback:!1,verificationMode:"strict"})})},onSuccess:async f=>{const B=String(f?.runId||"").trim();B&&mt(B),u(!1),t("ok","Planning started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),dt=xe({mutationFn:({path:f,body:B})=>a(f,{method:"POST",body:JSON.stringify(B)}),onSuccess:async(f,B)=>{if(B.path==="/api/orchestrator/request_revision"){const me=String(f?.runId||"").trim();me&&(mt(me),X("")),t("ok","Reworked plan created.")}B.path==="/api/orchestrator/approve"&&t("ok","Execution started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),Ge=xe({mutationFn:async f=>{const B=String(f||"").trim();if(!B)throw new Error("Missing run id.");return await a("/api/orchestrator/cancel",{method:"POST",body:JSON.stringify({runId:B})}).catch(()=>null),await a("/api/orchestrator/runs/hide",{method:"POST",body:JSON.stringify({runIds:[B]})}).catch(()=>null),B},onSuccess:async()=>{ot(),u(!0),X(""),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))}),Nt=ut(()=>{u(!0),ot(),_(!1),X("")},[ot]);be(()=>{const f=l.current;f&&ya(f)},[d,p,Rt,Ee,le,$e,Ze.length,bt.length,Ke,wt,Ue,ze,He,h]);const Ut=!Ee,ra=le==="planning"||le==="queued",Mt=le==="awaiting_approval",zt=["completed","failed","cancelled"].includes(le),Ct=le==="running",Vt=le==="paused",Yt=le==="failed"||le==="blocked",ua=["queued","planning","awaiting_approval","running","paused","blocked"].includes(le),Na=e(ta,{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(Tt,{children:Rt.map((f,B)=>{const me=String(f?.run_id||f?.runId||`run-${B}`),Le=me===Ee;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 ${Le?"active":""}`,onClick:()=>{u(!1),mt(me),_(!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:Ps(cm(f))})]}),e("span",{className:"tcp-subtle line-clamp-2 block text-[11px]",children:String(f?.objective||"").trim()||"No objective"})]})},me)})}),Rt.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No runs yet."})]})]}),e(Tt,{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:()=>_(!1)}):null})]});if(Ut){const f=String(D||"").trim().length>0&&String(P||"").trim().length>0;return e(ta,{children:[e("div",{ref:l,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[Na,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:()=>_(B=>!B),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:B=>x(B.target.value)}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr]",children:[e("button",{className:"tcp-btn",onClick:()=>{const B=String(P||Ie.data?.workspaceRoot||"/").trim();G(B||"/"),de(""),J(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,placeholder:"No workspace selected. Use Browse.",value:P})]}),e("div",{className:"tcp-subtle text-xs",children:["Selected folder: ",P||"none"]}),P?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:()=>ge.mutate(),disabled:ge.isPending||!f,children:[e("i",{"data-lucide":"send"}),"Send"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>I(B=>!B),children:[e("i",{"data-lucide":"sliders-horizontal"}),S?"Hide Advanced":"Show Advanced"]})]}),S?e("div",{className:"grid gap-2 rounded-lg border border-slate-700/60 bg-slate-900/20 p-2 md:grid-cols-3",children:[e("input",{className:"tcp-input",type:"number",min:"1",value:Q,onInput:B=>R(B.target.value),title:"max tasks"}),e("input",{className:"tcp-input",type:"number",min:"1",max:"16",value:we,onInput:B=>y(B.target.value),title:"max agents"}),e("input",{className:"tcp-input",value:v,onInput:B=>U(B.target.value),title:"workflow id"}),e("div",{className:"tcp-subtle md:col-span-3 text-xs",children:"Workflow id controls task routing template. Keep default unless you have a custom workflow."})]}):null]})]})})]}),k?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",C||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{T&&G(T)},disabled:!T,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{C&&(O(C),J(!1),de(""),t("ok",`Workspace selected: ${C}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{J(!1),de("")},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:B=>de(B.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:b.length?b.map(B=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>G(String(B?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(B?.name||B?.path||"")]},String(B?.path||B?.name))):e(We,{text:o?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}return e(ta,{children:[e("div",{ref:l,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[Na,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:()=>_(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:Nt,children:e("i",{"data-lucide":"arrow-left-to-line"})}),e("span",{children:"Orchestration Run"})]}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Plan review and execution"})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Ia(le),children:le||"unknown"}),e("span",{className:"inline-flex items-center gap-1 tcp-subtle",children:[e("i",{"data-lucide":"history"}),e("span",{children:Ps(Ne.data?.run?.updated_at_ms||Ne.data?.run?.created_at_ms)})]}),e("span",{className:"tcp-subtle",children:["id: ",Ee]}),e("span",{className:"tcp-subtle",children:["plan: ",fe]})]}),ra?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,Mt?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:pe,onInput:f=>X(f.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",disabled:!pe.trim(),onClick:()=>dt.mutate({path:"/api/orchestrator/request_revision",body:{runId:Ee,feedback:pe,maxTasks:Number(Q||4),maxAgents:Number(we||3),workflowId:v}}),children:[e("i",{"data-lucide":"pencil"}),"Rework Plan"]}),e("button",{className:"tcp-btn-primary",onClick:()=>dt.mutate({path:"/api/orchestrator/approve",body:{runId:Ee}}),children:[e("i",{"data-lucide":"play"}),"Execute Plan"]}),e("button",{className:"tcp-btn-danger",disabled:Ge.isPending,onClick:()=>Ge.mutate(Ee),children:[e("i",{"data-lucide":"trash-2"}),"Discard Plan"]})]})]}):null,!ra&&!Mt?e("div",{className:"mb-3 flex flex-wrap gap-2",children:[Ct?e("button",{className:"tcp-btn",onClick:()=>dt.mutate({path:"/api/orchestrator/pause",body:{runId:Ee}}),children:[e("i",{"data-lucide":"square"}),"Pause"]}):null,Vt?e("button",{className:"tcp-btn",onClick:()=>dt.mutate({path:"/api/orchestrator/resume",body:{runId:Ee}}),children:[e("i",{"data-lucide":"play"}),"Resume"]}):null,Yt?e("button",{className:"tcp-btn",onClick:()=>dt.mutate({path:"/api/orchestrator/continue",body:{runId:Ee}}),children:[e("i",{"data-lucide":"rotate-cw"}),"Continue Run"]}):null,ua?e("button",{className:"tcp-btn-danger",onClick:()=>dt.mutate({path:"/api/orchestrator/cancel",body:{runId:Ee}}),children:[e("i",{"data-lucide":"x"}),"Cancel"]}):null,e("button",{className:"tcp-btn",onClick:Nt,children:[e("i",{"data-lucide":"plus"}),"New Prompt"]})]}):null,zt?e("div",{className:"mb-3 rounded-lg border border-slate-700/60 bg-slate-900/25 p-2 text-xs tcp-subtle",children:le==="failed"?"This run is failed. Continue the run or retry a failed task.":`This run is ${le}. Start a new prompt to continue.`}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workspace Files"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Refresh","aria-label":"Refresh",onClick:()=>{$.refetch()},disabled:!ve,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:!qt,onClick:()=>{qt&&Oe(qt)},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:!ve,onClick:()=>{ve&&Oe(ve)},children:e("i",{"data-lucide":"home"})})]}),e("div",{className:"mb-2 tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:$e||ve||"No workspace"}),Ae?null:e("div",{className:"mb-2 rounded-lg border border-amber-400/40 bg-amber-950/20 p-2 text-xs text-amber-200",children:"File listing for this workspace is not exposed by the current server scope. Directory navigation still works."}),e("div",{className:"grid max-h-[220px] min-h-0 gap-1 overflow-auto",children:[Ze.map(f=>{const B=String(f?.path||"");return e("button",{className:"tcp-list-item text-left",onClick:()=>Oe(B),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(f?.name||B)})]})},`dir-${B}`)}),bt.map(f=>{const B=String(f?.path||"");return e("button",{className:`tcp-list-item text-left ${B===Ke?"border-amber-400/70":""}`,onClick:()=>ae(B),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||B)})]}),e("span",{className:"tcp-subtle shrink-0 text-[11px]",children:dm(f?.size)})]})},`file-${B}`)}),!Ze.length&&!bt.length?e(We,{text:"No files or folders in this workspace location."}):null]})]}),Ke?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:[_e?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:Ke})]})]}),Ye.isLoading?e("div",{className:"tcp-subtle text-xs",children:"Loading file..."}):_e?e("div",{className:"max-h-[420px] overflow-auto rounded-lg border border-slate-700/60 bg-black",children:e("iframe",{className:"h-[420px] w-full bg-black",sandbox:"allow-scripts allow-forms allow-pointer-lock allow-modals allow-downloads",allow:"fullscreen; autoplay; clipboard-write",allowFullScreen:!0,srcDoc:wt,title:Ke,scrolling:"yes"})}):te?e("div",{className:"tcp-markdown tcp-markdown-ai max-h-[260px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-950/40 p-3",dangerouslySetInnerHTML:{__html:cn(wt)}}):e("pre",{className:"tcp-code max-h-[260px] overflow-auto whitespace-pre-wrap break-words",children:wt||"No text content."})]}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:e("div",{className:"font-medium",children:"Executor Verification"})}),xt.length?e("div",{className:"grid max-h-44 gap-2 overflow-auto",children:xt.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:Ia(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:()=>V(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(Ms(f)),t("ok","Copied verification feedback.")}catch(B){t("err",B instanceof Error?B.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),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:Ba(Date.now())})]}),H.length?e("div",{className:"grid max-h-40 gap-2 overflow-auto",children:H.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:Ia(f.type.includes("failed")?"failed":"running"),children:f.type}),e("span",{className:"tcp-subtle",children:Ba(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"})}),K?e(ta,{children:[e("div",{className:"tcp-code max-h-28 overflow-auto whitespace-pre-wrap break-words",children:pt||"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:lt.length?lt.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(tm,{budget:W})}),e(xi,{tasks:N,currentTaskId:it.currentTaskId,selectedTaskId:Re,workflowSummaryByTaskId:ct,onTaskSelect:f=>{const B=Re===f.id?"":f.id;re(B),qe(f.id)},onRetryTask:f=>dt.mutate({path:"/api/orchestrator/retry",body:{runId:Ee,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:()=>re(""),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:[Pe.length," actions"]})]}),Pe.length?e("div",{className:"grid max-h-56 gap-2 overflow-auto",children:Pe.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:Ia(f.status),children:f.status})]}),e("div",{className:"tcp-subtle",children:["run: ",f.runId]}),e("div",{className:"tcp-subtle",children:["updated: ",Ba(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:kt||"no workflow id"}),e("span",{className:"tcp-subtle",children:Array.isArray(Et.data?.workflow?.steps)?`${Et.data.workflow.steps.length} steps`:"workflow metadata pending"}),e("span",{className:"tcp-subtle",children:Array.isArray(Et.data?.hooks)?`${Et.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:Se.length?Se.map((f,B)=>{const me=String(f?.run_id||`workflow-run-${B}`).trim(),Le=me===ue,Fe=String(f?.status||"unknown").trim(),tt=on(f);return e("button",{type:"button",className:`tcp-list-item text-left ${Le?"border-amber-400/70":""}`,onClick:()=>M(me),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:me}),e("span",{className:Ia(Fe),children:Fe})]}),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: ",tt||"n/a"]}),e("div",{className:"tcp-subtle text-xs",children:["actions:"," ",Array.isArray(f?.actions)?f.actions.length:0]})]},me)}):e(We,{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"}),ke?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:Ia(String(ke?.status||"unknown")),children:String(ke?.status||"unknown")}),e("span",{className:"tcp-subtle",children:["trigger: ",String(ke?.trigger_event||"manual")]}),e("span",{className:"tcp-subtle",children:["source: ",String(ke?.source_event_id||"n/a")]})]}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:Array.isArray(ke?.actions)&&ke.actions.length?ke.actions.map((f,B)=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:"font-medium",children:String(f?.action||"unknown action")}),e("span",{className:Ia(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||ke?.task_id||"n/a")]}),String(f?.task_id||ke?.task_id||"").trim()?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>re(String(f?.task_id||ke?.task_id||"").trim()),children:"Focus task"}):null]}),e("div",{className:"tcp-subtle",children:["started: ",Ba(f?.started_at_ms)]}),e("div",{className:"tcp-subtle",children:["finished: ",Ba(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")}-${B}`)):e("div",{className:"tcp-subtle text-xs",children:"No recorded workflow actions for this run."})})]}):e(We,{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"})})]}),he.length?e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:[...he].filter(f=>{const B=on(f.data?.properties||{});if(Re&&B&&B!==Re)return!1;if(!ue)return!0;const me=String(f.data?.properties?.runID||"").trim();return!me||me===ue}).reverse().map((f,B)=>{const me=pm(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:Ia(me.endsWith(".failed")?"failed":me.endsWith(".completed")?"completed":"running"),children:me}),e("span",{className:"tcp-subtle",children:Ba(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}-${B}`)})}):e("div",{className:"tcp-subtle text-xs",children:"No workflow events streamed for this run yet."})]}),e(Tt,{children:[j?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:Ia(j.state),children:lm(j.state)}),e("span",{className:"tcp-badge-info",children:j.id}),j.assigned_role?e("span",{className:"tcp-subtle",children:["role: ",j.assigned_role]}):null,j.gate?e("span",{className:"tcp-subtle",children:["gate: ",j.gate]}):null,j.workflow_id?e("span",{className:"tcp-subtle",children:["workflow: ",j.workflow_id]}):null,j.session_id?e("span",{className:"tcp-subtle",children:["session: ",j.session_id]}):null]}),e("div",{className:"tcp-verification-content grid gap-3",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Title"}),e("div",{className:"rounded-lg border border-slate-800/80 bg-slate-950/70 px-3 py-2 text-sm text-slate-100",children:j.title||"Untitled task"})]}),j.description?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Description"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words",children:j.description})]}):null,e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Dependencies"}),j.dependencies.length?e("div",{className:"flex flex-wrap gap-2",children:j.dependencies.map(f=>e("span",{className:"rounded border border-slate-700/60 px-2 py-1 text-xs text-slate-200",children:["<-"," ",f]},`${j.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: ",j.runtime_status||"n/a"]}),e("div",{className:"tcp-subtle",children:["retry count: ",Number(j.retry_count||0)]}),ct?.[j.id]?e("div",{className:"tcp-subtle",children:["workflow runs:"," ",ct[j.id].runs,ct[j.id].failed?`, failed ${ct[j.id].failed}`:""]}):null,j.runtime_detail?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:["detail: ",j.runtime_detail]}):null]})]})]}),String(j.error_message||"").trim()?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Error"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words text-rose-100",children:String(j.error_message||"").trim()})]}):null]}),e("div",{className:"tcp-confirm-actions mt-4",children:[e("button",{className:"tcp-btn",onClick:()=>{re(j.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:()=>V("")}),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:()=>V(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Ia(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: ",Ba(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(Ms(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:()=>V(""),children:"Close"})})]})]}):null]})]})]})})]}),e(Tt,{children:He&&Ke&&_e?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:Ke})]}),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:wt,title:`${Ke} fullscreen preview`,scrolling:"yes"})})})]})}):null}),k?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",C||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{T&&G(T)},disabled:!T,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{C&&(O(C),J(!1),de(""),t("ok",`Workspace selected: ${C}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{J(!1),de("")},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=>de(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:()=>G(String(f?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(f?.name||f?.path||"")]},String(f?.path||f?.name))):e(We,{text:o?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}function gm(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function fm({api:a,toast:t}){const n=aa(),[r,s]=w("uploads"),l=Z({queryKey:["files",r],queryFn:()=>a(`/api/files/list?dir=${encodeURIComponent(r)}`).catch(()=>({files:[]})),refetchInterval:12e3}),d=xe({mutationFn:p=>a("/api/files/delete",{method:"POST",body:JSON.stringify({path:p})}),onSuccess:async()=>{t("ok","File removed."),await n.invalidateQueries({queryKey:["files",r]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),u=gm(l.data,"files");return e("div",{className:"grid gap-4",children:e(Kt,{title:"Files",subtitle:"Browse and delete uploaded files",children:[e("div",{className:"mb-3 flex gap-2",children:[e("input",{className:"tcp-input",value:r,onInput:p=>s(p.target.value),placeholder:"uploads"}),e("button",{className:"tcp-btn",onClick:()=>l.refetch(),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("div",{className:"grid gap-2",children:u.length?u.map((p,_)=>{const D=String(p?.path||p?.name||`file-${_}`);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(We,{text:"No files found for this directory."})})]})})}function bm(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function vm({client:a,toast:t}){const n=aa(),[r,s]=w(""),[l,d]=w(null),u=Z({queryKey:["memory",r],queryFn:()=>(r.trim()?a.memory.search({query:r,limit:40}):a.memory.list({q:"",limit:40})).catch(()=>({items:[]})),refetchInterval:15e3}),p=xe({mutationFn:x=>a.memory.delete(x),onSuccess:async()=>{t("ok","Memory record deleted."),await n.invalidateQueries({queryKey:["memory"]})},onError:x=>t("err",x instanceof Error?x.message:String(x))}),_=bm(u.data,"items"),D=L(()=>_.map((x,P)=>{const O=String(x?.id||`mem-${P}`),k=String(x?.text||x?.content||x?.value||""),J=k.length>340?`${k.slice(0,340)}...`:k;return{id:O,text:k,compact:J,html:cn(k)}}),[_]);return e(Mn,{className:"grid gap-4",children:e(ft,{title:"Memory",subtitle:"Search recent records and open full entry details inline.",actions:e(ta,{children:[e(je,{tone:"info",children:[D.length," results"]}),r.trim()?e(je,{tone:"ghost",children:["Filter: ",r]}):e(je,{tone:"ghost",children:"Browsing latest memory"})]}),children:[e(va,{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 P=l===x.id;return e(Me.article,{layout:!0,className:`tcp-list-item cursor-pointer ${P?"border-amber-500/60":""}`,onClick:()=>d(P?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(je,{tone:P?"info":"ghost",children:P?"expanded":"compact"}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:O=>{O.stopPropagation(),p.mutate(x.id)},children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]}),e(Tt,{initial:!1,mode:"wait",children:P?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(We,{text:"No memory records found."})})]})})}const Ti=[{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 ym(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function wm(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function xm(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 km(a,t){const n=String(t||"").trim();if(n)return{type:"cron",cron_expression:n,timezone:"UTC"};const r=Ti.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 Nm(a){const t=String(a?.template_id||a?.templateID||a?.id||"").trim();if(!t)return null;const n=String(a?.display_name||a?.displayName||a?.name||"").trim(),r=String(a?.role||"worker").trim()||"worker",s=a?.default_model||a?.defaultModel||{},l=String(s?.provider_id||s?.providerId||"").trim(),d=String(s?.model_id||s?.modelId||"").trim();return{templateId:t,displayName:n||t,role:r,modelLabel:l&&d?`${l}/${d}`:""}}function _m({client:a,toast:t}){const n=aa(),r=Pt(null),[s,l]=w("Daily Engineering Standup"),[d,u]=w(""),[p,_]=w("Every morning"),[D,x]=w(""),[P,O]=w("docs/standups/{{date}}.md"),[k,J]=w([]),[A,G]=w(null),ee=Z({queryKey:["teams","standup","templates"],queryFn:()=>a?.agentTeams?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:12e3}),de=Z({queryKey:["teams","standup","health"],queryFn:()=>a?.health?.().catch(()=>({}))??Promise.resolve({}),refetchInterval:3e4});be(()=>{const R=String(de.data?.workspaceRoot||de.data?.workspace_root||"").trim();R&&u(we=>we||R)},[de.data]);const S=L(()=>ym(ee.data,"templates").map(Nm).filter(R=>!!R),[ee.data]),I=xe({mutationFn:async()=>{const R=String(s||"").trim(),we=String(d||"").trim();if(!R)throw new Error("Standup name is required.");const y=wm(we);if(y)throw new Error(y);if(!k.length)throw new Error("Select at least one participant template.");return await a?.agentTeams?.composeStandup?.({name:R,workspaceRoot:we,schedule:km(p,D),participantTemplateIds:k,reportPathTemplate:String(P||"").trim()||void 0})||null},onSuccess:R=>{G(R?.automation||null)},onError:R=>t("err",R instanceof Error?R.message:String(R))}),Q=xe({mutationFn:async()=>{const R=A||(await I.mutateAsync())?.automation;if(!R)throw new Error("Standup compose failed.");return a?.automationsV2?.create?.(R)},onSuccess:async()=>{t("ok","Agent standup automation created."),G(null),await n.invalidateQueries({queryKey:["automations"]})},onError:R=>t("err",R instanceof Error?R.message:String(R))});return be(()=>{const R=r.current;R&&ya(R)},[s,d,p,D,P,k.join(","),S.length,I.isPending,Q.isPending,!!A]),e("div",{ref:r,className:"grid gap-4 rounded-2xl border border-emerald-500/20 bg-emerald-500/5 p-4",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-emerald-300",children:"Agent Standup"}),e("h3",{className:"mt-1 text-lg font-semibold text-white",children:"Build a scheduled standup from saved agents"}),e("p",{className:"mt-1 text-sm text-slate-300",children:"Choose the personalities that should participate, preview the workflow, and create the automation from the same place you manage those agents."})]}),e("span",{className:"tcp-badge-ok",children:"MVP"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"Standup name",value:s,onInput:R=>l(R.target.value)}),e("input",{className:"tcp-input",placeholder:"/absolute/workspace/root",value:d,onInput:R=>u(R.target.value)}),e("select",{className:"tcp-input",value:p,onInput:R=>_(R.target.value),children:Ti.map(R=>e("option",{value:R.label,children:R.label},R.label))}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"Custom cron (optional)",value:D,onInput:R=>x(R.target.value)})]}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"docs/standups/{{date}}.md",value:P,onInput:R=>O(R.target.value)}),e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3 text-sm text-slate-300",children:"The markdown report path controls where the synthesized standup is written. Participant personalities come from the saved agents below."}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Participants"}),S.length?e("div",{className:"grid gap-2 md:grid-cols-2",children:S.map(R=>{const we=k.includes(R.templateId);return e("button",{type:"button",className:`tcp-list-item text-left transition-all ${we?"border-emerald-400/60 bg-emerald-400/10":""}`,onClick:()=>J(y=>y.includes(R.templateId)?y.filter(v=>v!==R.templateId):[...y,R.templateId]),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:R.displayName}),e("span",{className:"tcp-badge-info",children:R.role})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:R.templateId}),R.modelLabel?e("div",{className:"mt-2 text-xs text-emerald-200",children:R.modelLabel}):null]},R.templateId)})}):e(We,{text:"Create at least one saved agent below before composing a standup."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:I.isPending||!S.length,onClick:()=>I.mutate(),children:[e("i",{"data-lucide":"file-search"}),I.isPending?"Composing…":"Preview Standup Workflow"]}),e("button",{type:"button",className:"tcp-btn-primary",disabled:Q.isPending||!S.length,onClick:()=>Q.mutate(),children:[e("i",{"data-lucide":"rocket"}),Q.isPending?"Creating…":"Create Standup Automation"]})]}),A?e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("strong",{children:String(A?.name||"Standup preview")}),e("span",{className:"tcp-badge-info",children:[Array.isArray(A?.flow?.nodes)?A.flow.nodes.length:0," nodes"]})]}),e("div",{className:"grid gap-2 text-xs text-slate-300",children:[e("div",{children:["schedule: ",xm(A?.schedule)]}),e("div",{children:["report:"," ",String(A?.metadata?.standup?.report_path_template||P)]}),e("div",{children:["participants:"," ",String((A?.metadata?.standup?.participant_template_ids||k).join(", "))]})]})]}):null]})}const $s=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],Sm={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."},Im=["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."],Wn={templateId:"",displayName:"",avatarUrl:"",role:"worker",systemPrompt:"",modelProvider:"",modelId:""};function vr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Cm(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 Am(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 Os({client:a,toast:t}){const n=aa(),r=a?.agentTeams,s=Pt(null),[l,d]=w(Wn),[u,p]=w(null),_=Pt(null),D=Z({queryKey:["teams","templates"],queryFn:()=>r?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:8e3}),x=Z({queryKey:["teams","instances"],queryFn:()=>r?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),P=Z({queryKey:["teams","approvals"],queryFn:()=>r?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),O=xe({mutationFn:async()=>{if(!l.templateId.trim())throw new Error("Template ID is required.");return u?r?.updateTemplate?.(u,{display_name:l.displayName.trim()||void 0,avatar_url:l.avatarUrl.trim()||void 0,role:l.role,system_prompt:l.systemPrompt.trim()||void 0,default_model:l.modelProvider.trim()&&l.modelId.trim()?{provider_id:l.modelProvider.trim(),model_id:l.modelId.trim()}:void 0}):r?.createTemplate?.({template:Am(l)})},onSuccess:async()=>{t("ok",u?"Template updated.":"Template created."),d(Wn),p(null),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),k=xe({mutationFn:y=>r?.deleteTemplate?.(y),onSuccess:async()=>{t("ok","Template deleted."),u&&(p(null),d(Wn)),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),J=xe({mutationFn:({requestId:y,decision:v})=>v==="approve"?r?.approveSpawn?.(y):r?.denySpawn?.(y),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),A=L(()=>vr(D.data,"templates").map(Cm).filter(y=>y.templateId),[D.data]),G=vr(x.data,"instances"),ee=vr(P.data,"spawnApprovals"),de=!!(u||l.templateId||l.displayName||l.systemPrompt),S=l.displayName.trim()||l.templateId.trim()||"New Agent",I=S.slice(0,1).toUpperCase()||"A",Q=Sm[l.role],R=l.avatarUrl.trim();be(()=>{const y=s.current;y&&ya(y)},[A.length,G.length,ee.length,l.role,l.templateId,l.displayName,l.avatarUrl,l.modelProvider,l.modelId,l.systemPrompt,u,O.isPending,k.isPending,J.isPending]);const we=y=>{if(!y)return;if(y.size>10*1024*1024){t("err","Avatar image is too large (max 10 MB).");return}const v=new FileReader;v.onload=()=>{const U=typeof v.result=="string"?v.result:"";if(!U){t("err","Failed to read avatar image.");return}d(pe=>({...pe,avatarUrl:U}))},v.onerror=()=>t("err","Failed to read avatar image."),v.readAsDataURL(y)};return e("div",{ref:s,className:"grid gap-4",children:[e(Kt,{title:"Agent Standup",subtitle:"Compose scheduled standups from the same saved agents you manage here",children:e(_m,{client:a,toast:t})}),e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(Kt,{title:"Agents",subtitle:"Create reusable agent personalities, prompts, and default models for automation workflows",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-cyan-300",children:"Reusable Personalities"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Each saved agent defines a persistent personality for automation workflows. Define who the agent is, what kind of work it owns, and which default model it should use. These personalities can be reused in standups and other workflow responses."})]}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"template-id",value:l.templateId,disabled:!!u,onInput:y=>d(v=>({...v,templateId:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Display name",value:l.displayName,onInput:y=>d(v=>({...v,displayName:y.target.value}))}),e("select",{className:"tcp-input",value:l.role,onInput:y=>d(v=>({...v,role:y.target.value})),children:$s.map(y=>e("option",{value:y,children:y},y))}),e("input",{className:"tcp-input",placeholder:"Avatar URL or upload (optional)",value:l.avatarUrl,onInput:y=>d(v=>({...v,avatarUrl:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model provider (optional)",value:l.modelProvider,onInput:y=>d(v=>({...v,modelProvider:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model ID (optional)",value:l.modelId,onInput:y=>d(v=>({...v,modelId:y.target.value}))})]}),e("div",{className:"grid gap-3 lg:grid-cols-[1.15fr_0.85fr]",children:[e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Prompt Guidance"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Write the lasting perspective for this agent, not a one-off task. Good prompts describe ownership and judgment: frontend lead, backend lead, product ops, incident watcher."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:Im.map(y=>e("button",{type:"button",className:"tcp-btn h-auto min-h-8 px-3 py-2 text-left text-xs",onClick:()=>d(v=>({...v,systemPrompt:y})),children:"Use Example"},y))})]}),e("div",{className:"rounded-[28px] border border-slate-800/80 bg-[radial-gradient(circle_at_top,_rgba(34,211,238,0.18),_transparent_45%),linear-gradient(180deg,rgba(15,23,42,0.9),rgba(2,6,23,0.96))] p-5",children:[e("div",{className:"flex items-start justify-between gap-4",children:[e("div",{className:"flex items-start gap-4",children:[e("div",{className:"flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-lg font-semibold text-cyan-100",children:R?e("img",{src:R,alt:S,className:"h-full w-full object-cover"}):I}),e("div",{className:"min-w-0",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-white",children:S}),e("span",{className:"tcp-badge-info",children:l.role})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:l.templateId.trim()||"template-id"}),e("div",{className:"mt-2 text-sm text-slate-300",children:Q})]})]}),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:()=>_.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{type:"button",className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>d(y=>({...y,avatarUrl:""})),children:e("i",{"data-lucide":"trash-2"})})]})]}),e("div",{className:"mt-3 text-xs text-slate-400",children:"Upload an image like Settings Identity preview, or paste a direct avatar URL."}),e("input",{ref:_,type:"file",accept:"image/*",className:"hidden",onChange:y=>{we(y.target.files?.[0]||null),y.target.value=""}}),e("div",{className:"mt-4 rounded-2xl border border-slate-800/70 bg-black/20 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Personality Preview"}),e("div",{className:"mt-2 whitespace-pre-wrap text-sm leading-6 text-slate-200",children:l.systemPrompt.trim()||"This agent will respond from the persistent personality you define here across workflows and standups."})]}),(l.modelProvider.trim()||l.modelId.trim())&&e("div",{className:"mt-3 text-xs text-cyan-200",children:["Default model: ",l.modelProvider.trim()||"provider","/",l.modelId.trim()||"model"]})]})]}),e("textarea",{className:"tcp-input min-h-[140px]",placeholder:"Persistent system prompt",value:l.systemPrompt,onInput:y=>d(v=>({...v,systemPrompt:y.target.value}))}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:O.isPending,onClick:()=>O.mutate(),children:[e("i",{"data-lucide":"save"}),u?"Update Agent":"Create Agent"]}),de&&e("button",{type:"button",className:"tcp-btn",onClick:()=>{p(null),d(Wn)},children:[e("i",{"data-lucide":"rotate-ccw"}),"Reset"]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Saved Agents"}),e("div",{className:"tcp-subtle text-xs",children:[A.length," saved"]})]}),A.length?A.map(y=>e("div",{className:"tcp-list-item",children:e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[e("strong",{children:y.displayName||y.templateId}),e("span",{className:"tcp-badge-info",children:y.role}),y.modelProvider&&y.modelId?e("span",{className:"tcp-badge-ok",children:[y.modelProvider,"/",y.modelId]}):null]}),e("div",{className:"tcp-subtle text-xs",children:y.templateId}),y.systemPrompt?e("div",{className:"mt-2 line-clamp-4 text-xs text-slate-300",children:y.systemPrompt}):e("div",{className:"mt-2 text-xs text-slate-500",children:"No persistent prompt set yet."})]}),e("div",{className:"flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{p(y.templateId),d({templateId:y.templateId,displayName:y.displayName,avatarUrl:y.avatarUrl,role:$s.includes(y.role)?y.role:"worker",systemPrompt:y.systemPrompt,modelProvider:y.modelProvider,modelId:y.modelId})},children:[e("i",{"data-lucide":"pencil"}),"Edit"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>k.mutate(y.templateId),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]})},y.templateId)):e(We,{title:"No agents yet",text:"Create your first saved personality here, then reuse it across automation workflows and standups."})]})]})}),e(Kt,{title:"Team Instances",subtitle:"Running collaborative agent instances",children:e("div",{className:"grid gap-2",children:G.length?G.map((y,v)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(y?.template_id||y?.templateID||y?.instance_id||"Instance")}),e("span",{className:"tcp-badge-info",children:String(y?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs",children:["mission: ",String(y?.mission_id||y?.missionID||"n/a")]})]},String(y?.instance_id||y?.id||v))):e(We,{text:"No team instances found."})})}),e(Kt,{title:"Spawn Approvals",subtitle:"Pending team approval requests",children:e("div",{className:"grid gap-2",children:ee.length?ee.map((y,v)=>{const U=String(y?.approval_id||y?.request_id||y?.id||`request-${v}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 font-medium",children:String(y?.reason||y?.title||U)}),e("div",{className:"tcp-subtle text-xs",children:U}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>J.mutate({requestId:U,decision:"approve"}),children:[e("i",{"data-lucide":"badge-check"}),"Approve"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>J.mutate({requestId:U,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},U)}):e(We,{text:"No pending approvals."})})})]})]})}function zn(a){return a?.type||a?.event||"event"}function Es(a){const t=String(a||"").trim().toLowerCase();return["server.connected","engine.lifecycle.ready","engine.heartbeat","engine.lifecycle.heartbeat"].includes(t)}function Ds(a){return String(a?.type||a?.event||"").trim()==="context.run.stream"&&String(a?.run_id||a?.runId||"").trim().startsWith("workflow-")}function Pm({client:a,toast:t,navigate:n}){const[r,s]=w([]),[l,d]=w(""),[u,p]=w("all"),[_,D]=w(!0),[x,P]=w(null),O=L(()=>!x||!Ds(x.data)?"":String(x.data?.run_id||x.data?.runId||"").trim(),[x]),k=Z({queryKey:["feed","workflow-context-run",O],enabled:!!O,queryFn:()=>Lt(`/api/engine/context/runs/${encodeURIComponent(O)}`).catch(()=>({run:null}))}),J=Z({queryKey:["feed","workflow-context-blackboard",O],enabled:!!O,queryFn:()=>Lt(`/api/engine/context/runs/${encodeURIComponent(O)}/blackboard`).catch(()=>({blackboard:null}))});Va("/api/global/event",S=>{try{const I=JSON.parse(S.data);s(Q=>[...Q.slice(-299),{at:Date.now(),data:I}])}catch{}},{enabled:!0});const A=L(()=>{const S=new Map;for(const I of r){const Q=zn(I.data);_&&Es(Q)||S.set(Q,(S.get(Q)||0)+1)}return[...S.entries()].sort((I,Q)=>Q[1]-I[1])},[r,_]),G=L(()=>{const S=l.trim().toLowerCase();return r.filter(I=>{const Q=zn(I.data);return _&&Es(Q)||u!=="all"&&Q!==u?!1:S?`${Q} ${JSON.stringify(I.data||{})}`.toLowerCase().includes(S):!0}).slice(-240).reverse()},[r,l,u,_]);async function ee(S){try{const I=await Lt("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:S,source:{kind:"control_panel_feed",event:"pack.detected"}})});t("ok",`Installed ${I?.installed?.name||"pack"}`)}catch(I){t("err",I instanceof Error?I.message:String(I))}}async function de(S){try{const I=await Lt("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:String(S?.properties?.attachment_id||S?.attachment_id||""),path:String(S?.properties?.path||S?.path||""),connector:String(S?.properties?.connector||S?.connector||"")||void 0,channel_id:String(S?.properties?.channel_id||S?.channel_id||"")||void 0,sender_id:String(S?.properties?.sender_id||S?.sender_id||"")||void 0})});t("ok",`Installed ${I?.installed?.name||"pack"}`)}catch(I){t("err",I instanceof Error?I.message:String(I))}}return e(Mn,{className:"grid gap-4",children:[e(ft,{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:_?"tcp-badge-ok":"tcp-badge-info",children:_?"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(va,{className:"mb-3",children:[e("input",{className:"tcp-input min-w-[220px] flex-1",value:l,onInput:S=>d(S.target.value),placeholder:"Filter by type or payload"}),e(or,{active:u==="all",onClick:()=>p("all"),children:[e("i",{"data-lucide":"list"}),"All"]}),e(or,{active:_,onClick:()=>D(S=>!S),children:[e("i",{"data-lucide":_?"filter":"filter-x"}),_?"Hide noise":"Show noise"]}),A.slice(0,8).map(([S,I])=>e(or,{active:u===S,onClick:()=>p(S),children:[e("i",{"data-lucide":"activity"}),S," (",I,")"]},S))]}),e("div",{className:"grid max-h-[68vh] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:G.length?G.map((S,I)=>{const Q=zn(S.data),R=String(Q).startsWith("pack."),we=Ds(S.data),y=String(S.data?.properties?.path||S.data?.path||""),v=String(S.data?.properties?.attachment_id||S.data?.attachment_id||"");return e("article",{className:"tcp-list-item cursor-pointer",onClick:()=>P(S),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:Q}),e("div",{className:"flex items-center gap-2",children:[we?e("span",{className:"tcp-badge-warn",children:"workflow context"}):null,e("span",{className:"tcp-badge-info",children:new Date(S.at).toLocaleTimeString()})]})]}),e("p",{className:"tcp-subtle mt-1 text-xs",children:we?`run: ${String(S.data?.run_id||S.data?.runId||"n/a")}`:`session: ${String(S.data?.sessionID||S.data?.sessionId||"n/a")}`}),we?e("p",{className:"tcp-subtle mt-1 text-xs",children:["kind: ",String(S.data?.kind||"context_run_event")," · seq:"," ",String(S.data?.seq||"-")]}):null,R?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open pack library"]}),y?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),ee(y)},children:[e("i",{"data-lucide":"download"}),"Install from path"]}):null,y&&v?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),de(S.data)},children:[e("i",{"data-lucide":"paperclip"}),"Install attachment"]}):null]}):null,we?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),n("orchestrator")},children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open workflow lab"]})]}):null]},`${S.at}-${I}`)}):e(We,{text:"No events have arrived yet."})})]}),e(er,{open:!!x,onClose:()=>P(null),title:x?zn(x.data):"Event",children:x?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Captured at"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:new Date(x.at).toLocaleString()})]}),O?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(k.data?.run?.objective||O)}),e("span",{className:"tcp-badge-info",children:String(k.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(J.data?.blackboard?.tasks)?J.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(J.data?.blackboard?.artifacts)?J.data.blackboard.artifacts.length:0]})]}):null,e("pre",{className:"tcp-code",children:Ht(x.data)}),O?e("pre",{className:"tcp-code",children:Ht({run:k.data?.run||null,blackboard:J.data?.blackboard||null})}):null]}):null})]})}function Tm({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 Rm({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:Aa.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(Tm,{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(Tt,{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:Aa.spring.snappy,children:[e("i",{"data-lucide":"badge-check"}),"Active"]}):null})]},r.id)})})}function zr(a){try{return new URL(a)}catch{return null}}function Pr(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"mcp-server"}function js(a){const t=zr(a);if(!t)return"";const n=String(t.hostname||"").toLowerCase();if(!n)return"";if(n.endsWith("composio.dev"))return"composio";const r=n.split(".").filter(Boolean);if(!r.length)return"";const s=["backend","api","mcp","www"].includes(r[0])&&r[1]||r[0];return Pr(s)}function Ri(a){const t=zr(a);return t?String(t.hostname||"").toLowerCase().endsWith("composio.dev"):!1}function qm({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()}`}:Ri(r)?{"x-api-key":s}:{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}}function Mm(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>":Ri(r)?"Auto mode: selected x-api-key for this endpoint":"Auto mode: using Authorization Bearer token"}function yr(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 $m(a){return Array.isArray(a)?a.map(t=>yr(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):!a||typeof a!="object"?[]:Array.isArray(a.servers)?a.servers.map(t=>yr(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):Object.entries(a).map(([t,n])=>yr(n&&typeof n=="object"?n:{transport:String(n||"")},t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name))}function Om(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 Em(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 wr(a,t){const n=t&&typeof t=="object"?t:{};return{botToken:"",allowedUsers:Array.isArray(n.allowed_users)?n.allowed_users.join(", "):"",mentionOnly:n.mention_only!==!1&&a==="discord"?!0:!!n.mention_only,guildId:String(n.guild_id||"").trim(),channelId:String(n.channel_id||"").trim(),styleProfile:String(n.style_profile||"default").trim()||"default"}}function Dm(a){const t=String(a||"").split(",").map(n=>n.trim()).filter(Boolean);return t.length?t:["*"]}function jm(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 Um(a,t){const n=String(a?.catalog_message||"").trim();return n||`Default model: ${t||"none"}`}function Us({client:a,api:t,toast:n,navigate:r,currentRoute:s,identity:l,themes:d,setTheme:u,themeId:p,refreshProviderStatus:_,refreshIdentityStatus:D}){const x=aa(),P=Pt(null),[O,k]=w({}),[J,A]=w(String(l?.botName||"Tandem")),[G,ee]=w(String(l?.botAvatarUrl||"")),[de,S]=w("Control Center"),[I,Q]=w("providers"),[R,we]=w("auto"),[y,v]=w(""),[U,pe]=w(""),[X,$e]=w("10000"),[Oe,Ke]=w(""),[ae,ue]=w(""),[M,he]=w(!1),[Te,Re]=w(!1),[re,Ue]=w(!1),[qe,ze]=w({}),[V,He]=w({}),[ne,Ie]=w(!1),[ht,se]=w(""),[F,rt]=w(""),[mt,ot]=w("none"),[St,Ee]=w(""),[Rt,yt]=w(""),[Ot,Je]=w(!0),[Qe,nt]=w(""),[ye,Ne]=w("manual"),[Ve,le]=w(""),[it,N]=w(!1),[W,ve]=w(!1),[De,o]=w(""),[b,T]=w(""),[C,$]=w(""),[Ye,Ze]=w("auto"),[bt,qt]=w(""),[Ae,wt]=w(""),[It,te]=w(!0),[_e,h]=w(!1),[j,z]=w(!0),[K,H]=w(!1),[fe,Be]=w(""),[pt,lt]=w(""),xt=Pt(null),et=async()=>{const c=a?.identity;return c?.get?c.get():t("/api/engine/config/identity",{method:"GET"})},kt=async c=>{const q=a?.identity;return q?.patch?q.patch(c):t("/api/engine/config/identity",{method:"PATCH",body:JSON.stringify(c)})},Et=Z({queryKey:["settings","identity","config"],queryFn:()=>et().catch(()=>({identity:{}}))});be(()=>{const c=Et.data?.identity?.bot||{},q=c?.aliases||{},oe=String(c?.canonicalName||c?.canonical_name||l?.botName||"Tandem").trim(),at=String(c?.avatarUrl||c?.avatar_url||l?.botAvatarUrl||"").trim(),At=String(q?.controlPanel||q?.control_panel||"").trim();A(oe||"Tandem"),ee(at),S(At||"Control Center")},[l?.botAvatarUrl,l?.botName,Et.data]),be(()=>{s==="mcp"&&Q("mcp"),s==="channels"&&Q("channels"),s==="bug-monitor"&&Q("bug_monitor")},[s]);const Wt=Z({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[],connected:[]}))}),vt=Z({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({default:"",providers:{}}))}),ct=Z({queryKey:["settings","search","config"],queryFn:()=>t("/api/system/search-settings",{method:"GET"}).catch(()=>null)});be(()=>{const c=ct.data?.settings||null;c&&(we(String(c.backend||"auto").trim()||"auto"),v(String(c.tandem_url||"").trim()),pe(String(c.searxng_url||"").trim()),$e(String(c.timeout_ms||1e4)))},[ct.data]);const Se=Z({queryKey:["settings","browser","status"],queryFn:()=>t("/api/engine/browser/status",{method:"GET"}).catch(()=>null),refetchInterval:3e4}),[Pe,ga]=w(null),ke=xe({mutationFn:()=>t("/api/engine/browser/install",{method:"POST"}),onSuccess:async()=>{n("ok","Browser sidecar installed on the engine host."),await Se.refetch()},onError:c=>n("err",c instanceof Error?c.message:String(c))}),ge=xe({mutationFn:()=>t("/api/engine/browser/smoke-test",{method:"POST",body:JSON.stringify({url:"https://example.com"})}),onSuccess:async c=>{ga(c),n("ok","Browser smoke test passed."),await Se.refetch()},onError:c=>{ga(null),n("err",c instanceof Error?c.message:String(c))}}),dt=Z({queryKey:["settings","mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:1e4}),Ge=Z({queryKey:["settings","mcp","tools"],queryFn:()=>a.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),Nt=Z({queryKey:["settings","mcp","catalog"],queryFn:()=>t("/api/engine/mcp/catalog",{method:"GET"}).catch(()=>null),refetchInterval:6e4}),Ut=Z({queryKey:["settings","bug-monitor","config"],queryFn:()=>t("/api/engine/config/bug-monitor",{method:"GET"}).catch(()=>({bug_monitor:{}}))}),ra=Z({queryKey:["settings","bug-monitor","status"],queryFn:()=>t("/api/engine/bug-monitor/status",{method:"GET"}).catch(()=>({status:{}})),refetchInterval:1e4}),Mt=Z({queryKey:["settings","bug-monitor","drafts"],queryFn:()=>t("/api/engine/bug-monitor/drafts?limit=10",{method:"GET"}).catch(()=>({drafts:[]})),refetchInterval:15e3}),zt=Z({queryKey:["settings","bug-monitor","incidents"],queryFn:()=>t("/api/engine/bug-monitor/incidents?limit=10",{method:"GET"}).catch(()=>({incidents:[]})),refetchInterval:1e4}),Ct=Z({queryKey:["settings","bug-monitor","posts"],queryFn:()=>t("/api/engine/bug-monitor/posts?limit=10",{method:"GET"}).catch(()=>({posts:[]})),refetchInterval:15e3}),Vt=Z({queryKey:["settings","bug-monitor","workspace-browser",fe],enabled:K&&!!fe,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(fe)}`,{method:"GET"})}),Yt=Z({queryKey:["settings","channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),ua=Z({queryKey:["settings","channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),Na=xe({mutationFn:async({providerId:c,modelId:q})=>a.providers.setDefaults(c,q),onSuccess:async()=>{n("ok","Updated provider defaults."),await Promise.all([x.invalidateQueries({queryKey:["settings","providers"]}),_()])},onError:c=>n("err",c instanceof Error?c.message:String(c))}),f=xe({mutationFn:async()=>t("/api/engine/config/bug-monitor",{method:"PATCH",body:JSON.stringify({bug_monitor:{enabled:it,paused:W,workspace_root:String(De||"").trim()||null,repo:String(b||"").trim()||null,mcp_server:String(C||"").trim()||null,provider_preference:String(Ye||"auto").trim(),model_policy:bt&&Ae?{default_model:{provider_id:bt,model_id:Ae}}:null,auto_create_new_issues:It,require_approval_for_new_issues:_e,auto_comment_on_matched_open_issues:j,label_mode:"reporter_only"}})}),onSuccess:async()=>{n("ok","Bug Monitor settings saved."),await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})])},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),B=xe({mutationFn:async()=>t("/api/engine/capabilities/bindings/refresh-builtins",{method:"POST"}),onSuccess:async()=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]}),x.invalidateQueries({queryKey:["settings","mcp"]})]),n("ok","Capability bindings refreshed from built-ins.")},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),me=xe({mutationFn:async({draftId:c,decision:q})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(c)}/${q}`,{method:"POST",body:JSON.stringify({reason:`${q}d from control panel settings`})}),onSuccess:async(c,q)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor draft ${q.decision==="approve"?"approved":"denied"}.`)},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),Le=xe({mutationFn:async({draftId:c})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(c)}/triage-run`,{method:"POST"}),onSuccess:async c=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",c?.deduped?`Bug Monitor triage run already exists: ${c?.run?.run_id||"unknown"}`:`Bug Monitor triage run created: ${c?.run?.run_id||"unknown"}`)},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),Fe=xe({mutationFn:async({action:c})=>t(`/api/engine/bug-monitor/${c}`,{method:"POST"}),onSuccess:async(c,q)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor ${q.action==="pause"?"paused":"resumed"}.`)},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),tt=xe({mutationFn:async({incidentId:c})=>t(`/api/engine/bug-monitor/incidents/${encodeURIComponent(c)}/replay`,{method:"POST"}),onSuccess:async c=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",c?.deduped?`Bug Monitor triage run already exists: ${c?.run?.run_id||"unknown"}`:`Bug Monitor replay queued triage: ${c?.run?.run_id||"unknown"}`)},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),_t=xe({mutationFn:async({draftId:c})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(c)}/publish`,{method:"POST"}),onSuccess:async c=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",c?.action==="comment_issue"?`Bug Monitor commented on issue #${c?.draft?.issue_number||"unknown"}.`:`Bug Monitor published issue #${c?.draft?.issue_number||"unknown"}.`)},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),Jt=xe({mutationFn:async({draftId:c})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(c)}/recheck-match`,{method:"POST"}),onSuccess:async c=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`GitHub match result: ${String(c?.action||"rechecked").replaceAll("_"," ")}.`)},onError:c=>{const q=c instanceof Error?c.message:String(c?.detail||c?.error||c);n("err",q)}}),sa=xe({mutationFn:({providerId:c,apiKey:q})=>a.providers.setApiKey(c,q),onSuccess:async()=>{n("ok","API key updated."),await _()},onError:c=>n("err",c instanceof Error?c.message:String(c))}),Qt=xe({mutationFn:async c=>t("/api/system/search-settings",{method:"PATCH",body:JSON.stringify(c)}),onSuccess:async c=>{Ke(""),ue(""),await x.invalidateQueries({queryKey:["settings","search"]}),n("ok",c?.restart_required?"Search settings saved. Restart tandem-engine to apply them.":"Search settings saved.")},onError:c=>n("err",c instanceof Error?c.message:String(c))}),Xt=xe({mutationFn:async()=>{const q=(Et.data?.identity?.bot||{})?.aliases||{},oe=String(J||"").trim();if(!oe)throw new Error("Bot name is required.");const at=String(G||"").trim(),At=String(de||"").trim();return kt({identity:{bot:{canonical_name:oe,avatar_url:at||null,aliases:{...q,control_panel:At||void 0}}}})},onSuccess:async()=>{n("ok","Identity updated."),await Promise.all([x.invalidateQueries({queryKey:["settings","identity"]}),D()])},onError:c=>n("err",c instanceof Error?c.message:String(c))}),wa=ut(async()=>x.invalidateQueries({queryKey:["settings","channels"]}),[x]),Ka=xe({mutationFn:async c=>{const q=qe[c];if(!q)throw new Error(`No draft found for ${c}.`);const oe={allowed_users:Dm(q.allowedUsers),mention_only:!!q.mentionOnly},at=String(q.botToken||"").trim();if(at&&(oe.bot_token=at),c==="telegram"&&(oe.style_profile=String(q.styleProfile||"default").trim()||"default"),c==="discord"&&(oe.guild_id=String(q.guildId||"").trim()),c==="slack"){const At=String(q.channelId||"").trim();if(!At&&!Yt.data?.slack?.channel_id)throw new Error("Slack channel ID is required.");At&&(oe.channel_id=At)}return a.channels.put(c,oe)},onSuccess:async(c,q)=>{n("ok",`Saved ${q} channel settings.`),He(oe=>({...oe,[q]:null})),ze(oe=>({...oe,[q]:{...oe[q],botToken:""}})),await wa()},onError:c=>n("err",c instanceof Error?c.message:String(c))}),Xa=xe({mutationFn:async c=>a.channels.delete(c),onSuccess:async(c,q)=>{n("ok",`Removed ${q} channel settings.`),He(oe=>({...oe,[q]:null})),ze(oe=>({...oe,[q]:wr(q,null)})),await wa()},onError:c=>n("err",c instanceof Error?c.message:String(c))}),hn=xe({mutationFn:async c=>{const q=qe[c],oe={bot_token:String(q?.botToken||"").trim()||void 0};return a.channels.verify(c,oe)},onSuccess:(c,q)=>{He(oe=>({...oe,[q]:c})),n("ok",`${q} verification complete.`)},onError:c=>n("err",c instanceof Error?c.message:String(c))}),Za=ut(async()=>x.invalidateQueries({queryKey:["settings","mcp"]}),[x]),ia=xe({mutationFn:async({action:c,server:q})=>{if(!q)throw new Error("No MCP server selected.");if(c==="connect")return a.mcp.connect(q.name);if(c==="disconnect")return a.mcp.disconnect(q.name);if(c==="refresh")return a.mcp.refresh(q.name);if(c==="toggle-enabled")return a.mcp.setEnabled(q.name,!q.enabled);if(c==="delete")return t(`/api/engine/mcp/${encodeURIComponent(q.name)}`,{method:"DELETE"});throw new Error(`Unknown action: ${c}`)},onSuccess:async(c,q)=>{await Za(),q.action==="connect"&&n("ok",`Connected ${q.server?.name}.`),q.action==="disconnect"&&n("ok",`Disconnected ${q.server?.name}.`),q.action==="refresh"&&n("ok",`Refreshed ${q.server?.name}.`),q.action==="toggle-enabled"&&n("ok",`${q.server?.enabled?"Disabled":"Enabled"} ${q.server?.name}.`),q.action==="delete"&&n("ok",`Deleted ${q.server?.name}.`)},onError:c=>n("err",c instanceof Error?c.message:String(c))}),ma=xe({mutationFn:async()=>{const c=String(F||"").trim(),q=js(c),oe=Pr(ht||q);if(!c)throw new Error("Transport URL is required.");if(!zr(c)&&!c.startsWith("stdio:"))throw new Error("Transport must be a valid URL or stdio:* transport.");const at=qm({authMode:mt,token:St,customHeader:Rt,transport:c}),At={name:oe,transport:c,enabled:!0};Object.keys(at).length&&(At.headers=at);const na=String(Qe||"").trim();if(na&&na!==oe&&await t(`/api/engine/mcp/${encodeURIComponent(na)}`,{method:"DELETE"}).catch(()=>null),await a.mcp.add(At),Ot&&!(await a.mcp.connect(At.name))?.ok)throw new Error(`Added "${At.name}" but connect failed.`);return At.name},onSuccess:async c=>{await Za(),Ie(!1),se(""),rt(""),ot("none"),Ee(""),yt(""),Je(!0),nt(""),n("ok",`Saved MCP "${c}".`)},onError:c=>n("err",c instanceof Error?c.message:String(c))}),En=c=>{if(!c)return;if(c.size>10*1024*1024){n("err","Avatar image is too large (max 10 MB).");return}const q=new FileReader;q.onload=()=>{const oe=typeof q.result=="string"?q.result:"";if(!oe){n("err","Failed to read avatar image.");return}ee(oe)},q.onerror=()=>n("err","Failed to read avatar image."),q.readAsDataURL(c)},_a=Array.isArray(Wt.data?.all)?Wt.data.all:[],fa=L(()=>$m(dt.data),[dt.data]),La=L(()=>Om(Ge.data),[Ge.data]),$a=L(()=>Em(Nt.data?.catalog||Nt.data||null),[Nt.data]),Dn=L(()=>new Set(fa.map(c=>c.name.toLowerCase())),[fa]),en=L(()=>{const c=String(Ve||"").trim().toLowerCase();return $a.servers.filter(q=>c?q.name.toLowerCase().includes(c)||q.slug.toLowerCase().includes(c)||q.transportUrl.toLowerCase().includes(c):!0).slice(0,36)},[$a.servers,Ve]),gn=fa.filter(c=>c.connected).length,Ce=L(()=>ra.data?.status||{},[ra.data]),Sa=L(()=>Array.isArray(Mt.data?.drafts)?Mt.data.drafts||[]:[],[Mt.data]),fn=L(()=>Array.isArray(zt.data?.incidents)?zt.data.incidents||[]:[],[zt.data]),tn=L(()=>Array.isArray(Ct.data?.posts)?Ct.data.posts||[]:[],[Ct.data]),ba=L(()=>fa.find(c=>c.name.toLowerCase()===String(C||"").trim().toLowerCase())||null,[C,fa]),Wa=L(()=>_a.find(c=>String(c?.id||"").toLowerCase()===String(bt||"").trim().toLowerCase())||null,[bt,_a]),an=L(()=>{const c=Wa&&typeof Wa=="object"?Wa.models||{}:{};return Object.keys(c).sort((q,oe)=>q.localeCompare(oe))},[Wa]),za=Array.isArray(Se.data?.blocking_issues)?Se.data?.blocking_issues||[]:[],Oa=Array.isArray(Se.data?.recommendations)?Se.data?.recommendations||[]:[],i=Array.isArray(Se.data?.install_hints)?Se.data?.install_hints||[]:[],m=["telegram","discord","slack"],E=m.filter(c=>!!ua.data?.[c]?.connected).length,Y=Array.isArray(Vt.data?.directories)?Vt.data.directories:[],ce=String(pt||"").trim().toLowerCase(),st=L(()=>ce?Y.filter(c=>String(c?.name||c?.path||"").trim().toLowerCase().includes(ce)):Y,[Y,ce]),Dt=String(Vt.data?.parent||"").trim(),oa=String(Vt.data?.dir||fe||"").trim();be(()=>{const c=Ut.data?.bug_monitor&&typeof Ut.data?.bug_monitor=="object"?Ut.data.bug_monitor:{};N(!!c.enabled),ve(!!c.paused),o(String(c.workspace_root||"").trim()),T(String(c.repo||"").trim()),$(String(c.mcp_server||"").trim()),Ze(String(c.provider_preference||"auto").trim()||"auto"),qt(String(c.model_policy?.default_model?.provider_id||"").trim()),wt(String(c.model_policy?.default_model?.model_id||"").trim()),te(c.auto_create_new_issues!==!1),h(!!c.require_approval_for_new_issues),z(c.auto_comment_on_matched_open_issues!==!1)},[Ut.data]),be(()=>{const c=Yt.data&&typeof Yt.data=="object"?Yt.data:{};ze(q=>{const oe={...q};for(const at of m)oe[at]||(oe[at]=wr(at,c[at]));return oe})},[Yt.data]);const xa=(c,q)=>{const oe=String(q||"").trim();oe&&Na.mutate({providerId:c,modelId:oe})},la=c=>{if(c){Ne("manual");const q=c.headers&&typeof c.headers=="object"?c.headers:{},oe=Object.keys(q),at=oe.find(na=>String(na).toLowerCase()==="authorization"),At=oe.find(na=>String(na).toLowerCase()==="x-api-key");nt(c.name),se(c.name),rt(c.transport||""),Je(c.connected||!1),At?(ot("x-api-key"),yt(""),Ee(String(q[At]||"").trim())):at?(ot("bearer"),yt(""),Ee(String(q[at]||"").replace(/^bearer\s+/i,"").trim())):oe.length===1?(ot("custom"),yt(oe[0]),Ee(String(q[oe[0]]||"").trim())):(ot("none"),yt(""),Ee(""))}else Ne("catalog"),nt(""),se(""),rt(""),ot("none"),yt(""),Ee(""),Je(!0);Ie(!0)},Pa=async()=>{const c=await t("/api/engine/bug-monitor/debug",{method:"GET"});await navigator.clipboard.writeText(JSON.stringify(c,null,2)),n("ok","Bug Monitor debug payload copied.")},Zt=[{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"}],Ea=L(()=>Mm(mt,St,Rt,F),[mt,Rt,St,F]);return be(()=>{const c=P.current;c?ya(c):ya()},[I,it,W,De,C,Ce.readiness?.runtime_ready,Ce.runtime?.monitoring_active,Ce.runtime?.paused,Ce.runtime?.pending_incidents,Ce.pending_drafts,Sa.length,fn.length,B.isPending,Fe.isPending,me.isPending,tt.isPending,Le.isPending,f.isPending,ia.isPending,Qt.isPending]),e(Mn,{className:"grid gap-4",children:e("div",{ref:P,className:"grid gap-4",children:[e("div",{className:"tcp-settings-tabs",children:Zt.map(c=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${I===c.id?"active":""}`,onClick:()=>Q(c.id),children:[e("i",{"data-lucide":c.icon}),c.label]},c.id))}),e(In,{main:e(tc,{className:"grid gap-4",children:[I==="providers"?e(ft,{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(je,{tone:String(vt.data?.default||"").trim()?"ok":"warn",children:["Default: ",String(vt.data?.default||"none")]}),e(je,{tone:"info",children:[String(Wt.data?.connected?.length||0)," connected"]}),e("button",{className:"tcp-btn",onClick:()=>_().then(()=>n("ok","Provider status refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh provider"]})]}),children:e("div",{className:"grid gap-3",children:[e("button",{type:"button",className:"tcp-list-item text-left",onClick:()=>Ue(c=>!c),"aria-expanded":re,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":re?"chevron-down":"chevron-right"}),e("span",{children:re?"Hide provider catalog":"Show provider catalog"})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[_a.length," providers available for configuration. Expand to change models and API keys."]})]}),e(je,{tone:"info",children:[String(Wt.data?.connected?.length||0)," connected"]})]})}),e(Tt,{initial:!1,children:re?e(Me.div,{className:"grid gap-3",initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:_a.length?_a.map(c=>{const q=String(c?.id||""),oe=Object.keys(c?.models||{}),at=String(vt.data?.providers?.[q]?.default_model||oe[0]||""),At=String(O[q]??at).trim(),na=At.toLowerCase(),Bt=oe.filter(ca=>na?ca.toLowerCase().includes(na):!0).slice(0,80),ea=jm(c,oe.length),$i=Um(c,at),Qr=Xs[q]||null,Gr=String(Qr?.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:q}),e("div",{className:"tcp-subtle text-xs",children:$i})]}),e(je,{tone:ea.tone,children:ea.text})]})}),e("div",{className:"mt-3 grid gap-3",children:[Gr?e("div",{className:"flex justify-end",children:e("a",{className:"tcp-btn h-8 px-3 text-xs",href:Gr,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Get API key"]})}):null,e("form",{className:"grid gap-2",onSubmit:ca=>{ca.preventDefault(),xa(q,At)},children:[e("div",{className:"flex gap-2",children:[e("input",{className:"tcp-input",value:At,placeholder:`Type model id for ${q}`,onInput:ca=>k(nn=>({...nn,[q]:ca.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:Bt.length?Bt.map(ca=>e("button",{type:"button",className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${ca===at?"bg-slate-700/40":""}`,onClick:()=>{k(nn=>({...nn,[q]:ca})),xa(q,ca)},children:ca},ca)):e("div",{className:"tcp-subtle px-2 py-1 text-xs",children:oe.length?"No matching models.":"No live catalog available. Type a model ID manually."})})]}),e("form",{onSubmit:ca=>{ca.preventDefault();const nn=ca.currentTarget.elements.namedItem("apiKey"),Hr=String(nn?.value||"").trim();Hr&&(sa.mutate({providerId:q,apiKey:Hr}),nn.value="")},className:"flex gap-2",children:[e("input",{name:"apiKey",className:"tcp-input",placeholder:String(Qr?.placeholder||`Set ${q} API key`)}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"save"}),"Save"]})]})]})]},q)}):e(We,{text:"No providers were detected from the engine catalog."})}):null})]})}):null,I==="search"?e(ft,{title:"Web Search",subtitle:"Configure the engine's `websearch` backend and provider keys.",actions:e(va,{children:[e(je,{tone:ct.data?.settings?.has_brave_key?"ok":"warn",children:["Brave"," ",ct.data?.settings?.has_brave_key?"configured":"missing"]}),e(je,{tone:ct.data?.settings?.has_exa_key?"ok":"warn",children:["Exa"," ",ct.data?.settings?.has_exa_key?"configured":"missing"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Qt.mutate({backend:R,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(X||"10000",10),brave_api_key:Oe.trim()||void 0,exa_api_key:ae.trim()||void 0}),disabled:!ct.data?.available||Qt.isPending,children:[e("i",{"data-lucide":"save"}),"Save"]})]}),children:ct.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:ct.data?.managed_env_path||"/etc/tandem/engine.env"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:ct.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:R,onChange:c=>we(c.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:X,onInput:c=>$e(c.target.value)})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"Tandem search URL"}),e("input",{className:"tcp-input",placeholder:"https://search.tandem.frumu.ai",value:y,onInput:c=>v(c.target.value)})]}),e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"SearxNG URL"}),e("input",{className:"tcp-input",placeholder:"http://127.0.0.1:8080",value:U,onInput:c=>pe(c.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(je,{tone:ct.data?.settings?.has_brave_key?"ok":"warn",children:ct.data?.settings?.has_brave_key?"Saved":"Missing"})]}),e("input",{className:"tcp-input",type:"password",placeholder:"Paste Brave Search key",value:Oe,onInput:c=>Ke(c.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Qt.mutate({backend:R,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(X||"10000",10),brave_api_key:Oe.trim()||void 0}),disabled:!Oe.trim()||Qt.isPending,children:"Save Brave Key"}),ct.data?.settings?.has_brave_key?e("button",{className:"tcp-btn",onClick:()=>Qt.mutate({backend:R,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(X||"10000",10),clear_brave_key:!0}),disabled:Qt.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(je,{tone:ct.data?.settings?.has_exa_key?"ok":"warn",children:ct.data?.settings?.has_exa_key?"Saved":"Missing"})]}),e("input",{className:"tcp-input",type:"password",placeholder:"Paste Exa API key",value:ae,onInput:c=>ue(c.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Qt.mutate({backend:R,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(X||"10000",10),exa_api_key:ae.trim()||void 0}),disabled:!ae.trim()||Qt.isPending,children:"Save Exa Key"}),ct.data?.settings?.has_exa_key?e("button",{className:"tcp-btn",onClick:()=>Qt.mutate({backend:R,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(X||"10000",10),clear_exa_key:!0}),disabled:Qt.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(We,{text:ct.data?.reason||"Search settings are only editable here when the panel points at a local engine host."})}):null,I==="identity"?e(ft,{title:"Identity preview",subtitle:"Live preview of how the assistant appears across the panel.",actions:e(va,{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:()=>Xt.mutate(),disabled:Xt.isPending,children:[e("i",{"data-lucide":"save"}),"Save"]})]}),children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"inline-flex items-center gap-3",children:[e("span",{className:"tcp-brand-avatar inline-grid h-12 w-12 rounded-xl",children:G?e("img",{src:G,alt:J||"Bot",className:"block h-full w-full object-cover"}):e("i",{"data-lucide":"cpu"})}),e("div",{children:[e("div",{className:"font-semibold",children:J||"Tandem"}),e("div",{className:"tcp-subtle text-xs",children:de||"Control Center"})]})]}),e(va,{children:[e("button",{className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>xt.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:J,onInput:c=>A(c.target.value),placeholder:"Bot name"}),e("input",{className:"tcp-input",value:de,onInput:c=>S(c.target.value),placeholder:"Control panel alias"}),e("input",{className:"tcp-input",value:G,onInput:c=>ee(c.target.value),placeholder:"Avatar URL or data URL"}),e("input",{ref:xt,type:"file",accept:"image/*",className:"hidden",onChange:c=>En(c.target.files?.[0]||null)})]})}):null,I==="theme"?e(ft,{title:"Theme studio",subtitle:"Preview tiles with richer feedback and immediate switching.",children:e(Rm,{themes:d,themeId:p,onChange:u})}):null,I==="channels"?e(ft,{title:"Channel connections",subtitle:"Telegram, Discord, and Slack delivery setup and live listener status.",actions:e(va,{children:[e(je,{tone:E?"ok":"warn",children:[E,"/",m.length," connected"]}),e("button",{className:"tcp-btn",onClick:()=>{wa()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh channels"]})]}),children:e("div",{className:"grid gap-3",children:m.map(c=>{const q=Yt.data?.[c]||{},oe=ua.data?.[c]||{},at=qe[c]||wr(c,q),At=V[c],na=!!q?.has_token||!!(Array.isArray(q?.allowed_users)&&q.allowed_users.length)||!!String(q?.guild_id||"").trim()||!!String(q?.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:c}),e("div",{className:"tcp-subtle text-xs",children:c==="telegram"?"Bot token, allowed users, and style profile.":c==="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(je,{tone:oe.connected?"ok":"warn",children:oe.connected?"Connected":oe.enabled?"Configured":"Disconnected"}),e(je,{tone:q.has_token?"info":"warn",children:q.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:q.has_token?String(q.token_masked||"********"):`Paste ${c} bot token`,value:at.botToken,onInput:Bt=>ze(ea=>({...ea,[c]:{...at,botToken:Bt.target.value}}))}),q.has_token&&!at.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:at.allowedUsers,onInput:Bt=>ze(ea=>({...ea,[c]:{...at,allowedUsers:Bt.target.value}}))})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[c==="telegram"?e("input",{className:"tcp-input",placeholder:"Style profile",value:at.styleProfile,onInput:Bt=>ze(ea=>({...ea,[c]:{...at,styleProfile:Bt.target.value}}))}):null,c==="discord"?e("input",{className:"tcp-input",placeholder:"Guild ID (optional)",value:at.guildId,onInput:Bt=>ze(ea=>({...ea,[c]:{...at,guildId:Bt.target.value}}))}):null,c==="slack"?e("input",{className:"tcp-input",placeholder:"Default channel ID",value:at.channelId,onInput:Bt=>ze(ea=>({...ea,[c]:{...at,channelId:Bt.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:at.mentionOnly,onChange:Bt=>ze(ea=>({...ea,[c]:{...at,mentionOnly:Bt.target.checked}}))}),"Mention only"]})]}),e("div",{className:"tcp-subtle text-xs",children:["Active sessions: ",Number(oe.active_sessions||0),oe.last_error?` · Last error: ${oe.last_error}`:""]}),At?.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:At.hints.map((Bt,ea)=>e("div",{className:"tcp-subtle",children:Bt},`${c}-hint-${ea}`))})]}):null,e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:Ka.isPending,onClick:()=>Ka.mutate(c),children:[e("i",{"data-lucide":"save"}),"Save"]}),c==="discord"?e("button",{className:"tcp-btn",disabled:hn.isPending,onClick:()=>hn.mutate("discord"),children:[e("i",{"data-lucide":"shield-check"}),"Verify"]}):null,e("button",{className:"tcp-btn-danger",disabled:Xa.isPending||!na,onClick:()=>Xa.mutate(c),children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},c)})})}):null,I==="mcp"?e(ft,{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(je,{tone:gn?"ok":"warn",children:[gn,"/",fa.length," connected"]}),e(je,{tone:"info",children:[La.length," tools"]}),e("button",{className:"tcp-btn-primary",onClick:()=>la(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]}),e("button",{className:"tcp-btn",onClick:()=>{Za()},children:[e("i",{"data-lucide":"refresh-cw"}),"Reload"]})]}),children:e("div",{className:"grid gap-3",children:[fa.length?fa.map(c=>{const q=Object.keys(c.headers||{}).filter(Boolean),oe=Array.isArray(c.toolCache)?c.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:c.name}),e("div",{className:"tcp-subtle text-sm",children:c.transport||"No transport set"})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(je,{tone:c.connected?"ok":"warn",children:c.connected?"Connected":"Disconnected"}),e(je,{tone:c.enabled?"info":"warn",children:c.enabled?"Enabled":"Disabled"}),e(je,{tone:"info",children:[oe," tools"]})]})]}),c.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:c.lastError}):null,e("div",{className:"tcp-subtle text-xs",children:q.length?`Auth headers: ${q.join(", ")}`:"No stored auth headers."}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>la(c),children:"Edit"}),e("button",{className:"tcp-btn",disabled:ia.isPending,onClick:()=>ia.mutate({action:c.connected?"disconnect":"connect",server:c}),children:c.connected?"Disconnect":"Connect"}),e("button",{className:"tcp-btn",disabled:ia.isPending,onClick:()=>ia.mutate({action:"refresh",server:c}),children:"Refresh"}),e("button",{className:"tcp-btn",disabled:ia.isPending,onClick:()=>ia.mutate({action:"toggle-enabled",server:c}),children:c.enabled?"Disable":"Enable"}),e("button",{className:"tcp-btn-danger",disabled:ia.isPending,onClick:()=>ia.mutate({action:"delete",server:c}),children:"Delete"})]})]},c.name)}):e("div",{className:"grid gap-3",children:[e(We,{text:"No MCP servers configured."}),e("div",{className:"flex justify-start",children:e("button",{className:"tcp-btn-primary",onClick:()=>la(),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:La.length?La.slice(0,250).join(`
|
|
2459
|
+
`):"No MCP tools discovered yet. Connect a server first."})]})]})}):null,I==="bug_monitor"?e(ft,{title:"Bug monitor",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(je,{tone:Ce.runtime?.monitoring_active?Ce.readiness?.publish_ready?"ok":"info":Ce.readiness?.ingest_ready?"info":"warn",children:Ce.runtime?.monitoring_active?Ce.readiness?.publish_ready?"Monitoring":"Watching locally":Ce.readiness?.ingest_ready?"Ready":"Not ready"}),W||Ce.runtime?.paused?e(je,{tone:"warn",children:"Paused"}):null,e(je,{tone:"info",children:[Number(Ce.runtime?.pending_incidents||0)," incidents"]}),e(je,{tone:"info",children:[Number(Ce.pending_drafts||0)," pending drafts"]}),e(je,{tone:"info",children:[Number(Ce.pending_posts||0)," post attempts"]}),e("button",{className:"tcp-icon-btn",title:"Reload status","aria-label":"Reload status",onClick:()=>Promise.all([ra.refetch(),Mt.refetch(),zt.refetch(),Ct.refetch()]).then(()=>n("ok","Bug Monitor status refreshed.")),children:e("i",{"data-lucide":"refresh-cw"})}),e("button",{className:"tcp-icon-btn",title:W||Ce.runtime?.paused?"Resume monitoring":"Pause monitoring","aria-label":W||Ce.runtime?.paused?"Resume monitoring":"Pause monitoring",disabled:Fe.isPending,onClick:()=>Fe.mutate({action:W||Ce.runtime?.paused?"resume":"pause"}),children:e("i",{"data-lucide":W||Ce.runtime?.paused?"play":"pause"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:B.isPending,onClick:()=>B.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Pa()},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 ${it?"ring-1 ring-emerald-400/40":""}`,onClick:()=>N(c=>!c),children:[e("div",{className:"font-medium",children:it?W?"Paused":"Enabled":"Disabled"}),e("div",{className:"tcp-subtle text-xs",children:it?W?"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 c=String(De||"/").trim();Be(c||"/"),lt(""),H(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,value:De,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>o(""),disabled:!De,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),e("div",{className:"tcp-subtle text-xs",children:De?`Reporter analysis root: ${De}`:"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:b,onChange:c=>T(c.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:C,onChange:c=>$(c.target.value),children:[e("option",{value:"",children:"Select an MCP server"}),fa.map(c=>e("option",{value:c.name,children:c.name},c.name))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider preference"}),e("select",{className:"tcp-input",value:Ye,onChange:c=>Ze(c.target.value),children:[e("option",{value:"auto",children:"Auto"}),e("option",{value:"official_github",children:"Official GitHub"}),e("option",{value:"composio",children:"Composio"}),e("option",{value:"arcade",children:"Arcade"})]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider"}),e("select",{className:"tcp-input",value:bt,onChange:c=>{const q=c.target.value;qt(q),wt("")},children:[e("option",{value:"",children:"Select a provider"}),_a.map(c=>e("option",{value:String(c?.id||""),children:String(c?.id||"")},String(c?.id||"")))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Model"}),e("input",{className:"tcp-input",value:Ae,onChange:c=>wt(c.target.value),list:"bug-monitor-models",disabled:!bt,placeholder:bt?"Type or paste a model id":"Choose a provider first",spellCheck:!1}),e("datalist",{id:"bug-monitor-models",children:an.map(c=>e("option",{value:c},c))}),e("div",{className:"tcp-subtle text-xs",children:bt?an.length?`${an.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 ${It&&!_e?"ring-1 ring-emerald-400/40":""}`,onClick:()=>{te(c=>!c),_e&&It&&h(!1)},children:[e("div",{className:"font-medium",children:"Auto-create new issues"}),e("div",{className:"tcp-subtle text-xs",children:It?"New drafts post to GitHub automatically.":"New drafts stay internal until published manually."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${_e?"ring-1 ring-amber-400/40":""}`,onClick:()=>{h(c=>{const q=!c;return q&&te(!1),q})},children:[e("div",{className:"font-medium",children:"Require approval"}),e("div",{className:"tcp-subtle text-xs",children:_e?"New drafts wait for a manual publish click.":"Approval gate disabled."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${j?"ring-1 ring-sky-400/40":""}`,onClick:()=>z(c=>!c),children:[e("div",{className:"font-medium",children:"Auto-comment matches"}),e("div",{className:"tcp-subtle text-xs",children:j?"Open matching GitHub issues receive new evidence comments.":"Matching issues are detected but not updated automatically."})]})]})]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:f.isPending,title:"Save Bug Monitor settings","aria-label":"Save Bug Monitor settings",onClick:()=>f.mutate(),children:[e("i",{"data-lucide":"save"}),f.isPending?"Saving...":null]}),e("button",{className:"tcp-icon-btn",title:"Add MCP server","aria-label":"Add MCP server",onClick:()=>la(),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:B.isPending,onClick:()=>B.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Pa()},children:e("i",{"data-lucide":"copy"})}),ba?e("button",{className:"tcp-icon-btn",title:ba.connected?"Refresh selected MCP":"Connect selected MCP","aria-label":ba.connected?"Refresh selected MCP":"Connect selected MCP",disabled:ia.isPending,onClick:()=>ia.mutate({action:ba.connected?"refresh":"connect",server:ba}),children:e("i",{"data-lucide":ba.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:Ce.runtime?.monitoring_active?Ce.readiness?.publish_ready?"Monitoring":"Watching locally":Ce.runtime?.paused||W?"Paused":Ce.readiness?.ingest_ready?"Ready":"Blocked"}),e("div",{className:"tcp-subtle text-xs",children:Ce.runtime?.last_runtime_error||Ce.last_error||"No blocking issue reported."}),!Ce.readiness?.publish_ready&&Array.isArray(Ce.missing_required_capabilities)&&Ce.missing_required_capabilities.length?e("div",{className:"tcp-subtle mt-2 text-xs",children:["Missing: ",Ce.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:ba?.name||"None selected"}),e("div",{className:"tcp-subtle text-xs",children:ba?ba.connected?"Connected":"Disconnected":"No server selected"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Bindings: ",Ce.binding_source_version||"unknown version",Ce.bindings_last_merged_at_ms?` · merged ${new Date(Ce.bindings_last_merged_at_ms).toLocaleString()}`:""]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Local directory:"," ",De||String(Ce.config?.workspace_root||"").trim()||"engine workspace root"]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last event:"," ",String(Ce.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:Ce.selected_model?.provider_id&&Ce.selected_model?.model_id?`${Ce.selected_model.provider_id} / ${Ce.selected_model.model_id}`:"No dedicated model selected"}),e("div",{className:"tcp-subtle text-xs",children:Ce.readiness?.selected_model_ready?"Available":"Fail-closed when unavailable"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last processed:"," ",Ce.runtime?.last_processed_at_ms?new Date(Number(Ce.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:"," ",Ce.required_capabilities?.github_list_issues?"ready":"missing"]}),e("div",{children:["github.get_issue:"," ",Ce.required_capabilities?.github_get_issue?"ready":"missing"]}),e("div",{children:["github.create_issue:"," ",Ce.required_capabilities?.github_create_issue?"ready":"missing"]}),e("div",{children:["github.comment_on_issue:"," ",Ce.required_capabilities?.github_comment_on_issue?"ready":"missing"]})]}),Array.isArray(Ce.resolved_capabilities)&&Ce.resolved_capabilities.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:Ce.resolved_capabilities.map((c,q)=>e("div",{children:[String(c.capability_id||"unknown"),":"," ",String(c.tool_name||"unresolved")]},`${c.capability_id||"cap"}-${q}`))}):null,Array.isArray(Ce.selected_server_binding_candidates)&&Ce.selected_server_binding_candidates.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:Ce.selected_server_binding_candidates.map((c,q)=>e("div",{children:[String(c.capability_id||"unknown"),":"," ",String(c.binding_tool_name||"unknown"),c.matched?" · matched":" · candidate"]},`${c.capability_id||"candidate"}-${q}`))}):null,Array.isArray(Ce.discovered_mcp_tools)&&Ce.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:Ce.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:"," ",_e?"Manual publish":It?"Auto-create":"Internal draft only"]}),e("div",{children:["Matched open issues:"," ",j?"Auto-comment":"Detect only"]}),e("div",{children:"Dedupe: Fingerprint marker + label"}),e("div",{children:"Labels: bug-monitor"}),e("div",{children:"Workspace write tools: Disabled"}),e("div",{children:"Model fallback: Fail closed"})]})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent incidents"}),fn.length?e("div",{className:"grid gap-2",children:fn.map(c=>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:c.title||c.event_type}),e(je,{tone:c.last_error?"warn":"info",children:c.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[c.event_type," · seen"," ",Number(c.occurrence_count||0),"x"," · ",c.updated_at_ms?new Date(c.updated_at_ms).toLocaleString():"time unavailable"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:c.workspace_root||"engine workspace root"}),c.last_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:c.last_error}):null,c.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:c.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:tt.isPending,onClick:()=>tt.mutate({incidentId:c.incident_id}),children:e("i",{"data-lucide":"rotate-cw"})}),c.triage_run_id?e("span",{className:"tcp-subtle text-xs",children:["triage run: ",c.triage_run_id]}):null,c.draft_id?e("span",{className:"tcp-subtle text-xs",children:["draft: ",c.draft_id]}):null]})]},c.incident_id))}):e(We,{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"}),Sa.length?e("div",{className:"grid gap-2",children:Sa.map(c=>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:c.title||c.fingerprint}),e(je,{tone:c.status==="approval_required"?"warn":"info",children:c.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[c.repo," ·"," ",c.issue_number?`issue #${c.issue_number}`:"draft only"," ","·"," ",c.created_at_ms?new Date(c.created_at_ms).toLocaleString():"time unavailable"]}),c.github_status?e("div",{className:"tcp-subtle mt-1 text-xs",children:["GitHub: ",c.github_status,c.matched_issue_number?` · matched #${c.matched_issue_number}${c.matched_issue_state?` (${c.matched_issue_state})`:""}`:""]}):null,c.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:c.detail}):null,c.last_post_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:c.last_post_error}):null,c.triage_run_id?e("div",{className:"tcp-subtle mt-2 text-xs",children:["triage run: ",c.triage_run_id]}):null,c.status==="approval_required"?e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:me.isPending,title:"Approve draft","aria-label":"Approve draft",onClick:()=>me.mutate({draftId:c.draft_id,decision:"approve"}),children:[e("i",{"data-lucide":"check"}),me.isPending?"Updating...":null]}),e("button",{className:"tcp-icon-btn",title:"Deny draft","aria-label":"Deny draft",disabled:me.isPending,onClick:()=>me.mutate({draftId:c.draft_id,decision:"deny"}),children:e("i",{"data-lucide":"x"})})]}):null,c.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:_t.isPending,onClick:()=>_t.mutate({draftId:c.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:Jt.isPending,onClick:()=>Jt.mutate({draftId:c.draft_id}),children:e("i",{"data-lucide":"refresh-cw"})})]}),(c.github_issue_url||c.github_comment_url)&&e("div",{className:"mt-3 flex flex-wrap gap-2 text-xs",children:[c.github_issue_url?e("a",{className:"tcp-btn",href:c.github_issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,c.github_comment_url?e("a",{className:"tcp-btn",href:c.github_comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]}),(c.status==="draft_ready"||c.status==="triage_queued")&&!c.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:Le.isPending,onClick:()=>Le.mutate({draftId:c.draft_id}),children:e("i",{"data-lucide":"sparkles"})})}):null]},c.draft_id))}):e(We,{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"}),tn.length?e("div",{className:"grid gap-2",children:tn.map(c=>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:c.operation}),e(je,{tone:c.status==="posted"?"ok":"warn",children:c.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[c.repo,c.issue_number?` · issue #${c.issue_number}`:"",c.updated_at_ms?` · ${new Date(c.updated_at_ms).toLocaleString()}`:""]}),c.error?e("div",{className:"tcp-subtle mt-1 text-xs",children:c.error}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[c.issue_url?e("a",{className:"tcp-btn",href:c.issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,c.comment_url?e("a",{className:"tcp-btn",href:c.comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]})]},c.post_id))}):e(We,{text:"No GitHub post attempts yet."})]})]})}):null,I==="browser"?e(ft,{title:"Browser readiness",subtitle:"Operational browser status, diagnostics, and recovery actions.",actions:e(va,{children:[e("button",{className:"tcp-btn",onClick:()=>{Se.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>ke.mutate(),disabled:ke.isPending,children:[e("i",{"data-lucide":"download"}),ke.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>ge.mutate(),disabled:ge.isPending,children:[e("i",{"data-lucide":"globe"}),ge.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>he(!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:Se.data?Se.data.runnable?"Ready":Se.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",Se.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:Se.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Se.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:Se.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Se.data?.browser?.version||Se.data?.browser?.channel||"No version detected"})]})]}),za.length?e("div",{className:"mt-3 grid gap-2",children:za.map((c,q)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:c.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:c.message||"Unknown browser issue."})]},`${c.code||"issue"}-${q}`))}):null,Pe?e("div",{className:"mt-3 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:[e("div",{className:"font-medium",children:["Smoke test passed",Pe.title?`: ${Pe.title}`:""]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:Pe.final_url||Pe.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",Pe.load_state||"unknown"," · elements:"," ",String(Pe.element_count??0)," · closed:"," ",Pe.closed?"yes":"no"]}),Pe.excerpt?e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto whitespace-pre-wrap break-words",children:Pe.excerpt}):null]}):null]}):null]}),aside:e("div",{className:"grid gap-4",children:[e(ft,{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(Wt.data?.connected?.length||0)," connected, default"," ",String(vt.data?.default||"none")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Browser automation"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:Se.data?Se.data.runnable?"Ready":Se.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(c=>c.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:[gn," connected, ",La.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:[Ce.readiness?.runtime_ready?"Ready":it?"Enabled but blocked":"Disabled"," · ",Number(Ce.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:[E," connected, ",m.length," available"]})]})]})}),e(ft,{title:"Quick access",subtitle:"Jump straight to the section you need.",children:e("div",{className:"grid gap-2",children:Zt.map(c=>e("button",{className:"tcp-list-item flex items-center justify-between text-left",onClick:()=>Q(c.id),children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":c.icon}),c.label]}),I===c.id?e(je,{tone:"ok",children:"open"}):null]},c.id))})})]})}),e(er,{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(Tt,{children:K?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:()=>{H(!1),lt("")}}),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: ",oa||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{Dt&&Be(Dt)},disabled:!Dt,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{oa&&(o(oa),H(!1),lt(""),n("ok",`Bug Monitor directory selected: ${oa}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{H(!1),lt("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:pt,onInput:c=>lt(c.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:st.length?st.map(c=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>Be(String(c?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(c?.name||c?.path||"")]},String(c?.path||c?.name))):e(We,{text:ce?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e(er,{open:M,onClose:()=>he(!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:Se.data?Se.data.runnable?"Ready":Se.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",Se.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:Se.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Se.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:Se.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Se.data?.browser?.version||Se.data?.browser?.channel||"No version detected"})]})]}),e(va,{children:[e("button",{className:"tcp-btn",onClick:()=>{Se.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>ke.mutate(),disabled:ke.isPending,children:[e("i",{"data-lucide":"download"}),ke.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>ge.mutate(),disabled:ge.isPending,children:[e("i",{"data-lucide":"globe"}),ge.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(c=>n("err",c instanceof Error?c.message:String(c))),children:[e("i",{"data-lucide":"activity"}),"Re-run diagnostics"]})]}),Se.isLoading?e(We,{text:"Loading browser diagnostics..."}):Se.data?e(ta,{children:[za.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Blocking issues"}),za.map((c,q)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:c.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:c.message||"Unknown browser issue."})]},`${c.code||"issue"}-${q}`))]}):e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:"Browser automation is ready on this machine."}),Pe?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Latest smoke test"}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:Pe.title||"Smoke test"}),e("div",{className:"tcp-subtle text-xs",children:Pe.final_url||Pe.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",Pe.load_state||"unknown"," · elements:"," ",String(Pe.element_count??0)," · closed:"," ",Pe.closed?"yes":"no"]}),Pe.excerpt?e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:Pe.excerpt}):null]})]}):null,Oa.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommendations"}),Oa.map((c,q)=>e("div",{className:"tcp-list-item text-sm",children:c},`browser-recommendation-${q}`))]}):null,i.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Install hints"}),i.map((c,q)=>e("div",{className:"tcp-list-item text-sm",children:c},`browser-install-hint-${q}`))]}):null,Se.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: ",Se.data.last_error]}):null]}):e(We,{text:"Browser diagnostics are unavailable."})]})}),e(Tt,{children:ne?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:()=>Ie(!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:Qe?"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:()=>Ie(!1),children:e("i",{"data-lucide":"x"})})]}),e("form",{className:"grid gap-3",onSubmit:c=>{c.preventDefault(),ma.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:()=>Ne("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:()=>Ne("manual"),children:[e("i",{"data-lucide":"square-pen"}),"Manual"]})]}),ye==="catalog"?e("div",{className:"grid gap-3",children:[e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"tcp-subtle text-sm",children:$a.generatedAt?`Built-in MCP packs · generated ${$a.generatedAt}`:"Built-in MCP packs"}),e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{Nt.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("input",{className:"tcp-input",value:Ve,onInput:c=>le(c.target.value),placeholder:"Search built-in MCP packs"}),e("div",{className:"grid max-h-[26rem] gap-2 overflow-auto pr-1 md:grid-cols-2",children:en.length?en.map(c=>{const q=Dn.has(String(c.serverConfigName||c.slug||"").toLowerCase());return e("div",{className:"tcp-list-item grid gap-2",children:[e("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-semibold",children:c.name}),e("div",{className:"tcp-subtle text-xs",children:[c.slug,c.requiresSetup?" · setup required":""]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(je,{tone:"info",children:[c.toolCount," tools"]}),e(je,{tone:c.requiresAuth?"warn":"ok",children:c.requiresAuth?"Auth":"Authless"})]})]}),e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:c.description||c.transportUrl}),e("div",{className:"tcp-subtle break-all text-xs",children:c.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:()=>{se(Pr(c.serverConfigName||c.slug||c.name)),rt(c.transportUrl),Ne("manual"),n("ok",`Loaded ${c.name}. Review and save when ready.`)},children:"Use pack"}),c.documentationUrl?e("a",{className:"tcp-btn h-8 px-3 text-xs",href:c.documentationUrl,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Docs"]}):null,q?e(je,{tone:"ok",children:"added"}):null]})]},c.slug)}):e(We,{text:"No built-in MCP packs match this search."})})]}):e(ta,{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:ht,onInput:c=>se(c.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:mt,onChange:c=>ot(c.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:F,onInput:c=>{const q=c.target.value;if(rt(q),!String(ht||"").trim()||ht==="mcp-server"){const oe=js(q);oe&&se(oe)}},placeholder:"https://example.com/mcp"})]}),mt==="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:Rt,onInput:c=>yt(c.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:St,onInput:c=>Ee(c.target.value),placeholder:"token"}),e("div",{className:"tcp-subtle text-xs",children:Ea})]}),e("label",{className:"inline-flex items-center gap-2 text-sm text-slate-200",children:[e("input",{type:"checkbox",className:"accent-slate-400",checked:Ot,onChange:c=>Je(c.target.checked)}),"Connect after save"]})]}),e("div",{className:"tcp-confirm-actions mt-2",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>Ie(!1),children:"Cancel"}),e("button",{type:"submit",className:"tcp-btn-primary",disabled:ma.isPending,children:[e("i",{"data-lucide":"save"}),"Save MCP server"]})]})]})]})]}):null})]})})}function Bm({routeId:a,pageProps:t}){switch(qr(a)){case"chat":return e(zc,{...t});case"studio":return e(Ld,{...t});case"automations":case"packs":case"teams":return e(Vu,{...t});case"agents":return e(Os,{...t});case"channels":return e(Yu,{...t});case"mcp":return e(Us,{...t});case"packs-detail":return e(em,{...t});case"orchestrator":return e(hm,{...t});case"files":return e(fm,{...t});case"memory":return e(vm,{...t});case"teams-detail":return e(Os,{...t});case"feed":return e(Pm,{...t});case"settings":return e(Us,{...t});default:return e(bc,{...t})}}const Fm={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."},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 Km({identity:a,currentRoute:t,providerLocked:n,navRoutes:r,onNavigate:s,onPaletteOpen:l,onThemeCycle:d,onLogout:u,statusBar:p,routeKey:_,children:D,providerGate:x}){const[P,O]=w(!1),[k,J]=w(!1),A=String(a.botAvatarUrl||"").trim(),G=Gs();be(()=>{O(!1)},[t]),be(()=>{try{ya()}catch{}},[t,P,p.bugMonitor?.enabled,p.bugMonitor?.monitoringActive,p.bugMonitor?.paused,p.bugMonitor?.pendingIncidents,p.bugMonitor?.blocked]),be(()=>{J(!1)},[A]);const ee=Fm[t]||{title:String(r.find(([y])=>y===t)?.[1]||"Control Panel"),subtitle:"Desktop-inspired operations UI for Tandem."},de=L(()=>r.find(([y])=>y===t)||r[0],[t,r]),S=L(()=>{const y=p.bugMonitor;return y?.enabled?y.blocked?{toneClass:"blocked",label:"Bug Monitor blocked",shortLabel:"Blocked"}:y.paused?{toneClass:"paused",label:"Bug Monitor paused",shortLabel:"Paused"}:y.pendingIncidents>0?{toneClass:"incidents",label:`Bug Monitor incidents: ${y.pendingIncidents}`,shortLabel:`${y.pendingIncidents} incident${y.pendingIncidents===1?"":"s"}`}:y.monitoringActive?{toneClass:"watching",label:"Bug Monitor watching",shortLabel:"Watching"}:{toneClass:"ready",label:"Bug Monitor ready",shortLabel:"Ready"}:null},[p.bugMonitor]),I=()=>A&&!k?e("img",{src:A,alt:a.botName,className:"block h-full w-full object-cover",onError:()=>J(!0)}):e("span",{className:"text-sm font-semibold uppercase",children:String(a.botName||"T").trim().slice(0,1)||"T"}),Q=()=>r.map(([y,v,U])=>{const pe=t===y,X=n&&y!=="settings";return e("button",{type:"button",title:v,disabled:X,className:`tcp-rail-icon ${pe?"active":""} ${X?"locked":""}`,onClick:()=>s(y),children:[pe?e(Me.span,{layoutId:"tcp-icon-indicator",className:"tcp-rail-icon-indicator"}):null,e("i",{"data-lucide":U})]},y)}),R=(y=!1)=>r.map(([v,U,pe])=>{const X=t===v,$e=n&&v!=="settings";return e("button",{type:"button",disabled:$e,className:`tcp-context-link ${X?"active":""} ${$e?"locked":""}`,onClick:()=>{s(v),y&&O(!1)},children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":pe}),e("span",{children:U})]}),X?e("span",{className:"tcp-context-link-dot"}):null]},v)}),we=(y=!1)=>e(ta,{children:[y?e("div",{className:"tcp-context-hero",children:[e(Zn,{className:"tcp-context-hero-glow"}),e("div",{className:"relative z-10 flex items-center gap-3",children:[e("div",{className:"tcp-brand-avatar h-11 w-11",children:I()}),e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:a.controlPanelName||`${a.botName} Control Panel`}),e("div",{className:"tcp-subtle text-xs",children:"Workspace navigation and system status"})]})]})]}):null,e("div",{className:`tcp-context-section ${y?"":"xl:hidden"}`.trim(),children:[e("div",{className:"tcp-context-section-label",children:"Navigation"}),e("nav",{className:"grid gap-1",children:R(y)})]}),y?e("div",{className:"tcp-context-section",children:[e("div",{className:"tcp-context-section-label",children:"System"}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Engine"}),p.engineHealthy?e(ka,{tone:"ok",text:"healthy"}):e(ka,{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(ka,{tone:"live",text:String(p.activeRuns)}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"idle"})]}),S?e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Bug Monitor"}),e("button",{type:"button",className:`tcp-bug-monitor-pill ${S.toneClass}`,title:p.bugMonitor?.lastError?`${S.label}: ${p.bugMonitor.lastError}`:S.label,onClick:()=>{s("bug-monitor"),y&&O(!1)},children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:S.shortLabel})]})]}):null]})]}):null,e("div",{className:"tcp-context-section mt-auto",children:[e("div",{className:"tcp-context-section-label",children:"Actions"}),e("div",{className:"grid gap-2",children:[e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{l(),y&&O(!1)},children:[e("i",{"data-lucide":"search"}),"Command palette"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{d(),y&&O(!1)},children:[e("i",{"data-lucide":"paint-bucket"}),"Cycle theme"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{u(),y&&O(!1)},children:[e("i",{"data-lucide":"log-out"}),"Logout"]})]})]})]});return e("div",{className:`tcp-shell ${t==="chat"?"tcp-shell-chat":""}`.trim(),children:[e(Zn,{className:"tcp-shell-background",children:[e("div",{className:"tcp-shell-glow tcp-shell-glow-a"}),e("div",{className:"tcp-shell-glow tcp-shell-glow-b"})]}),e("aside",{className:"tcp-icon-rail hidden xl:flex",children:[e("button",{type:"button",className:"tcp-rail-brand",onClick:()=>s("dashboard"),children:e("div",{className:"tcp-brand-avatar h-10 w-10",children:I()})}),e("nav",{className:"tcp-rail-nav",children:Q()}),e("div",{className:"tcp-rail-footer",children:[e(Nn,{title:"Command palette",onClick:l,children:e("i",{"data-lucide":"search"})}),e(Nn,{title:"Cycle theme",onClick:d,children:e("i",{"data-lucide":"paint-bucket"})}),e(Nn,{title:"Logout",onClick:u,children:e("i",{"data-lucide":"log-out"})}),e("div",{className:"mt-2 flex justify-center",children:p.engineHealthy?e(ka,{tone:"ok"}):e(ka,{tone:"warn"})})]})]}),e("aside",{className:"tcp-context-rail hidden lg:flex xl:hidden",children:we(!1)}),e("main",{className:`tcp-main-shell ${t==="chat"?"tcp-main-shell-fill":""}`.trim(),children:[e("section",{className:"tcp-mobile-topbar lg:hidden",children:[e("button",{type:"button",className:"tcp-btn h-10 px-3",onClick:()=>O(!0),children:[e("i",{"data-lucide":"menu"}),"Menu"]}),e("div",{className:"min-w-0 flex-1",children:[e("div",{className:"truncate text-sm font-semibold",children:ee.title}),e("div",{className:"tcp-subtle truncate text-xs",children:de?.[1]||ee.subtitle})]}),S?e("button",{type:"button",className:`tcp-bug-monitor-pill ${S.toneClass}`,title:p.bugMonitor?.lastError?`${S.label}: ${p.bugMonitor.lastError}`:S.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"})]}):null,p.activeRuns>0?e(ka,{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:[S?e("button",{type:"button",className:`tcp-bug-monitor-pill ${S.toneClass}`,title:p.bugMonitor?.lastError?`${S.label}: ${p.bugMonitor.lastError}`:S.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:S.shortLabel})]}):null,e("span",{className:p.providerBadge,children:p.providerText}),p.engineHealthy?e(ka,{tone:"ok",text:"Engine healthy"}):e(ka,{tone:"warn",text:"Checking engine"}),p.activeRuns>0?e(ka,{tone:"live",text:`${p.activeRuns} run`}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"No active runs"})]})]}),e(Tt,{mode:"wait",children:e(Me.section,{className:`tcp-main-content ${t==="chat"?"tcp-main-content-fill":""}`.trim(),initial:G?!1:{opacity:0,y:18},animate:G?void 0:{opacity:1,y:0},exit:G?void 0:{opacity:0,y:-14},transition:G?void 0:{duration:Aa.duration.normal,ease:Aa.easing.standard},children:D},_)})]}),e(Tt,{children:P?e(Me.div,{className:"tcp-mobile-drawer lg:hidden",initial:G?!1:{opacity:0},animate:G?void 0:{opacity:1},exit:G?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-mobile-drawer-backdrop","aria-label":"Close navigation",onClick:()=>O(!1)}),e(Me.aside,{className:"tcp-mobile-drawer-panel",initial:G?!1:{x:"-100%"},animate:G?void 0:{x:0},exit:G?void 0:{x:"-100%"},transition:G?void 0:Aa.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(Nn,{title:"Close",onClick:()=>O(!1),children:e("i",{"data-lucide":"x"})})]}),we(!0)]})]}):null}),e(Tt,{children:x||null})]})}function qi(a){const t=String(a||"").trim().toLowerCase();return!!t&&t!=="ollama"&&t!=="local"}function Lm(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&&!qi(n);return r(a[n])||r(a.providers?.[n])}function Wm(a,t,n){const r=String(a?.default||a?.selected_model?.provider_id||"").trim(),s=a?.providers?.[r]||{},l=String(s.default_model||s.defaultModel||a?.selected_model?.model_id||"").trim(),d=Array.isArray(t?.connected)?t.connected:[],u=new Set(d.map(D=>String(D||"").trim().toLowerCase())),p=Lm(n,r),_=!!r&&!!l&&u.has(r.toLowerCase())&&(!qi(r)||p);return{ready:_,defaultProvider:r,defaultModel:l,connected:[...u],error:"",needsOnboarding:!_}}const Jr="tandem_control_panel_token";function Bs(){try{return localStorage.getItem(Jr)||""}catch{return""}}function zm(a){try{localStorage.setItem(Jr,a)}catch{}}function Jm(){try{localStorage.removeItem(Jr)}catch{}}function Qm(a,t){return Z({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 Wm(n,r,s)}catch(n){return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:n instanceof Error?n.message:String(n),needsOnboarding:!0}}}})}function Gm(a,t){return Z({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 Lt("/api/engine/config/identity",{method:"GET"}))?.identity||{},s=String(r?.bot?.canonical_name||r?.bot?.canonicalName||"").trim(),l=r?.bot?.aliases||{},d=String(r?.bot?.avatar_url||r?.bot?.avatarUrl||"").trim(),u=String(l?.control_panel||l?.controlPanel||"").trim(),p=s||"Tandem";return{botName:p,botAvatarUrl:d,controlPanelName:u||`${p} Control Panel`}}catch{return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"}}}})}function Hm(a){return Z({queryKey:["bug-monitor","status"],enabled:a,refetchInterval:a?1e4:!1,queryFn:async()=>{try{return await Lt("/api/engine/bug-monitor/status",{method:"GET"})}catch{return null}}})}function Vm(){const a=aa(),{toast:t}=gc(),{route:n,navigate:r}=pc(),[s,l]=w(Yl()),[d,u]=w(!1),[p,_]=w(!1),D=Pt(!1);be(()=>{Xl(s)},[s]);const P=Z({queryKey:["auth","me"],retry:!1,refetchInterval:3e4,queryFn:()=>Lt("/api/auth/me",{method:"GET"})}).isSuccess;be(()=>{try{ya()}catch{}},[P,n]);const O=L(()=>P?new Il({baseUrl:"/api/engine",token:"session"}):null,[P]),k=Qm(O,P),J=Gm(O,P),A=hi(P),G=gd(P),ee=Hm(P),de=xe({mutationFn:async({token:qe})=>{await Lt("/api/auth/login",{method:"POST",body:JSON.stringify({token:qe})})},onSuccess:(qe,ze)=>{ze.remember?zm(ze.token):Jm(),a.invalidateQueries({queryKey:["auth","me"]}),t("ok","Signed in."),r("dashboard")},onError:qe=>{t("err",qe instanceof Error?qe.message:String(qe))}});be(()=>{if(P||de.isPending||D.current)return;const qe=Bs().trim();if(!qe){D.current=!0;return}D.current=!0,de.mutate({token:qe,remember:!0})},[P,de]);const S=ut(async()=>{await Lt("/api/auth/logout",{method:"POST"}).catch(()=>{}),a.removeQueries({queryKey:["auth"]}),a.removeQueries({queryKey:["provider"]}),a.removeQueries({queryKey:["identity"]}),a.invalidateQueries({queryKey:["auth","me"]}),t("info","Logged out.")},[a,t]),I=L(()=>new Set(["chat","studio","agents","orchestrator","teams"]),[]),Q=!!k.data?.needsOnboarding,R=P&&Q;be(()=>{if(!R){_(!1);return}I.has(n)&&(r("settings"),p||(_(!0),t("info","Set provider + default model first to unlock the control panel.")))},[I,r,p,R,n,t]);const we=R&&I.has(n)?"settings":n,y=ut(async()=>{await a.invalidateQueries({queryKey:["provider","status"]})},[a]),v=ut(async()=>{await a.invalidateQueries({queryKey:["identity"]})},[a]),U=ut(qe=>{const ze=Zl(qe);return l(ze.id),ze},[l]),pe=J.data||{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"},X={client:O,api:Lt,toast:t,navigate:r,currentRoute:we,providerStatus:{ready:!!k.data?.ready,defaultProvider:k.data?.defaultProvider||"",defaultModel:k.data?.defaultModel||"",connected:k.data?.connected||[],error:k.data?.error||"",needsOnboarding:!!k.data?.needsOnboarding},identity:pe,refreshProviderStatus:y,refreshIdentityStatus:v,providerHints:Xs,themes:ln,setTheme:U,themeId:s},$e=L(()=>{const qe=Zs.map(([V,He])=>({id:`route:${V}`,label:`Go to ${He}`,group:"Routes",onSelect:()=>r(V)})),ze=[{id:"action:new-chat",label:"New chat session",group:"Actions",onSelect:()=>{window.dispatchEvent(new CustomEvent("tcp:new-chat")),r("chat")}},{id:"action:start-engine-check",label:"Check engine health",group:"Actions",onSelect:async()=>{try{const V=await Lt("/api/system/health"),He=V?.engine?.ready||V?.engine?.healthy?"healthy":"unhealthy";t("info",`Engine ${He}: ${V?.engineUrl||"n/a"}`)}catch(V){t("err",V instanceof Error?V.message:String(V))}}},{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,...ze]},[r,t]);if(ic(()=>u(qe=>!qe)),!P)return e(sc,{loginMutation:de,savedToken:Bs(),controlPanelName:pe.controlPanelName,onCheckEngine:async()=>{const qe=await Lt("/api/system/health");return`Engine check: ${qe?.engine?.ready||qe?.engine?.healthy?"healthy":"unhealthy"} at ${qe?.engineUrl||"n/a"}`}});const Oe=k.data?.ready?"tcp-badge-ok":"tcp-badge-warn",Ke=k.data?.ready?`${k.data?.defaultProvider||"none"}/${k.data?.defaultModel||"none"}`:"provider setup required",ae=ee.data||null,ue=!!ae?.config?.enabled,M=Number(ae?.runtime?.pending_incidents||0),he=!!ae?.runtime?.monitoring_active,Te=!!ae?.runtime?.paused,Re=!!ae?.readiness?.ingest_ready,re=!!ae?.readiness?.publish_ready,Ue=String(ae?.runtime?.last_runtime_error||ae?.last_error||"").trim();return e(ta,{children:[e(Km,{identity:pe,currentRoute:we,providerLocked:R,navRoutes:cc,onNavigate:r,onPaletteOpen:()=>u(!0),onThemeCycle:()=>U(Vl(s)),onLogout:S,statusBar:{engineHealthy:!!(A.data?.engine?.ready||A.data?.engine?.healthy),providerBadge:Oe,providerText:Ke,activeRuns:["planning","awaiting_approval","running"].includes(String(G.data?.status||"").toLowerCase())?1:0,bugMonitor:ue?{enabled:!0,monitoringActive:he,paused:Te,pendingIncidents:M,blocked:!Re,lastError:he&&!re&&Ue?`Watching locally only. ${Ue}`:Ue}:null},routeKey:we,providerGate:R&&we!=="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(Bm,{routeId:we,pageProps:X})}),e(oc,{open:d,onClose:()=>u(!1),actions:$e})]})}function Ym(){return e(hc,{children:e(Vm,{})})}const Xm=new ol({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),Mi=document.getElementById("app");if(!Mi)throw new Error("Missing #app host");ji(Mi).render(e(Ui,{children:e(Fi,{client:Xm,children:e(Ym,{})})}));
|