@adhdev/daemon-standalone 0.9.82-rc.259 → 0.9.82-rc.260
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/package.json
CHANGED
|
@@ -26,7 +26,7 @@ var pp=Object.defineProperty;var hp=(e,t,r)=>t in e?pp(e,t,{enumerable:!0,config
|
|
|
26
26
|
50% { transform: translateY(-7px); }
|
|
27
27
|
100% { transform: translateY(0px); }
|
|
28
28
|
}
|
|
29
|
-
`})]})}function al(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function mf(e){var t;return al(e.activeInteractivePrompt)||al((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function pf(e){return e.sessionId||e.instanceId||e.id}function hf(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=mf(n);if(!a)continue;const o=pf(n);if(r&&r!==o&&r!==n.id)continue;return{daemonId:n.daemonId||n.id.split(":")[0]||n.id,sessionId:o,routeId:n.id,providerType:n.type,title:n.title||n.cliName||n.type,prompt:a}}return null}function gd(e,t){var n;const r={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(u=>u.trim()).filter(Boolean))),c=(n=o.freeformText)==null?void 0:n.trim();r[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:r}}function ol(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function il(e,t){var r,n;return!!((r=t==null?void 0:t.freeformText)!=null&&r.trim())||(((n=t==null?void 0:t.selectedLabels)==null?void 0:n.length)||0)>0||e.options.length===0&&e.allowFreeform}function ff({label:e,description:t,selected:r,disabled:n,onClick:a}){return s.jsx("button",{type:"button",disabled:n,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${r?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-primary bg-surface-secondary text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"} ${n?"cursor-not-allowed opacity-60":""}`,children:s.jsxs("span",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border ${r?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-secondary"}`,children:r?s.jsx(ld,{size:12}):null}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&s.jsx("span",{className:"mt-0.5 block text-xs leading-5 text-text-muted",children:t})]})]})})}function yd({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var C;const[o,i]=l.useState(()=>ol(e)),[c,u]=l.useState(0);l.useEffect(()=>{i(ol(e)),u(0)},[e==null?void 0:e.prompt.promptId]);const m=(e==null?void 0:e.prompt.questions)||[],d=m.length,p=c===d-1,h=d===1,b=m[c],v=b?o[b.questionId]:void 0,f=b?il(b,v):!1,w=l.useMemo(()=>e?e.prompt.questions.every(S=>il(S,o[S.questionId])):!1,[e,o]);if(!e)return null;const j=(S,I)=>{i(E=>{const D=E[S.questionId]||{selectedLabels:[]},T=D.selectedLabels||[],M=S.multiSelect?T.includes(I)?T.filter(R=>R!==I):[...T,I]:[I];return{...E,[S.questionId]:{...D,selectedLabels:M}}})},g=(S,I)=>{i(E=>({...E,[S]:{...E[S]||{selectedLabels:[]},freeformText:I}}))},y=()=>{c<d-1&&u(S=>S+1)},N=()=>{c>0&&u(S=>S-1)},k=()=>{!w||t||n(o)},x=gd(e.prompt,o);return s.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/50 px-4 py-6",children:s.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-lg border border-border-primary bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border-primary px-5 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[s.jsx(zs,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[!h&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",d]}),s.jsx("button",{type:"button",onClick:a,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(vt,{size:16})})]})]}),!h&&s.jsx("div",{className:"flex gap-1.5 px-5 pt-3",children:m.map((S,I)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${I<c?"bg-accent-primary":I===c?"bg-accent-primary/60":"bg-border-primary"}`},S.questionId))}),s.jsxs("div",{className:"space-y-4 px-5 py-4",children:[b&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[b.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:b.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[h?"":`${c+1}. `,b.question]})]}),s.jsx("div",{className:"grid gap-2",children:b.options.map(S=>{var I;return s.jsx(ff,{label:S.label,description:S.description||S.preview,selected:(((I=x.answers[b.questionId])==null?void 0:I.selectedLabels)||[]).includes(S.label),disabled:t,onClick:()=>j(b,S.label)},S.label)})}),b.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((C=o[b.questionId])==null?void 0:C.freeformText)||"",disabled:t,onChange:S=>g(b.questionId,S.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("div",{children:!h&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:N,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),h||p?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:!w||t,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:!f||t,children:"Next"})]})]})]})})}function ca(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return n;const c=Math.floor(i/60);if(c<60)return`${c}m${r}`;const u=Math.floor(c/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const vd=e=>ca(e);function xf(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Vs(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function bf(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...xf(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function zn(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function da(e,t,r){const n=zn(e,t),a=Vs(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||c,h=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:h,requiresAction:m,isWorking:d,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":h?"task_complete":"idle"}}function gf(e,t,r){return da(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function wd({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Vs(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},i=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(zs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,u)=>{const m=i(c).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),p=/^(reject|deny|delete|remove|abort)/.test(m),h=r===c,b=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:b,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":p?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${b&&!h?"opacity-40":"opacity-100"} ${b?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:p?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:h?"⏳ ...":i(c)},u)})})]})]})}const Qo="adhdev_controls_bar_visible",wo="adhdev:controlsbarvisibilitychange";function Na(e){if(!e)return!1;try{return e.getItem(Qo)==="1"}catch{return!1}}function yf(e,t){if(t)try{t.setItem(Qo,e?"1":"0")}catch{}}function vf(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(wo,{detail:{visible:e}}))}function Zo(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Na(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&yf(i,window.localStorage),c&&vf(i)},[]);l.useEffect(()=>{const i=u=>{const m=u.detail,d=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Na(window.localStorage);r.current=d,t(d)},c=u=>{if(u.key!==Qo)return;const m=Na(window.localStorage);r.current=m,t(m)};return window.addEventListener(wo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(wo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{n(i)},[n]),o=l.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var wf=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function jf(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Lt(e,t){if(jf(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":r==="waiting_choice"?"waiting_choice":wf.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function jo(e){return Lt(e)==="generating"}function ll(e,t){return Lt(e,t)==="waiting_approval"}function wt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function kf(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),o=r%24;return`${a}d ${o}h`}function Sa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function jd(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function Nf(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Sf(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Cf(e){return Nf(e.trim().replace(/\.local$/i,""))}function If(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function kd(e,t={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Sf(i));if(r&&r!=="Unknown")return Cf(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Pt(e,t={}){return If(e)||kd(e,t)}function Nd(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Sd(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ns(e,t){return Nd(e).join(" · ")}function Ar(e){return e.transport==="pty"}function $s(e){return e.transport==="acp"}function Mf(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:wt(e)}function cl(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=wt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function Af(e,t=[],r=[]){var u,m,d,p;const n=Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="waiting_choice")return"waiting_choice";if(n==="generating")return"generating";const a=t.find(h=>ll(h.status,{activeModal:h.activeModal})||jo(h.status));if(a)return Lt(a.status,{activeModal:a.activeModal});const o=r.find(h=>ll(h.status,{activeModal:h.activeModal})||jo(h.status));if(o)return Lt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Lt((u=t[0])==null?void 0:u.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const c=Lt((d=r[0])==null?void 0:d.status,{activeModal:(p=r[0])==null?void 0:p.activeModal});return c!=="idle"?c:"idle"}function Tf(e){return Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function _f(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Lt(n.status);if(!o){t.set(a,{...n,status:i});continue}const c=r.indexOf(o.status||"idle"),u=r.indexOf(i||"idle");u>=0&&(c<0||u<c)&&t.set(a,{...n,status:i})}return Array.from(t.values())}function Lf(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Pf(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Lf(t.receivedAt)||0}function Rf(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ko(e){return Math.max(Rf(e),Pf(e.activeChat))}function Df(e,t,r,n,a,o){const i=t-e;if(i!==0)return i;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function ei(e,t){return Df(ko(e),ko(t),Pt(e,{fallbackId:e.id}),Pt(t,{fallbackId:t.id}),e.id,t.id)}const Cd="adhdev_notification_prefs",dl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function $f(){try{const e=localStorage.getItem(Cd);if(e){const t=JSON.parse(e);return{...dl,...t}}}catch{}return{...dl}}function Ef(e){try{localStorage.setItem(Cd,JSON.stringify(e))}catch{}}let Xt=$f(),Nn=[];function Bf(){Nn.forEach(e=>e())}function Ff(e){Xt={...Xt,...e},Ef(Xt),Bf()}function Of(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return Nn.push(r),()=>{Nn=Nn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{Ff(r)},[]);return[{...Xt},t]}function yr(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const zf={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Id(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Md(){return"Notification"in window&&Notification.permission==="granted"}let ms=null;function Hf(e){return e!==!1}async function Wf(){if(ms!==null)return ms;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ms=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ms=!!await e.pushManager.getSubscription(),ms):(ms=!1,!1)}catch{return ms=!1,!1}}function No(e,t,r){if(Md())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Kf(e,t={}){const r={...zf,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let u=!1;return Wf().then(m=>{u||i(m)}),()=>{u=!0}},[]);const c=l.useCallback((u,m,d)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,No(u,m,d))},[r.throttleMs]);l.useEffect(()=>{var u;if(!(!r.enabled||!Md())&&yr("browser")&&!Hf(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,Lt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),p=Lt(m.status,{activeModal:m.activeModal}),h=m.name||m.id;if(r.onApproval&&yr("approval")&&p==="waiting_approval"&&d!=="waiting_approval"){const b=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,b.slice(0,120),`approval-${m.id}`)}r.onComplete&&yr("completion")&&jo(d)&&p==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&d!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const Uf=/^(run|approve|accept|yes|allow|always)/,Gf=/^(run|approve|accept|yes|allow|always|proceed|save)/,Vf=/^(reject|deny|delete|remove|abort|cancel|no)/;function ti(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function qf(e){const t=ti(e).toLowerCase();return Uf.test(t)?"primary":Vf.test(t)?"danger":"default"}function Yf(e){return Gf.test(ti(e).toLowerCase())?"approve":"reject"}function Xf(e){return e.map((t,r)=>({label:ti(t),variant:qf(t),action:Yf(t),button:t,buttonIndex:r}))}function Jf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Qf(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Zf{constructor(){Ue(this,"dedupMap",new Map);Ue(this,"DEDUP_WINDOW_MS",5e3);Ue(this,"DEDUP_MAX_SIZE",50);Ue(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ue(this,"toastCallbacks",[]);Ue(this,"statusEventCallbacks",[]);Ue(this,"resolveActionFn",null);Ue(this,"viewRequestRespondFn",null);Ue(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var v;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const f of this.statusEventCallbacks)f(t);const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=wt(m);const p=this.resolveOwningDaemon(t);if(p){const f=Pt(p,{fallbackId:p.id});f&&(d=!m||m==="adhdev-daemon"?f:`${f}/${d}`)}let h="",b="info";if(t.event==="agent:generating_completed"){const f=t.duration?` (${t.duration}s)`:"";h=`✅ ${d} agent task completed${f}`,b="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(h=`⚡ ${d} approval needed`,b="warning",(v=t.modalButtons)!=null&&v.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(t);if(!f)return;const w=this.resolveActionFn,j=Xf(t.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{w(f,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),g=Jf(d,t.modalMessage,h),y=Date.now();this.emitToast({id:y,message:g,type:b,timestamp:y,targetKey:n||f,actions:j,duration:15e3}),h=""}}else if(t.event==="monitor:long_generating"){const f=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";h=`⚠️ ${d} agent is taking a long time${f}`,b="warning",yr("browser")&&!document.hasFocus()&&No(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const f=t.requesterName||"A team member",w=t.requestId,j=t.orgId;if(h=`👁️ ${f} wants to view your session`,b="warning",w&&j&&this.viewRequestRespondFn){const g=Date.now(),y=Qf(j,w,this.viewRequestRespondFn,(N,k)=>console.error(`[EventManager] ${N} view request failed:`,k));this.emitToast({id:g,message:h,type:b,timestamp:g,actions:y,duration:3e4}),h=""}yr("browser")&&!document.hasFocus()&&No("👁️ View Request",`${f} wants to view your session`,`view-request-${w}`)}else t.event==="team:view_request_approved"?(h="✅ View request approved",b="success"):t.event==="team:view_request_rejected"&&(h=`❌ ${t.targetName||"Team member"} declined your view request`,b="warning");if(h){const f=Date.now();this.emitToast({id:f,message:h,type:b,timestamp:f,targetKey:n||t.daemonId,duration:5e3})}}}const tt=new Zf,ul=new Map;function Hn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Es(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ua(e){return Hn(e)?Hn(e.result)?e.result:e:null}function ex(e){const t=ua(e);return!t||!Hn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function nn(e){const t=ua(e);return!t||!Hn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function tr(e){const t=ua(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function an(e){const t=ua(e);return!!t&&t.success===!1}function tx(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";tt.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";tt.showToast(n.notification.body,a)}}}function sx(e,t){return e&&Es(e.currentValue)?e.currentValue:t}function rx(e,t){return Es(t)?Es(e)?typeof e=="string"&&e.trim()==="":!0:!1}function nx(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Es(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Es(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Es(a)?a:void 0}function Sn(e,t){return e.options||t[e.id]||[]}const ax={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function ox(e,t,r){var n;return((n=ax[t])==null?void 0:n.has(r.id))===!0}function si(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!ox(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Ca(e,t){return{value:t}}function ix(e,t,r){var a;return r?((a=Sn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const lx={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function cx({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=lt(),u=`${e}:${t||n}`,m=lx[n]||"#94a3b8",[d,p]=l.useState({}),h=l.useRef({}),b=l.useRef(i);h.current=d,b.current=i;const v=l.useRef(0),f={};for(const L of o||[])L.defaultValue!==void 0&&(f[L.id]=L.defaultValue);const w={...f,...i||{},...Date.now()<v.current?d:{}};l.useEffect(()=>{i&&Date.now()>v.current&&p({})},[i]);const[j,g]=l.useState(ul.get(u)||{}),[y,N]=l.useState(null),[k,x]=l.useState(null),C=l.useCallback(async(L,O={})=>{const P={...O,...t&&{targetSessionId:t}};return await c(e,L,P)},[e,t,c]),S=l.useCallback(async(L,O={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...P,scriptName:L,...O})},[C,n,r,t]),I=l.useCallback((L,O,P)=>{const B=sx(P,O);p($=>({...$,[L.id]:B})),tx(P==null?void 0:P.effects)},[]),E=l.useCallback((L,O)=>{p(P=>{const B={...P};return O===void 0?delete B[L.id]:B[L.id]=O,B}),v.current=0},[]);if(!o||o.length===0)return null;const D=si(o,{hostIdeType:r,providerType:n});if(D.length===0)return null;const T=async L=>{if(y===L.id){N(null);return}if(Sn(L,j).length>0){N(L.id);return}if(L.dynamic&&L.listScript){x(L.id);try{const P=await S(L.listScript,{}),B=ex(P);if(!B){const te=tr(P);te&&tt.showToast(te,"warning");return}const $=B.options;g(te=>{const se={...te,[L.id]:$};return ul.set(u,se),se});const z=nx(L.id,{localOverrideUntil:v.current,localValues:h.current,controlValues:b.current,defaultValues:f});if(rx(z,B.currentValue)){const te=B.currentValue;p(se=>({...se,[L.id]:te}))}N(L.id)}catch(P){const B=P instanceof Error?P.message:`Could not load ${L.label}`;tt.showToast(B,"warning")}finally{x(null)}}},M=async(L,O)=>{N(null);const P=(i==null?void 0:i[L.id])??f[L.id];p(B=>({...B,[L.id]:O})),v.current=Date.now()+5e3;try{if(!L.setScript)return;const B=await S(L.setScript,Ca(L,O)),$=nn(B);if($&&!$.ok||an(B))throw new Error(($==null?void 0:$.error)||tr(B)||`Could not update ${L.label}`);I(L,O,$)}catch(B){E(L,P);const $=B instanceof Error?B.message:`Could not update ${L.label}`;tt.showToast($,"warning")}},R=async L=>{const O=Sn(L,j).map(se=>se.value);if(O.length===0)return;const P=String(w[L.id]||""),$=(O.indexOf(P)+1)%O.length,z=O[$];if(typeof z!="string")return;const te=(i==null?void 0:i[L.id])??f[L.id];p(se=>({...se,[L.id]:z})),v.current=Date.now()+5e3;try{if(!L.setScript)return;const se=await S(L.setScript,Ca(L,z)),Y=nn(se);if(Y&&!Y.ok||an(se))throw new Error((Y==null?void 0:Y.error)||tr(se)||`Could not update ${L.label}`);I(L,z,Y)}catch(se){E(L,te);const Y=se instanceof Error?se.message:`Could not update ${L.label}`;tt.showToast(Y,"warning")}},W=async L=>{const P=!w[L.id],B=(i==null?void 0:i[L.id])??f[L.id];p($=>({...$,[L.id]:P})),v.current=Date.now()+5e3;try{if(!L.setScript)return;const $=await S(L.setScript,Ca(L,P)),z=nn($);if(z&&!z.ok||an($))throw new Error((z==null?void 0:z.error)||tr($)||`Could not update ${L.label}`);I(L,P,z)}catch($){E(L,B);const z=$ instanceof Error?$.message:`Could not update ${L.label}`;tt.showToast(z,"warning")}},A=async L=>{if(!L.invokeScript)return;if(L.confirmMessage){const P=[L.confirmTitle,L.confirmMessage,L.confirmLabel].filter($=>typeof $=="string"&&$.trim().length>0);if(!window.confirm(P.join(`
|
|
29
|
+
`})]})}function al(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function mf(e){var t;return al(e.activeInteractivePrompt)||al((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function pf(e){return e.sessionId||e.instanceId||e.id}function hf(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=mf(n);if(!a)continue;const o=pf(n);if(r&&r!==o&&r!==n.id)continue;return{daemonId:n.daemonId||n.id.split(":")[0]||n.id,sessionId:o,routeId:n.id,providerType:n.type,title:n.title||n.cliName||n.type,prompt:a}}return null}function gd(e,t){var n;const r={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(u=>u.trim()).filter(Boolean))),c=(n=o.freeformText)==null?void 0:n.trim();r[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:r}}function ol(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function il(e,t){var r,n;return!!((r=t==null?void 0:t.freeformText)!=null&&r.trim())||(((n=t==null?void 0:t.selectedLabels)==null?void 0:n.length)||0)>0||e.options.length===0&&e.allowFreeform}function ff({label:e,description:t,selected:r,multiSelect:n,disabled:a,onClick:o}){return s.jsx("button",{type:"button",disabled:a,role:n?"checkbox":"radio","aria-checked":r,onClick:o,className:`w-full text-left rounded-md border px-3 py-2 transition ${r?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-primary bg-surface-secondary text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"} ${a?"cursor-not-allowed opacity-60":""}`,children:s.jsxs("span",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${n?"rounded-sm":"rounded-full"} ${r?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-secondary"}`,children:r?s.jsx(ld,{size:12}):null}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&s.jsx("span",{className:"mt-0.5 block text-xs leading-5 text-text-muted",children:t})]})]})})}function yd({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var C;const[o,i]=l.useState(()=>ol(e)),[c,u]=l.useState(0);l.useEffect(()=>{i(ol(e)),u(0)},[e==null?void 0:e.prompt.promptId]);const m=(e==null?void 0:e.prompt.questions)||[],d=m.length,p=c===d-1,h=d===1,b=m[c],v=b?o[b.questionId]:void 0,f=b?il(b,v):!1,w=l.useMemo(()=>e?e.prompt.questions.every(S=>il(S,o[S.questionId])):!1,[e,o]);if(!e)return null;const j=(S,I)=>{i(E=>{const D=E[S.questionId]||{selectedLabels:[]},T=D.selectedLabels||[],M=S.multiSelect?T.includes(I)?T.filter(R=>R!==I):[...T,I]:[I];return{...E,[S.questionId]:{...D,selectedLabels:M}}})},g=(S,I)=>{i(E=>({...E,[S]:{...E[S]||{selectedLabels:[]},freeformText:I}}))},y=()=>{c<d-1&&u(S=>S+1)},N=()=>{c>0&&u(S=>S-1)},k=()=>{!w||t||n(o)},x=gd(e.prompt,o);return s.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/50 px-4 py-6",children:s.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-lg border border-border-primary bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border-primary px-5 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[s.jsx(zs,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[!h&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",d]}),s.jsx("button",{type:"button",onClick:a,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(vt,{size:16})})]})]}),!h&&s.jsx("div",{className:"flex gap-1.5 px-5 pt-3",children:m.map((S,I)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${I<c?"bg-accent-primary":I===c?"bg-accent-primary/60":"bg-border-primary"}`},S.questionId))}),s.jsxs("div",{className:"space-y-4 px-5 py-4",children:[b&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[b.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:b.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[h?"":`${c+1}. `,b.question]}),b.multiSelect&&b.options.length>0&&s.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:"Select all that apply"})]}),s.jsx("div",{className:"grid gap-2",role:b.multiSelect?"group":"radiogroup","aria-label":b.question,children:b.options.map(S=>{var I;return s.jsx(ff,{label:S.label,description:S.description||S.preview,selected:(((I=x.answers[b.questionId])==null?void 0:I.selectedLabels)||[]).includes(S.label),multiSelect:b.multiSelect,disabled:t,onClick:()=>j(b,S.label)},S.label)})}),b.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((C=o[b.questionId])==null?void 0:C.freeformText)||"",disabled:t,onChange:S=>g(b.questionId,S.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("div",{children:!h&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:N,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),h||p?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:!w||t,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:!f||t,children:"Next"})]})]})]})})}function ca(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return n;const c=Math.floor(i/60);if(c<60)return`${c}m${r}`;const u=Math.floor(c/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const vd=e=>ca(e);function xf(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Vs(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function bf(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...xf(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function zn(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function da(e,t,r){const n=zn(e,t),a=Vs(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||c,h=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:h,requiresAction:m,isWorking:d,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":h?"task_complete":"idle"}}function gf(e,t,r){return da(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function wd({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Vs(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},i=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(zs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,u)=>{const m=i(c).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),p=/^(reject|deny|delete|remove|abort)/.test(m),h=r===c,b=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:b,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":p?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${b&&!h?"opacity-40":"opacity-100"} ${b?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:p?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:h?"⏳ ...":i(c)},u)})})]})]})}const Qo="adhdev_controls_bar_visible",wo="adhdev:controlsbarvisibilitychange";function Na(e){if(!e)return!1;try{return e.getItem(Qo)==="1"}catch{return!1}}function yf(e,t){if(t)try{t.setItem(Qo,e?"1":"0")}catch{}}function vf(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(wo,{detail:{visible:e}}))}function Zo(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Na(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&yf(i,window.localStorage),c&&vf(i)},[]);l.useEffect(()=>{const i=u=>{const m=u.detail,d=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Na(window.localStorage);r.current=d,t(d)},c=u=>{if(u.key!==Qo)return;const m=Na(window.localStorage);r.current=m,t(m)};return window.addEventListener(wo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(wo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{n(i)},[n]),o=l.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var wf=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function jf(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Lt(e,t){if(jf(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":r==="waiting_choice"?"waiting_choice":wf.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function jo(e){return Lt(e)==="generating"}function ll(e,t){return Lt(e,t)==="waiting_approval"}function wt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function kf(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),o=r%24;return`${a}d ${o}h`}function Sa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function jd(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function Nf(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Sf(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Cf(e){return Nf(e.trim().replace(/\.local$/i,""))}function If(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function kd(e,t={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Sf(i));if(r&&r!=="Unknown")return Cf(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Pt(e,t={}){return If(e)||kd(e,t)}function Nd(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Sd(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ns(e,t){return Nd(e).join(" · ")}function Ar(e){return e.transport==="pty"}function $s(e){return e.transport==="acp"}function Mf(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:wt(e)}function cl(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=wt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function Af(e,t=[],r=[]){var u,m,d,p;const n=Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="waiting_choice")return"waiting_choice";if(n==="generating")return"generating";const a=t.find(h=>ll(h.status,{activeModal:h.activeModal})||jo(h.status));if(a)return Lt(a.status,{activeModal:a.activeModal});const o=r.find(h=>ll(h.status,{activeModal:h.activeModal})||jo(h.status));if(o)return Lt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Lt((u=t[0])==null?void 0:u.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const c=Lt((d=r[0])==null?void 0:d.status,{activeModal:(p=r[0])==null?void 0:p.activeModal});return c!=="idle"?c:"idle"}function Tf(e){return Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function _f(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Lt(n.status);if(!o){t.set(a,{...n,status:i});continue}const c=r.indexOf(o.status||"idle"),u=r.indexOf(i||"idle");u>=0&&(c<0||u<c)&&t.set(a,{...n,status:i})}return Array.from(t.values())}function Lf(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Pf(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Lf(t.receivedAt)||0}function Rf(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ko(e){return Math.max(Rf(e),Pf(e.activeChat))}function Df(e,t,r,n,a,o){const i=t-e;if(i!==0)return i;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function ei(e,t){return Df(ko(e),ko(t),Pt(e,{fallbackId:e.id}),Pt(t,{fallbackId:t.id}),e.id,t.id)}const Cd="adhdev_notification_prefs",dl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function $f(){try{const e=localStorage.getItem(Cd);if(e){const t=JSON.parse(e);return{...dl,...t}}}catch{}return{...dl}}function Ef(e){try{localStorage.setItem(Cd,JSON.stringify(e))}catch{}}let Xt=$f(),Nn=[];function Bf(){Nn.forEach(e=>e())}function Ff(e){Xt={...Xt,...e},Ef(Xt),Bf()}function Of(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return Nn.push(r),()=>{Nn=Nn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{Ff(r)},[]);return[{...Xt},t]}function yr(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const zf={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Id(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Md(){return"Notification"in window&&Notification.permission==="granted"}let ms=null;function Hf(e){return e!==!1}async function Wf(){if(ms!==null)return ms;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ms=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ms=!!await e.pushManager.getSubscription(),ms):(ms=!1,!1)}catch{return ms=!1,!1}}function No(e,t,r){if(Md())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Kf(e,t={}){const r={...zf,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let u=!1;return Wf().then(m=>{u||i(m)}),()=>{u=!0}},[]);const c=l.useCallback((u,m,d)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,No(u,m,d))},[r.throttleMs]);l.useEffect(()=>{var u;if(!(!r.enabled||!Md())&&yr("browser")&&!Hf(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,Lt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),p=Lt(m.status,{activeModal:m.activeModal}),h=m.name||m.id;if(r.onApproval&&yr("approval")&&p==="waiting_approval"&&d!=="waiting_approval"){const b=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,b.slice(0,120),`approval-${m.id}`)}r.onComplete&&yr("completion")&&jo(d)&&p==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&d!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const Uf=/^(run|approve|accept|yes|allow|always)/,Gf=/^(run|approve|accept|yes|allow|always|proceed|save)/,Vf=/^(reject|deny|delete|remove|abort|cancel|no)/;function ti(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function qf(e){const t=ti(e).toLowerCase();return Uf.test(t)?"primary":Vf.test(t)?"danger":"default"}function Yf(e){return Gf.test(ti(e).toLowerCase())?"approve":"reject"}function Xf(e){return e.map((t,r)=>({label:ti(t),variant:qf(t),action:Yf(t),button:t,buttonIndex:r}))}function Jf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Qf(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Zf{constructor(){Ue(this,"dedupMap",new Map);Ue(this,"DEDUP_WINDOW_MS",5e3);Ue(this,"DEDUP_MAX_SIZE",50);Ue(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ue(this,"toastCallbacks",[]);Ue(this,"statusEventCallbacks",[]);Ue(this,"resolveActionFn",null);Ue(this,"viewRequestRespondFn",null);Ue(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var v;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const f of this.statusEventCallbacks)f(t);const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=wt(m);const p=this.resolveOwningDaemon(t);if(p){const f=Pt(p,{fallbackId:p.id});f&&(d=!m||m==="adhdev-daemon"?f:`${f}/${d}`)}let h="",b="info";if(t.event==="agent:generating_completed"){const f=t.duration?` (${t.duration}s)`:"";h=`✅ ${d} agent task completed${f}`,b="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(h=`⚡ ${d} approval needed`,b="warning",(v=t.modalButtons)!=null&&v.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(t);if(!f)return;const w=this.resolveActionFn,j=Xf(t.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{w(f,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),g=Jf(d,t.modalMessage,h),y=Date.now();this.emitToast({id:y,message:g,type:b,timestamp:y,targetKey:n||f,actions:j,duration:15e3}),h=""}}else if(t.event==="monitor:long_generating"){const f=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";h=`⚠️ ${d} agent is taking a long time${f}`,b="warning",yr("browser")&&!document.hasFocus()&&No(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const f=t.requesterName||"A team member",w=t.requestId,j=t.orgId;if(h=`👁️ ${f} wants to view your session`,b="warning",w&&j&&this.viewRequestRespondFn){const g=Date.now(),y=Qf(j,w,this.viewRequestRespondFn,(N,k)=>console.error(`[EventManager] ${N} view request failed:`,k));this.emitToast({id:g,message:h,type:b,timestamp:g,actions:y,duration:3e4}),h=""}yr("browser")&&!document.hasFocus()&&No("👁️ View Request",`${f} wants to view your session`,`view-request-${w}`)}else t.event==="team:view_request_approved"?(h="✅ View request approved",b="success"):t.event==="team:view_request_rejected"&&(h=`❌ ${t.targetName||"Team member"} declined your view request`,b="warning");if(h){const f=Date.now();this.emitToast({id:f,message:h,type:b,timestamp:f,targetKey:n||t.daemonId,duration:5e3})}}}const tt=new Zf,ul=new Map;function Hn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Es(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ua(e){return Hn(e)?Hn(e.result)?e.result:e:null}function ex(e){const t=ua(e);return!t||!Hn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function nn(e){const t=ua(e);return!t||!Hn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function tr(e){const t=ua(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function an(e){const t=ua(e);return!!t&&t.success===!1}function tx(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";tt.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";tt.showToast(n.notification.body,a)}}}function sx(e,t){return e&&Es(e.currentValue)?e.currentValue:t}function rx(e,t){return Es(t)?Es(e)?typeof e=="string"&&e.trim()==="":!0:!1}function nx(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Es(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Es(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Es(a)?a:void 0}function Sn(e,t){return e.options||t[e.id]||[]}const ax={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function ox(e,t,r){var n;return((n=ax[t])==null?void 0:n.has(r.id))===!0}function si(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!ox(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Ca(e,t){return{value:t}}function ix(e,t,r){var a;return r?((a=Sn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const lx={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function cx({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=lt(),u=`${e}:${t||n}`,m=lx[n]||"#94a3b8",[d,p]=l.useState({}),h=l.useRef({}),b=l.useRef(i);h.current=d,b.current=i;const v=l.useRef(0),f={};for(const L of o||[])L.defaultValue!==void 0&&(f[L.id]=L.defaultValue);const w={...f,...i||{},...Date.now()<v.current?d:{}};l.useEffect(()=>{i&&Date.now()>v.current&&p({})},[i]);const[j,g]=l.useState(ul.get(u)||{}),[y,N]=l.useState(null),[k,x]=l.useState(null),C=l.useCallback(async(L,O={})=>{const P={...O,...t&&{targetSessionId:t}};return await c(e,L,P)},[e,t,c]),S=l.useCallback(async(L,O={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...P,scriptName:L,...O})},[C,n,r,t]),I=l.useCallback((L,O,P)=>{const B=sx(P,O);p($=>({...$,[L.id]:B})),tx(P==null?void 0:P.effects)},[]),E=l.useCallback((L,O)=>{p(P=>{const B={...P};return O===void 0?delete B[L.id]:B[L.id]=O,B}),v.current=0},[]);if(!o||o.length===0)return null;const D=si(o,{hostIdeType:r,providerType:n});if(D.length===0)return null;const T=async L=>{if(y===L.id){N(null);return}if(Sn(L,j).length>0){N(L.id);return}if(L.dynamic&&L.listScript){x(L.id);try{const P=await S(L.listScript,{}),B=ex(P);if(!B){const te=tr(P);te&&tt.showToast(te,"warning");return}const $=B.options;g(te=>{const se={...te,[L.id]:$};return ul.set(u,se),se});const z=nx(L.id,{localOverrideUntil:v.current,localValues:h.current,controlValues:b.current,defaultValues:f});if(rx(z,B.currentValue)){const te=B.currentValue;p(se=>({...se,[L.id]:te}))}N(L.id)}catch(P){const B=P instanceof Error?P.message:`Could not load ${L.label}`;tt.showToast(B,"warning")}finally{x(null)}}},M=async(L,O)=>{N(null);const P=(i==null?void 0:i[L.id])??f[L.id];p(B=>({...B,[L.id]:O})),v.current=Date.now()+5e3;try{if(!L.setScript)return;const B=await S(L.setScript,Ca(L,O)),$=nn(B);if($&&!$.ok||an(B))throw new Error(($==null?void 0:$.error)||tr(B)||`Could not update ${L.label}`);I(L,O,$)}catch(B){E(L,P);const $=B instanceof Error?B.message:`Could not update ${L.label}`;tt.showToast($,"warning")}},R=async L=>{const O=Sn(L,j).map(se=>se.value);if(O.length===0)return;const P=String(w[L.id]||""),$=(O.indexOf(P)+1)%O.length,z=O[$];if(typeof z!="string")return;const te=(i==null?void 0:i[L.id])??f[L.id];p(se=>({...se,[L.id]:z})),v.current=Date.now()+5e3;try{if(!L.setScript)return;const se=await S(L.setScript,Ca(L,z)),Y=nn(se);if(Y&&!Y.ok||an(se))throw new Error((Y==null?void 0:Y.error)||tr(se)||`Could not update ${L.label}`);I(L,z,Y)}catch(se){E(L,te);const Y=se instanceof Error?se.message:`Could not update ${L.label}`;tt.showToast(Y,"warning")}},W=async L=>{const P=!w[L.id],B=(i==null?void 0:i[L.id])??f[L.id];p($=>({...$,[L.id]:P})),v.current=Date.now()+5e3;try{if(!L.setScript)return;const $=await S(L.setScript,Ca(L,P)),z=nn($);if(z&&!z.ok||an($))throw new Error((z==null?void 0:z.error)||tr($)||`Could not update ${L.label}`);I(L,P,z)}catch($){E(L,B);const z=$ instanceof Error?$.message:`Could not update ${L.label}`;tt.showToast(z,"warning")}},A=async L=>{if(!L.invokeScript)return;if(L.confirmMessage){const P=[L.confirmTitle,L.confirmMessage,L.confirmLabel].filter($=>typeof $=="string"&&$.trim().length>0);if(!window.confirm(P.join(`
|
|
30
30
|
|
|
31
31
|
`)))return}const O=(i==null?void 0:i[L.id])??f[L.id];try{const P=await S(L.invokeScript),B=nn(P);if(B&&!B.ok||an(P))throw new Error((B==null?void 0:B.error)||tr(P)||`Could not run ${L.label}`);B&&I(L,O??!0,B)}catch(P){E(L,O);const B=P instanceof Error?P.message:`Could not run ${L.label}`;tt.showToast(B,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),D.map(L=>{const O=String(w[L.id]||""),P=ix(L,j,O),B=y===L.id,$=k===L.id,z=Sn(L,j),te="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(L.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${m}55`:"var(--border-default)",background:B?`${m}10`:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(L),title:L.label,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$?"Loading…":P||L.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),B&&z.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:L.label}),z.map(se=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:se.value===O?`${m}14`:"transparent",color:se.value===O?"var(--text-primary)":"var(--text-secondary)",borderLeft:se.value===O?`2px solid ${m}`:"2px solid transparent"},title:se.description||se.label,onMouseEnter:Y=>{Y.currentTarget.style.background=`${m}10`},onMouseLeave:Y=>{Y.currentTarget.style.background=se.value===O?`${m}14`:"transparent"},onClick:()=>void M(L,se.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:se.label}),se.value===O&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},se.value))]})]})]},L.id);case"cycle":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void R(L),title:`Click to cycle: ${z.map(se=>se.label).join(" → ")}`,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||L.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},L.id);case"toggle":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:O?`${m}44`:"var(--border-default)",background:O?`${m}14`:"var(--surface-tertiary)",color:O?m:"var(--text-muted)"},onClick:()=>void W(L),"aria-pressed":!!O,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),L.label]},L.id);case"action":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void A(L),children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L.resultDisplay==="inline"&&O?`${L.label}: ${O}`:L.label})]},L.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O?`${L.label}: ${O}`:L.label})]},L.id);default:return null}})]})})}function dx({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:u}){const{isVisible:m}=Zo(),d=si(c,{hostIdeType:a,providerType:o});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(cx,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:d,controlValues:u})})}const sr=5,Ad=10*1024*1024;function ux({hasDraft:e,isBusy:t=!1}){return!e||t}function mx(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function px(e){if(e.size>Ad)return null;const t=await mx(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function hx(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Td=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:i,onForceSend:c,canForceSend:u=!1,isActive:m=!0,showControlsToggle:d=!1,animateVisibility:p=!0,onControlsToggle:h,messageInput:b}){const v=l.useRef(null),f=l.useRef(null),[w,j]=l.useState(""),[g,y]=l.useState([]),[N,k]=l.useState(null),[x,C]=l.useState(!1),S=l.useRef(!1),{isVisible:I,toggleVisibility:E}=Zo(),D=hx(b),T=!!w.trim()||g.length>0;l.useEffect(()=>{j(""),y([]),k(null)},[t]),l.useEffect(()=>{var B;m&&((B=v.current)==null||B.focus({preventScroll:!0}))},[t,m]),l.useEffect(()=>{const B=v.current;B&&(B.style.height="auto",B.style.height=`${Math.min(B.scrollHeight,160)}px`)},[w]);const M=l.useCallback(async B=>{k(null);const $=Array.from(B).filter(ge=>ge.type.startsWith("image/"));if($.length===0)return;const z=sr-g.length;if(z<=0){k(`Max ${sr} images`);return}const te=$.slice(0,z);if(te.filter(ge=>ge.size>Ad).length>0){k("Image too large (max 10 MB)");return}const ne=(await Promise.all(te.map(px))).filter(ge=>ge!==null);y(ge=>[...ge,...ne])},[g.length]),R=l.useCallback(B=>{y($=>$.filter((z,te)=>te!==B))},[]),W=l.useCallback(async()=>{const B=w.trim();if(!B&&g.length===0||a||S.current)return;S.current=!0;const $=g.length>0?[...g]:void 0;try{await i(B,$)!==!1&&(j(""),y([]),k(null))}finally{S.current=!1}},[w,g,a,i]),A=l.useCallback(async()=>{if(!u||!c)return;const B=w.trim();if(!B&&g.length===0||S.current)return;S.current=!0;const $=g.length>0?[...g]:void 0;try{await c(B,$)!==!1&&(j(""),y([]),k(null))}finally{S.current=!1}},[g,u,w,c]),L=l.useCallback(B=>{D&&(B.preventDefault(),C(!0))},[D]),O=l.useCallback(()=>C(!1),[]),P=l.useCallback(B=>{D&&(B.preventDefault(),C(!1),B.dataTransfer.files.length>0&&M(B.dataTransfer.files))},[D,M]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",p?"transition-all duration-200 ease-out":"",x?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:m?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:m?200:0,opacity:m?1:0,transform:m?"translateY(0)":"translateY(10px)",padding:m?"10px 12px":"0 12px",pointerEvents:m?"auto":"none"},"aria-hidden":!m,onDragOver:L,onDragLeave:O,onDrop:P,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((B,$)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:B.previewUrl,alt:B.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>R($),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${B.name}`,children:"✕"})]},$))}),s.jsxs("div",{className:"flex gap-2 items-center",title:m?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{E(),h==null||h()},"aria-label":I?"Hide controls":"Show controls","aria-pressed":I,title:I?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),D&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:f,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:B=>{B.target.files&&M(B.target.files),B.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var B;return(B=f.current)==null?void 0:B.click()},disabled:g.length>=sr,title:g.length>=sr?`Max ${sr} images`:"Attach image",className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("textarea",{ref:v,rows:1,placeholder:o||(D&&g.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:w,onChange:B=>j(B.target.value),onPaste:B=>{D&&B.clipboardData.files.length>0&&Array.from(B.clipboardData.files).some(z=>z.type.startsWith("image/"))&&(B.preventDefault(),M(B.clipboardData.files))},onKeyDown:B=>{B.key==="Enter"&&(B.nativeEvent.isComposing||B.shiftKey||(B.preventDefault(),W()))},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),s.jsx("button",{onClick:()=>{W()},disabled:ux({hasDraft:T,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${T&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:T&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:T?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),u&&s.jsx("button",{type:"button",onClick:()=>{A()},disabled:!T,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${T?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(N||D&&x)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${N?"text-red-400":"text-[var(--accent-primary)]"}`,children:N||"Drop image here"}),o&&!N&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})});function ml(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function pl(e){if(!e)return"";const t=Date.now()-e;if(t<0)return"";const r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function fx({sessionId:e,daemonId:t,onClose:r}){const{sendCommand:n}=lt(),[a,o]=l.useState(!0),[i,c]=l.useState(null),[u,m]=l.useState(null),d=l.useCallback(async()=>{o(!0),m(null);try{const p=await n(t,"get_session_info",{targetSessionId:e}),h=p&&typeof p=="object"?p:{},b=h.result&&typeof h.result=="object"?h.result:h;b!=null&&b.success?c(b):(m((b==null?void 0:b.error)||"Failed to load session info"),c(null))}catch(p){m((p==null?void 0:p.message)||String(p)),c(null)}finally{o(!1)}},[n,t,e]);return l.useEffect(()=>{d()},[d]),l.useEffect(()=>{const p=h=>{h.key==="Escape"&&r()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Session info",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:r,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-border-default rounded-lg shadow-xl max-w-2xl w-full max-h-[85vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[s.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),s.jsx("button",{type:"button",onClick:r,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[a&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),u&&s.jsx("div",{className:"text-red-500",children:u}),(i==null?void 0:i.session)&&s.jsxs(hl,{title:"Session",children:[s.jsx(Dt,{k:"Session ID",v:s.jsx(rr,{children:i.session.sessionId})}),s.jsx(Dt,{k:"Provider",v:`${i.session.providerName||i.session.providerType} (${i.session.providerType})`}),i.session.transport&&s.jsx(Dt,{k:"Transport",v:i.session.transport}),i.session.workspace&&s.jsx(Dt,{k:"Workspace",v:s.jsx(rr,{children:i.session.workspace})}),s.jsx(Dt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[ml(i.session.spawnedAtMs),i.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:pl(i.session.spawnedAtMs)}):null]})}),i.session.providerSessionId&&s.jsx(Dt,{k:"Provider session ID",v:s.jsx(rr,{children:i.session.providerSessionId})})]}),(i==null?void 0:i.coordinator)&&s.jsxs(hl,{title:"Mesh coordinator",children:[s.jsx(Dt,{k:"Mesh ID",v:s.jsx(rr,{children:i.coordinator.meshId})}),i.coordinator.cliType&&s.jsx(Dt,{k:"Coordinator CLI",v:i.coordinator.cliType}),s.jsx(Dt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[ml(i.coordinator.startedAt),i.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:pl(i.coordinator.startedAt)}):null]})}),i.coordinator.injection&&s.jsx(Dt,{k:"Prompt injection",v:`${i.coordinator.injection.mode}${i.coordinator.injection.target?` → ${i.coordinator.injection.target}`:""}`}),i.coordinator.mcpConfigPath&&s.jsx(Dt,{k:"MCP config",v:s.jsx(rr,{children:i.coordinator.mcpConfigPath})}),i.coordinator.extraSystemPrompt&&s.jsx(fl,{title:"Per-launch extra prompt",body:i.coordinator.extraSystemPrompt,defaultOpen:!0}),i.coordinator.systemPrompt&&s.jsx(fl,{title:"Final system prompt (click to expand)",body:i.coordinator.systemPrompt})]}),i&&!i.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with."})]}),s.jsxs("div",{className:"border-t border-border-subtle px-4 py-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void d(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function hl({title:e,children:t}){return s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),s.jsx("div",{className:"space-y-1",children:t})]})}function Dt({k:e,v:t}){return s.jsxs("div",{className:"flex gap-3",children:[s.jsx("div",{className:"w-44 shrink-0 text-text-secondary",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function rr({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function fl({title:e,body:t,defaultOpen:r=!1}){const[n,a]=l.useState(r);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:()=>a(o=>!o),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[n?"▾":"▸"," ",e]}),n&&s.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}function xx({sessionId:e,daemonId:t}){const[r,n]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>n(!0),title:"Session info — system prompt, MCP config, spawned at, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),r&&s.jsx(fx,{sessionId:e,daemonId:t,onClose:()=>n(!1)})]})}const Ze=e=>e.transport==="pty",qs=(e,t)=>Ze(e)?e.mode||"terminal":"chat",_d=(e,t)=>Ze(e)&&qs(e)==="terminal",Ye=e=>e.transport==="acp",bx=180;function ls(e){return e.streamSource!=="agent-stream"}function Ms(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ld(e){return e.machineName||""}function Fr(e){return Ms(e)}function Vt(e){return e.agentType||""}function Wn(e){return e.hostIdeType||""}function ri(e){return e.displayPrimary||e.agentName||"Agent"}function Pd(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function gx(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Rd(e){const t=gx(e),r=Fs(t==null?void 0:t.content),n=Fs(e.lastMessagePreview);return r||n||""}function yx(e,t=bx){const r=Fs(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function vx(e){return yx(Rd(e)||e.displaySecondary||"")}function Dd(e){return[e.displaySecondary,Ld(e)].filter(Boolean)}function Ws(e){return e.agentName||wt(Vt(e))}function wx(e){var t,r;if(!ls(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return wt(Wn(e)||Vt(e))}function $d(e){return ls(e)?e.sessionId:e.nativeSessionId}function xl(e){return ls(e)?"native":e.tabKey}function jx(e){return e.sessionId}function kx(e,t){if(t)return ls(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Nx(e,t){const r=Vt(e),n=ls(e),a=Ze(e)||Ye(e),o=n?a?Ws(e)||(t==null?void 0:t.cliName)||wt(Wn(e)||r):t!=null&&t.type?wt(t.type):wt(Wn(e)||r):Ws(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:Ye(e),isCliTerminal:_d(e),providerType:r,displayLabel:o,targetEntry:kx(e,t)}}function bs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ze(e)||Ye(e)?{agentType:Vt(e)}:e.streamSource==="agent-stream"?{agentType:Vt(e)}:t}function gs(e){return e?Fr(e):""}function nr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function ni(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function bl(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Message queued and will send after the current reply finishes.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function Ed(){return"select_session"}function Sx(){return"open_panel"}function Cx({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function gl(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function on(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function vr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ai(e){return e instanceof Error?e.message:String(e||"")}function yl(e){const t=ai(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function vl(e,t){const r=ai(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function wl(e,t,r,n={}){const a=bs(r);if(!t||t.length===0)return{message:e,...n.force?{force:!0}:{},...a};const o=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&o.push({type:"text",text:e}),{message:e,input:{parts:o,textFallback:e},...n.force?{force:!0}:{},...a}}function ma({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[u,m]=l.useState(null),d=l.useRef(!1),p=l.useRef(null);l.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const h=l.useCallback(async(j,g)=>{if(!t||d.current)return!1;const y=j.trim(),N=ni(t);if(Cx({hasMessage:!!y,blockedMessage:N,sendInFlight:d.current}))return N&&m(N),!1;const k=Date.now(),x={tabKey:t.tabKey,message:y,timestamp:k};if(gl(p.current,x))return m(null),!0;d.current=!0,c(!0),m(null),p.current=x;try{const C=gs(t);if(!C)return p.current=on(p.current,x),m("Unable to send message right now."),!1;const S=await e(C,"send_chat",wl(y,g,t)),I=vr(S);if(I!=null&&I.deduplicated)return m(null),!0;if((I==null?void 0:I.sent)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");if((I==null?void 0:I.success)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");return m(null),!0}catch(C){const S=ai(C);return S.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",S):console.warn("Send blocked/failed",C),p.current=on(p.current,x),m(bl(C)),!1}finally{d.current=!1,c(!1)}},[t,e]),b=l.useCallback(async(j,g)=>{if(!t||d.current)return!1;const y=j.trim();if(!y&&(!g||g.length===0))return!1;const N=Date.now(),k={tabKey:t.tabKey,message:`force:${y}`,timestamp:N};if(gl(p.current,k))return m(null),!0;d.current=!0,c(!0),m(null),p.current=k;try{const x=gs(t);if(!x)return p.current=on(p.current,k),m("Unable to send message right now."),!1;const C=await e(x,"send_chat",wl(y,g,t,{force:!0})),S=vr(C);if((S==null?void 0:S.success)===!1||(S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return m(null),!0}catch(x){return console.warn("Force send blocked/failed",x),p.current=on(p.current,k),m(bl(x)),!1}finally{d.current=!1,c(!1)}},[t,e]),v=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),f=l.useCallback(async j=>{if(t)try{const y=(t.modalButtons||[]).indexOf(j),N=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),x=gs(t);if(!x)return;const C=await e(x,"resolve_action",{button:j,action:k?"approve":"reject",...y>=0&&{buttonIndex:y},...bs(t)}),S=vr(C);S.success||r(I=>[...I,{routeId:t.tabKey,text:vl(j,S==null?void 0:S.error),timestamp:Date.now()}])}catch(g){yl(g)||console.error("[ModalButton] Error:",g),r(y=>[...y,{routeId:t.tabKey,text:yl(g)?vl(j,g):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),w=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Sx(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(j){console.error("Focus agent failed",j)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:h,handleForceSendChat:b,handleRelaunch:v,handleModalButton:f,handleFocusAgent:w}}const Ix=10,Mx=8e3,Ax=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Tx(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function So(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Ax.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Tx(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>So(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,So(a,n,r+1)]))}function ar(e,t){return Array.isArray(e)?e.slice(-t):[]}function _x(e,t=Date.now()){const r=e&&t-e.firstAt<=Mx,n=r?e.count+1:1;return n>=Ix?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Bd(e){var n,a;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:ar(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:ar(t.messages,10),visibleMessagesTail:ar(e.visibleMessages,5),historyMessagesTail:ar(e.chatTailState.historyMessages,5),actionLogsTail:ar(e.actionLogs.filter(o=>o.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return So(r)}function Fd(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function Od(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function zd(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
32
32
|
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
package/public/index.html
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<meta name="description" content="ADHDev self-hosted dashboard for controlling AI agents" />
|
|
8
8
|
<link rel="icon" href="/otter-logo.png" />
|
|
9
9
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet" />
|
|
10
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
+
<script type="module" crossorigin src="/assets/index-C5W61nZC.js"></script>
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/vendor-BHUMCOj6.js">
|
|
12
12
|
<link rel="stylesheet" crossorigin href="/assets/index-DW-XJSIP.css">
|
|
13
13
|
</head>
|
|
@@ -762,6 +762,28 @@ function buildQueueMaintenanceReport(queue) {
|
|
|
762
762
|
cleanupCandidateCount: cleanupCandidates.length
|
|
763
763
|
};
|
|
764
764
|
}
|
|
765
|
+
function buildCompactQueueMaintenanceReport(maintenance) {
|
|
766
|
+
const staleAssignedTasks = Array.isArray(maintenance.staleAssignedTasks) ? maintenance.staleAssignedTasks : [];
|
|
767
|
+
const cleanupCandidateCount = maintenance.cleanupCandidateCount ?? 0;
|
|
768
|
+
return {
|
|
769
|
+
readOnly: true,
|
|
770
|
+
mutationPerformed: false,
|
|
771
|
+
sourceOfTruth: "mesh_work_queue_file",
|
|
772
|
+
payloadMode: "compact",
|
|
773
|
+
staleAssignedDefinition: maintenance.staleAssignedDefinition,
|
|
774
|
+
historicalDefinition: maintenance.historicalDefinition,
|
|
775
|
+
// staleAssignedTasks are active assigned rows (not historical) — retain a
|
|
776
|
+
// bounded sample so coordinators can still see drift without the full array.
|
|
777
|
+
staleAssignedTasks: staleAssignedTasks.slice(0, 5),
|
|
778
|
+
staleAssignedSampleLimit: 5,
|
|
779
|
+
staleAssignedCount: maintenance.staleAssignedCount ?? staleAssignedTasks.length,
|
|
780
|
+
historicalRecordCount: maintenance.historicalRecordCount ?? 0,
|
|
781
|
+
oldHistoricalRecordCount: maintenance.oldHistoricalRecordCount ?? 0,
|
|
782
|
+
cleanupCandidateCount,
|
|
783
|
+
cleanupCandidatesOmitted: true,
|
|
784
|
+
cleanupCandidatesHint: "Per-row cleanup candidates are omitted in compact mode; call mesh_view_queue with verbose=true for the full maintenance/cleanupDryRun rows."
|
|
785
|
+
};
|
|
786
|
+
}
|
|
765
787
|
function annotateQueueStaleness(queue, mesh) {
|
|
766
788
|
const liveness = buildQueueLivenessIndex(mesh);
|
|
767
789
|
const now = Date.now();
|
|
@@ -1991,7 +2013,7 @@ var MESH_VIEW_QUEUE_TOOL = {
|
|
|
1991
2013
|
enum: ["all", "active", "historical"],
|
|
1992
2014
|
description: "Optional row view. active returns pending/assigned rows, historical returns completed/failed/cancelled rows, all returns every persisted queue row. Defaults to all for compatibility."
|
|
1993
2015
|
},
|
|
1994
|
-
compact: { type: "boolean", description: "Slim payload for LLM callers. Default true. Drops large historical (completed/failed/cancelled) row arrays in favor of
|
|
2016
|
+
compact: { type: "boolean", description: "Slim payload for LLM callers. Default true. Drops large historical (completed/failed/cancelled) queue row arrays, the full staleDirectWork orphan array (kept as staleDirectWorkSummary counts), and per-row maintenance cleanupCandidates in favor of counts; pending/assigned active rows are retained. Set false (or verbose=true) for the full dashboard-grade payload." },
|
|
1995
2017
|
verbose: { type: "boolean", description: "Force the full payload; overrides compact." }
|
|
1996
2018
|
}
|
|
1997
2019
|
}
|
|
@@ -2035,7 +2057,9 @@ var MESH_SEND_TASK_TOOL = {
|
|
|
2035
2057
|
session_id: { type: "string", description: "Agent session ID on the target node." },
|
|
2036
2058
|
message: { type: "string", description: "Natural-language task to send to the agent." },
|
|
2037
2059
|
task_mode: { type: "string", enum: ["code_change", "validation", "live_debug_readonly", "launch_app", "convergence"], description: "Optional task-mode contract. live_debug_readonly rejects obvious write/commit/push/deploy/destructive instructions before local or remote direct dispatch." },
|
|
2038
|
-
taskMode: { type: "string", enum: ["code_change", "validation", "live_debug_readonly", "launch_app", "convergence"], description: "CamelCase alias for task_mode." }
|
|
2060
|
+
taskMode: { type: "string", enum: ["code_change", "validation", "live_debug_readonly", "launch_app", "convergence"], description: "CamelCase alias for task_mode." },
|
|
2061
|
+
mission_id: { type: "string", description: "Mission this task belongs to (mesh_mission record id). When set, the directly dispatched task is attributed to the mission task aggregates exactly like mesh_enqueue_task, including terminal completion. Omit for an unattributed direct dispatch." },
|
|
2062
|
+
missionId: { type: "string", description: "CamelCase alias for mission_id." }
|
|
2039
2063
|
},
|
|
2040
2064
|
required: ["node_id", "session_id", "message"]
|
|
2041
2065
|
}
|
|
@@ -2234,6 +2258,23 @@ var MESH_REFINE_NODE_TOOL = {
|
|
|
2234
2258
|
required: ["node_id"]
|
|
2235
2259
|
}
|
|
2236
2260
|
};
|
|
2261
|
+
var MESH_REFINE_BATCH_TOOL = {
|
|
2262
|
+
name: "mesh_refine_batch",
|
|
2263
|
+
description: "Batch Refinery: converge multiple sibling worktree nodes onto the base branch in one conflict-aware sequential pipeline. Orders nodes by change-area (non-submodule nodes first, submodule-touching nodes serialized last) so each merged sibling advances the base and the next node auto-rebases + re-checks patch-equivalence before its own merge. Each node runs the same validation/patch-equivalence/submodule-reachability/merge/cleanup gates as mesh_refine_node. Conflicting or blocked nodes are isolated as blocked_review while the rest of the batch proceeds. Defaults to dry-run (plan only); set execute=true to converge. Never force-pushes or resets.",
|
|
2264
|
+
inputSchema: {
|
|
2265
|
+
type: "object",
|
|
2266
|
+
properties: {
|
|
2267
|
+
node_ids: {
|
|
2268
|
+
type: "array",
|
|
2269
|
+
items: { type: "string" },
|
|
2270
|
+
description: "Optional explicit node IDs to converge, in any order (the tool computes the safe merge order). When omitted, all local worktree nodes that need convergence are auto-collected."
|
|
2271
|
+
},
|
|
2272
|
+
execute: { type: "boolean", description: "When true, run validation/rebase/merge for each node in order. Defaults false/dry-run." },
|
|
2273
|
+
dry_run: { type: "boolean", description: "Preview the ordering + per-node validation plan without executing. Defaults true unless execute=true; dry_run=true overrides execute." }
|
|
2274
|
+
},
|
|
2275
|
+
required: []
|
|
2276
|
+
}
|
|
2277
|
+
};
|
|
2237
2278
|
var MESH_REFINE_CONFIG_SCHEMA_TOOL = {
|
|
2238
2279
|
name: "mesh_refine_config_schema",
|
|
2239
2280
|
description: "Return the Repo Mesh Refinery config JSON schema and supported repo-local config locations. This is the validation source of truth; heuristic command detection is suggestions-only.",
|
|
@@ -2300,6 +2341,7 @@ var ALL_MESH_TOOLS = [
|
|
|
2300
2341
|
MESH_CLONE_NODE_TOOL,
|
|
2301
2342
|
MESH_REMOVE_NODE_TOOL,
|
|
2302
2343
|
MESH_REFINE_NODE_TOOL,
|
|
2344
|
+
MESH_REFINE_BATCH_TOOL,
|
|
2303
2345
|
MESH_REFINE_CONFIG_SCHEMA_TOOL,
|
|
2304
2346
|
MESH_VALIDATE_REFINE_CONFIG_TOOL,
|
|
2305
2347
|
MESH_SUGGEST_REFINE_CONFIG_TOOL,
|
|
@@ -2522,16 +2564,13 @@ async function meshStatus(ctx, args = {}) {
|
|
|
2522
2564
|
});
|
|
2523
2565
|
if (asyncRefineJobs.length > 0) {
|
|
2524
2566
|
if (compact) {
|
|
2525
|
-
const
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
}
|
|
2533
|
-
if (activeJobs.length > 0) response.asyncRefineJobs = activeJobs;
|
|
2534
|
-
response.asyncRefineJobsSummary = { total: asyncRefineJobs.length, byStatus };
|
|
2567
|
+
const summary = (0, import_daemon_core.summarizeMeshAsyncRefineJobs)(asyncRefineJobs);
|
|
2568
|
+
if (summary.activeJobs.length > 0) response.asyncRefineJobs = summary.activeJobs;
|
|
2569
|
+
response.asyncRefineJobsSummary = {
|
|
2570
|
+
total: summary.total,
|
|
2571
|
+
byStatus: summary.byStatus,
|
|
2572
|
+
...summary.staleTerminal > 0 ? { staleTerminal: summary.staleTerminal } : {}
|
|
2573
|
+
};
|
|
2535
2574
|
} else {
|
|
2536
2575
|
response.asyncRefineJobs = asyncRefineJobs;
|
|
2537
2576
|
}
|
|
@@ -2835,6 +2874,11 @@ async function meshViewQueue(ctx, args) {
|
|
|
2835
2874
|
const visibleQueue = compact ? queue.filter((task) => !HISTORICAL_QUEUE_STATUSES.has(String(task?.status || ""))) : queue;
|
|
2836
2875
|
const wantActiveQueueArray = view === "active" || statusFilter?.some((status) => ACTIVE_QUEUE_STATUSES.has(status));
|
|
2837
2876
|
const wantHistoricalQueueArray = !compact && (view === "historical" || requestedHistoricalRows);
|
|
2877
|
+
const staleDirectWorkSummary = (0, import_daemon_core.buildCompactStaleDirectWorkSummary)(activeWorkEvidence.staleDirectWork, {
|
|
2878
|
+
note: activeWorkEvidence.staleDirectWorkNote,
|
|
2879
|
+
detailHint: "Full stale direct entries are omitted from mesh_view_queue in compact mode. Call mesh_view_queue with verbose=true, or inspect mesh_task_history for ledger detail."
|
|
2880
|
+
});
|
|
2881
|
+
const maintenanceForResponse = compact ? buildCompactQueueMaintenanceReport(maintenance) : maintenance;
|
|
2838
2882
|
return JSON.stringify({
|
|
2839
2883
|
success: true,
|
|
2840
2884
|
payloadMode: compact ? "compact" : "full",
|
|
@@ -2852,7 +2896,8 @@ async function meshViewQueue(ctx, args) {
|
|
|
2852
2896
|
queue: visibleQueue,
|
|
2853
2897
|
...compact ? { historicalRowsOmitted: true, historicalRowsHint: "Completed/failed/cancelled rows are omitted in compact mode; see historicalCounts. Call mesh_view_queue with verbose=true (or view=historical, compact=false) for full rows." } : {},
|
|
2854
2898
|
activeWork: activeWorkEvidence.activeWork,
|
|
2855
|
-
|
|
2899
|
+
staleDirectWorkSummary,
|
|
2900
|
+
...compact ? {} : { staleDirectWork: activeWorkEvidence.staleDirectWork },
|
|
2856
2901
|
activeWorkSummary: activeWorkEvidence.summary,
|
|
2857
2902
|
...pollingGuidance ? { pollingGuidance } : {},
|
|
2858
2903
|
...rateResult.rateLimitExceeded ? { pollingRateAdvisory: { type: "rate_limit_exceeded", tool: "mesh_view_queue", callsInWindow: rateResult.callsInWindow, message: rateResult.advisory } } : {},
|
|
@@ -2868,8 +2913,8 @@ async function meshViewQueue(ctx, args) {
|
|
|
2868
2913
|
visibleHistoricalCount: visibleSummary.historicalCount,
|
|
2869
2914
|
staleAssignedTasks,
|
|
2870
2915
|
staleAssignedCount: maintenance.staleAssignedCount,
|
|
2871
|
-
queueMaintenance:
|
|
2872
|
-
cleanupDryRun:
|
|
2916
|
+
queueMaintenance: maintenanceForResponse,
|
|
2917
|
+
cleanupDryRun: maintenanceForResponse,
|
|
2873
2918
|
...recentDispatchFailures.length > 0 ? {
|
|
2874
2919
|
recentDispatchFailures,
|
|
2875
2920
|
dispatchFailureCount: recentDispatchFailures.length,
|
|
@@ -2935,6 +2980,7 @@ async function meshQueueRequeue(ctx, args) {
|
|
|
2935
2980
|
}
|
|
2936
2981
|
async function meshSendTask(ctx, args) {
|
|
2937
2982
|
const requestedTaskMode = readString(args.task_mode) || readString(args.taskMode);
|
|
2983
|
+
const missionId = readString(args.missionId) || readString(args.mission_id) || void 0;
|
|
2938
2984
|
const modeValidation = (0, import_daemon_core.validateMeshTaskModeRequest)(requestedTaskMode, args.message);
|
|
2939
2985
|
if (!modeValidation.valid) {
|
|
2940
2986
|
return JSON.stringify({
|
|
@@ -3051,6 +3097,16 @@ async function meshSendTask(ctx, args) {
|
|
|
3051
3097
|
via: "p2p_direct",
|
|
3052
3098
|
dispatchedAt
|
|
3053
3099
|
});
|
|
3100
|
+
if (missionId) {
|
|
3101
|
+
(0, import_daemon_core.recordDirectDispatchTask)(ctx.mesh.id, args.message, {
|
|
3102
|
+
id: taskId,
|
|
3103
|
+
missionId,
|
|
3104
|
+
assignedNodeId: args.node_id,
|
|
3105
|
+
assignedSessionId: dispatchedSessionId,
|
|
3106
|
+
taskMode,
|
|
3107
|
+
dispatchedAt
|
|
3108
|
+
});
|
|
3109
|
+
}
|
|
3054
3110
|
} catch {
|
|
3055
3111
|
}
|
|
3056
3112
|
}
|
|
@@ -3224,6 +3280,19 @@ async function meshSendTask(ctx, args) {
|
|
|
3224
3280
|
dispatchedToIdleSession: sessionWasIdle,
|
|
3225
3281
|
dispatchedAt
|
|
3226
3282
|
});
|
|
3283
|
+
if (missionId) {
|
|
3284
|
+
try {
|
|
3285
|
+
(0, import_daemon_core.recordDirectDispatchTask)(ctx.mesh.id, args.message, {
|
|
3286
|
+
id: taskId,
|
|
3287
|
+
missionId,
|
|
3288
|
+
assignedNodeId: args.node_id,
|
|
3289
|
+
assignedSessionId: args.session_id,
|
|
3290
|
+
taskMode,
|
|
3291
|
+
dispatchedAt
|
|
3292
|
+
});
|
|
3293
|
+
} catch {
|
|
3294
|
+
}
|
|
3295
|
+
}
|
|
3227
3296
|
let deliveryId;
|
|
3228
3297
|
try {
|
|
3229
3298
|
const { createSessionDelivery: createDelivery } = await import("@adhdev/daemon-core");
|
|
@@ -3261,7 +3330,8 @@ async function meshSendTask(ctx, args) {
|
|
|
3261
3330
|
const task = (0, import_daemon_core.enqueueTask)(ctx.mesh.id, args.message, {
|
|
3262
3331
|
targetNodeId: args.node_id,
|
|
3263
3332
|
targetSessionId: args.session_id,
|
|
3264
|
-
taskMode
|
|
3333
|
+
taskMode,
|
|
3334
|
+
...missionId ? { missionId } : {}
|
|
3265
3335
|
});
|
|
3266
3336
|
const queueTrigger = await triggerMeshQueueAndReport(ctx);
|
|
3267
3337
|
const pendingEvents = (0, import_daemon_core.drainPendingMeshCoordinatorEvents)(ctx.mesh.id, ctx.localDaemonId);
|
|
@@ -3664,6 +3734,28 @@ async function meshRefineNode(ctx, args) {
|
|
|
3664
3734
|
}
|
|
3665
3735
|
return JSON.stringify(result, null, 2);
|
|
3666
3736
|
}
|
|
3737
|
+
async function meshRefineBatch(ctx, args = {}) {
|
|
3738
|
+
await refreshMeshFromDaemon(ctx);
|
|
3739
|
+
const nodeIds = Array.isArray(args.node_ids) ? args.node_ids.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
|
|
3740
|
+
const result = await ctx.transport.command("batch_refine_mesh_nodes", {
|
|
3741
|
+
meshId: ctx.mesh.id,
|
|
3742
|
+
...nodeIds ? { nodeIds } : {},
|
|
3743
|
+
...args.execute !== void 0 ? { execute: args.execute } : {},
|
|
3744
|
+
...args.dry_run !== void 0 ? { dryRun: args.dry_run } : {},
|
|
3745
|
+
inlineMesh: ctx.mesh
|
|
3746
|
+
});
|
|
3747
|
+
const payload = unwrapCommandPayload(result) ?? result;
|
|
3748
|
+
if (payload?.batch && payload?.dryRun === false && Array.isArray(payload?.results)) {
|
|
3749
|
+
for (const outcome of payload.results) {
|
|
3750
|
+
if (outcome?.convergence === "merged_to_main" || outcome?.convergence === "skipped_patch_equivalent") {
|
|
3751
|
+
const idx = ctx.mesh.nodes.findIndex((n) => n.id === outcome.nodeId);
|
|
3752
|
+
if (idx >= 0) ctx.mesh.nodes.splice(idx, 1);
|
|
3753
|
+
}
|
|
3754
|
+
}
|
|
3755
|
+
ctx.mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3756
|
+
}
|
|
3757
|
+
return JSON.stringify(result, null, 2);
|
|
3758
|
+
}
|
|
3667
3759
|
async function meshReviewInbox(ctx, args = {}) {
|
|
3668
3760
|
await refreshMeshFromDaemon(ctx);
|
|
3669
3761
|
const meshId = (args.mesh_id ?? ctx.mesh.id).trim();
|
|
@@ -4853,6 +4945,9 @@ async function startMcpServer(opts) {
|
|
|
4853
4945
|
case "mesh_refine_node":
|
|
4854
4946
|
text = await meshRefineNode(meshCtx, a);
|
|
4855
4947
|
break;
|
|
4948
|
+
case "mesh_refine_batch":
|
|
4949
|
+
text = await meshRefineBatch(meshCtx, a);
|
|
4950
|
+
break;
|
|
4856
4951
|
case "mesh_refine_config_schema":
|
|
4857
4952
|
text = await meshRefineConfigSchema(meshCtx);
|
|
4858
4953
|
break;
|