agent-relay-server 0.120.0 → 0.120.2
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/docs/openapi.json +1 -1
- package/package.json +3 -3
- package/public/assets/MessageBubble-DazQ9Rn-.js +2 -0
- package/public/assets/{MessageBubble-BJXjk3GB.js.map → MessageBubble-DazQ9Rn-.js.map} +1 -1
- package/public/assets/PlanGraphPanel-DpTiGCkz.js +2 -0
- package/public/assets/PlanGraphPanel-DpTiGCkz.js.map +1 -0
- package/public/assets/{activity-BUt4FiFQ.js → activity-DReCE2mK.js} +2 -2
- package/public/assets/{activity-BUt4FiFQ.js.map → activity-DReCE2mK.js.map} +1 -1
- package/public/assets/{agent-profiles-C1dvEaGS.js → agent-profiles-D3ba8Xpe.js} +2 -2
- package/public/assets/{agent-profiles-C1dvEaGS.js.map → agent-profiles-D3ba8Xpe.js.map} +1 -1
- package/public/assets/agents-BcsIxadm.js +2 -0
- package/public/assets/{agents-DvJZ0Tcz.js.map → agents-BcsIxadm.js.map} +1 -1
- package/public/assets/{analytics-DMLoMwta.js → analytics-0lOlkaib.js} +2 -2
- package/public/assets/{analytics-DMLoMwta.js.map → analytics-0lOlkaib.js.map} +1 -1
- package/public/assets/{automation-DICpRUGK.js → automation-D66mthBn.js} +2 -2
- package/public/assets/{automation-DICpRUGK.js.map → automation-D66mthBn.js.map} +1 -1
- package/public/assets/{branch-state-badge-BYE2U_y4.js → branch-state-badge-NH-l2Eh3.js} +2 -2
- package/public/assets/{branch-state-badge-BYE2U_y4.js.map → branch-state-badge-NH-l2Eh3.js.map} +1 -1
- package/public/assets/{channels-3SlDQL3j.js → channels-BlHLMQVk.js} +2 -2
- package/public/assets/{channels-3SlDQL3j.js.map → channels-BlHLMQVk.js.map} +1 -1
- package/public/assets/chat-rwffRsPX.js +2 -0
- package/public/assets/chat-rwffRsPX.js.map +1 -0
- package/public/assets/{connectors-CrEW591Q.js → connectors-CdsiaLD3.js} +2 -2
- package/public/assets/{connectors-CrEW591Q.js.map → connectors-CdsiaLD3.js.map} +1 -1
- package/public/assets/{formatted-body-ChERiS0y.js → formatted-body-C1AprxyU.js} +3 -3
- package/public/assets/{formatted-body-ChERiS0y.js.map → formatted-body-C1AprxyU.js.map} +1 -1
- package/public/assets/formatted-body-impl-D_ZJQVNk.js +3 -0
- package/public/assets/formatted-body-impl-D_ZJQVNk.js.map +1 -0
- package/public/assets/{index-CtBqO8vm.js → index-DfPouNiV.js} +10 -10
- package/public/assets/index-DfPouNiV.js.map +1 -0
- package/public/assets/{insights-DBjaf3N5.js → insights-BJf1vwrf.js} +2 -2
- package/public/assets/{insights-DBjaf3N5.js.map → insights-BJf1vwrf.js.map} +1 -1
- package/public/assets/{integrations-B-bdliwU.js → integrations-BZSHasnY.js} +2 -2
- package/public/assets/{integrations-B-bdliwU.js.map → integrations-BZSHasnY.js.map} +1 -1
- package/public/assets/{maintenance-EWlKbynM.js → maintenance-uEI1lArh.js} +2 -2
- package/public/assets/{maintenance-EWlKbynM.js.map → maintenance-uEI1lArh.js.map} +1 -1
- package/public/assets/{managed-agents-DzjKwBh4.js → managed-agents-mX3hHpOP.js} +4 -4
- package/public/assets/{managed-agents-DzjKwBh4.js.map → managed-agents-mX3hHpOP.js.map} +1 -1
- package/public/assets/{markdown-preview-impl-bwLB6Gc-.js → markdown-preview-impl-ClNwMC48.js} +2 -2
- package/public/assets/{markdown-preview-impl-bwLB6Gc-.js.map → markdown-preview-impl-ClNwMC48.js.map} +1 -1
- package/public/assets/{memory-DEwJsFNK.js → memory-OfusEzGh.js} +2 -2
- package/public/assets/{memory-DEwJsFNK.js.map → memory-OfusEzGh.js.map} +1 -1
- package/public/assets/messages-DsQGj0gU.js +2 -0
- package/public/assets/{messages-BSMkT9X2.js.map → messages-DsQGj0gU.js.map} +1 -1
- package/public/assets/{orchestrators-Bl8k3KxQ.js → orchestrators-BwWyl4mB.js} +2 -2
- package/public/assets/{orchestrators-Bl8k3KxQ.js.map → orchestrators-BwWyl4mB.js.map} +1 -1
- package/public/assets/overview-CED1SeTY.js +2 -0
- package/public/assets/{overview-CdFe7Dmc.js.map → overview-CED1SeTY.js.map} +1 -1
- package/public/assets/{pairs-0ewxtvFZ.js → pairs-BNu6ZWg4.js} +2 -2
- package/public/assets/{pairs-0ewxtvFZ.js.map → pairs-BNu6ZWg4.js.map} +1 -1
- package/public/assets/{projects-DEn85LQb.js → projects-BmopRiUD.js} +2 -2
- package/public/assets/{projects-DEn85LQb.js.map → projects-BmopRiUD.js.map} +1 -1
- package/public/assets/{prompt-settings-CMQ2tHe0.js → prompt-settings-Ci2n1cFt.js} +2 -2
- package/public/assets/{prompt-settings-CMQ2tHe0.js.map → prompt-settings-Ci2n1cFt.js.map} +1 -1
- package/public/assets/{registry-DntwLc8a.js → registry-DwXnDIql.js} +2 -2
- package/public/assets/{registry-DntwLc8a.js.map → registry-DwXnDIql.js.map} +1 -1
- package/public/assets/security-AW5EbdOm.js +3 -0
- package/public/assets/security-AW5EbdOm.js.map +1 -0
- package/public/assets/{select-B19D5ToH.js → select-CEeWX4hp.js} +2 -2
- package/public/assets/{select-B19D5ToH.js.map → select-CEeWX4hp.js.map} +1 -1
- package/public/assets/settings-DYUdGz4G.js +6 -0
- package/public/assets/{settings-BzYvlKIL.js.map → settings-DYUdGz4G.js.map} +1 -1
- package/public/assets/store-BaslPLIP.js +9 -0
- package/public/assets/store-BaslPLIP.js.map +1 -0
- package/public/assets/{tasks-vZ5VRoO8.js → tasks-DxCsrY4g.js} +2 -2
- package/public/assets/{tasks-vZ5VRoO8.js.map → tasks-DxCsrY4g.js.map} +1 -1
- package/public/assets/{teams-E3rI5gkA.js → teams-CF7vi-oM.js} +2 -2
- package/public/assets/{teams-E3rI5gkA.js.map → teams-CF7vi-oM.js.map} +1 -1
- package/public/assets/{terminal-viewer-impl-24nB6STe.js → terminal-viewer-impl-Dy3vqOnW.js} +2 -2
- package/public/assets/{terminal-viewer-impl-24nB6STe.js.map → terminal-viewer-impl-Dy3vqOnW.js.map} +1 -1
- package/public/assets/types-uVOXgvMT.js.map +1 -1
- package/public/assets/{work-queue-Bql5E-C3.js → work-queue-BPaGXrCE.js} +2 -2
- package/public/assets/{work-queue-Bql5E-C3.js.map → work-queue-BPaGXrCE.js.map} +1 -1
- package/public/assets/{workspaces-DjQ6EdrZ.js → workspaces-BLEXgnlj.js} +2 -2
- package/public/assets/{workspaces-DjQ6EdrZ.js.map → workspaces-BLEXgnlj.js.map} +1 -1
- package/public/index.html +3 -3
- package/runner/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/runner/src/config.ts +24 -3
- package/src/automations/reconcile.ts +69 -4
- package/src/branch-landed.ts +18 -7
- package/src/bus.ts +23 -16
- package/src/db/connection.ts +29 -1
- package/src/db/maintenance-worker.ts +25 -0
- package/src/db/message-reads.ts +69 -44
- package/src/db/migrations.ts +1 -0
- package/src/db/provider-quotas.ts +6 -7
- package/src/db/schema.ts +2 -1
- package/src/maintenance/jobs.ts +3 -3
- package/src/mcp/index.ts +5 -5
- package/src/mcp/tools-workspace.ts +8 -3
- package/src/routes/orchestrator-proxy.ts +7 -6
- package/src/routes/tasks.ts +29 -0
- package/src/routes/workspaces.ts +9 -2
- package/src/runtime-tokens.ts +4 -0
- package/src/security.ts +31 -7
- package/src/server.ts +40 -18
- package/src/services/git-remote.ts +29 -0
- package/src/services/issue-lifecycle.ts +6 -6
- package/src/services/project.ts +47 -1
- package/src/services/send-message.ts +2 -4
- package/src/services/spawn-agent.ts +2 -2
- package/src/services/task-lifecycle.ts +6 -5
- package/src/settings/registry.ts +6 -4
- package/src/spawn-targets.ts +2 -2
- package/src/sse.ts +37 -18
- package/src/steward.ts +10 -6
- package/src/terminal-authz.ts +50 -0
- package/src/token-db.ts +3 -3
- package/src/validation.ts +1 -1
- package/src/workspace-actions.ts +46 -4
- package/src/workspace-auto-merge.ts +120 -13
- package/src/workspace-orphans.ts +1 -1
- package/src/workspace-probe.ts +19 -10
- package/public/assets/MessageBubble-BJXjk3GB.js +0 -2
- package/public/assets/PlanGraphPanel-DI5JOnm1.js +0 -2
- package/public/assets/PlanGraphPanel-DI5JOnm1.js.map +0 -1
- package/public/assets/agents-DvJZ0Tcz.js +0 -2
- package/public/assets/chat-_I9nvxj2.js +0 -2
- package/public/assets/chat-_I9nvxj2.js.map +0 -1
- package/public/assets/formatted-body-impl-CiaUIrP3.js +0 -3
- package/public/assets/formatted-body-impl-CiaUIrP3.js.map +0 -1
- package/public/assets/index-CtBqO8vm.js.map +0 -1
- package/public/assets/messages-BSMkT9X2.js +0 -2
- package/public/assets/overview-CdFe7Dmc.js +0 -2
- package/public/assets/security-CYwC-26O.js +0 -3
- package/public/assets/security-CYwC-26O.js.map +0 -1
- package/public/assets/settings-BzYvlKIL.js +0 -6
- package/public/assets/store-BuuJUn70.js +0 -9
- package/public/assets/store-BuuJUn70.js.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./chunk-CilyBKbf.js";import{G as t,Hn as n,Ot as r,P as i,a,g as o,h as s,hr as c,nr as l,rt as u,st as d,vn as f}from"./lucide-react-Dc3ZwCBi.js";import{f as p,t as m}from"./store-BuuJUn70.js";import{K as h,d as g,f as _,h as v,k as y}from"./display-exQDWum3.js";import{t as b}from"./badge-BhUZ1cAb.js";import{t as x}from"./button-C-V4oij1.js";import{t as S}from"./formatted-body-ChERiS0y.js";import{Dt as C,St as w}from"./index-CtBqO8vm.js";import{r as T,t as E}from"./card-Br1JLjTH.js";var D=e(c(),1),O=l();function k(e,t){if(t.startsWith(`/`))return t;let n=`${e.replace(/\/+$/,``)}/${t}`.split(`/`),r=[];for(let e of n)!e||e===`.`||(e===`..`?r.pop():r.push(e));return`/`+r.join(`/`)}function A(e){let t=e.replace(/\/+$/,``),n=t.lastIndexOf(`/`);return n>0?t.slice(0,n):`/`}function j(){let e=p(),n=m(e=>e.messages),r=m(e=>e.agentsById),i=m(e=>e.selectedAgent),o=m(e=>e.channelFilter),s=m(e=>e.tagFilter),c=m(e=>e.replyTo),l=m(e=>e.set),f=m(e=>e.openCompose),h=m(e=>e.startReply),_=m(e=>e.doClaim),v=m(e=>e.doDeliveryAction),y=m(e=>e.doDeleteMessage),S=m(e=>e.openThread),T=m(e=>e.cancelReply),E=w(),k=C(),A=(0,D.useMemo)(()=>{let e=[...n].sort((e,t)=>t.id-e.id);return i&&(e=e.filter(e=>e.from===i||e.to===i)),o&&(e=e.filter(e=>e.channel===o)),s&&(e=e.filter(e=>((r[e.from]||r[e.to])?.tags||[]).includes(s))),e},[n,i,o,s,r]),j=(0,D.useMemo)(()=>{let e=[],t=new Map;for(let n of A){let r=n.threadId??n.id;t.has(r)||t.set(r,[]),t.get(r).push(n),n.id===r&&e.push(n)}let n=new Set(e.map(e=>e.id));for(let t of A)!n.has(t.threadId??t.id)&&!e.find(e=>e.id===t.id)&&e.push(t);return e.sort((e,t)=>t.id-e.id),e.map(e=>({root:e,replies:(t.get(e.id)||[]).filter(t=>t.id!==e.id).sort((e,t)=>e.id-t.id)}))},[A]);function N(e){return r[e]?g(r[e]):e.slice(-10)}let P=(0,D.useMemo)(()=>[...new Set(n.map(e=>e.channel).filter(Boolean))],[n]);return(0,O.jsxs)(`div`,{className:`space-y-4`,children:[(0,O.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-2`,children:[(0,O.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,O.jsx)(d,{className:`w-5 h-5 text-muted-foreground`}),(0,O.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Messages`}),(0,O.jsx)(b,{variant:`secondary`,children:A.length})]}),(0,O.jsxs)(x,{size:`sm`,onClick:f,children:[(0,O.jsx)(t,{className:`w-4 h-4 mr-1`}),` Compose`]})]}),(0,O.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,O.jsxs)(`select`,{className:`rounded-md border border-input bg-background px-3 py-1.5 text-sm`,value:i,onChange:e=>l({selectedAgent:e.target.value}),children:[(0,O.jsx)(`option`,{value:``,children:`All agents`}),E.map(e=>(0,O.jsx)(`option`,{value:e.id,children:g(e)},e.id))]}),(0,O.jsxs)(`select`,{className:`rounded-md border border-input bg-background px-3 py-1.5 text-sm`,value:s,onChange:e=>l({tagFilter:e.target.value}),children:[(0,O.jsx)(`option`,{value:``,children:`All tags`}),k.map(e=>(0,O.jsxs)(`option`,{value:e,children:[`#`,e]},e))]}),(0,O.jsxs)(`select`,{className:`rounded-md border border-input bg-background px-3 py-1.5 text-sm`,value:o,onChange:e=>l({channelFilter:e.target.value}),children:[(0,O.jsx)(`option`,{value:``,children:`All channels`}),P.map(e=>(0,O.jsx)(`option`,{value:e,children:e},e))]})]}),c&&(0,O.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md bg-blue-500/10 border border-blue-500/20 px-3 py-2 text-sm text-blue-300`,children:[(0,O.jsx)(u,{className:`w-4 h-4 shrink-0`}),(0,O.jsxs)(`span`,{children:[`Replying to message #`,c.id,` from `,(0,O.jsx)(`strong`,{children:N(c.from)})]}),(0,O.jsx)(x,{variant:`ghost`,size:`sm`,className:`ml-auto h-6 px-1.5`,onClick:T,children:(0,O.jsx)(a,{className:`w-3.5 h-3.5`})})]}),(0,O.jsx)(`div`,{className:`h-[calc(100dvh-15rem)] overflow-y-auto`,children:(0,O.jsxs)(`div`,{className:`space-y-2 pr-2`,children:[j.length===0&&(0,O.jsx)(`div`,{className:`text-center text-muted-foreground py-16 text-sm`,children:`No messages`}),j.map(({root:t,replies:n})=>(0,O.jsxs)(`div`,{className:`space-y-1`,children:[(0,O.jsx)(M,{msg:t,now:e,agentLabel:N,agentsById:r,onReply:()=>h(t),onClaim:()=>_(t.id),onRetry:()=>v(t.id,`retry-now`),onMarkDead:()=>v(t.id,`mark-dead`,`Marked dead from dashboard`),onClear:()=>v(t.id,`clear`,`Cleared after manual handling`),onDelete:()=>y(t.id),onThread:t.threadId?()=>S(t.threadId):void 0,replyCount:n.length}),n.map(t=>(0,O.jsx)(`div`,{className:`ml-6`,children:(0,O.jsx)(M,{msg:t,now:e,agentLabel:N,agentsById:r,onReply:()=>h(t),onClaim:()=>_(t.id),onRetry:()=>v(t.id,`retry-now`),onMarkDead:()=>v(t.id,`mark-dead`,`Marked dead from dashboard`),onClear:()=>v(t.id,`clear`,`Cleared after manual handling`),onDelete:()=>y(t.id)})},t.id))]},t.id))]})})]})}function M({msg:e,now:t,agentLabel:a,agentsById:s,onReply:c,onClaim:l,onRetry:d,onMarkDead:p,onClear:g,onDelete:C,onThread:w,replyCount:j}){let[M,P]=(0,D.useState)(!1),F=y(e),I=m(e=>e.openFilesAt);m(e=>e.openTaskDetailById);let L=e.deliveryStatus===`queued`||e.deliveryStatus===`failed`||e.deliveryStatus===`dead`||!!(e.deliveryLastError||e.deliveryPoisonReason),R=s[e.from===`user`?e.to:e.from];function z(e){return k((typeof R?.meta?.cwd==`string`?R.meta.cwd:``)||`/`,e)}function B(e,t){let n=z(e);I({path:A(n),selectedPath:n,line:t,overlay:!0})}return(0,O.jsx)(E,{className:`group relative`,children:(0,O.jsxs)(T,{className:`p-3`,children:[(0,O.jsxs)(`div`,{className:`min-w-0`,children:[(0,O.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap text-xs text-muted-foreground mb-1`,children:[(0,O.jsx)(`span`,{className:`font-medium text-foreground`,children:a(e.from)}),(0,O.jsx)(`span`,{children:`→`}),(0,O.jsx)(`span`,{children:_(e.to,s)}),e.channel&&(0,O.jsxs)(b,{variant:`outline`,className:`text-xs px-1.5 py-0 gap-0.5`,children:[(0,O.jsx)(r,{className:`w-2.5 h-2.5`}),e.channel]}),e.claimedBy&&(0,O.jsxs)(b,{variant:`outline`,className:`text-xs px-1.5 py-0 text-emerald-400 border-emerald-500/30`,children:[(0,O.jsx)(f,{className:`w-2.5 h-2.5 mr-0.5`}),`claimed`]}),L&&(0,O.jsx)(N,{msg:e,now:t}),e.subject&&(0,O.jsx)(`span`,{className:`font-medium text-foreground`,children:e.subject}),(0,O.jsxs)(`span`,{className:`ml-auto shrink-0`,title:v(e.createdAt),children:[(0,O.jsxs)(`span`,{className:`opacity-40 mr-1`,children:[`#`,e.id]}),h(t,e.createdAt)]})]}),F&&(0,O.jsx)(`div`,{className:`cursor-pointer`,onClick:()=>P(e=>!e),children:(0,O.jsx)(S,{text:F,rawBody:e.body,issueRepo:R?.issueRepo,className:`text-sm text-muted-foreground ${M?``:`max-h-[3.75rem] overflow-hidden`}`,onOpenPath:B,resolvePathTitle:(e,t)=>`${z(e)}${t?`:${t}`:``}`})})]}),(0,O.jsxs)(`div`,{className:`absolute top-2 right-2 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity bg-card rounded-md shadow-sm border border-border px-1 py-0.5`,children:[(0,O.jsx)(x,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs`,onClick:c,title:`Reply`,children:(0,O.jsx)(u,{className:`w-3.5 h-3.5`})}),e.claimable&&!e.claimedBy&&(0,O.jsx)(x,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs text-orange-400 hover:text-orange-300`,onClick:l,title:`Claim`,children:(0,O.jsx)(f,{className:`w-3.5 h-3.5`})}),L&&(0,O.jsx)(x,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs text-blue-400 hover:text-blue-300`,onClick:d,title:`Retry delivery now`,children:(0,O.jsx)(i,{className:`w-3.5 h-3.5`})}),e.deliveryStatus!==`dead`&&L&&(0,O.jsx)(x,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs text-red-400 hover:text-red-300`,onClick:p,title:`Mark dead`,children:(0,O.jsx)(n,{className:`w-3.5 h-3.5`})}),(e.deliveryStatus===`failed`||e.deliveryStatus===`dead`)&&(0,O.jsx)(x,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs text-emerald-400 hover:text-emerald-300`,onClick:g,title:`Clear after manual handling`,children:(0,O.jsx)(f,{className:`w-3.5 h-3.5`})}),w&&(j??0)>0&&(0,O.jsxs)(x,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs`,onClick:w,title:`Thread`,children:[`+`,j]}),(0,O.jsx)(x,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs text-red-400 hover:text-red-300`,onClick:C,title:`Delete`,children:(0,O.jsx)(o,{className:`w-3.5 h-3.5`})})]})]})})}function N({msg:e,now:t}){let n=e.deliveryStatus||`pending`,r=e.deliveryPoisonReason||e.deliveryLastError||(e.deliveryNextRetryAt?`retry ${h(t,e.deliveryNextRetryAt)}`:void 0);return(0,O.jsxs)(b,{variant:`outline`,className:`text-xs px-1.5 py-0 ${n===`dead`?`text-red-300 border-red-500/30 bg-red-500/10`:n===`failed`?`text-amber-300 border-amber-500/30 bg-amber-500/10`:`text-blue-300 border-blue-500/30 bg-blue-500/10`}`,title:r||n,children:[(0,O.jsx)(s,{className:`w-2.5 h-2.5 mr-0.5`}),n,e.deliveryAttempts?` ${e.deliveryAttempts}x`:``]})}export{j as MessagesView};
|
|
2
|
-
//# sourceMappingURL=messages-BSMkT9X2.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./chunk-CilyBKbf.js";import{$n as t,Ln as n,Tt as r,gt as i,h as a,hr as o,ht as s,nr as c,nt as l,st as u,u as d}from"./lucide-react-Dc3ZwCBi.js";import{f,t as p}from"./store-BuuJUn70.js";import{K as m,M as h,X as g,d as _,f as v,g as y,lt as b,q as x}from"./display-exQDWum3.js";import{t as S}from"./badge-BhUZ1cAb.js";import{t as C}from"./agent-type-icon-BEz393ra.js";import{Ct as w,U as T,bt as E,gt as D,ot as O,xt as k}from"./index-CtBqO8vm.js";import{o as A,r as j,s as M,t as N}from"./card-Br1JLjTH.js";var P=e(o(),1),F=c();function I(){let e=p(e=>e.stats),o=p(e=>e.agents),c=p(e=>e.messages),I=p(e=>e.health),L=f(),R=p(e=>e.agentsById),z=p(e=>e.switchView),B=p(e=>e.runHealthAction),V=p(e=>e.managedPolicies),H=p(e=>e.showOffline),U=w(),W=k(),G=E(),K=(0,P.useMemo)(()=>{let e=g(o,!1,V);return H||(e=e.filter(e=>e.status!==`offline`)),[...e].sort((e,t)=>(b[e.status]??9)-(b[t.status]??9)||x(t.lastSeen)-x(e.lastSeen))},[o,H,V]),q=K.slice(0,20),J=[...c].sort((e,t)=>t.id-e.id).slice(0,15),Y=I&&I.status!==`ok`?y(I.checks||[]):[];function X(e){z(e)}return(0,F.jsxs)(`div`,{className:`space-y-6`,children:[(0,F.jsxs)(`div`,{className:`grid grid-cols-2 md:grid-cols-4 gap-4`,children:[(0,F.jsxs)(N,{className:`cursor-pointer hover:border-zinc-600 transition-colors`,onClick:()=>X(`agents`),children:[(0,F.jsx)(A,{className:`pb-1 pt-4 px-4`,children:(0,F.jsxs)(M,{className:`text-xs font-medium text-muted-foreground flex items-center gap-1.5`,children:[(0,F.jsx)(d,{className:`w-3.5 h-3.5`}),`Agents`]})}),(0,F.jsxs)(j,{className:`px-4 pb-4`,children:[(0,F.jsx)(`div`,{className:`text-2xl font-bold`,children:K.length}),(0,F.jsxs)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:[U,` online`]})]})]}),(0,F.jsxs)(N,{className:`cursor-pointer hover:border-zinc-600 transition-colors`,onClick:()=>X(`agents`),children:[(0,F.jsx)(A,{className:`pb-1 pt-4 px-4`,children:(0,F.jsxs)(M,{className:`text-xs font-medium text-muted-foreground flex items-center gap-1.5`,children:[(0,F.jsx)(t,{className:`w-3.5 h-3.5`}),`Busy`]})}),(0,F.jsxs)(j,{className:`px-4 pb-4`,children:[(0,F.jsx)(`div`,{className:`text-2xl font-bold`,children:W}),(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:`in a turn now`})]})]}),(0,F.jsxs)(N,{className:`cursor-pointer hover:border-zinc-600 transition-colors`,onClick:()=>X(`messages`),children:[(0,F.jsx)(A,{className:`pb-1 pt-4 px-4`,children:(0,F.jsxs)(M,{className:`text-xs font-medium text-muted-foreground flex items-center gap-1.5`,children:[(0,F.jsx)(l,{className:`w-3.5 h-3.5`}),`Messages 24h`]})}),(0,F.jsxs)(j,{className:`px-4 pb-4`,children:[(0,F.jsx)(`div`,{className:`text-2xl font-bold`,children:e.messagesLast24h??`—`}),(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:`last 24 hours`})]})]}),(0,F.jsxs)(N,{className:`cursor-pointer hover:border-zinc-600 transition-colors`,onClick:()=>X(`messages`),children:[(0,F.jsx)(A,{className:`pb-1 pt-4 px-4`,children:(0,F.jsxs)(M,{className:`text-xs font-medium text-muted-foreground flex items-center gap-1.5`,children:[(0,F.jsx)(u,{className:`w-3.5 h-3.5`}),`Total Messages`]})}),(0,F.jsxs)(j,{className:`px-4 pb-4`,children:[(0,F.jsx)(`div`,{className:`text-2xl font-bold`,children:e.messages??`—`}),(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:`all time`})]})]})]}),Y.length>0&&(0,F.jsxs)(N,{className:`border-yellow-500/40 bg-yellow-500/5`,children:[(0,F.jsx)(A,{className:`pb-2 pt-4 px-4`,children:(0,F.jsxs)(M,{className:`text-sm font-medium text-yellow-400 flex items-center gap-2`,children:[(0,F.jsx)(a,{className:`w-4 h-4`}),`Health Alerts (`,Y.length,`)`]})}),(0,F.jsx)(j,{className:`px-4 pb-4 space-y-2`,children:Y.map(e=>(0,F.jsxs)(`div`,{className:`text-sm space-y-1`,children:[(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsx)(S,{variant:`outline`,className:e.status===`error`?`border-red-500/40 text-red-400`:`border-yellow-500/40 text-yellow-400`,children:e.status}),(0,F.jsx)(`span`,{className:`font-medium`,children:e.name})]}),(0,F.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.detail}),e.subjects.length>0&&(0,F.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.subjects.map(e=>(0,F.jsxs)(S,{variant:`secondary`,className:`max-w-full truncate text-[11px]`,title:[e.id,e.status,e.detail].filter(Boolean).join(` · `),children:[e.label||e.id,e.status?` · ${e.status}`:``,e.detail?` · ${e.detail}`:``]},e.id))}),e.actions.length>0&&(0,F.jsx)(`div`,{className:`flex flex-wrap gap-1.5 pt-0.5`,children:e.actions.slice(0,3).map(e=>(0,F.jsx)(`button`,{onClick:()=>B(e),className:`text-xs text-blue-400 hover:text-blue-300 underline underline-offset-2`,children:e.label},e.label))})]},e.name))})]}),(0,F.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-4`,children:[(0,F.jsx)(N,{className:`cursor-pointer hover:border-zinc-600 transition-colors ${G.unreadInbox>0?`border-red-500/40`:``}`,onClick:()=>X(`chat`),children:(0,F.jsxs)(j,{className:`p-4 flex items-center gap-3`,children:[(0,F.jsx)(`div`,{className:`p-2 rounded-lg ${G.unreadInbox>0?`bg-red-500/15`:`bg-zinc-800`}`,children:(0,F.jsx)(r,{className:`w-4 h-4 ${G.unreadInbox>0?`text-red-400`:`text-zinc-400`}`})}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`div`,{className:`text-lg font-bold`,children:G.unreadInbox}),(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Unread`})]})]})}),(0,F.jsx)(N,{className:`cursor-pointer hover:border-zinc-600 transition-colors ${G.pendingPairInvites>0?`border-yellow-500/40`:``}`,onClick:()=>X(`pairs`),children:(0,F.jsxs)(j,{className:`p-4 flex items-center gap-3`,children:[(0,F.jsx)(`div`,{className:`p-2 rounded-lg ${G.pendingPairInvites>0?`bg-yellow-500/15`:`bg-zinc-800`}`,children:(0,F.jsx)(i,{className:`w-4 h-4 ${G.pendingPairInvites>0?`text-yellow-400`:`text-zinc-400`}`})}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`div`,{className:`text-lg font-bold`,children:G.pendingPairInvites}),(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Pair invites`})]})]})}),(0,F.jsx)(N,{className:`cursor-pointer hover:border-zinc-600 transition-colors ${G.claimableTasks>0?`border-orange-500/40`:``}`,onClick:()=>X(`work`),children:(0,F.jsxs)(j,{className:`p-4 flex items-center gap-3`,children:[(0,F.jsx)(`div`,{className:`p-2 rounded-lg ${G.claimableTasks>0?`bg-orange-500/15`:`bg-zinc-800`}`,children:(0,F.jsx)(s,{className:`w-4 h-4 ${G.claimableTasks>0?`text-orange-400`:`text-zinc-400`}`})}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`div`,{className:`text-lg font-bold`,children:G.claimableTasks}),(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Claimable waiting`})]})]})})]}),(0,F.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-6`,children:[(0,F.jsxs)(N,{children:[(0,F.jsx)(A,{className:`pb-2 pt-4 px-4`,children:(0,F.jsxs)(M,{className:`text-sm font-medium flex items-center gap-2`,children:[(0,F.jsx)(n,{className:`w-4 h-4 text-muted-foreground`}),`Agents`,(0,F.jsx)(`span`,{className:`ml-auto text-xs text-muted-foreground font-normal`,children:q.length})]})}),(0,F.jsx)(j,{className:`px-0 pb-0`,children:(0,F.jsx)(T,{className:`h-[340px]`,children:q.length===0?(0,F.jsx)(`div`,{className:`px-4 pb-4 text-sm text-muted-foreground`,children:`No agents registered.`}):(0,F.jsx)(`div`,{className:`space-y-0`,children:q.map((e,t)=>(0,F.jsxs)(`div`,{children:[t>0&&(0,F.jsx)(D,{}),(0,F.jsxs)(`div`,{className:`flex items-center gap-2.5 px-4 py-2.5 hover:bg-zinc-800/50 transition-colors cursor-pointer`,onClick:()=>p.getState().openAgentDetail(e),children:[(0,F.jsx)(O,{agent:e,now:L}),(0,F.jsx)(C,{agent:e}),(0,F.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,F.jsx)(`div`,{className:`text-sm font-medium truncate`,children:_(e)}),e.tags.length>0&&(0,F.jsx)(`div`,{className:`flex gap-1 mt-0.5 flex-wrap`,children:e.tags.slice(0,2).map(e=>(0,F.jsx)(S,{variant:`outline`,className:`text-[9px] px-1 py-0 h-4`,children:e},e))})]}),(0,F.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:m(L,e.lastSeen)})]})]},e.id))})})})]}),(0,F.jsxs)(N,{children:[(0,F.jsx)(A,{className:`pb-2 pt-4 px-4`,children:(0,F.jsxs)(M,{className:`text-sm font-medium flex items-center gap-2`,children:[(0,F.jsx)(t,{className:`w-4 h-4 text-muted-foreground`}),`Recent Activity`,(0,F.jsx)(`span`,{className:`ml-auto text-xs text-muted-foreground font-normal`,children:J.length})]})}),(0,F.jsx)(j,{className:`px-0 pb-0`,children:(0,F.jsx)(T,{className:`h-[340px]`,children:J.length===0?(0,F.jsx)(`div`,{className:`px-4 pb-4 text-sm text-muted-foreground`,children:`No recent messages.`}):(0,F.jsx)(`div`,{className:`space-y-0`,children:J.map((e,t)=>(0,F.jsxs)(`div`,{children:[t>0&&(0,F.jsx)(D,{}),(0,F.jsxs)(`div`,{className:`px-4 py-2.5 hover:bg-zinc-800/50 transition-colors`,children:[(0,F.jsxs)(`div`,{className:`flex items-center gap-1 text-xs text-muted-foreground mb-0.5`,children:[(0,F.jsx)(`span`,{className:`text-foreground font-medium truncate max-w-[100px]`,children:v(e.from,R)}),(0,F.jsx)(`span`,{children:`→`}),(0,F.jsx)(`span`,{className:`truncate max-w-[100px]`,children:v(e.to,R)}),(0,F.jsxs)(`span`,{className:`ml-auto shrink-0 tabular-nums`,children:[(0,F.jsxs)(`span`,{className:`opacity-40 mr-1`,children:[`#`,e.id]}),m(L,e.createdAt)]})]}),(0,F.jsx)(`div`,{className:`text-xs text-foreground line-clamp-2 leading-snug`,children:h(e)})]})]},e.id))})})})]})]})]})}export{I as OverviewView};
|
|
2
|
-
//# sourceMappingURL=overview-CdFe7Dmc.js.map
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./chunk-CilyBKbf.js";import{Ct as t,P as n,V as r,g as i,hr as a,j as o,nr as s,rr as c,w as l}from"./lucide-react-Dc3ZwCBi.js";import{t as u}from"./badge-BhUZ1cAb.js";import{t as d}from"./button-C-V4oij1.js";import{t as f}from"./input-CtLT7WXi.js";import{t as p}from"./copy-button-BStzXgtd.js";import{H as m}from"./index-CtBqO8vm.js";import{o as h,r as g,s as _,t as v}from"./card-Br1JLjTH.js";var y=e(a(),1),b=s(),x=[`admin:*`,`token:read`,`token:write`,`agent:read`,`agent:write`,`message:read`,`message:send`,`task:read`,`task:write`,`command:read`,`command:write`,`memory:read`,`memory:write`,`memory:admin`,`mcp:use`,`terminal:attach`,`logs:read`,`integration:read`,`integration:write`,`channel:read`,`channel:write`,`stats:read`,`health:read`,`events:read`],S={agents:``,policies:``,targets:``,channels:``,orchestrators:``,cwdPrefixes:``,memoryScopes:``,spawnRequestIds:``,terminalAttach:!1,logsRead:!1},C={id:``,name:``,description:``,role:`provider`,scope:[`agent:read`,`message:read`,`message:send`],ttlSeconds:`86400`,constraints:{...S}};function w(){let[e,a]=(0,y.useState)([]),[s,w]=(0,y.useState)([]),[k,j]=(0,y.useState)(``),[M,F]=(0,y.useState)(C),[I,L]=(0,y.useState)(``),[R,z]=(0,y.useState)(``),[B,V]=(0,y.useState)({...S}),[H,U]=(0,y.useState)(``),[W,G]=(0,y.useState)(``),[K,q]=(0,y.useState)(`profiles`),J=(0,y.useMemo)(()=>e.find(e=>e.id===k),[e,k]);(0,y.useEffect)(()=>{Y()},[]);async function Y(){let[e,t]=await Promise.all([c(`GET`,`/token-profiles`),c(`GET`,`/tokens`)]);a(e),w(t),!k&&e[0]&&(j(e[0].id),F(D(e[0])),L(e[0].id))}function X(e){j(e.id),F(D(e)),U(``)}function Z(){j(``),F({...C,constraints:{...S}}),G(``)}async function Q(){let e=O(M),t=k?await c(`PATCH`,`/token-profiles/${encodeURIComponent(k)}`,e):await c(`POST`,`/token-profiles`,e);await Y(),j(t.id),F(D(t)),L(t.id),G(`${t.name} saved`)}async function $(e){await c(`DELETE`,`/token-profiles/${encodeURIComponent(e.id)}`),Z(),await Y()}async function ee(){let t=e.find(e=>e.id===I);U((await c(`POST`,`/tokens`,{profileId:I,sub:R||t?.role||`component`,constraints:A(B),createdBy:`dashboard`})).token),z(``),V({...S}),await Y()}async function te(e){await c(`POST`,`/tokens/${encodeURIComponent(e.jti)}/revoke`),await Y()}return(0,b.jsxs)(`div`,{className:`space-y-4`,children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h1`,{className:`text-lg font-semibold`,children:`Security`}),(0,b.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Token profiles and scoped component tokens`})]}),(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsxs)(`div`,{className:`inline-flex rounded-md border border-border overflow-hidden`,children:[(0,b.jsxs)(`button`,{type:`button`,onClick:()=>q(`profiles`),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors ${K===`profiles`?`bg-primary/15 text-primary`:`text-muted-foreground hover:bg-accent`}`,children:[(0,b.jsx)(l,{className:`h-3.5 w-3.5`}),`Profiles`]}),(0,b.jsxs)(`button`,{type:`button`,onClick:()=>q(`tokens`),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm border-l border-border transition-colors ${K===`tokens`?`bg-primary/15 text-primary`:`text-muted-foreground hover:bg-accent`}`,children:[(0,b.jsx)(t,{className:`h-3.5 w-3.5`}),`Tokens`]})]}),(0,b.jsxs)(d,{variant:`outline`,onClick:()=>void Y(),children:[(0,b.jsx)(n,{className:`h-4 w-4`}),`Refresh`]}),K===`profiles`&&(0,b.jsxs)(d,{onClick:Z,children:[(0,b.jsx)(r,{className:`h-4 w-4`}),`New profile`]})]})]}),K===`profiles`&&(0,b.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[340px_minmax(0,1fr)]`,children:[(0,b.jsxs)(v,{children:[(0,b.jsx)(h,{children:(0,b.jsxs)(_,{className:`flex items-center gap-2 text-sm`,children:[(0,b.jsx)(l,{className:`h-4 w-4`}),`Profiles`]})}),(0,b.jsx)(g,{className:`space-y-2`,children:e.map(e=>(0,b.jsxs)(`button`,{type:`button`,onClick:()=>X(e),className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${e.id===k?`border-primary bg-primary/10`:`border-border hover:bg-accent`}`,children:[(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,children:e.name}),e.builtIn&&(0,b.jsx)(u,{variant:`secondary`,className:`text-[10px]`,children:`built-in`})]}),(0,b.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,b.jsx)(`span`,{children:e.role}),(0,b.jsxs)(`span`,{children:[e.scope.length,` scopes`]}),e.ttlSeconds&&(0,b.jsx)(`span`,{children:P(e.ttlSeconds)})]})]},e.id))})]}),(0,b.jsxs)(v,{children:[(0,b.jsx)(h,{children:(0,b.jsx)(_,{className:`text-sm`,children:J?J.name:`New profile`})}),(0,b.jsxs)(g,{className:`space-y-4`,children:[(0,b.jsxs)(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[(0,b.jsx)(T,{label:`Profile id`,children:(0,b.jsx)(f,{disabled:!!k,value:M.id,onChange:e=>F({...M,id:e.target.value})})}),(0,b.jsx)(T,{label:`Name`,children:(0,b.jsx)(f,{value:M.name,onChange:e=>F({...M,name:e.target.value})})}),(0,b.jsx)(T,{label:`Role`,children:(0,b.jsx)(f,{value:M.role,onChange:e=>F({...M,role:e.target.value})})}),(0,b.jsx)(T,{label:`TTL seconds`,children:(0,b.jsx)(f,{inputMode:`numeric`,value:M.ttlSeconds,onChange:e=>F({...M,ttlSeconds:e.target.value})})})]}),(0,b.jsx)(T,{label:`Description`,children:(0,b.jsx)(m,{rows:2,value:M.description,onChange:e=>F({...M,description:e.target.value})})}),(0,b.jsxs)(`div`,{className:`space-y-2`,children:[(0,b.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Scopes`}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:x.map(e=>(0,b.jsx)(`button`,{type:`button`,onClick:()=>F({...M,scope:N(M.scope,e)}),className:`rounded border px-2 py-1 text-xs ${M.scope.includes(e)?`border-primary/50 bg-primary/15 text-primary`:`border-border text-muted-foreground hover:bg-accent`}`,children:e},e))})]}),(0,b.jsx)(E,{value:M.constraints,onChange:e=>F({...M,constraints:e})}),(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,b.jsxs)(d,{disabled:J?.builtIn,onClick:()=>void Q(),children:[(0,b.jsx)(o,{className:`h-4 w-4`}),`Save`]}),J&&!J.builtIn&&(0,b.jsxs)(d,{variant:`destructive`,onClick:()=>void $(J),children:[(0,b.jsx)(i,{className:`h-4 w-4`}),`Delete`]}),J?.builtIn&&(0,b.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Built-in profiles are managed by Relay.`})]})]})]})]}),K===`tokens`&&(0,b.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[380px_minmax(0,1fr)]`,children:[(0,b.jsxs)(v,{children:[(0,b.jsx)(h,{children:(0,b.jsxs)(_,{className:`flex items-center gap-2 text-sm`,children:[(0,b.jsx)(t,{className:`h-4 w-4`}),`Issue token`]})}),(0,b.jsxs)(g,{className:`space-y-3`,children:[(0,b.jsx)(T,{label:`Profile`,children:(0,b.jsx)(`select`,{className:`h-9 w-full rounded-md border border-input bg-background px-3 text-sm`,value:I,onChange:e=>L(e.target.value),children:e.map(e=>(0,b.jsx)(`option`,{value:e.id,children:e.name},e.id))})}),(0,b.jsx)(T,{label:`Subject`,children:(0,b.jsx)(f,{value:R,onChange:e=>z(e.target.value),placeholder:`component id`})}),(0,b.jsx)(E,{compact:!0,value:B,onChange:V}),(0,b.jsxs)(d,{className:`w-full`,disabled:!I,onClick:()=>void ee(),children:[(0,b.jsx)(t,{className:`h-4 w-4`}),`Issue`]}),H&&(0,b.jsxs)(`div`,{className:`rounded-md border border-border bg-muted/30 p-2`,children:[(0,b.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,b.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`New token`}),(0,b.jsx)(p,{value:H,label:`Copy token`,size:`sm`,variant:`ghost`,onCopied:()=>G(`Copied`)})]}),(0,b.jsx)(`code`,{className:`block max-h-24 overflow-auto break-all text-xs`,children:H})]}),W&&(0,b.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:W})]})]}),(0,b.jsxs)(v,{children:[(0,b.jsx)(h,{children:(0,b.jsx)(_,{className:`text-sm`,children:`Issued tokens`})}),(0,b.jsxs)(g,{className:`space-y-2`,children:[s.length===0&&(0,b.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No tokens issued yet`}),s.slice(0,20).map(e=>(0,b.jsxs)(`div`,{className:`rounded-md border border-border p-2`,children:[(0,b.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,b.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,b.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.sub}),(0,b.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[e.role,` `,e.profileId?`· ${e.profileId}`:``]})]}),e.revokedAt?(0,b.jsx)(u,{variant:`destructive`,children:`revoked`}):(0,b.jsx)(d,{variant:`ghost`,size:`sm`,onClick:()=>void te(e),children:(0,b.jsx)(i,{className:`h-3.5 w-3.5`})})]}),(0,b.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:[e.scope.slice(0,4).map(e=>(0,b.jsx)(u,{variant:`outline`,className:`text-[10px]`,children:e},e)),e.scope.length>4&&(0,b.jsxs)(u,{variant:`secondary`,className:`text-[10px]`,children:[`+`,e.scope.length-4]})]})]},e.jti))]})]})]})]})}function T({label:e,children:t}){return(0,b.jsxs)(`label`,{className:`block space-y-1.5 text-sm`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground`,children:e}),t]})}function E({value:e,onChange:t,compact:n=!1}){return(0,b.jsxs)(`div`,{className:`space-y-3`,children:[!n&&(0,b.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Constraints`}),(0,b.jsx)(`div`,{className:`grid gap-3 ${n?``:`md:grid-cols-2`}`,children:[[`agents`,`Agents`],[`policies`,`Policies`],[`targets`,`Targets`],[`channels`,`Channels`],[`orchestrators`,`Orchestrators`],[`cwdPrefixes`,`CWD prefixes`],[`memoryScopes`,`Memory scopes`],[`spawnRequestIds`,`Spawn requests`]].map(([r,i])=>(0,b.jsx)(T,{label:i,children:(0,b.jsx)(m,{rows:n?2:3,value:String(e[r]||``),onChange:n=>t({...e,[r]:n.target.value}),placeholder:`one per line`})},r))}),(0,b.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,b.jsxs)(`label`,{className:`flex items-center gap-2 rounded border border-border px-2 py-1 text-xs`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:e.terminalAttach,onChange:n=>t({...e,terminalAttach:n.target.checked})}),`Terminal attach`]}),(0,b.jsxs)(`label`,{className:`flex items-center gap-2 rounded border border-border px-2 py-1 text-xs`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:e.logsRead,onChange:n=>t({...e,logsRead:n.target.checked})}),`Log read`]})]})]})}function D(e){return{id:e.id,name:e.name,description:e.description||``,role:e.role,scope:e.scope,ttlSeconds:e.ttlSeconds?String(e.ttlSeconds):``,constraints:k(e.constraints)}}function O(e){return{id:e.id||void 0,name:e.name,description:e.description||void 0,role:e.role,scope:e.scope,ttlSeconds:e.ttlSeconds?Number(e.ttlSeconds):void 0,constraints:A(e.constraints)}}function k(e){return{agents:M(e?.agents),policies:M(e?.policies),targets:M(e?.targets),channels:M(e?.channels),orchestrators:M(e?.orchestrators),cwdPrefixes:M(e?.cwdPrefixes),memoryScopes:M(e?.memoryScopes),spawnRequestIds:M(e?.spawnRequestIds),terminalAttach:e?.terminalAttach===!0,logsRead:e?.logsRead===!0}}function A(e){let t={};for(let n of[`agents`,`policies`,`targets`,`channels`,`orchestrators`,`cwdPrefixes`,`memoryScopes`,`spawnRequestIds`]){let r=j(String(e[n]||``));r.length&&Object.assign(t,{[n]:r})}return e.terminalAttach&&(t.terminalAttach=!0),e.logsRead&&(t.logsRead=!0),Object.keys(t).length?t:void 0}function j(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(Boolean)}function M(e){return(e??[]).join(`
|
|
2
|
-
`)}function N(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function P(e){return e%86400==0?`${e/86400}d`:e%3600==0?`${e/3600}h`:`${e}s`}export{w as SecurityView};
|
|
3
|
-
//# sourceMappingURL=security-CYwC-26O.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"security-CYwC-26O.js","names":[],"sources":["../../dashboard/src/components/views/security.tsx"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\nimport { api } from '@/lib/api'\nimport { Badge } from '@/components/ui/badge'\nimport { Button } from '@/components/ui/button'\nimport { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'\nimport { Input } from '@/components/ui/input'\nimport { Textarea } from '@/components/ui/textarea'\nimport { KeyRound, Plus, Save, Shield, Trash2, RotateCcw } from 'lucide-react'\nimport { CopyButton } from '@/components/shared/copy-button'\nimport type { TokenConstraints, TokenProfile, TokenRecord } from '@/types'\n\nconst scopeOptions = [\n 'admin:*',\n 'token:read',\n 'token:write',\n 'agent:read',\n 'agent:write',\n 'message:read',\n 'message:send',\n 'task:read',\n 'task:write',\n 'command:read',\n 'command:write',\n 'memory:read',\n 'memory:write',\n 'memory:admin',\n 'mcp:use',\n 'terminal:attach',\n 'logs:read',\n 'integration:read',\n 'integration:write',\n 'channel:read',\n 'channel:write',\n 'stats:read',\n 'health:read',\n 'events:read',\n]\n\ninterface ProfileForm {\n id: string\n name: string\n description: string\n role: string\n scope: string[]\n ttlSeconds: string\n constraints: ConstraintForm\n}\n\ninterface ConstraintForm {\n agents: string\n policies: string\n targets: string\n channels: string\n orchestrators: string\n cwdPrefixes: string\n memoryScopes: string\n spawnRequestIds: string\n terminalAttach: boolean\n logsRead: boolean\n}\n\nconst emptyConstraints: ConstraintForm = {\n agents: '',\n policies: '',\n targets: '',\n channels: '',\n orchestrators: '',\n cwdPrefixes: '',\n memoryScopes: '',\n spawnRequestIds: '',\n terminalAttach: false,\n logsRead: false,\n}\n\nconst emptyProfile: ProfileForm = {\n id: '',\n name: '',\n description: '',\n role: 'provider',\n scope: ['agent:read', 'message:read', 'message:send'],\n ttlSeconds: '86400',\n constraints: { ...emptyConstraints },\n}\n\nexport function SecurityView() {\n const [profiles, setProfiles] = useState<TokenProfile[]>([])\n const [tokens, setTokens] = useState<TokenRecord[]>([])\n const [selectedId, setSelectedId] = useState('')\n const [form, setForm] = useState<ProfileForm>(emptyProfile)\n const [issueProfileId, setIssueProfileId] = useState('')\n const [issueSub, setIssueSub] = useState('')\n const [issueConstraints, setIssueConstraints] = useState<ConstraintForm>({ ...emptyConstraints })\n const [issuedToken, setIssuedToken] = useState('')\n const [status, setStatus] = useState('')\n const [tab, setTab] = useState<'profiles' | 'tokens'>('profiles')\n\n const selected = useMemo(() => profiles.find((profile) => profile.id === selectedId), [profiles, selectedId])\n\n useEffect(() => { void refresh() }, [])\n\n async function refresh() {\n const [nextProfiles, nextTokens] = await Promise.all([\n api<TokenProfile[]>('GET', '/token-profiles'),\n api<TokenRecord[]>('GET', '/tokens'),\n ])\n setProfiles(nextProfiles)\n setTokens(nextTokens)\n if (!selectedId && nextProfiles[0]) {\n setSelectedId(nextProfiles[0].id)\n setForm(profileToForm(nextProfiles[0]))\n setIssueProfileId(nextProfiles[0].id)\n }\n }\n\n function selectProfile(profile: TokenProfile) {\n setSelectedId(profile.id)\n setForm(profileToForm(profile))\n setIssuedToken('')\n }\n\n function newProfile() {\n setSelectedId('')\n setForm({ ...emptyProfile, constraints: { ...emptyConstraints } })\n setStatus('')\n }\n\n async function saveProfile() {\n const body = formToProfileBody(form)\n const saved = selectedId\n ? await api<TokenProfile>('PATCH', `/token-profiles/${encodeURIComponent(selectedId)}`, body)\n : await api<TokenProfile>('POST', '/token-profiles', body)\n await refresh()\n setSelectedId(saved.id)\n setForm(profileToForm(saved))\n setIssueProfileId(saved.id)\n setStatus(`${saved.name} saved`)\n }\n\n async function deleteProfile(profile: TokenProfile) {\n await api('DELETE', `/token-profiles/${encodeURIComponent(profile.id)}`)\n newProfile()\n await refresh()\n }\n\n async function issueToken() {\n const profile = profiles.find((item) => item.id === issueProfileId)\n const result = await api<{ token: string; record: TokenRecord }>('POST', '/tokens', {\n profileId: issueProfileId,\n sub: issueSub || profile?.role || 'component',\n constraints: constraintsFromForm(issueConstraints),\n createdBy: 'dashboard',\n })\n setIssuedToken(result.token)\n setIssueSub('')\n setIssueConstraints({ ...emptyConstraints })\n await refresh()\n }\n\n async function revokeToken(token: TokenRecord) {\n await api('POST', `/tokens/${encodeURIComponent(token.jti)}/revoke`)\n await refresh()\n }\n\n return (\n <div className=\"space-y-4\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div>\n <h1 className=\"text-lg font-semibold\">Security</h1>\n <p className=\"text-sm text-muted-foreground\">Token profiles and scoped component tokens</p>\n </div>\n <div className=\"flex items-center gap-2\">\n <div className=\"inline-flex rounded-md border border-border overflow-hidden\">\n <button type=\"button\" onClick={() => setTab('profiles')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors ${tab === 'profiles' ? 'bg-primary/15 text-primary' : 'text-muted-foreground hover:bg-accent'}`}>\n <Shield className=\"h-3.5 w-3.5\" />Profiles\n </button>\n <button type=\"button\" onClick={() => setTab('tokens')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm border-l border-border transition-colors ${tab === 'tokens' ? 'bg-primary/15 text-primary' : 'text-muted-foreground hover:bg-accent'}`}>\n <KeyRound className=\"h-3.5 w-3.5\" />Tokens\n </button>\n </div>\n <Button variant=\"outline\" onClick={() => void refresh()}><RotateCcw className=\"h-4 w-4\" />Refresh</Button>\n {tab === 'profiles' && <Button onClick={newProfile}><Plus className=\"h-4 w-4\" />New profile</Button>}\n </div>\n </div>\n\n {tab === 'profiles' && (\n <div className=\"grid gap-4 xl:grid-cols-[340px_minmax(0,1fr)]\">\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2 text-sm\"><Shield className=\"h-4 w-4\" />Profiles</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-2\">\n {profiles.map((profile) => (\n <button\n key={profile.id}\n type=\"button\"\n onClick={() => selectProfile(profile)}\n className={`w-full rounded-md border px-3 py-2 text-left transition-colors ${profile.id === selectedId ? 'border-primary bg-primary/10' : 'border-border hover:bg-accent'}`}\n >\n <div className=\"flex items-center gap-2\">\n <span className=\"min-w-0 flex-1 truncate text-sm font-medium\">{profile.name}</span>\n {profile.builtIn && <Badge variant=\"secondary\" className=\"text-[10px]\">built-in</Badge>}\n </div>\n <div className=\"mt-1 flex items-center gap-2 text-xs text-muted-foreground\">\n <span>{profile.role}</span>\n <span>{profile.scope.length} scopes</span>\n {profile.ttlSeconds && <span>{formatTtl(profile.ttlSeconds)}</span>}\n </div>\n </button>\n ))}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-sm\">{selected ? selected.name : 'New profile'}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"grid gap-3 md:grid-cols-2\">\n <Field label=\"Profile id\"><Input disabled={Boolean(selectedId)} value={form.id} onChange={(e) => setForm({ ...form, id: e.target.value })} /></Field>\n <Field label=\"Name\"><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></Field>\n <Field label=\"Role\"><Input value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })} /></Field>\n <Field label=\"TTL seconds\"><Input inputMode=\"numeric\" value={form.ttlSeconds} onChange={(e) => setForm({ ...form, ttlSeconds: e.target.value })} /></Field>\n </div>\n <Field label=\"Description\"><Textarea rows={2} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></Field>\n\n <div className=\"space-y-2\">\n <div className=\"text-sm text-muted-foreground\">Scopes</div>\n <div className=\"flex flex-wrap gap-1.5\">\n {scopeOptions.map((scope) => {\n const active = form.scope.includes(scope)\n return (\n <button\n key={scope}\n type=\"button\"\n onClick={() => setForm({ ...form, scope: toggle(form.scope, scope) })}\n className={`rounded border px-2 py-1 text-xs ${active ? 'border-primary/50 bg-primary/15 text-primary' : 'border-border text-muted-foreground hover:bg-accent'}`}\n >\n {scope}\n </button>\n )\n })}\n </div>\n </div>\n\n <ConstraintEditor value={form.constraints} onChange={(constraints) => setForm({ ...form, constraints })} />\n\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button disabled={selected?.builtIn} onClick={() => void saveProfile()}><Save className=\"h-4 w-4\" />Save</Button>\n {selected && !selected.builtIn && (\n <Button variant=\"destructive\" onClick={() => void deleteProfile(selected)}><Trash2 className=\"h-4 w-4\" />Delete</Button>\n )}\n {selected?.builtIn && <span className=\"text-xs text-muted-foreground\">Built-in profiles are managed by Relay.</span>}\n </div>\n </CardContent>\n </Card>\n </div>\n )}\n\n {tab === 'tokens' && (\n <div className=\"grid gap-4 xl:grid-cols-[380px_minmax(0,1fr)]\">\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2 text-sm\"><KeyRound className=\"h-4 w-4\" />Issue token</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n <Field label=\"Profile\">\n <select className=\"h-9 w-full rounded-md border border-input bg-background px-3 text-sm\" value={issueProfileId} onChange={(e) => setIssueProfileId(e.target.value)}>\n {profiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.name}</option>)}\n </select>\n </Field>\n <Field label=\"Subject\"><Input value={issueSub} onChange={(e) => setIssueSub(e.target.value)} placeholder=\"component id\" /></Field>\n <ConstraintEditor compact value={issueConstraints} onChange={setIssueConstraints} />\n <Button className=\"w-full\" disabled={!issueProfileId} onClick={() => void issueToken()}><KeyRound className=\"h-4 w-4\" />Issue</Button>\n {issuedToken && (\n <div className=\"rounded-md border border-border bg-muted/30 p-2\">\n <div className=\"mb-1 flex items-center justify-between gap-2\">\n <span className=\"text-xs text-muted-foreground\">New token</span>\n <CopyButton value={issuedToken} label=\"Copy token\" size=\"sm\" variant=\"ghost\" onCopied={() => setStatus('Copied')} />\n </div>\n <code className=\"block max-h-24 overflow-auto break-all text-xs\">{issuedToken}</code>\n </div>\n )}\n {status && <p className=\"text-xs text-muted-foreground\">{status}</p>}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-sm\">Issued tokens</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-2\">\n {tokens.length === 0 && <p className=\"text-xs text-muted-foreground\">No tokens issued yet</p>}\n {tokens.slice(0, 20).map((token) => (\n <div key={token.jti} className=\"rounded-md border border-border p-2\">\n <div className=\"flex items-start gap-2\">\n <div className=\"min-w-0 flex-1\">\n <div className=\"truncate text-sm font-medium\">{token.sub}</div>\n <div className=\"text-xs text-muted-foreground\">{token.role} {token.profileId ? `· ${token.profileId}` : ''}</div>\n </div>\n {token.revokedAt ? <Badge variant=\"destructive\">revoked</Badge> : <Button variant=\"ghost\" size=\"sm\" onClick={() => void revokeToken(token)}><Trash2 className=\"h-3.5 w-3.5\" /></Button>}\n </div>\n <div className=\"mt-1 flex flex-wrap gap-1\">\n {token.scope.slice(0, 4).map((scope) => <Badge key={scope} variant=\"outline\" className=\"text-[10px]\">{scope}</Badge>)}\n {token.scope.length > 4 && <Badge variant=\"secondary\" className=\"text-[10px]\">+{token.scope.length - 4}</Badge>}\n </div>\n </div>\n ))}\n </CardContent>\n </Card>\n </div>\n )}\n </div>\n )\n}\n\nfunction Field({ label, children }: { label: string; children: React.ReactNode }) {\n return <label className=\"block space-y-1.5 text-sm\"><span className=\"text-muted-foreground\">{label}</span>{children}</label>\n}\n\nfunction ConstraintEditor({ value, onChange, compact = false }: { value: ConstraintForm; onChange: (value: ConstraintForm) => void; compact?: boolean }) {\n const fields: Array<[keyof ConstraintForm, string]> = [\n ['agents', 'Agents'],\n ['policies', 'Policies'],\n ['targets', 'Targets'],\n ['channels', 'Channels'],\n ['orchestrators', 'Orchestrators'],\n ['cwdPrefixes', 'CWD prefixes'],\n ['memoryScopes', 'Memory scopes'],\n ['spawnRequestIds', 'Spawn requests'],\n ]\n return (\n <div className=\"space-y-3\">\n {!compact && <div className=\"text-sm text-muted-foreground\">Constraints</div>}\n <div className={`grid gap-3 ${compact ? '' : 'md:grid-cols-2'}`}>\n {fields.map(([key, label]) => (\n <Field key={key} label={label}>\n <Textarea\n rows={compact ? 2 : 3}\n value={String(value[key] || '')}\n onChange={(e) => onChange({ ...value, [key]: e.target.value })}\n placeholder=\"one per line\"\n />\n </Field>\n ))}\n </div>\n <div className=\"flex flex-wrap gap-2\">\n <label className=\"flex items-center gap-2 rounded border border-border px-2 py-1 text-xs\">\n <input type=\"checkbox\" checked={value.terminalAttach} onChange={(e) => onChange({ ...value, terminalAttach: e.target.checked })} />\n Terminal attach\n </label>\n <label className=\"flex items-center gap-2 rounded border border-border px-2 py-1 text-xs\">\n <input type=\"checkbox\" checked={value.logsRead} onChange={(e) => onChange({ ...value, logsRead: e.target.checked })} />\n Log read\n </label>\n </div>\n </div>\n )\n}\n\nfunction profileToForm(profile: TokenProfile): ProfileForm {\n return {\n id: profile.id,\n name: profile.name,\n description: profile.description || '',\n role: profile.role,\n scope: profile.scope,\n ttlSeconds: profile.ttlSeconds ? String(profile.ttlSeconds) : '',\n constraints: formFromConstraints(profile.constraints),\n }\n}\n\nfunction formToProfileBody(form: ProfileForm) {\n return {\n id: form.id || undefined,\n name: form.name,\n description: form.description || undefined,\n role: form.role,\n scope: form.scope,\n ttlSeconds: form.ttlSeconds ? Number(form.ttlSeconds) : undefined,\n constraints: constraintsFromForm(form.constraints),\n }\n}\n\nfunction formFromConstraints(constraints: TokenConstraints | undefined): ConstraintForm {\n return {\n agents: linesText(constraints?.agents),\n policies: linesText(constraints?.policies),\n targets: linesText(constraints?.targets),\n channels: linesText(constraints?.channels),\n orchestrators: linesText(constraints?.orchestrators),\n cwdPrefixes: linesText(constraints?.cwdPrefixes),\n memoryScopes: linesText(constraints?.memoryScopes),\n spawnRequestIds: linesText(constraints?.spawnRequestIds),\n terminalAttach: constraints?.terminalAttach === true,\n logsRead: constraints?.logsRead === true,\n }\n}\n\nfunction constraintsFromForm(form: ConstraintForm): TokenConstraints | undefined {\n const constraints: TokenConstraints = {}\n const arrayFields: Array<keyof ConstraintForm> = ['agents', 'policies', 'targets', 'channels', 'orchestrators', 'cwdPrefixes', 'memoryScopes', 'spawnRequestIds']\n for (const field of arrayFields) {\n const values = lines(String(form[field] || ''))\n if (values.length) Object.assign(constraints, { [field]: values })\n }\n if (form.terminalAttach) constraints.terminalAttach = true\n if (form.logsRead) constraints.logsRead = true\n return Object.keys(constraints).length ? constraints : undefined\n}\n\nfunction lines(value: string): string[] {\n return value.split(/\\r?\\n|,/).map((line) => line.trim()).filter(Boolean)\n}\n\nfunction linesText(value: string[] | undefined): string {\n return (value ?? []).join('\\n')\n}\n\nfunction toggle(values: string[], item: string): string[] {\n return values.includes(item) ? values.filter((value) => value !== item) : [...values, item]\n}\n\nfunction formatTtl(seconds: number): string {\n if (seconds % 86400 === 0) return `${seconds / 86400}d`\n if (seconds % 3600 === 0) return `${seconds / 3600}h`\n return `${seconds}s`\n}\n"],"mappings":"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"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./chunk-CilyBKbf.js";import{$t as t,C as n,G as r,Jn as i,Jt as a,L as o,M as s,Nn as c,Nt as l,O as u,Q as d,Sn as f,Un as p,V as m,Yt as h,bn as g,er as _,g as v,hr as y,j as b,kn as x,l as S,m as C,nr as w,pt as T,rr as E,sr as ee,vn as te,wn as ne}from"./lucide-react-Dc3ZwCBi.js";import{g as D,m as O,t as k,u as re}from"./store-BuuJUn70.js";import{c as ie,d as ae,h as A,p as oe}from"./types-uVOXgvMT.js";import{t as se}from"./themes-DjSwmAZN.js";import{a as j,i as M,n as N,r as P,t as F}from"./select-B19D5ToH.js";import{t as I}from"./badge-BhUZ1cAb.js";import{t as L}from"./button-C-V4oij1.js";import{t as R}from"./input-CtLT7WXi.js";import{H as ce,_t as z}from"./index-CtBqO8vm.js";import{i as B,n as V,o as H,r as U,s as W,t as G}from"./card-Br1JLjTH.js";import{t as le}from"./user-avatar-DuwCFrER.js";var K=e(y(),1);function q(e){return`${e.namespace}/${e.key}`}function ue(e){return`/settings/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.key)}`}function de(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`settings`}function fe(e){let t=new Map;for(let n of e.filter(e=>e.readable)){let e=n.display?.group?.trim()||n.namespace;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({group:e,slug:de(e),settings:t.sort(pe)})).sort((e,t)=>me(e.settings)-me(t.settings)||e.group.localeCompare(t.group))}function pe(e,t){return(e.display?.order??2**53-1)-(t.display?.order??2**53-1)||e.display?.label?.localeCompare(t.display?.label??``)||q(e).localeCompare(q(t))}function me(e){return Math.min(...e.map(e=>e.display?.order??2**53-1))}function he(e){return Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type}function ge(e,t,n){if(!t.length)return n;let[r,...i]=t;if(r===void 0)return n;if(typeof r==`number`){let t=Array.isArray(e)?[...e]:[];return t[r]=ge(t[r],i,n),t}let a=ae(e)?{...e}:{},o=ge(a[r],i,n);return o===void 0?delete a[r]:a[r]=o,a}function _e(e){if(e.default!==void 0)return e.default;if(e.const!==void 0)return e.const;if(e.enum?.length)return e.enum[0];switch(he(e)){case`boolean`:return!1;case`integer`:case`number`:return 0;case`array`:return[];case`object`:return{};case`string`:return``;default:return}}function ve(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(Boolean)}function ye(e){return Array.isArray(e)?e.map(e=>String(e)).join(`
|
|
2
|
-
`):``}function be(e){return ae(e)?Object.entries(e).map(([e,t])=>`${e}=${String(t??``)}`).join(`
|
|
3
|
-
`):``}function xe(e){return Object.fromEntries(e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(`=`);return t>=0?[e.slice(0,t).trim(),e.slice(t+1)]:[e,``]}))}var J=w(),Se=`__unset__`;function Ce(e){return e===`server-runtime`?`Server runtime`:e===`bootstrap`?`Bootstrap`:`Browser`}function we(e){return e===`server-runtime`?`Stored by Relay and mutable while the server is running.`:e===`bootstrap`?`Read from startup configuration; restart or host config changes are required.`:`Stored only in this browser profile.`}function Te(e){return e===`browser`?(0,J.jsx)(d,{className:`size-3.5`}):(0,J.jsx)(u,{className:`size-3.5`})}function Ee(e){return e.details??[]}function De({group:e,settings:t,onSaved:n}){let r=[...new Set(t.map(e=>e.tier))];return(0,J.jsxs)(`section`,{className:`space-y-3`,children:[(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,J.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,J.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:r.map(e=>(0,J.jsxs)(I,{variant:`outline`,className:`gap-1`,title:we(e),children:[Te(e),Ce(e)]},e))})]}),t.length===0?(0,J.jsx)(G,{size:`sm`,children:(0,J.jsx)(U,{className:`text-sm text-muted-foreground`,children:`No settings in this group.`})}):(0,J.jsx)(`div`,{className:`space-y-3`,children:t.map(e=>(0,J.jsx)(Oe,{setting:e,onSaved:n},q(e)))})]})}function Oe({setting:e,onSaved:t}){let[n,r]=(0,K.useState)(()=>e.value??e.defaults??_e(e.schema)),[i,a]=(0,K.useState)(!1),[o,s]=(0,K.useState)(``),[c,l]=(0,K.useState)([]),u=e.writable&&e.tier===`server-runtime`;function d(e,t){r(n=>ge(n,e,t)),l([]),s(``)}async function f(){if(u){a(!0),l([]),s(``);try{let i=await E(`PUT`,ue(e),{value:n,updatedBy:`dashboard`});r(i.value),t(i),s(`Saved`)}catch(e){let t=Ee(e);l(t.length?t:[e.message])}finally{a(!1)}}}return(0,J.jsxs)(G,{size:`sm`,children:[(0,J.jsxs)(H,{children:[(0,J.jsxs)(W,{className:`flex flex-wrap items-center gap-2 text-sm`,children:[e.display.label,(0,J.jsxs)(I,{variant:`outline`,className:`gap-1`,title:we(e.tier),children:[Te(e.tier),Ce(e.tier)]}),!e.writable&&(0,J.jsx)(I,{variant:`secondary`,children:`Read only`})]}),e.display.description&&(0,J.jsx)(B,{children:e.display.description}),(0,J.jsx)(V,{children:(0,J.jsxs)(L,{size:`sm`,onClick:f,disabled:!u||i,children:[(0,J.jsx)(b,{className:`size-4`}),i?`Saving`:`Save`]})})]}),(0,J.jsxs)(U,{className:`space-y-3`,children:[(0,J.jsx)(ke,{schema:e.schema,value:n,path:[],label:e.display.label,required:!0,disabled:!u||i,onChange:d}),(0,J.jsxs)(`p`,{className:`flex flex-wrap items-center gap-x-2 text-[11px] text-muted-foreground`,children:[(0,J.jsxs)(`code`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono`,children:[e.namespace,`/`,e.key]}),(0,J.jsxs)(`span`,{children:[`read `,(0,J.jsx)(`span`,{className:`text-foreground/70`,children:e.scope.read})]}),(0,J.jsx)(`span`,{"aria-hidden":!0,children:`·`}),(0,J.jsxs)(`span`,{children:[`write `,(0,J.jsx)(`span`,{className:`text-foreground/70`,children:e.scope.write})]})]}),c.length>0&&(0,J.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:[(0,J.jsxs)(`div`,{className:`mb-1 flex items-center gap-2 font-medium`,children:[(0,J.jsx)(g,{className:`size-4`}),`Save failed`]}),(0,J.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:c.map(e=>(0,J.jsx)(`li`,{children:e},e))})]}),o&&(0,J.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-emerald-500`,children:[(0,J.jsx)(te,{className:`size-4`}),o]})]})]})}function ke(e){let{schema:t,value:n,path:r,label:i,required:a,disabled:o,onChange:s}=e,c=he(t);if(t.enum?.length){let e=n==null||n===``?Se:String(n);return(0,J.jsx)(Y,{label:i,description:t.description,children:(0,J.jsxs)(F,{value:e,onValueChange:e=>s(r,e===`__unset__`?void 0:e),disabled:o,children:[(0,J.jsx)(M,{children:(0,J.jsx)(j,{})}),(0,J.jsxs)(N,{children:[!a&&(0,J.jsx)(P,{value:`__unset__`,children:`Not set`}),t.enum.map(e=>(0,J.jsx)(P,{value:String(e),children:String(e)},String(e)))]})]})})}if(c===`boolean`)return(0,J.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-md border bg-muted/20 p-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:i}),t.description&&(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:t.description})]}),(0,J.jsx)(z,{checked:!!n,onCheckedChange:e=>s(r,e),disabled:o})]});if(c===`integer`||c===`number`)return(0,J.jsx)(Y,{label:i,description:t.description,children:(0,J.jsx)(R,{type:`number`,min:typeof t.minimum==`number`?t.minimum:void 0,max:typeof t.maximum==`number`?t.maximum:void 0,step:c===`integer`?1:`any`,value:typeof n==`number`?n:``,disabled:o,onChange:e=>s(r,e.target.value===``&&!a?void 0:Number(e.target.value))})});if(c===`array`)return(0,J.jsx)(Y,{label:i,description:t.description??`One item per line.`,children:(0,J.jsx)(ce,{rows:Math.min(8,Math.max(3,Array.isArray(n)?n.length+1:3)),value:ye(n),disabled:o,onChange:e=>s(r,ve(e.target.value))})});if(c===`object`){let e=t.properties??{},a=new Set(t.required??[]);return Object.keys(e).length===0&&t.additionalProperties?(0,J.jsx)(Y,{label:i,description:t.description??`KEY=value, one entry per line.`,children:(0,J.jsx)(ce,{rows:5,value:be(n),disabled:o,onChange:e=>s(r,xe(e.target.value))})}):(0,J.jsxs)(`div`,{className:`space-y-3`,children:[r.length>0&&(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:i}),t.description&&(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:t.description})]}),(0,J.jsx)(`div`,{className:`grid gap-3 md:grid-cols-2`,children:Object.entries(e).map(([e,t])=>{let i=ae(n)?n[e]:void 0;return(0,J.jsx)(ke,{schema:t,value:i===void 0&&a.has(e)?_e(t):i,path:[...r,e],label:t.title||Ae(e),required:a.has(e),disabled:o,onChange:s},e)})})]})}return(0,J.jsx)(Y,{label:i,description:t.description,children:(0,J.jsx)(R,{value:typeof n==`string`?n:n==null?``:String(n),disabled:o,onChange:e=>s(r,e.target.value===``&&!a?void 0:e.target.value)})})}function Y({label:e,description:t,children:n}){return(0,J.jsxs)(`label`,{className:`block space-y-1.5 text-sm`,children:[(0,J.jsx)(`span`,{className:`text-muted-foreground`,children:e}),n,t&&(0,J.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:t})]})}function Ae(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[-_]+/g,` `).replace(/^\w/,e=>e.toUpperCase())}function je(){let e=k(e=>e.theme),t=k(e=>e.showReasoning),n=k(e=>e.set);return(0,J.jsxs)(`section`,{className:`space-y-4`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-base font-semibold`,children:`Browser preferences`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`These are stored in local dashboard state, not in Relay server config.`})]}),(0,J.jsxs)(G,{size:`sm`,children:[(0,J.jsxs)(H,{children:[(0,J.jsx)(W,{className:`text-sm`,children:`Dashboard display`}),(0,J.jsx)(B,{className:`text-xs`,children:`Browser tier · persisted in this browser profile.`}),(0,J.jsx)(V,{children:(0,J.jsxs)(I,{variant:`outline`,className:`gap-1`,children:[(0,J.jsx)(d,{className:`size-3.5`}),`Browser`]})})]}),(0,J.jsxs)(U,{className:`grid gap-3 md:grid-cols-2`,children:[(0,J.jsx)(Y,{label:`Theme`,children:(0,J.jsxs)(F,{value:e,onValueChange:e=>n({theme:e}),children:[(0,J.jsx)(M,{children:(0,J.jsx)(j,{})}),(0,J.jsx)(N,{children:se.map(e=>(0,J.jsx)(P,{value:e.id,children:e.label},e.id))})]})}),(0,J.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-md border bg-muted/20 p-3`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,J.jsx)(c,{className:`size-4`}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:`Show reasoning details`}),(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Display captured reasoning/tool steps in chat. Server capture is controlled separately by provider reasoningCapture.`})]})]}),(0,J.jsx)(z,{checked:t,onCheckedChange:e=>n({showReasoning:e})})]})]})]}),(0,J.jsx)(Me,{})]})}function Me(){let e=k(e=>e.voiceTtsEnabled),t=k(e=>e.setVoiceTtsEnabled),n=k(e=>e.voiceTtsMode),r=k(e=>e.setVoiceTtsMode),i=k(e=>e.voiceTtsKokoroVoice),a=k(e=>e.setVoiceTtsKokoroVoice),o=k(e=>e.voiceTtsBrowserVoice),s=k(e=>e.setVoiceTtsBrowserVoice),c=k(e=>e.voiceInputMode),l=k(e=>e.setVoiceInputMode),[u,d]=(0,K.useState)(()=>D());(0,K.useEffect)(()=>{if(typeof window>`u`||!(`speechSynthesis`in window))return;let e=()=>d(D());return e(),window.speechSynthesis.addEventListener?.(`voiceschanged`,e),()=>window.speechSynthesis.removeEventListener?.(`voiceschanged`,e)},[]);let f=O.some(e=>e.id===i)?O:[...O,{id:i,label:i}];return(0,J.jsxs)(G,{size:`sm`,children:[(0,J.jsxs)(H,{children:[(0,J.jsxs)(W,{className:`flex items-center gap-2 text-sm`,children:[(0,J.jsx)(S,{className:`size-4`}),`Voice`]}),(0,J.jsx)(B,{className:`text-xs`,children:`Browser tier TTS and push-to-talk behavior.`}),(0,J.jsx)(V,{children:(0,J.jsx)(z,{checked:e,onCheckedChange:t})})]}),(0,J.jsxs)(U,{className:`grid gap-3 md:grid-cols-2`,children:[(0,J.jsx)(Y,{label:`Speech engine`,children:(0,J.jsxs)(F,{value:n,onValueChange:e=>r(e),children:[(0,J.jsx)(M,{children:(0,J.jsx)(j,{})}),(0,J.jsxs)(N,{children:[(0,J.jsx)(P,{value:`kokoro`,children:`Kokoro (server, fallback to browser)`}),(0,J.jsx)(P,{value:`browser`,children:`Browser Web Speech API`})]})]})}),(0,J.jsx)(Y,{label:`Kokoro voice`,children:(0,J.jsxs)(F,{value:i,onValueChange:a,children:[(0,J.jsx)(M,{children:(0,J.jsx)(j,{})}),(0,J.jsx)(N,{children:f.map(e=>(0,J.jsx)(P,{value:e.id,children:e.label},e.id))})]})}),(0,J.jsx)(Y,{label:`Browser voice`,children:(0,J.jsxs)(F,{value:o||`__unset__`,onValueChange:e=>s(e===`__unset__`?``:e),children:[(0,J.jsx)(M,{children:(0,J.jsx)(j,{})}),(0,J.jsxs)(N,{children:[(0,J.jsx)(P,{value:Se,children:`System default`}),u.map(e=>(0,J.jsx)(P,{value:e.uri,children:e.label},e.uri))]})]})}),(0,J.jsx)(Y,{label:`Push-to-talk input`,children:(0,J.jsxs)(F,{value:c,onValueChange:e=>l(e),children:[(0,J.jsx)(M,{children:(0,J.jsx)(j,{})}),(0,J.jsxs)(N,{children:[(0,J.jsx)(P,{value:`compose`,children:`Fill message box`}),(0,J.jsx)(P,{value:`autosend`,children:`Send immediately`})]})]})})]})]})}function Ne({catalog:e,error:t,canWrite:i,onCatalog:o}){let s=e[0]?.provider??``,[c,l]=(0,K.useState)(s),[d,f]=(0,K.useState)(()=>Pe(s)),[p,g]=(0,K.useState)(``),[_,y]=(0,K.useState)([]),b=e.some(e=>e.provider===c)?c:s,x=e.find(e=>e.provider===b)??e[0],S=e.map(e=>e.provider);function C(e){f(t=>({...t,...e})),y([]),g(``)}function w(e){l(e),f(Pe(e)),y([]),g(``)}async function T(){o((await E(`GET`,`/providers`)).catalog)}async function ee(){if(i){y([]),g(``);try{await E(`PUT`,`/providers/${encodeURIComponent(d.provider)}/models/${encodeURIComponent(d.alias)}`,{label:d.label,providerModel:d.providerModel,efforts:ve(d.efforts),defaultEffort:d.defaultEffort.trim()||void 0,limits:d.limits,capabilities:d.capabilities,contextThreshold:Fe(d),disabled:d.disabled,updatedBy:`dashboard`}),await T(),g(`${d.alias} saved`),f(Pe(d.provider))}catch(e){let t=Ee(e);y(t.length?t:[e.message])}}}async function ne(e,t){if(i){y([]),g(``);try{await E(`PATCH`,`/providers/${encodeURIComponent(b)}/models/${encodeURIComponent(e.alias)}`,{disabled:t,updatedBy:`dashboard`}),await T(),g(`${e.alias} ${t?`disabled`:`enabled`}`)}catch(e){let t=Ee(e);y(t.length?t:[e.message])}}}async function D(e){if(i){y([]),g(``);try{await E(`DELETE`,`/providers/${encodeURIComponent(b)}/models/${encodeURIComponent(e.alias)}`),await T(),g(`${e.alias} removed`)}catch(e){let t=Ee(e);y(t.length?t:[e.message])}}}function O(e){f({provider:b,alias:e.alias,label:e.label,providerModel:e.providerModel,efforts:e.efforts.join(`, `),defaultEffort:e.defaultEffort??``,selfCompactUtilization:e.contextThreshold?.selfCompactUtilization?.toString()??``,warnUtilization:e.contextThreshold?.warnUtilization?.toString()??``,hardBackstopUtilization:e.contextThreshold?.hardBackstopUtilization?.toString()??``,disabled:!!e.disabled,limits:e.limits,capabilities:e.capabilities}),y([]),g(``)}return t?(0,J.jsx)(G,{size:`sm`,children:(0,J.jsxs)(U,{className:`text-sm text-muted-foreground`,children:[(0,J.jsxs)(`div`,{className:`mb-1 flex items-center gap-2 font-medium text-foreground`,children:[(0,J.jsx)(n,{className:`size-4`}),`Model catalog`]}),t]})}):(0,J.jsxs)(`section`,{className:`space-y-4`,children:[(0,J.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-base font-semibold`,children:`Model catalog`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Add override models, disable unavailable models, or remove custom entries from the provider catalog.`})]}),!i&&(0,J.jsx)(I,{variant:`secondary`,children:`Read only: needs settings:write:provider`})]}),(0,J.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:S.map(e=>(0,J.jsx)(L,{variant:e===b?`default`:`outline`,size:`sm`,onClick:()=>w(e),children:e},e))}),(0,J.jsxs)(G,{size:`sm`,children:[(0,J.jsxs)(H,{children:[(0,J.jsx)(W,{className:`text-sm`,children:`Add or edit model`}),(0,J.jsx)(V,{children:(0,J.jsxs)(I,{variant:`outline`,className:`gap-1`,children:[(0,J.jsx)(u,{className:`size-3.5`}),`Server runtime`]})})]}),(0,J.jsxs)(U,{className:`space-y-3`,children:[(0,J.jsxs)(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[(0,J.jsx)(Y,{label:`Alias`,children:(0,J.jsx)(R,{value:d.alias,disabled:!i,placeholder:`nightly`,onChange:e=>C({alias:e.target.value.trim()})})}),(0,J.jsx)(Y,{label:`Label`,children:(0,J.jsx)(R,{value:d.label,disabled:!i,placeholder:`Nightly Codex`,onChange:e=>C({label:e.target.value})})}),(0,J.jsx)(Y,{label:`Provider model`,children:(0,J.jsx)(R,{value:d.providerModel,disabled:!i,placeholder:`codex-nightly`,onChange:e=>C({providerModel:e.target.value})})}),(0,J.jsx)(Y,{label:`Efforts`,children:(0,J.jsx)(R,{value:d.efforts,disabled:!i,placeholder:`low, medium, high`,onChange:e=>C({efforts:e.target.value})})}),(0,J.jsx)(Y,{label:`Default effort`,children:(0,J.jsx)(R,{value:d.defaultEffort,disabled:!i,placeholder:`medium`,onChange:e=>C({defaultEffort:e.target.value})})}),(0,J.jsx)(Y,{label:`Self compact utilization`,children:(0,J.jsx)(R,{value:d.selfCompactUtilization,disabled:!i,placeholder:`0.80`,inputMode:`decimal`,onChange:e=>C({selfCompactUtilization:e.target.value})})}),(0,J.jsx)(Y,{label:`Warn utilization`,children:(0,J.jsx)(R,{value:d.warnUtilization,disabled:!i,placeholder:`default: self - 0.10`,inputMode:`decimal`,onChange:e=>C({warnUtilization:e.target.value})})}),(0,J.jsx)(Y,{label:`Hard backstop utilization`,children:(0,J.jsx)(R,{value:d.hardBackstopUtilization,disabled:!i,placeholder:`0.90`,inputMode:`decimal`,onChange:e=>C({hardBackstopUtilization:e.target.value})})}),(0,J.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-md border bg-muted/20 p-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:`Disabled`}),(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Keep visible but unavailable for new launches.`})]}),(0,J.jsx)(z,{checked:d.disabled,disabled:!i,onCheckedChange:e=>C({disabled:e})})]})]}),(0,J.jsxs)(L,{onClick:ee,disabled:!i||!d.alias||!d.label||!d.providerModel,children:[(0,J.jsx)(m,{className:`size-4`}),`Save model`]})]})]}),(0,J.jsxs)(`div`,{className:`space-y-2`,children:[x&&x.models.length===0&&(0,J.jsx)(G,{size:`sm`,children:(0,J.jsx)(U,{className:`text-sm text-muted-foreground`,children:`No models in this provider catalog yet.`})}),x?.models.map(e=>(0,J.jsx)(G,{size:`sm`,children:(0,J.jsxs)(U,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,J.jsxs)(`div`,{className:`min-w-0`,children:[(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,J.jsx)(`span`,{className:`font-medium`,children:e.label}),(0,J.jsx)(`code`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-xs`,children:e.alias}),e.disabled&&(0,J.jsx)(I,{variant:`secondary`,children:`Disabled`})]}),(0,J.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[e.providerModel,e.efforts.length>0?` · efforts ${e.efforts.join(`, `)}`:` · no effort levels`,e.defaultEffort?` · default ${e.defaultEffort}`:``,` · context ${Le(e)}`]})]}),(0,J.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,J.jsxs)(L,{variant:`outline`,size:`sm`,onClick:()=>O(e),children:[(0,J.jsx)(r,{className:`size-4`}),`Edit`]}),(0,J.jsxs)(L,{variant:`outline`,size:`sm`,disabled:!i,onClick:()=>void ne(e,!e.disabled),children:[e.disabled?(0,J.jsx)(a,{className:`size-4`}):(0,J.jsx)(h,{className:`size-4`}),e.disabled?`Enable`:`Disable`]}),(0,J.jsxs)(L,{variant:`outline`,size:`sm`,disabled:!i,onClick:()=>void D(e),children:[(0,J.jsx)(v,{className:`size-4`}),`Remove`]})]})]})},e.alias))]}),_.length>0&&(0,J.jsx)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:(0,J.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:_.map(e=>(0,J.jsx)(`li`,{children:e},e))})}),p&&(0,J.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-emerald-500`,children:[(0,J.jsx)(te,{className:`size-4`}),p]})]})}function Pe(e){return{provider:e,alias:``,label:``,providerModel:``,efforts:``,defaultEffort:``,selfCompactUtilization:``,warnUtilization:``,hardBackstopUtilization:``,disabled:!1}}function Fe(e){let t=Ie(e.selfCompactUtilization,`Self compact utilization`),n=Ie(e.warnUtilization,`Warn utilization`),r=Ie(e.hardBackstopUtilization,`Hard backstop utilization`);if(!(t===void 0&&n===void 0&&r===void 0)){if(t===void 0)throw Error(`Self compact utilization is required when setting context thresholds`);return{selfCompactUtilization:t,...n===void 0?{}:{warnUtilization:n},...r===void 0?{}:{hardBackstopUtilization:r}}}}function Ie(e,t){let n=e.trim();if(!n)return;let r=Number(n);if(!Number.isFinite(r))throw Error(`${t} must be a number`);return r}function Le(e){if(e.contextThreshold)return`self ${Re(e.contextThreshold.selfCompactUtilization)}, warn ${Re(e.contextThreshold.warnUtilization??Math.max(0,e.contextThreshold.selfCompactUtilization-.1))}`;let t=re(e.limits?.contextWindowTokens?.value);return`derived self ${Re(t.selfCompactUtilization)}, warn ${Re(t.warnUtilization)}`}function Re(e){return`${Math.round(e*100)}%`}var ze=5,Be=15,Ve={claude:`Claude`,codex:`Codex`};function He(e){return Math.round(e/6e4)}function Ue(e){return`${He(e)} min`}function We({canWrite:e}){let[t,n]=(0,K.useState)(null),[r,i]=(0,K.useState)(``),[a,o]=(0,K.useState)(``),[s,c]=(0,K.useState)(null);(0,K.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await E(`GET`,`/providers/quota-config`);e||n(t)}catch(t){e||i(t.message)}})(),()=>{e=!0}},[]);async function u(e,t){n(n=>({...n??{},[e]:t})),o(``),c(e);try{let r=await E(`PUT`,`/providers/${e}/quota-config`,t);n(t=>({...t??{},[e]:r}))}catch(t){o(`${Ve[e]??e}: ${t.message}`)}finally{c(null)}}let d=t?Object.keys(t).sort():[];return(0,J.jsxs)(`section`,{className:`space-y-4`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-base font-semibold`,children:`Quota`}),(0,J.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Per-provider quota collection and display. `,(0,J.jsx)(`strong`,{children:`Enabled`}),` governs collection (disabled stops polling — no API calls);`,(0,J.jsx)(`strong`,{children:` Show in widget`}),` governs display only.`]})]}),r&&(0,J.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:[(0,J.jsx)(g,{className:`mt-0.5 size-4`}),(0,J.jsx)(`span`,{children:r})]}),a&&(0,J.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:[(0,J.jsx)(g,{className:`mt-0.5 size-4`}),(0,J.jsx)(`span`,{children:a})]}),!t&&!r&&(0,J.jsx)(G,{size:`sm`,children:(0,J.jsxs)(U,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,J.jsx)(T,{className:`size-4 animate-spin`}),`Loading quota config…`]})}),d.map(r=>{let i=t[r],a=!e||s===r;return(0,J.jsxs)(G,{size:`sm`,children:[(0,J.jsxs)(H,{children:[(0,J.jsxs)(W,{className:`flex items-center gap-2 text-sm`,children:[(0,J.jsx)(l,{className:`size-4`}),Ve[r]??r,s===r&&(0,J.jsx)(T,{className:`size-3 animate-spin text-muted-foreground`})]}),(0,J.jsxs)(B,{className:`text-xs`,children:[i.enabled?`Polled every ${Ue(i.pollIntervalMs)}`:`Collection disabled`,i.enabled&&!i.showInWidget?` · hidden from widget`:``]})]}),(0,J.jsxs)(U,{className:`space-y-4`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-md border bg-muted/20 p-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:`Enabled`}),(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Collect quota for this provider. Off stops all polling (no API calls, no token spend).`})]}),(0,J.jsx)(z,{checked:i.enabled,disabled:a,onCheckedChange:e=>void u(r,{...i,enabled:e})})]}),(0,J.jsxs)(`div`,{className:`rounded-md border bg-muted/20 p-3 space-y-2`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:`Polling interval`}),(0,J.jsx)(I,{variant:`outline`,className:`tabular-nums`,children:Ue(i.pollIntervalMs)})]}),(0,J.jsx)(`input`,{type:`range`,min:ze,max:Be,step:1,value:He(i.pollIntervalMs),disabled:a||!i.enabled,onChange:e=>{let t=Number(e.target.value)*6e4;n(e=>({...e??{},[r]:{...i,pollIntervalMs:t}}))},onPointerUp:e=>void u(r,{...i,pollIntervalMs:Number(e.target.value)*6e4}),onKeyUp:e=>void u(r,{...i,pollIntervalMs:Number(e.target.value)*6e4}),className:`w-full accent-primary disabled:opacity-50`}),(0,J.jsxs)(`div`,{className:`flex justify-between text-[10px] text-muted-foreground`,children:[(0,J.jsxs)(`span`,{children:[ze,` min`]}),(0,J.jsxs)(`span`,{children:[Be,` min`]})]})]}),(0,J.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-md border bg-muted/20 p-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:`Show in quota widget`}),(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Display only. Off hides this provider from the dashboard widget; collection continues if enabled.`})]}),(0,J.jsx)(z,{checked:i.showInWidget,disabled:a,onCheckedChange:e=>void u(r,{...i,showInWidget:e})})]}),(0,J.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-md border bg-muted/20 p-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:`Burn-rate sparkline`}),(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Show a mini utilization chart per window in the expanded widget.`})]}),(0,J.jsx)(z,{checked:i.sparklineEnabled??!0,disabled:a,onCheckedChange:e=>void u(r,{...i,sparklineEnabled:e})})]}),(0,J.jsxs)(`div`,{className:`rounded-md border bg-muted/20 p-3 space-y-2`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,J.jsx)(`div`,{className:`text-sm font-medium`,children:`Sparkline range`}),(0,J.jsxs)(I,{variant:`outline`,className:`tabular-nums`,children:[i.sparklineRangeHours??8,`h`]})]}),(0,J.jsx)(`input`,{type:`range`,min:1,max:8,step:1,value:i.sparklineRangeHours??8,disabled:a||!(i.sparklineEnabled??!0),onChange:e=>{let t=Number(e.target.value);n(e=>({...e??{},[r]:{...i,sparklineRangeHours:t}}))},onPointerUp:e=>void u(r,{...i,sparklineRangeHours:Number(e.target.value)}),onKeyUp:e=>void u(r,{...i,sparklineRangeHours:Number(e.target.value)}),className:`w-full accent-primary disabled:opacity-50`}),(0,J.jsxs)(`div`,{className:`flex justify-between text-[10px] text-muted-foreground`,children:[(0,J.jsx)(`span`,{children:`1h`}),(0,J.jsx)(`span`,{children:`8h`})]})]})]})]},r)})]})}function Ge({message:e}){return(0,J.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:[(0,J.jsx)(g,{className:`mt-0.5 size-4 shrink-0`}),(0,J.jsx)(`span`,{children:e})]})}var Ke=oe(),X={cautionAt:.15,avoidLargeAt:.5,hardAvoidAt:1},qe=.99,Je=.5;function Z(e,t){return((e??t)*100).toFixed(0)}function Q(e){let t=Number(e);return!Number.isFinite(t)||t<0||t>100?null:t/100}function Ye({policy:e,canWrite:t,onPolicy:n}){let r=e.quotaBands,i=e.providerQuota??{},[a,o]=(0,K.useState)(Z(r?.cautionAt,X.cautionAt)),[s,c]=(0,K.useState)(Z(r?.avoidLargeAt,X.avoidLargeAt)),[l,u]=(0,K.useState)(Z(r?.hardAvoidAt,X.hardAvoidAt)),[d,f]=(0,K.useState)(()=>{let e={};for(let t of Ke){let n=i[t]??{};e[t]={backstop:Z(n.hardBackstopUtilization,qe),floor:Z(n.burnPenaltyUtilizationFloor,Je)}}return e}),[p,m]=(0,K.useState)(!1),[h,g]=(0,K.useState)(``),[_,v]=(0,K.useState)(!1),[y,x]=(0,K.useState)(``);async function S(){let t=Q(a),r=Q(s),i=Q(l);if(t===null){x(`Caution threshold must be 0–100%.`);return}if(r===null){x(`Avoid-large threshold must be 0–100%.`);return}if(i===null){x(`Hard-avoid threshold must be 0–100%.`);return}if(t>=r){x(`Caution must be less than avoid-large.`);return}if(r>=i){x(`Avoid-large must be less than hard-avoid.`);return}let o={};for(let e of Ke){let t=d[e],n=Q(t.backstop),r=Q(t.floor);if(n===null){x(`${A(e)}: hard-backstop must be 0–100%.`);return}if(r===null){x(`${A(e)}: burn-penalty floor must be 0–100%.`);return}o[e]={hardBackstopUtilization:n,burnPenaltyUtilizationFloor:r}}x(``),m(!0),g(``),v(!1);try{n(await E(`PUT`,`/routing-policy`,{...e,quotaBands:{cautionAt:t,avoidLargeAt:r,hardAvoidAt:i},providerQuota:o})),v(!0),setTimeout(()=>v(!1),2e3)}catch(e){g(e.message)}finally{m(!1)}}function C(e,t){f(n=>({...n,[e]:{...n[e],...t}})),x(``),v(!1)}function w(){x(``),v(!1)}return(0,J.jsxs)(G,{size:`sm`,children:[(0,J.jsxs)(H,{children:[(0,J.jsx)(W,{className:`text-sm`,children:`Quota thresholds`}),(0,J.jsx)(B,{className:`text-xs`,children:`Band cutoffs govern when the orchestrator starts penalising or blocking high-quota providers. Values are utilization percentages (0–100).`})]}),(0,J.jsxs)(U,{className:`space-y-4`,children:[(h||y)&&(0,J.jsx)(Ge,{message:h||y}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`mb-2 text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Band cutoffs`}),(0,J.jsx)(Xe,{caution:Number(a),avoidLarge:Number(s),hardAvoid:Number(l)}),(0,J.jsxs)(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-3`,children:[(0,J.jsx)($,{label:`Caution at`,hint:`Default: ${(X.cautionAt*100).toFixed(0)}%`,value:a,disabled:!t||p,onChange:e=>{o(e),w()}}),(0,J.jsx)($,{label:`Avoid-large at`,hint:`Default: ${(X.avoidLargeAt*100).toFixed(0)}%`,value:s,disabled:!t||p,onChange:e=>{c(e),w()}}),(0,J.jsx)($,{label:`Hard-avoid at`,hint:`Default: ${(X.hardAvoidAt*100).toFixed(0)}%`,value:l,disabled:!t||p,onChange:e=>{u(e),w()}})]})]}),Ke.map(e=>{let n=d[e];return(0,J.jsxs)(`div`,{children:[(0,J.jsxs)(`div`,{className:`mb-2 text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:[A(e),` overrides`]}),(0,J.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,J.jsx)($,{label:`Hard-backstop utilization`,hint:`Provider blocked above this. Default: ${(qe*100).toFixed(0)}%`,value:n.backstop,disabled:!t||p,onChange:t=>C(e,{backstop:t})}),(0,J.jsx)($,{label:`Burn-penalty floor`,hint:`Penalties suppressed below this. Default: ${(Je*100).toFixed(0)}%`,value:n.floor,disabled:!t||p,onChange:t=>C(e,{floor:t})})]})]},e)}),t&&(0,J.jsxs)(L,{size:`sm`,onClick:()=>void S(),disabled:p,children:[p?(0,J.jsx)(T,{className:`size-4 animate-spin`}):(0,J.jsx)(b,{className:`size-4`}),_?`Saved`:`Save thresholds`]})]})]})}function Xe({caution:e,avoidLarge:t,hardAvoid:n}){let r=e=>Math.max(0,Math.min(100,Number.isFinite(e)?e:0)),i=r(e),a=Math.max(i,r(t)),o=Math.max(a,r(n)),s=e=>`${e.toFixed(0)}%`,c=[{key:`normal`,label:`normal`,color:`bg-emerald-500`,from:0,to:i,range:`0–${s(i)}`},{key:`caution`,label:`caution`,color:`bg-amber-500`,from:i,to:a,range:`${s(i)}–${s(a)}`},{key:`avoid-large`,label:`avoid large`,color:`bg-orange-500`,from:a,to:o,range:`${s(a)}–${s(o)}`},{key:`hard-avoid`,label:`hard avoid`,color:`bg-red-500`,from:o,to:100,range:`≥ ${s(o)}`}];return(0,J.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,J.jsx)(`div`,{className:`flex h-2.5 overflow-hidden rounded-full bg-muted`,role:`img`,"aria-label":`Quota penalty bands from 0 to 100 percent`,children:c.map(e=>(0,J.jsx)(`div`,{className:_(e.color,`transition-[width] duration-300`),style:{width:`${e.to-e.from}%`},title:`${e.label} · ${e.range}`},e.key))}),(0,J.jsx)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-[10px] text-muted-foreground`,children:c.map(e=>(0,J.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,J.jsx)(`span`,{className:_(`size-2 shrink-0 rounded-full`,e.color)}),e.label,` `,(0,J.jsx)(`span`,{className:`tabular-nums text-foreground/70`,children:e.range})]},e.key))})]})}function $({label:e,hint:t,value:n,disabled:r,onChange:i}){return(0,J.jsxs)(`label`,{className:`space-y-1`,children:[(0,J.jsx)(`span`,{className:`text-[10px] font-medium text-muted-foreground`,children:e}),(0,J.jsxs)(`div`,{className:`relative`,children:[(0,J.jsx)(R,{value:n,onChange:e=>i(e.target.value),disabled:r,className:`h-8 pr-6 text-xs tabular-nums`}),(0,J.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 right-2.5 flex items-center text-xs text-muted-foreground`,children:`%`})]}),(0,J.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:t})]})}function Ze(){let[e,t]=(0,K.useState)(null),[n,r]=(0,K.useState)(!1),[i,s]=(0,K.useState)(``),[c,l]=(0,K.useState)(!1),[u,d]=(0,K.useState)(!1);async function p(){if(!u){r(!0),s(``);try{let[e,n]=await Promise.all([E(`GET`,`/routing-policy`),E(`GET`,`/agent-profiles/coordinator`).catch(()=>null)]);t({policy:e,profile:n}),d(!0)}catch(e){s(e.message)}finally{r(!1)}}}async function m(){d(!1),r(!0),s(``);try{let[e,n]=await Promise.all([E(`GET`,`/routing-policy`),E(`GET`,`/agent-profiles/coordinator`).catch(()=>null)]);t({policy:e,profile:n}),d(!0)}catch(e){s(e.message)}finally{r(!1)}}function h(){let e=!c;l(e),e&&!u&&p()}return(0,J.jsx)(G,{size:`sm`,children:(0,J.jsxs)(U,{className:`space-y-3`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 text-left`,onClick:h,children:[(0,J.jsx)(a,{className:`size-4 text-muted-foreground`}),(0,J.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,J.jsx)(`div`,{className:`text-sm font-semibold`,children:`What your coordinator knows`}),(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`Active routing policy + coordinator profile instructions (read-only)`})]}),c?(0,J.jsx)(ne,{className:`size-4 shrink-0 text-muted-foreground`}):(0,J.jsx)(f,{className:`size-4 shrink-0 text-muted-foreground`})]}),c&&(0,J.jsxs)(`div`,{className:`space-y-4 pt-1`,children:[(0,J.jsx)(`div`,{className:`flex justify-end`,children:(0,J.jsxs)(L,{variant:`outline`,size:`sm`,onClick:()=>void m(),disabled:n,children:[(0,J.jsx)(o,{className:_(`size-3.5`,n&&`animate-spin`)}),`Refresh`]})}),i&&(0,J.jsx)(Ge,{message:i}),n&&!e&&(0,J.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-muted-foreground py-2`,children:[(0,J.jsx)(T,{className:`size-3.5 animate-spin`}),`Loading…`]}),e&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Qe,{policy:e.policy}),e.profile?(0,J.jsx)(et,{profile:e.profile}):(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground italic`,children:`Coordinator profile not found.`})]})]})]})})}function Qe({policy:e}){let t=e.quotaBands,n=e.providerQuota??{};return(0,J.jsxs)(`div`,{className:`space-y-2`,children:[(0,J.jsx)(`div`,{className:`text-xs font-semibold text-muted-foreground uppercase tracking-wide`,children:`Active routing policy`}),e.rules.length===0?(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground italic`,children:`No rules — coordinators use their own heuristics.`}):(0,J.jsxs)(`div`,{className:`overflow-hidden rounded-md border border-border text-xs`,children:[(0,J.jsxs)(`div`,{className:`grid grid-cols-[1.5rem_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-px bg-border text-[10px] font-medium text-muted-foreground uppercase tracking-wide`,children:[(0,J.jsx)(`div`,{className:`bg-muted/40 px-2 py-1.5`,children:`#`}),(0,J.jsx)(`div`,{className:`bg-muted/40 px-2 py-1.5`,children:`Match`}),(0,J.jsx)(`div`,{className:`bg-muted/40 px-2 py-1.5`,children:`Target`}),(0,J.jsx)(`div`,{className:`bg-muted/40 px-2 py-1.5`,children:`Status`})]}),e.rules.map((e,t)=>(0,J.jsxs)(`div`,{className:_(`grid grid-cols-[1.5rem_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-px bg-border`,e.enabled===!1&&`opacity-50`),children:[(0,J.jsx)(`div`,{className:`bg-card px-2 py-1.5 text-muted-foreground tabular-nums`,children:t+1}),(0,J.jsxs)(`div`,{className:`bg-card px-2 py-1.5`,children:[e.label&&(0,J.jsx)(`div`,{className:`font-medium`,children:e.label}),e.match.taskType&&(0,J.jsxs)(`div`,{className:`font-mono`,children:[`task: `,e.match.taskType]}),e.match.capability&&(0,J.jsxs)(`div`,{className:`font-mono`,children:[`cap: `,e.match.capability]})]}),(0,J.jsxs)(`div`,{className:`bg-card px-2 py-1.5`,children:[(0,J.jsx)(`span`,{className:`font-medium`,children:e.target.provider}),e.target.model&&(0,J.jsxs)(`span`,{className:`text-muted-foreground`,children:[` / `,e.target.model]}),e.target.effort&&(0,J.jsxs)(`span`,{className:`text-muted-foreground`,children:[` (`,e.target.effort,`)`]})]}),(0,J.jsx)(`div`,{className:`bg-card px-2 py-1.5`,children:e.enabled===!1?(0,J.jsx)(`span`,{className:`text-muted-foreground`,children:`disabled`}):(0,J.jsx)(`span`,{className:`text-emerald-500`,children:`active`})})]},t))]}),(t||Object.keys(n).length>0)&&(0,J.jsxs)(`div`,{className:`rounded-md border border-border bg-muted/10 px-3 py-2 text-xs space-y-1`,children:[t&&(0,J.jsxs)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-0.5`,children:[t.cautionAt!==void 0&&(0,J.jsxs)(`span`,{children:[`caution ≥ `,(t.cautionAt*100).toFixed(0),`%`]}),t.avoidLargeAt!==void 0&&(0,J.jsxs)(`span`,{children:[`avoid-large ≥ `,(t.avoidLargeAt*100).toFixed(0),`%`]}),t.hardAvoidAt!==void 0&&(0,J.jsxs)(`span`,{children:[`hard-avoid ≥ `,(t.hardAvoidAt*100).toFixed(0),`%`]})]}),Object.entries(n).map(([e,t])=>(0,J.jsxs)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-0.5 text-muted-foreground`,children:[(0,J.jsx)(`span`,{className:`font-medium text-foreground`,children:A(e)}),t?.hardBackstopUtilization!==void 0&&(0,J.jsxs)(`span`,{children:[`backstop: `,(t.hardBackstopUtilization*100).toFixed(0),`%`]}),t?.burnPenaltyUtilizationFloor!==void 0&&(0,J.jsxs)(`span`,{children:[`floor: `,(t.burnPenaltyUtilizationFloor*100).toFixed(0),`%`]})]},e))]})]})}function $e({text:e,index:t}){return(0,J.jsxs)(`div`,{className:`relative max-h-72 overflow-y-auto rounded-md border border-border bg-muted/20`,children:[t!==void 0&&(0,J.jsxs)(`span`,{className:`sticky top-0 float-right m-1.5 rounded bg-muted px-1.5 py-0.5 text-[9px] font-medium tabular-nums text-muted-foreground`,children:[`#`,t]}),(0,J.jsx)(`pre`,{className:`whitespace-pre-wrap break-words px-3 py-2.5 font-sans text-[11px] leading-relaxed text-foreground/90`,children:e})]})}function et({profile:e}){return(0,J.jsxs)(`div`,{className:`space-y-2`,children:[(0,J.jsxs)(`div`,{className:`text-xs font-semibold text-muted-foreground uppercase tracking-wide`,children:[`Coordinator profile instructions`,(0,J.jsx)(I,{variant:`secondary`,className:`ml-2 text-[10px]`,children:e.name}),e.builtIn&&(0,J.jsx)(I,{variant:`outline`,className:`ml-1 text-[10px]`,children:`built-in`})]}),e.description&&(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.description}),(0,J.jsxs)(`div`,{className:`flex flex-wrap gap-2 text-[10px]`,children:[(0,J.jsxs)(I,{variant:`outline`,children:[`base: `,e.base]}),(0,J.jsxs)(I,{variant:`outline`,children:[`repo: `,e.instructions.repoInstructions]}),(0,J.jsxs)(I,{variant:`outline`,children:[`global: `,e.instructions.globalInstructions]}),e.provider&&(0,J.jsxs)(I,{variant:`outline`,children:[`provider: `,e.provider]})]}),e.instructions.system&&(0,J.jsxs)(`div`,{className:`space-y-1`,children:[(0,J.jsx)(`div`,{className:`text-[10px] font-medium text-muted-foreground uppercase tracking-wide`,children:`System prompt`}),(0,J.jsx)($e,{text:e.instructions.system})]}),e.instructions.append.length>0&&(0,J.jsxs)(`div`,{className:`space-y-2`,children:[(0,J.jsxs)(`div`,{className:`text-[10px] font-medium text-muted-foreground uppercase tracking-wide`,children:[`Appended instructions (`,e.instructions.append.length,`)`]}),e.instructions.append.map((e,t)=>(0,J.jsx)($e,{text:e,index:t+1},t))]}),e.instructions.append.length===0&&!e.instructions.system&&(0,J.jsx)(`div`,{className:`text-xs text-muted-foreground italic`,children:`No instruction blocks defined.`})]})}var tt=oe();function nt(){return{label:``,matchTaskType:``,matchCapability:``,targetProvider:tt[0]??``,targetModel:``,targetEffort:``,enabled:!0}}function rt(e){return{label:e.label??``,matchTaskType:e.match.taskType??``,matchCapability:e.match.capability??``,targetProvider:e.target.provider,targetModel:e.target.model??``,targetEffort:e.target.effort??``,enabled:e.enabled!==!1}}function it(e){return{...e.label.trim()?{label:e.label.trim()}:{},match:{...e.matchTaskType.trim()?{taskType:e.matchTaskType.trim()}:{},...e.matchCapability.trim()?{capability:e.matchCapability.trim()}:{}},target:{provider:e.targetProvider,...e.targetModel.trim()?{model:e.targetModel.trim()}:{},...e.targetEffort.trim()?{effort:e.targetEffort.trim()}:{}},enabled:e.enabled}}function at(e){return!e.matchTaskType.trim()&&!e.matchCapability.trim()?`At least one match criterion (task type or capability) is required.`:null}function ot({message:e}){return(0,J.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:[(0,J.jsx)(g,{className:`mt-0.5 size-4 shrink-0`}),(0,J.jsx)(`span`,{children:e})]})}function st({canWrite:e}){let[t,n]=(0,K.useState)(null),[r,i]=(0,K.useState)(!1),[a,s]=(0,K.useState)(``),[c,l]=(0,K.useState)(!1);!c&&!r&&!a&&(i(!0),(async()=>{try{n(await E(`GET`,`/routing-policy`)),l(!0)}catch(e){s(e.message)}finally{i(!1)}})());async function u(){i(!0),s(``);try{n(await E(`GET`,`/routing-policy`)),l(!0)}catch(e){s(e.message)}finally{i(!1)}}return(0,J.jsxs)(`div`,{className:`space-y-6`,children:[(0,J.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-base font-semibold`,children:`Routing`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Declarative rules mapping task types and capabilities to providers. Rules are advisory — coordinators apply them; explicit per-spawn arguments always take precedence.`})]}),(0,J.jsxs)(L,{variant:`outline`,size:`sm`,onClick:()=>void u(),disabled:r,children:[(0,J.jsx)(o,{className:_(`size-4`,r&&`animate-spin`)}),`Refresh`]})]}),a&&(0,J.jsx)(ot,{message:a}),r&&!t&&(0,J.jsx)(G,{size:`sm`,children:(0,J.jsxs)(U,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,J.jsx)(T,{className:`size-4 animate-spin`}),`Loading routing policy…`]})}),t&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(ct,{policy:t,canWrite:e,onPolicy:n}),(0,J.jsx)(Ye,{policy:t,canWrite:e,onPolicy:n})]}),(0,J.jsx)(Ze,{})]})}function ct({policy:e,canWrite:t,onPolicy:n}){let[r,i]=(0,K.useState)(!1),[a,o]=(0,K.useState)(``),[c,l]=(0,K.useState)(!1),[u,d]=(0,K.useState)(nt),[f,p]=(0,K.useState)(``),[h,g]=(0,K.useState)(null),[_,v]=(0,K.useState)(nt),[y,b]=(0,K.useState)(``);async function x(e){i(!0),o(``);try{n(await E(`PUT`,`/routing-policy`,e))}catch(e){o(e.message)}finally{i(!1)}}function S(t,n){let r=[...e.rules],i=t+n;i<0||i>=r.length||([r[t],r[i]]=[r[i],r[t]],x({...e,rules:r}))}function C(t){let n=e.rules.map((e,n)=>n===t?{...e,enabled:e.enabled===!1}:e);x({...e,rules:n})}function w(t){x({...e,rules:e.rules.filter((e,n)=>n!==t)})}function ee(){d(nt()),p(``),l(!0)}function te(){l(!1),p(``)}function ne(){let t=at(u);if(t){p(t);return}l(!1),x({...e,rules:[...e.rules,it(u)]})}function D(t){g(t),v(rt(e.rules[t])),b(``)}function O(){g(null),b(``)}function k(){if(h===null)return;let t=at(_);if(t){b(t);return}let n=e.rules.map((e,t)=>t===h?it(_):e);g(null),x({...e,rules:n})}return(0,J.jsxs)(G,{size:`sm`,children:[(0,J.jsxs)(H,{children:[(0,J.jsxs)(W,{className:`flex items-center gap-2 text-sm`,children:[(0,J.jsx)(s,{className:`size-4`}),`Rules`,(0,J.jsxs)(I,{variant:`outline`,className:`ml-auto text-[10px]`,children:[e.rules.length,` rule`,e.rules.length===1?``:`s`]}),r&&(0,J.jsx)(T,{className:`size-3 animate-spin text-muted-foreground`})]}),(0,J.jsx)(B,{className:`text-xs`,children:`Evaluated in order — first matching enabled rule wins. Rules are advisory; explicit spawn arguments override them.`})]}),(0,J.jsxs)(U,{className:`space-y-2`,children:[a&&(0,J.jsx)(ot,{message:a}),e.rules.length===0&&!c&&(0,J.jsx)(`div`,{className:`rounded-md border border-dashed border-border py-6 text-center text-xs text-muted-foreground`,children:`No rules — coordinators fall back to their own heuristics.`}),e.rules.map((n,i)=>h===i?(0,J.jsx)(ut,{form:_,error:y,onChange:v,onSave:k,onCancel:O},i):(0,J.jsx)(lt,{rule:n,idx:i,total:e.rules.length,canWrite:t,saving:r,onMoveUp:()=>S(i,-1),onMoveDown:()=>S(i,1),onToggle:()=>C(i),onEdit:()=>D(i),onRemove:()=>w(i)},i)),c&&(0,J.jsx)(ut,{form:u,error:f,onChange:d,onSave:ne,onCancel:te,isNew:!0}),t&&!c&&h===null&&(0,J.jsxs)(L,{variant:`outline`,size:`sm`,className:`w-full gap-1`,onClick:ee,disabled:r,children:[(0,J.jsx)(m,{className:`size-4`}),`Add rule`]})]})]})}function lt({rule:e,idx:t,total:n,canWrite:r,saving:a,onMoveUp:o,onMoveDown:s,onToggle:c,onEdit:l,onRemove:u}){return(0,J.jsxs)(`div`,{className:_(`group flex items-start gap-3 rounded-md border bg-muted/20 p-3`,e.enabled===!1&&`opacity-60`),children:[(0,J.jsxs)(`div`,{className:`flex flex-col items-center gap-0.5 pt-0.5`,children:[(0,J.jsx)(`button`,{type:`button`,title:`Move up`,onClick:o,disabled:!r||a||t===0,className:`rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-30`,children:(0,J.jsx)(p,{className:`size-3.5`})}),(0,J.jsx)(`button`,{type:`button`,title:`Move down`,onClick:s,disabled:!r||a||t===n-1,className:`rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-30`,children:(0,J.jsx)(i,{className:`size-3.5`})})]}),(0,J.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,J.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,J.jsxs)(`span`,{className:`text-[10px] tabular-nums text-muted-foreground`,children:[`#`,t+1]}),e.label&&(0,J.jsx)(`span`,{className:`text-xs font-medium`,children:e.label}),(0,J.jsx)(I,{variant:`outline`,className:`text-[10px]`,children:e.target.provider}),e.target.model&&(0,J.jsx)(I,{variant:`outline`,className:`text-[10px] font-mono`,children:e.target.model}),e.target.effort&&(0,J.jsx)(I,{variant:`outline`,className:`text-[10px]`,children:e.target.effort})]}),(0,J.jsxs)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted-foreground`,children:[e.match.taskType&&(0,J.jsxs)(`span`,{children:[`task-type: `,(0,J.jsx)(`span`,{className:`font-mono text-foreground`,children:e.match.taskType})]}),e.match.capability&&(0,J.jsxs)(`span`,{children:[`capability: `,(0,J.jsx)(`span`,{className:`font-mono text-foreground`,children:e.match.capability})]})]})]}),(0,J.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 opacity-70 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100`,children:[(0,J.jsx)(z,{checked:e.enabled!==!1,disabled:!r||a,onCheckedChange:c,title:e.enabled===!1?`Enable rule`:`Disable rule`}),r&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,title:`Edit`,onClick:l,disabled:a,className:`rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground disabled:pointer-events-none`,children:(0,J.jsxs)(`svg`,{className:`size-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,children:[(0,J.jsx)(`path`,{d:`M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7`}),(0,J.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z`})]})}),(0,J.jsx)(`button`,{type:`button`,title:`Remove`,onClick:u,disabled:a,className:`rounded p-1 text-destructive hover:bg-destructive/10 disabled:pointer-events-none`,children:(0,J.jsx)(v,{className:`size-3.5`})})]})]})]})}function ut({form:e,error:t,onChange:n,onSave:r,onCancel:i,isNew:a}){function o(t){n({...e,...t})}return(0,J.jsxs)(`div`,{className:`rounded-md border border-primary/30 bg-primary/5 p-3 space-y-3`,children:[(0,J.jsx)(`div`,{className:`text-xs font-semibold text-muted-foreground uppercase tracking-wide`,children:a?`New rule`:`Edit rule`}),(0,J.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,J.jsxs)(`label`,{className:`space-y-1`,children:[(0,J.jsx)(`span`,{className:`text-[10px] font-medium text-muted-foreground`,children:`Label (optional)`}),(0,J.jsx)(R,{value:e.label,onChange:e=>o({label:e.target.value}),placeholder:`e.g. Route GUI tasks to Claude`,className:`h-8 text-xs`})]}),(0,J.jsxs)(`label`,{className:`space-y-1`,children:[(0,J.jsx)(`span`,{className:`text-[10px] font-medium text-muted-foreground`,children:`Target provider`}),(0,J.jsxs)(F,{value:e.targetProvider,onValueChange:e=>o({targetProvider:e}),children:[(0,J.jsx)(M,{className:`h-8 text-xs`,children:(0,J.jsx)(j,{})}),(0,J.jsx)(N,{children:tt.map(e=>(0,J.jsx)(P,{value:e,className:`text-xs`,children:A(e)},e))})]})]})]}),(0,J.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,J.jsxs)(`label`,{className:`space-y-1`,children:[(0,J.jsx)(`span`,{className:`text-[10px] font-medium text-muted-foreground`,children:`Match task-type (prefix)`}),(0,J.jsx)(R,{value:e.matchTaskType,onChange:e=>o({matchTaskType:e.target.value}),placeholder:`e.g. gui, backend, mechanical`,className:`h-8 font-mono text-xs`}),(0,J.jsxs)(`span`,{className:`block text-[10px] leading-snug text-muted-foreground`,children:[`Prefix match — `,(0,J.jsx)(`span`,{className:`font-mono text-foreground`,children:`gui`}),` matches `,(0,J.jsx)(`span`,{className:`font-mono text-foreground`,children:`gui/ux`}),`, `,(0,J.jsx)(`span`,{className:`font-mono text-foreground`,children:`gui/layout`}),`.`]})]}),(0,J.jsxs)(`label`,{className:`space-y-1`,children:[(0,J.jsx)(`span`,{className:`text-[10px] font-medium text-muted-foreground`,children:`Match capability (exact)`}),(0,J.jsx)(R,{value:e.matchCapability,onChange:e=>o({matchCapability:e.target.value}),placeholder:`e.g. code, research, bounded`,className:`h-8 font-mono text-xs`}),(0,J.jsx)(`span`,{className:`block text-[10px] leading-snug text-muted-foreground`,children:`Exact match against the agent's capability tag. Both fields are AND-ed.`})]})]}),(0,J.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,J.jsxs)(`label`,{className:`space-y-1`,children:[(0,J.jsx)(`span`,{className:`text-[10px] font-medium text-muted-foreground`,children:`Model alias (optional)`}),(0,J.jsx)(R,{value:e.targetModel,onChange:e=>o({targetModel:e.target.value}),placeholder:`e.g. opus, gpt-5.4`,className:`h-8 font-mono text-xs`})]}),(0,J.jsxs)(`label`,{className:`space-y-1`,children:[(0,J.jsx)(`span`,{className:`text-[10px] font-medium text-muted-foreground`,children:`Effort (optional)`}),(0,J.jsx)(R,{value:e.targetEffort,onChange:e=>o({targetEffort:e.target.value}),placeholder:`e.g. high, low`,className:`h-8 text-xs`})]})]}),(0,J.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,J.jsx)(z,{checked:e.enabled,onCheckedChange:e=>o({enabled:e})}),(0,J.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Enabled`})]}),t&&(0,J.jsx)(ot,{message:t}),(0,J.jsxs)(`div`,{className:`flex gap-2`,children:[(0,J.jsxs)(L,{size:`sm`,onClick:r,children:[(0,J.jsx)(b,{className:`size-4`}),a?`Add`:`Save`]}),(0,J.jsx)(L,{size:`sm`,variant:`outline`,onClick:i,children:`Cancel`})]})]})}var dt=`browser`,ft=`models`,pt=`profile`,mt=`routing`,ht=[`branch.landed`,`landed-failure`,`agent.ready`,`agent.exited`,`agent.spawn_failed`,`agent.context_threshold`,`agent.quota_threshold`,`workspace.steward_task`,`workspace.conflict`,`workspace.review_request`];function gt(){if(typeof window>`u`)return``;let e=window.location.hash.replace(/^#/,``);return e.startsWith(`settings/`)?decodeURIComponent(e.slice(9)):``}function _t(e){if(typeof window>`u`)return;let t=new URL(window.location.href);t.hash=`settings/${encodeURIComponent(e)}`,window.history.pushState({},``,t)}function vt(){let[e,n]=(0,K.useState)([]),[r,i]=(0,K.useState)(null),[a,s]=(0,K.useState)([]),[c,l]=(0,K.useState)(()=>gt()),[u,d]=(0,K.useState)(!0),[f,p]=(0,K.useState)(``),[m,h]=(0,K.useState)(``);async function v(){d(!0),p(``),h(``);try{let[e,t,r]=await Promise.all([E(`GET`,`/settings`),E(`GET`,`/tokens/me`),E(`GET`,`/providers`).catch(e=>(h(e.message),{catalog:[]}))]);n(e.settings),i(t),s(r.catalog)}catch(e){p(e.message)}finally{d(!1)}}(0,K.useEffect)(()=>{v()},[]),(0,K.useEffect)(()=>{let e=()=>l(gt());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let y=(0,K.useMemo)(()=>fe(e),[e]),b=(0,K.useMemo)(()=>[...y.map(e=>({slug:e.slug,label:e.group,description:`${e.settings.length} schema setting${e.settings.length===1?``:`s`}`,kind:`descriptors`,settings:e.settings})),{slug:mt,label:`Routing`,description:`Rules, quota thresholds, coordinator view`,kind:`routing`,settings:[]},{slug:pt,label:`Profile`,description:`Display name and avatar`,kind:`profile`,settings:[]},{slug:dt,label:`Browser`,description:`Local dashboard preferences`,kind:`browser`,settings:[]},{slug:ft,label:`Models`,description:`Provider model catalog`,kind:`models`,settings:[]}],[y]),x=b.find(e=>e.slug===c)??b[0];function S(e){l(e),_t(e)}function C(e){n(t=>t.map(t=>q(t)===q(e)?e:t))}return(0,J.jsxs)(`div`,{className:`space-y-4`,children:[(0,J.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h1`,{className:`text-lg font-semibold`,children:`Settings`}),(0,J.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Schema-driven Relay settings, browser preferences, and model catalog controls.`})]}),(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r&&(0,J.jsxs)(I,{variant:`outline`,className:`gap-1`,children:[(0,J.jsx)(t,{className:`size-3`}),r.kind,`:`,r.actor]}),(0,J.jsxs)(L,{variant:`outline`,size:`sm`,onClick:()=>void v(),disabled:u,children:[(0,J.jsx)(o,{className:_(`size-4`,u&&`animate-spin`)}),`Refresh`]})]})]}),f&&(0,J.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:[(0,J.jsx)(g,{className:`mt-0.5 size-4`}),(0,J.jsx)(`span`,{children:f})]}),(0,J.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[230px_minmax(0,1fr)]`,children:[(0,J.jsx)(`nav`,{className:`space-y-1 lg:sticky lg:top-4 lg:self-start`,children:b.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:_(`w-full rounded-md border px-3 py-2 text-left text-sm transition-colors`,x?.slug===e.slug?`border-primary/50 bg-primary/10 text-foreground`:`border-transparent hover:border-border hover:bg-accent`),onClick:()=>S(e.slug),children:[(0,J.jsx)(`span`,{className:`block font-medium`,children:e.label}),(0,J.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.description})]},e.slug))}),(0,J.jsx)(`div`,{className:`min-w-0 space-y-4`,children:u&&!e.length?(0,J.jsx)(G,{size:`sm`,children:(0,J.jsx)(U,{className:`text-sm text-muted-foreground`,children:`Loading settings…`})}):x?.kind===`routing`?(0,J.jsx)(st,{canWrite:ie(r?.scopes,`settings:write:routing`)}):x?.kind===`descriptors`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(De,{group:x.label,settings:x.settings,onSaved:C}),x.label===`Providers`&&(0,J.jsx)(We,{canWrite:ie(r?.scopes,`settings:write:provider`)}),x.label===`Notifications`&&(0,J.jsx)(yt,{})]}):x?.kind===`profile`?(0,J.jsx)(bt,{}):x?.kind===`browser`?(0,J.jsx)(je,{}):(0,J.jsx)(Ne,{catalog:a,error:m,canWrite:ie(r?.scopes,`settings:write:provider`),onCatalog:s})})]})]})}function yt(){let[e,t]=(0,K.useState)(`branch.landed`),[n,r]=(0,K.useState)(`{
|
|
4
|
-
"repoRoot": "/repo"
|
|
5
|
-
}`),[i,a]=(0,K.useState)(null),[o,c]=(0,K.useState)(!1),[l,u]=(0,K.useState)(``);async function d(){c(!0),u(``);try{let t=JSON.parse(n);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Scope must be a JSON object`);a((await E(`POST`,`/notifications/preview`,{type:e,scope:t})).preview)}catch(e){a(null),u(e.message)}finally{c(!1)}}return(0,J.jsx)(G,{size:`sm`,children:(0,J.jsxs)(U,{className:`space-y-3`,children:[(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Who gets what`}),(0,J.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Dry-run notification routing without sending.`})]}),(0,J.jsxs)(L,{size:`sm`,onClick:()=>void d(),disabled:o,children:[(0,J.jsx)(s,{className:`size-4`}),`Preview`]})]}),(0,J.jsxs)(`div`,{className:`grid gap-3 md:grid-cols-[240px_minmax(0,1fr)]`,children:[(0,J.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,J.jsx)(`label`,{className:`text-xs font-medium text-muted-foreground`,children:`Type`}),(0,J.jsxs)(F,{value:e,onValueChange:t,children:[(0,J.jsx)(M,{className:`w-full`,children:(0,J.jsx)(j,{})}),(0,J.jsx)(N,{children:ht.map(e=>(0,J.jsx)(P,{value:e,children:e},e))})]})]}),(0,J.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,J.jsx)(`label`,{className:`text-xs font-medium text-muted-foreground`,children:`Scope`}),(0,J.jsx)(ce,{value:n,onChange:e=>r(e.target.value),rows:4,className:`font-mono text-xs`})]})]}),l&&(0,J.jsxs)(`div`,{className:`flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-2 text-xs text-destructive`,children:[(0,J.jsx)(g,{className:`mt-0.5 size-3.5`}),(0,J.jsx)(`span`,{children:l})]}),i&&(0,J.jsx)(`div`,{className:`overflow-hidden rounded-md border border-border`,children:i.recipients.length===0?(0,J.jsx)(`div`,{className:`px-3 py-4 text-center text-xs text-muted-foreground`,children:`No recipients`}):i.recipients.map(e=>(0,J.jsxs)(`div`,{className:`grid gap-1 border-b border-border px-3 py-2 text-xs last:border-b-0 md:grid-cols-[minmax(0,180px)_minmax(0,160px)_minmax(0,1fr)]`,children:[(0,J.jsx)(`span`,{className:`truncate font-medium`,children:e.recipient}),(0,J.jsx)(`span`,{className:`truncate font-mono text-muted-foreground`,children:e.matchedRule}),(0,J.jsx)(`span`,{className:`truncate text-muted-foreground`,children:e.reason})]},`${e.recipient}-${e.matchedRule}`))})]})})}function bt(){let e=k(e=>e.fetchUsers),t=(0,K.useRef)(null),[n,r]=(0,K.useState)(null),[i,a]=(0,K.useState)(``),[o,s]=(0,K.useState)(!0),[c,l]=(0,K.useState)(!1),[u,d]=(0,K.useState)(``);async function f(){s(!0),d(``);try{let e=await E(`GET`,`/users/me`);r(e),a(e.displayName||e.handle)}catch(e){d(e.message)}finally{s(!1)}}(0,K.useEffect)(()=>{f()},[]);async function p(){l(!0),d(``);try{let t=await E(`PATCH`,`/users/me`,{displayName:i});r(t),a(t.displayName||t.handle),await e()}catch(e){d(e.message)}finally{l(!1)}}async function m(n){if(n){l(!0),d(``);try{let t=await ee(`/users/me/avatar`,n);r(t.user),a(t.user.displayName||t.user.handle),await e()}catch(e){d(e.message)}finally{l(!1),t.current&&(t.current.value=``)}}}async function h(){l(!0),d(``);try{r(await E(`DELETE`,`/users/me/avatar`)),await e()}catch(e){d(e.message)}finally{l(!1)}}return(0,J.jsx)(G,{size:`sm`,children:(0,J.jsxs)(U,{className:`space-y-4`,children:[u&&(0,J.jsxs)(`div`,{className:`flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:[(0,J.jsx)(g,{className:`mt-0.5 size-4`}),(0,J.jsx)(`span`,{children:u})]}),(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4`,children:[(0,J.jsx)(le,{user:n??void 0,distinct:!0,className:`size-16 text-lg`}),(0,J.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[(0,J.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground`,htmlFor:`profile-display-name`,children:`Display name`}),(0,J.jsx)(`input`,{id:`profile-display-name`,className:`h-9 w-full rounded-md border border-input bg-background px-3 text-sm`,value:i,onChange:e=>a(e.target.value),disabled:o||c,maxLength:120})]})]}),(0,J.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,J.jsxs)(L,{size:`sm`,onClick:()=>void p(),disabled:o||c||!i.trim(),children:[(0,J.jsx)(b,{className:`size-4`}),`Save`]}),(0,J.jsxs)(L,{size:`sm`,variant:`outline`,onClick:()=>t.current?.click(),disabled:o||c,children:[(0,J.jsx)(C,{className:`size-4`}),`Upload`]}),(0,J.jsxs)(L,{size:`sm`,variant:`outline`,onClick:()=>void h(),disabled:o||c||!n?.avatarArtifactId,children:[(0,J.jsx)(v,{className:`size-4`}),`Remove`]}),c&&(0,J.jsx)(x,{className:`size-4 animate-pulse text-muted-foreground`}),(0,J.jsx)(`input`,{ref:t,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,className:`hidden`,onChange:e=>void m(e.target.files?.[0])})]})]})})}export{vt as SettingsView};
|
|
6
|
-
//# sourceMappingURL=settings-BzYvlKIL.js.map
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./chunk-CilyBKbf.js";import{ar as t,dr as n,fr as r,hr as i,lr as a,mr as o,or as s,rr as c}from"./lucide-react-Dc3ZwCBi.js";import{_ as l,d as u,f as d,p as f,u as p}from"./types-uVOXgvMT.js";import{$ as m,A as h,E as g,N as _,R as v,S as y,T as b,U as ee,at as x,d as te,et as S,it as C,k as ne,nt as w,p as T,q as re,rt as E,tt as D,y as ie}from"./display-exQDWum3.js";var O=e(i(),1),ae=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},oe=(e=>e?ae(e):ae),se=e=>e;function ce(e,t=se){let n=O.useSyncExternalStore(e.subscribe,O.useCallback(()=>t(e.getState()),[e,t]),O.useCallback(()=>t(e.getInitialState()),[e,t]));return O.useDebugValue(n),n}var le=e=>{let t=oe(e),n=e=>ce(t,e);return Object.assign(n,t),n},ue=(e=>e?le(e):le);function de(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var fe=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return fe(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return fe(t)(e)}}}},pe=(e,t)=>(n,r,i)=>{let a={storage:de(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return fe(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p};function me(e){if(!e)return``;let t=e.replace(/\r\n/g,`
|
|
2
|
-
`);return t=t.replace(/```[^\n]*\n([\s\S]*?)```/g,(e,t)=>{let n=t.replace(/\n+$/,``).split(`
|
|
3
|
-
`).length;return` code block, ${n} ${n===1?`line`:`lines`}. `}),t=t.replace(/```[^\n]*/g,` code block. `),t=ve(t),t=t.replace(/^#{1,6}\s+/gm,``),t=t.replace(/^\s*[-*+]\s+/gm,`. `),t=t.replace(/^\s*\d+\.\s+/gm,`. `),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`),t=t.replace(/(\*\*|__|\*|_)(.*?)\1/g,`$2`),t=t.replace(/[ \t]+/g,` `),t=t.replace(/\n{2,}/g,`. `),t=t.replace(/\s*\.\s*\.\s*(\.\s*)+/g,`. `),t.trim()}function he(e){return/\|/.test(e)&&e.trim().length>0}function ge(e){return/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/.test(e)}function _e(e){return e.trim().replace(/^\||\|$/g,``).split(`|`).map(e=>e.trim()).filter(e=>e.length>0)}function ve(e){let t=e.split(`
|
|
4
|
-
`),n=[],r=0;for(;r<t.length;){if(he(t[r])&&r+1<t.length&&ge(t[r+1])){let e=_e(t[r]),i=r+2,a=0;for(;i<t.length&&he(t[i])&&!ge(t[i]);)a++,i++;let o=e.length?`with columns ${e.join(`, `)}`:``,s=`${a} ${a===1?`row`:`rows`}`;n.push(`table ${o?`${o}, `:``}${s}.`.replace(/\s+/g,` `).trim()),r=i;continue}n.push(t[r]),r++}return n.join(`
|
|
5
|
-
`)}var k={ms:`milliseconds`,s:`seconds`,kb:`kilobytes`,mb:`megabytes`,gb:`gigabytes`,tb:`terabytes`};function ye(e){return e.split(``).join(` `)}function be(e){return e.split(``).map(e=>/[0-9]/.test(e)?e:e.toUpperCase()).join(` `)}var xe=[{name:`url`,pattern:/\bhttps?:\/\/\S+/gi,replace:` link `},{name:`path`,pattern:/(?:\/[A-Za-z0-9._-]+){2,}\/?/g,replace:e=>` `+e.replace(/[/._-]+/g,` `).trim()+` `},{name:`slash`,pattern:/(?<=[A-Za-z0-9])\/(?=[A-Za-z0-9])/g,replace:` `},{name:`func-call`,pattern:/\b([A-Za-z_$][\w$]*)\(\)/g,replace:`$1`},{name:`approx`,pattern:/~(?=\s*[\d.])/g,replace:`approximately `},{name:`range`,pattern:/(\d)\s*[-–—]\s*(?=\d)/g,replace:`$1 to `},{name:`version`,pattern:/\b(v?)(\d+(?:\.\d+){2,})\b/gi,replace:(e,t,n)=>`${t?`version `:``}${n.replace(/\./g,` dot `)}`},{name:`decimal`,pattern:/\b(\d+)\.(\d+)\b/g,replace:(e,t,n)=>`${t} point ${ye(n)}`},{name:`hash`,pattern:/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*[a-f])(?=[0-9a-f]*\d)[0-9a-f]{7,40}\b/gi,replace:e=>be(e)},{name:`id-camel`,pattern:/([a-z])(Id|ID)(s)?\b/g,replace:(e,t,n,r)=>`${t} I D${r?`s`:``}`},{name:`id-word`,pattern:/\b(?:id|Id|ID)(s)?\b/g,replace:(e,t)=>`I D${t?`s`:``}`},{name:`byte-unit`,pattern:/\b(\d+)\s?(kb|mb|gb|tb)\b/gi,replace:(e,t,n)=>`${t} ${k[n.toLowerCase()]}`},{name:`ms-unit`,pattern:/\b(\d{1,5})\s?ms\b/g,replace:(e,t)=>`${t} ${k.ms}`},{name:`s-unit`,pattern:/\b(\d{1,3})\s?s\b/g,replace:(e,t)=>`${t} ${k.s}`},{name:`live-adjective`,pattern:/\b(is|are|was|were|be|been|being|now|and|stays?|staying|went|go|goes|going|deployed|it's|that's|here's|there's|we're|you're|they're)\s+live\b/gi,replace:(e,t)=>`${t} lyve`},{name:`interior-dot`,pattern:/\.(?=[A-Za-z0-9])/g,replace:` dot `}];function Se(e){if(!e)return``;let t=e;for(let e of xe)t=t.replace(e.pattern,e.replace);return t.replace(/[ \t]{2,}/g,` `).trim()}function Ce(e){return Se(me(e))}var we=[{id:`am_michael`,label:`Michael (US ♂)`},{id:`am_adam`,label:`Adam (US ♂)`},{id:`af_heart`,label:`Heart (US ♀)`},{id:`af_bella`,label:`Bella (US ♀)`},{id:`af_nicole`,label:`Nicole (US ♀)`},{id:`af_sarah`,label:`Sarah (US ♀)`},{id:`bm_george`,label:`George (UK ♂)`},{id:`bf_emma`,label:`Emma (UK ♀)`}],A=220;function Te(e){let t=e.match(/[^.!?]+[.!?]*\s*/g)?.map(e=>e.trim()).filter(Boolean)??[e],n=[];for(let e of t){if(e.length<=A){n.push(e);continue}let t=e;for(;t.length>A;){let e=t.lastIndexOf(` `,A);e<=0&&(e=A),n.push(t.slice(0,e).trim()),t=t.slice(e).trim()}t&&n.push(t)}return n}var j=typeof window<`u`&&`speechSynthesis`in window,M=new class{enabled=!1;lang=`en-US`;mode=`kokoro`;kokoroVoice=`am_michael`;browserVoice=``;active=null;queue=[];currentChat=null;speaking=!1;gen=0;audioEl=null;audioUrl=null;playingKey=null;manual=!1;listeners=new Set;get available(){return j||typeof Audio<`u`}isEnabled(){return this.enabled}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getPlayingKey(){return this.playingKey}setPlayingKey(e){if(e!==this.playingKey){this.playingKey=e;for(let e of this.listeners)e()}}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.reset())}setLang(e){this.lang=e}setMode(e){e!==this.mode&&(this.mode=e,this.reset())}setKokoroVoice(e){this.kokoroVoice=e}setBrowserVoice(e){this.browserVoice=e}setActiveChat(e){e!==this.active&&(this.active=e,this.queue=this.queue.filter(t=>t.chatId===e))}onResponse(e,t){if(!this.enabled||!this.available||!e||e!==this.active)return;let n=Ce(t);n&&(this.speaking&&(this.manual||this.currentChat&&this.currentChat!==e)&&(this.queue=[],this.cancel()),this.queue.push({chatId:e,text:n}),this.pump())}speak(e,t){if(!this.available)return;let n=Ce(e);if(!n)return;this.reset(),this.manual=!0,this.speaking=!0,this.currentChat=null,this.setPlayingKey(t??null);let r=++this.gen,i=Te(n),a=()=>{r===this.gen&&(this.speaking=!1,this.manual=!1,this.setPlayingKey(null))};this.mode===`kokoro`?this.speakKokoro(i,0,r,a):this.speakBrowser(i,0,r,a)}bargeIn(){this.reset()}reset(){this.queue=[],this.cancel()}cancel(){this.gen++,this.currentChat=null,this.speaking=!1,this.manual=!1,this.setPlayingKey(null);try{window.speechSynthesis.cancel()}catch{}this.stopAudio()}stopAudio(){if(this.audioEl)try{this.audioEl.pause(),this.audioEl.src=``}catch{}if(this.audioUrl){try{URL.revokeObjectURL(this.audioUrl)}catch{}this.audioUrl=null}}pump(){if(this.speaking)return;let e=this.queue.shift();if(!e)return;this.speaking=!0,this.manual=!1,this.currentChat=e.chatId;let t=++this.gen,n=Te(e.text),r=()=>{t===this.gen&&(this.speaking=!1,this.currentChat=null,this.pump())};this.mode===`kokoro`?this.speakKokoro(n,0,t,r):this.speakBrowser(n,0,t,r)}speakBrowser(e,t,n,r){if(n!==this.gen)return;if(!j||t>=e.length)return r();let i=new SpeechSynthesisUtterance(e[t]),a=this.browserVoice?window.speechSynthesis.getVoices().find(e=>e.voiceURI===this.browserVoice):void 0;a?(i.voice=a,i.lang=a.lang):i.lang=this.lang||navigator.language||`en-US`,i.onend=()=>this.speakBrowser(e,t+1,n,r),i.onerror=()=>this.speakBrowser(e,t+1,n,r),window.speechSynthesis.speak(i)}speakKokoro(e,t,n,r,i){if(n!==this.gen)return;let a=e[t];if(a===void 0)return r();let o=i??this.fetchSpeech(a),s=e[t+1],c=s===void 0?void 0:this.fetchSpeech(s);o.then(i=>{n===this.gen&&this.playBlob(i,n,()=>this.speakKokoro(e,t+1,n,r,c),()=>{this.speakBrowser(e,t,n,r)})}).catch(()=>{n===this.gen&&this.speakBrowser(e,t,n,r)})}fetchSpeech(e){return s(`/connectors/voice/call/speak`,{text:e,voice:this.kokoroVoice})}playBlob(e,t,n,r){if(t!==this.gen)return;if(typeof Audio>`u`)return r();this.stopAudio(),this.audioEl||=new Audio;let i=URL.createObjectURL(e);this.audioUrl=i;let a=this.audioEl;a.src=i,a.onended=()=>{t===this.gen&&n()},a.onerror=()=>{t===this.gen&&r()},a.play().catch(()=>{t===this.gen&&r()})}};function Ee(){if(!j)return[];try{return window.speechSynthesis.getVoices().map(e=>({uri:e.voiceURI,label:`${e.name} (${e.lang})`,lang:e.lang})).sort((e,t)=>e.lang.localeCompare(t.lang)||e.label.localeCompare(t.label))}catch{return[]}}var De=typeof navigator<`u`&&!!navigator.mediaDevices?.getUserMedia&&typeof window<`u`&&`MediaRecorder`in window;function Oe(){for(let e of[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/mp4`])if(typeof MediaRecorder<`u`&&MediaRecorder.isTypeSupported?.(e))return e}var ke=class{rec=null;chunks=[];stream=null;async start(){this.stream=await navigator.mediaDevices.getUserMedia({audio:!0}),this.chunks=[];let e=Oe();this.rec=new MediaRecorder(this.stream,e?{mimeType:e}:void 0),this.rec.ondataavailable=e=>{e.data.size&&this.chunks.push(e.data)},this.rec.start()}async stop(){let e=this.rec;if(!e)return this.teardown(),null;let t=new Promise(t=>{e.onstop=()=>t()});try{e.stop()}catch{}await t;let n=e.mimeType||`audio/webm`,r=new Blob(this.chunks,{type:n});return this.teardown(),r.size?r:null}cancel(){try{this.rec?.stop()}catch{}this.teardown()}teardown(){this.stream?.getTracks().forEach(e=>e.stop()),this.rec=null,this.stream=null,this.chunks=[]}};async function Ae(e){return((await t(`/connectors/voice/call/transcribe`,e))?.text??``).trim()}var N=ue((e,t)=>({now:Date.now(),_timer:null,start(){t()._timer||e({_timer:setInterval(()=>e({now:Date.now()}),1e3)})},stop(){let n=t()._timer;n&&(clearInterval(n),e({_timer:null}))}}));function je(){return N(e=>e.now)}function Me(e=3e4){return N(t=>Math.floor(t.now/e))}var Ne=.1,Pe=.9,P=.8,Fe=.4,F=256e3,Ie=1e6;function Le(e){return{provider:e.id,label:e.label,defaultModel:e.catalog.defaultModel,models:e.catalog.models}}var Re=Object.fromEntries(l().map(e=>[e.id,Le(e)]));function ze(e){let t=Be(e);return{selfCompactUtilization:t,warnUtilization:Ve(t),hardBackstopUtilization:Math.max(Pe,t)}}function Be(e){return!Number.isFinite(e)||!e||e<=F?P:e>=Ie?Fe:He(P-(e-F)/(Ie-F)*(P-Fe))}function Ve(e){return He(Math.max(0,e-Ne))}function He(e){return Math.round(e*1e3)/1e3}function I(e,t){let n=t?.find(t=>t.provider===e)??Re[e];if(!n)throw Error(`unknown provider catalog: ${e}`);return n}function Ue(e){return!e.disabled&&!e.unavailable}function We(e){let t=e.defaultModel,n=t?e.models.find(e=>e.alias===t):void 0;if(n&&Ue(n))return{alias:n.alias,preferred:t,fellBack:!1};let r=e.models.find(Ue);return{alias:r?.alias,preferred:t,fellBack:r?.alias!==t}}function L(e){return e?.providers[0]??f()[0]??``}function R(e,t){return I(e,t).models.filter(e=>!e.disabled)}function z(e,t){return We(I(e,t)).alias??``}function Ge(e,t){return e.filter(e=>e.status===`online`&&v(t,e.baseDir)).sort((e,t)=>_(t.baseDir).length-_(e.baseDir).length)[0]}function Ke(e,t){let n=e.find(e=>e.managedAgents.some(e=>e.agentId===t.id));if(n)return n;let r=typeof t.meta?.cwd==`string`?t.meta.cwd:``;return r?Ge(e,r):void 0}var qe=`/settings/chat/scroll`,Je=150,Ye=1e3,B=new Map,V=null,H=null;function Xe(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.stick!=`boolean`||t.topKey!==null&&typeof t.topKey!=`string`||typeof t.offset!=`number`||!Number.isFinite(t.offset)?null:{stick:t.stick,topKey:t.topKey,offset:Math.max(0,t.offset)}}function Ze(e){return B.get(e)}function Qe(e,t){B.delete(e),B.set(e,t),$e(),tt()}function $e(){for(;B.size>Je;){let e=B.keys().next().value;if(e===void 0)break;B.delete(e)}}function et(){let e={};for(let[t,n]of B)e[t]=n;return e}function tt(){V!==null&&clearTimeout(V),V=setTimeout(()=>{nt()},Ye)}async function nt(){V!==null&&(clearTimeout(V),V=null);try{await c(`PUT`,qe,{value:et()})}catch{}}function rt(){return H||(H=(async()=>{try{let e=(await c(`GET`,qe)).value;if(!e||typeof e!=`object`)return;for(let[t,n]of Object.entries(e)){if(B.has(t))continue;let e=Xe(n);e&&B.set(t,e)}$e()}catch{}})(),H)}function it(e,t){return t.issueRepo||!e?.issueRepo?t:{...t,issueRepo:e.issueRepo}}function at(e){let t={};for(let n of e)t[n.id]=n;return t}function U(e,t){let n=e.findIndex(e=>e.id===t.id),r=[...e];return n>=0?r[n]=t:r.push(t),r}var ot=3e3;function st(e,t,n,r=Date.now(),i){if(!t||!n)return e;let a=[...e[t]||[]],o=i||`s-${n}-${r}`;return a.some(e=>e.id===o)||a.some(e=>e.status===n&&Math.abs(e.timestamp-r)<=ot)?e:(a.push({id:o,status:n,timestamp:r}),a.length>200&&a.splice(0,a.length-200),{...e,[t]:a})}function ct(e,t){if(!(!e||e.status===t.status)){if((e.status===`offline`||e.status===`stale`)&&(t.status===`online`||t.status===`idle`||t.status===`busy`))return`online`;if(t.status===`offline`)return`offline`}}var lt=new Set([`compacting`,`compacted`,`clearing-context`,`context-cleared`]);function ut(e){let t=e.meta?.timelineEvent;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t.status;if(typeof n!=`string`||!n)return;let r=t.id,i=t.timestamp;return{status:n,...typeof r==`string`?{id:r}:{},...typeof i==`number`&&Number.isFinite(i)?{timestamp:i}:{}}}function dt(e){let t=e.params?.agentId;return typeof t==`string`&&t?t:typeof e.target==`string`&&e.target?e.target:void 0}function ft(e,t){if(t===`command.dispatched`)return e.type===`agent.compact`?`compaction-requested`:e.type===`agent.clearContext`?`clear-requested`:e.type===`agent.shutdown`?`shutting-down`:void 0;if(t===`command.succeeded`){if(e.type===`agent.shutdown`)return`shutdown`;if(e.type===`agent.restart`)return`restarted`}}function pt(e){return JSON.stringify(e)}function mt(e,t){let n=new Map(e.map(e=>[e.id,e])),r=!(e.length===t.length&&e.every((e,n)=>e.id===t[n]?.id)),i=t.map(e=>{let t=n.get(e.id);return t&&pt(t)===pt(e)?t:(r=!0,e)});return r?i:e}function W(e,t){let n=[...new Map(t.map(e=>[e.id,e])).values()],r=new Map(e.map(e=>[e.id,e])),i=!(e.length===n.length&&e.every((e,t)=>e.id===n[t]?.id)),a=n.map(e=>{let t=r.get(e.id);return t&&JSON.stringify(t)===JSON.stringify(e)?t:(i=!0,e)});return i?a:e}function ht(){return typeof document>`u`?!0:document.hidden}function gt(e,t){return!!(e&&t.view===`chat`&&t.selectedInboxThread===e&&!ht())}function _t(e){return e.threadPeer||e.agentId||``}function vt(e,t){return gt(_t(e),t)}function yt(e){return e.filter(e=>e.to===`user`&&e.from!==`user`&&y(e)).reduce((e,t)=>Math.max(e,t.id),0)}function bt(e){if(e.from===`user`||e.to===`user`)return!0;let t=typeof e.payload?.direction==`string`?e.payload.direction:void 0;return e.kind===`channel.event`&&t===`inbound`}var xt={enabled:!0,browserEnabled:!1,messages:!0,replies:!0,errors:!0};function St(e,t){return t.enabled?e.kind===`message`?t.messages:e.kind===`reply`?t.replies:t.errors:!1}function Ct(){return typeof window<`u`&&`Notification`in window}function G(){return Ct()?window.Notification.permission:`unsupported`}function wt(e,t){return!St(e,t.notificationSettings)||!t.notificationSettings.browserEnabled||G()!==`granted`||vt(e,t)?!1:ht()||t.view!==`chat`}function Tt(e,t){if(G()===`granted`)try{let n=new window.Notification(e.title,{body:e.body,tag:e.id,icon:`icons/agent-relay-192.png`,data:{view:e.view,threadPeer:e.threadPeer,agentId:e.agentId,messageId:e.messageId}});n.onclick=()=>{window.focus(),t(),n.close()}}catch{}}var Et=(e,t)=>({notification:null,toastNotification:null,notifications:[],notificationUnread:0,notificationSettings:{...xt},notificationPermission:G(),confirmModal:{show:!1,title:``,message:``,action:null},errorModal:{show:!1,title:``,message:``},openConfirm(t,n,r){e({confirmModal:{show:!0,title:t,message:n,action:r}})},showError(t,n){e({errorModal:{show:!0,title:t,message:n}})},showNotification(t){e({notification:t,toastNotification:null}),setTimeout(()=>e({notification:null}),3e3)},handleRelayNotification(n){let r=t();if(!St(n,r.notificationSettings)||r.notifications.some(e=>e.id===n.id))return;if(n.messageId&&(n.kind===`message`||n.kind===`reply`)){let e=r.messages.find(e=>e.id===n.messageId);if(e&&!bt(e))return}let i=vt(n,r),a=`${n.title}: ${n.body}`;e({notifications:[n,...r.notifications].slice(0,100),notificationUnread:i?r.notificationUnread:Math.min(99,r.notificationUnread+1),notification:i?r.notification:a,toastNotification:i?r.toastNotification:n}),i||setTimeout(()=>{t().toastNotification?.id===n.id&&e({notification:null,toastNotification:null})},4500),wt(n,r)&&Tt(n,()=>t().openNotification(n)),i&&n.threadPeer&&n.messageId&&t().markInboxThreadReadTo(n.threadPeer,n.messageId)},async openNotification(n){if(e({notificationUnread:0}),n.threadPeer&&(t().openInboxThread(n.threadPeer),n.messageId&&t().markInboxThreadReadTo(n.threadPeer,n.messageId)),n.view&&await t().switchView(n.view),n.agentId&&n.view===`agents`){let e=t().agentsById[n.agentId];e&&t().openAgentDetail(e)}},dismissToast(){e({notification:null,toastNotification:null})},markNotificationsRead(){e({notificationUnread:0})},clearNotifications(){e({notifications:[],notificationUnread:0})},async requestBrowserNotifications(){if(!Ct()){e({notificationPermission:`unsupported`,notificationSettings:{...t().notificationSettings,browserEnabled:!1}}),t().showNotification(`Browser notifications are not supported here`);return}let n=await window.Notification.requestPermission();e({notificationPermission:n,notificationSettings:{...t().notificationSettings,browserEnabled:n===`granted`}}),t().showNotification(n===`granted`?`Browser notifications enabled`:`Browser notifications not enabled`)}}),Dt=e=>({voiceTtsEnabled:!1,voiceTtsLang:`en-US`,voiceTtsMode:`kokoro`,voiceTtsKokoroVoice:`am_michael`,voiceTtsBrowserVoice:``,voiceInputMode:`compose`,setVoiceTtsEnabled(t){M.setEnabled(t),e({voiceTtsEnabled:t})},setVoiceTtsLang(t){M.setLang(t),e({voiceTtsLang:t})},setVoiceTtsMode(t){M.setMode(t),e({voiceTtsMode:t})},setVoiceTtsKokoroVoice(t){M.setKokoroVoice(t),e({voiceTtsKokoroVoice:t})},setVoiceTtsBrowserVoice(t){M.setBrowserVoice(t),e({voiceTtsBrowserVoice:t})},setVoiceInputMode(t){e({voiceInputMode:t})}}),Ot=null;function kt(e){let t=e.voiceTtsEnabled&&e.view===`chat`&&e.selectedInboxThread||null;t!==Ot&&(Ot=t,M.setActiveChat(t))}var At=e=>(t,i)=>({theme:`dark`,view:`overview`,autoRefresh:!0,mobileMenuOpen:!1,commandPaletteOpen:!1,commandQuery:``,connected:!1,connectionError:!1,quotaSeq:0,authNeeded:!1,authToken:``,stats:{},fileOrchestratorId:``,filePath:``,fileSelectedPath:``,fileSelectedLine:0,fileOverlayOpen:!1,_es:null,_refreshTimer:null,_refreshInFlight:!1,set:e=>t(e),async init(){await e.waitForHydration();let a=i().authToken;a&&n(a),o(i().view),M.setEnabled(i().voiceTtsEnabled),M.setLang(i().voiceTtsLang),M.setMode(i().voiceTtsMode),M.setKokoroVoice(i().voiceTtsKokoroVoice),M.setBrowserVoice(i().voiceTtsBrowserVoice),kt(i()),r(()=>{i().authNeeded||t({authNeeded:!0,connectionError:!1})}),rt(),t({notificationPermission:G()}),i().startClock();try{t({stats:await c(`GET`,`/stats`)})}catch(e){if(e.status===401){t({authNeeded:!0});return}}await i().refresh(),i().fetchAllIssueRefs(),i().connectSSE(),i().startAutoRefresh()},async switchView(e){o(e),t({view:e,mobileMenuOpen:!1});let n=i();[`chat`,`messages`].includes(e)&&await Promise.all([n.fetchMessages(),n.fetchChatHistoryImports(),n.fetchDeliverableTasks({unfiltered:!0})]),e===`activity`&&await Promise.all([n.fetchMessages(),n.fetchPairs(),n.fetchTasks(),n.fetchActivityEvents()]),e===`work`&&await Promise.all([n.fetchMessages(),n.fetchTasks()]),e===`pairs`&&await n.fetchPairs(),e===`channels`&&await Promise.all([n.fetchChannels(),n.fetchIntegrations()]),e===`connectors`&&await n.fetchConnectors(),e===`integrations`&&await n.fetchIntegrations(),e===`memory`&&await n.refreshMemory(),e===`tasks`&&await Promise.all([n.fetchTasks(),n.fetchDeliverableTasks()]),e===`teams`&&await Promise.all([n.fetchTeams(),n.fetchTeamOutcomeAggregates(),n.refreshIssueRefs()]),e===`automation`&&await Promise.all([n.fetchAutomations(),n.fetchAutomationRuns()]),e===`maintenance`&&await n.fetchMaintenanceJobs(),e===`workspaces`&&await Promise.all([n.fetchWorkspaces(),n.fetchOrchestrators(),n.fetchAgents()]),e===`files`&&await n.fetchOrchestrators(),e===`analytics`&&await n.fetchAnalytics()},startClock(){N.getState().start()},stopClock(){N.getState().stop()},startAutoRefresh(){i().stopAutoRefresh(),i().autoRefresh&&t({_refreshTimer:setInterval(()=>i().refreshLiveData(),x)})},stopAutoRefresh(){let e=i();e._refreshTimer&&(clearInterval(e._refreshTimer),t({_refreshTimer:null}))},async apiCall(e,t,n){return c(e,t,n)},async openFilesAt(e){let n=i();t({fileOrchestratorId:e.orchestratorId||Ge(n.orchestrators,e.selectedPath||e.path)?.id||n.orchestrators.find(e=>e.status===`online`)?.id||``,filePath:e.path,fileSelectedPath:e.selectedPath||``,fileSelectedLine:e.line||0,fileOverlayOpen:e.overlay===!0}),e.overlay||await i().switchView(`files`)},async openFilesForAgent(e,t=!1){let n=typeof e.meta?.cwd==`string`?e.meta.cwd:``;if(!n){i().showNotification(`Agent has no cwd`);return}let r=Ke(i().orchestrators,e);if(!r){i().showNotification(`No online orchestrator covers that cwd`);return}await i().openFilesAt({orchestratorId:r.id,path:n,overlay:t})},closeFileOverlay(){t({fileOverlayOpen:!1})},async refresh(){let e=i();await Promise.all([e.fetchStats(),e.fetchHealth(),e.fetchAgents(),e.fetchUsers(),e.fetchOrchestrators(),e.fetchPairs(),e.fetchMessages(),e.fetchTasks(),e.fetchDeliverableTasks({unfiltered:!0}),e.fetchChannels(),e.fetchConnectors(),e.fetchIntegrations(),e.fetchAutomations(),e.fetchAutomationRuns(),e.fetchManagedPolicies(),e.fetchAgentProfiles(),e.fetchToolGroupCatalog(),e.fetchMaintenanceJobs(),e.fetchWorkspaces(),e.fetchInboxState(),e.fetchActivityEvents(),e.fetchChatHistoryImports(),e.fetchProviderCatalog()])},async refreshLiveData(){if(!(i()._refreshInFlight||i().authNeeded)){t({_refreshInFlight:!0});try{try{let e=await c(`GET`,`/stats`);t(i().connectionError?{stats:e,connectionError:!1}:{stats:e})}catch(e){if(e.status===401)return;i().connectionError||t({connectionError:!0});return}let e=i(),n=[e.fetchHealth(),e.fetchAgents(),e.fetchOrchestrators(),e.fetchPairs(),e.fetchMessages(),e.fetchTasks(),e.fetchManagedPolicies(),e.fetchInboxState()],r=e.view;[`chat`,`messages`].includes(r)&&n.push(e.fetchChatHistoryImports(),e.fetchDeliverableTasks({unfiltered:!0})),r===`activity`&&n.push(e.fetchActivityEvents()),r===`memory`&&n.push(e.refreshMemory()),r===`automation`&&n.push(e.fetchAutomations(),e.fetchAutomationRuns()),r===`channels`&&n.push(e.fetchChannels(),e.fetchIntegrations()),r===`connectors`&&n.push(e.fetchConnectors()),r===`integrations`&&n.push(e.fetchIntegrations()),r===`maintenance`&&n.push(e.fetchMaintenanceJobs()),r===`profiles`&&n.push(e.fetchAgentProfiles()),r===`workspaces`&&n.push(e.fetchWorkspaces()),r===`analytics`&&n.push(e.fetchAnalytics()),r===`teams`&&n.push(e.fetchTeams(),e.fetchTeamOutcomeAggregates(),e.refreshIssueRefs()),e.agentDetailOpen&&e.agentDetailId&&n.push(e.fetchAgentIssueActivity(e.agentDetailId)),r===`tasks`&&n.push(e.fetchDeliverableTasks()),e.taskDetailOpen&&e.taskDetailId&&n.push(e.fetchTaskDetail(e.taskDetailId)),await Promise.all(n)}finally{t({_refreshInFlight:!1})}}},async fetchStats(){try{t({stats:await c(`GET`,`/stats`)})}catch{}},connectSSE(){i().disconnectSSE(),t({_es:a(i().authToken,{connected:()=>{t(i().connectionError?{connected:!0,connectionError:!1}:{connected:!0}),i().refreshLiveData();let e=Object.entries(i().agentChatByAgent).filter(([,e])=>e.loadedInitial).map(([e])=>e);Promise.all(e.map(e=>i().gapFillAgentChat(e))),i().refreshPlans(),i().refreshIssueRefs()},disconnected:()=>t({connected:!1}),message:(e,n)=>{if(e!==`connected`){if(e===`message.new`){let e=JSON.parse(n);if(e.kind===`session`&&e.from!==`user`){let t=e.payload?.session;t?.type===`response`&&t?.origin===`provider`&&M.onResponse(ie(e),e.body)}let r=i();if(!r.messages.some(t=>t.id===e.id)){let n=[...r.messages,e];n.length>500&&n.splice(0,n.length-500),t({messages:n})}let a=ie(e);for(let t of Object.keys(i().agentChatByAgent))i().appendChatTail(t,[e]);b(e)&&y(e)&>(a,r)&&i().markInboxThreadReadTo(a,e.id);return}if(e===`message.queued`||e===`message.expired`||e===`message.delivery_updated`||e===`message.reaction_updated`){let e=JSON.parse(n);t({messages:U(i().messages,e)}),i().applyChatMessageUpdate(e);return}if(e===`notification.created`){i().handleRelayNotification(JSON.parse(n));return}if(e===`plan.created`||e===`plan.changed`){let e=JSON.parse(n),t=e.plan??e.data?.plan;t&&i().upsertPlan(t);return}if(e===`plan.deleted`){let e=JSON.parse(n),t=e.plan??e.data?.plan,r=t?.id??e.planId??e.id??e.data?.planId??e.data?.id;(t||r)&&i().removePlan(t??r);return}if(e===`team.dissolved`){let e=JSON.parse(n);e.teamId&&i().markTeamDissolved({teamId:e.teamId,outcomeStatus:e.outcomeStatus,reason:e.reason}),Promise.all([i().fetchTeams(),i().fetchTeamOutcomeAggregates()]);return}if(e===`activity.created`){let e=JSON.parse(n);t({activityEvents:U(i().activityEvents,e)}),e.issueRefId&&i().fetchIssueRef(e.issueRefId),e.agentId&&i().agentDetailOpen&&i().agentDetailId===e.agentId&&i().fetchAgentIssueActivity(e.agentId);return}if(e===`agent.status`){let e=JSON.parse(n),r=i(),a=r.agentsById[e.id],o=it(a,e);if(t({agents:U(r.agents,o),agentsById:{...r.agentsById,[o.id]:o}}),r.livenessMismatches[o.id]&&o.status!==`offline`){let e={...r.livenessMismatches};delete e[o.id],t({livenessMismatches:e})}let s=r.commandStalls[o.id];if(s){let e=ut(o);if(e?.status&<.has(e.status)&&(e.timestamp??0)>s.ts){let e={...r.commandStalls};delete e[o.id],t({commandStalls:e})}}let c=ut(o),l=c?.status??ct(a,o);if(l){let e=c?.timestamp??Date.now(),n=c?.id||`agent-status:${o.id}:${l}:${e}`;t({chatStatusEvents:st(r.chatStatusEvents,o.id,l,e,n)})}return}if(e===`dashboard.presence`){let e=JSON.parse(n);e.agentId&&i().applyPresence(e.agentId,e.viewers??[]);return}if(e===`liveness.mismatch`){let e=JSON.parse(n);e.agentId&&t({livenessMismatches:{...i().livenessMismatches,[e.agentId]:{agentId:e.agentId,detail:e.detail??`Process reported running but relay marked it offline`,ts:Date.now(),policyName:e.policyName,spawnRequestId:e.spawnRequestId}}});return}if(e===`command.stalled`){let e=JSON.parse(n);if(e.agentId){let n=Date.now(),r=e.kind??`compact`,a=r===`clear`?`clear-stalled`:`compaction-stalled`;t({commandStalls:{...i().commandStalls,[e.agentId]:{agentId:e.agentId,kind:r,detail:e.detail??`A context command was requested but never started — the session may need manual intervention.`,ts:n,commandId:e.commandId}},chatStatusEvents:st(i().chatStatusEvents,e.agentId,a,n,`command-stalled:${e.agentId}:${e.commandId??n}`)})}return}if(e===`agent.removed`){let e=JSON.parse(n),r=i(),a={...r.agentsById};delete a[e.id];let o={...r.livenessMismatches};delete o[e.id];let s={...r.commandStalls};delete s[e.id],t({livenessMismatches:o,commandStalls:s}),t({agents:r.agents.filter(t=>t.id!==e.id),agentsById:a});return}if(e===`provider-quota.updated`){t({quotaSeq:i().quotaSeq+1});return}if(e===`message.claimed`){let e=JSON.parse(n);t({messages:i().messages.map(t=>t.id===e.messageId?{...t,claimedBy:e.claimedBy,claimExpiresAt:e.claimExpiresAt}:t)});return}if(e===`message.claim_released`){let e=JSON.parse(n);t({messages:i().messages.map(t=>t.id===e.messageId?{...t,claimedBy:void 0,claimedAt:void 0,claimExpiresAt:void 0}:t)});return}if(e===`message.deleted`){let e=JSON.parse(n);t({messages:i().messages.filter(t=>t.id!==e.messageId)});return}if(e===`orchestrator.status`){let e=JSON.parse(n);t({orchestrators:U(i().orchestrators,e)});return}if(e===`orchestrator.removed`){let e=JSON.parse(n);t({orchestrators:i().orchestrators.filter(t=>t.id!==e.id)});return}if(e===`policy.state.changed`||e===`config.changed`){i().fetchManagedPolicies();return}if(e===`command.dispatched`||e===`command.succeeded`){let r=JSON.parse(n).command;if(r){let n=ft(r,e);if(n){let e=typeof r.updatedAt==`number`?r.updatedAt:typeof r.createdAt==`number`?r.createdAt:Date.now();t({chatStatusEvents:st(i().chatStatusEvents,dt(r),n,e,r.id?`command:${r.id}:${n}`:void 0)})}}return}if(e.startsWith(`task.`)){let e=JSON.parse(n);if(e.kind===`deliverable`){let n=i(),r=U(n.deliverableTasks,e),a=!n.deliverableStatusFilter||e.status===n.deliverableStatusFilter,o=e.deliverableStage??`none`,s=!n.deliverableStageFilter||o===n.deliverableStageFilter,c=!n.deliverableProjectFilter||e.projectId===n.deliverableProjectFilter;t({deliverableTasks:a&&s&&c?r:r.filter(t=>t.id!==e.id)}),n.taskDetailById[e.id]&&t({taskDetailById:{...n.taskDetailById,[e.id]:e}})}else t({tasks:U(i().tasks,e)})}}}})})},disconnectSSE(){let e=i()._es;e&&(e.close(),t({_es:null}))},openCommandPalette(){t({commandQuery:``,commandPaletteOpen:!0})},closeCommandPalette(){t({commandPaletteOpen:!1,commandQuery:``})},async runCommand(e){let{action:n,payload:r}=e;if(i().closeCommandPalette(),n===`openView`)await i().switchView(r.view);else if(n===`agentPreset`)t({showOffline:!0,agentPresetFilter:r.preset||``}),await i().switchView(`agents`);else if(n===`copy`)try{await navigator.clipboard?.writeText(r.value||``)}catch{}else if(n===`messageAgent`){let e=i().agentsById[r.agentId];e&&i().openComposeToAgent(e)}else n===`pairAgent`?i().openPairInvite(r.agentId):n===`filterTag`?(t({agentTagFilter:r.tag||``,tagFilter:r.tag||``}),await i().switchView(`agents`)):n===`exportActivity`&&i().exportActivity(r.format||`markdown`)},async saveTokenAndRefresh(){let e=i().authToken;n(e);try{await c(`GET`,`/stats`)}catch(e){if(e.status===401){t({authNeeded:!0});return}}t({authNeeded:!1,connectionError:!1}),i().connectSSE(),await i().refresh(),i().startAutoRefresh()},destroy(){r(null),i().disconnectSSE(),i().stopAutoRefresh(),i().stopClock()}}),jt=(e,t)=>({users:[],usersById:{},presenceByAgent:{},async fetchUsers(){try{let n=await c(`GET`,`/users`),r=W(t().users,n);if(r===t().users)return;let i={};for(let e of r)i[e.id]=e;e({users:r,usersById:i})}catch{}},applyPresence(n,r){e({presenceByAgent:{...t().presenceByAgent,[n]:r}})},async announcePresence(e,n,r){try{let i=await c(`POST`,`/agents/`+encodeURIComponent(e)+`/presence`,{typing:n,...r?{leaving:!0}:{}});t().applyPresence(e,i.viewers??[])}catch{}}}),Mt=(e,t)=>({agents:[],agentsById:{},showOffline:!1,showBuiltIns:!1,agentSort:`status`,agentSortDir:`asc`,agentPresetFilter:``,agentStatusFilter:``,agentTagFilter:``,agentHostFilter:``,selectedAgent:``,agentDetailOpen:!1,agentDetailId:``,livenessMismatches:{},commandStalls:{},channelDetailOpen:!1,channelDetailId:``,renameModal:{show:!1,agentId:``,label:``},tagFilter:``,async fetchAgents(){try{let n=await c(`GET`,`/agents`),r=W(t().agents,n);if(r===t().agents)return;e({agents:r,agentsById:at(r)})}catch{}},openAgentDetail(t){e({agentDetailId:t.id,agentDetailOpen:!0})},closeAgentDetail(){e({agentDetailOpen:!1})},openChannelDetail(t){e({channelDetailId:t.id,channelDetailOpen:!0})},closeChannelDetail(){e({channelDetailOpen:!1})},openRename(t){e({renameModal:{show:!0,agentId:t.id,label:t.label||``}})},async doRename(){let n=t(),r=n.renameModal.label.trim()||null;try{await c(`PATCH`,`/agents/`+n.renameModal.agentId+`/label`,{label:r}),e({renameModal:{...n.renameModal,show:!1}})}catch(e){t().showError(`Rename Failed`,e.message)}},async doDeleteAgent(n){try{await c(`DELETE`,`/agents/`+n);let r=t(),i={...r.agentsById};delete i[n],e({agents:r.agents.filter(e=>e.id!==n),agentsById:i,selectedAgent:r.selectedAgent===n?``:r.selectedAgent})}catch(e){t().showError(`Delete Failed`,e.message)}},async doAgentAction(e,n,r){try{await c(`POST`,`/agents/`+encodeURIComponent(e.id)+`/actions`,{action:n,...r?{surface:{component:r}}:{}});let i=n===`restart`?`Restart`:n===`resume`?`Resume`:n===`shutdown`?`Shutdown`:n===`compact`?`Compact`:n===`clearContext`?`Clear context`:n;t().showNotification(`${i} command sent to ${te(e)}`),await Promise.all([t().fetchMessages(),t().fetchActivityEvents()])}catch(e){t().showError(`Action Failed`,e.message)}}}),K=300,q={messages:[],oldestLoadedId:null,hasMore:!0,loading:!1,loadedInitial:!1};function Nt(e,t){let n=new URLSearchParams;for(let[e,r]of Object.entries(t))n.set(e,String(r));return`/agents/${encodeURIComponent(e)}/chat?${n.toString()}`}function Pt(e,t){return t.filter(t=>h(e,t)&&!g(t)).sort((e,t)=>e.id-t.id)}function Ft(e,t){return W(e,[...e,...t].sort((e,t)=>e.id-t.id))}function It(e,t){return t.some(e=>e.from===`user`)?e.filter(e=>e.id>=0||e.from!==`user`):e}function J(e){return e[0]?.id??null}var Lt=12,Y=[];function Rt(e){let t=Y.indexOf(e);t!==-1&&Y.splice(t,1),Y.unshift(e)}function zt(e,t){let n=new Set(t.filter(Boolean)),r=0;for(let t of Y){if(r>=Lt)break;e[t]?.loadedInitial&&(n.add(t),r++)}let i={};for(let[t,r]of Object.entries(e))(!r.loadedInitial||n.has(t))&&(i[t]=r);return i}var Bt=(e,t)=>({messages:[],agentChatByAgent:{},threadHistory:{},threadMessages:[],threadOpen:!1,chatHistoryImports:[],selectedInboxThread:``,replyTo:null,composeOpen:!1,showReasoning:!1,chatAgentSearch:``,chatAgentProviderFilter:``,chatAgentStatusFilter:``,chatAgentTagFilter:``,chatAgentCapFilter:``,chatAgentHostFilter:``,chatAgentSort:`status`,chatAgentSortDir:`asc`,chatAgentGroupBy:``,chatAgentFiltersCollapsed:!0,chatCollapsedChildren:[],feedObserveAll:!1,coordinatorFollows:[],coordinatorMutes:[],chatStatusEvents:{},chatStickToBottom:!0,chatHasNewItems:!1,inboxReadCursors:{},inboxArchivedThreads:{},inboxDrafts:{},chatSending:!1,inboxSearch:``,inboxSort:`attention`,inboxSortDir:`desc`,inboxShowArchived:!1,channelFilter:``,compose:{...m},inboxCompose:{...S},async fetchMessages(){try{let n=t(),r=`/messages?limit=100`;n.view===`messages`&&n.selectedAgent&&(r+=`&for=`+encodeURIComponent(n.selectedAgent)),n.view===`messages`&&n.channelFilter&&(r+=`&channel=`+encodeURIComponent(n.channelFilter));let i=await c(`GET`,r),a=mt(t().messages,i);e({messages:a});let o=t(),s=o.selectedInboxThread;if(gt(s,o)){let e=0;for(let t of a)t.id>e&&ie(t)===s&&b(t)&&y(t)&&(e=t.id);e&&t().markInboxThreadReadTo(s,e)}}catch{}},async loadAgentChat(n){if(!n)return;Rt(n);let r=t().agentChatByAgent[n];if(!r?.loading){r?.loadedInitial&&r.messages.length>0||e(e=>({agentChatByAgent:{...e.agentChatByAgent,[n]:{...e.agentChatByAgent[n]??q,loading:!0}}}));try{let r=await c(`GET`,Nt(n,{limit:K})),i=Pt(n,r),a=t().agentChatByAgent[n]??q,o=a.loadedInitial?Ft(It(a.messages,i),i):W([],i),s=a.loadedInitial?a.hasMore:r.length===K;e(e=>({agentChatByAgent:zt({...e.agentChatByAgent,[n]:{messages:o,oldestLoadedId:J(o),hasMore:s,loading:!1,loadedInitial:!0}},[n,t().selectedAgent,t().selectedInboxThread])}))}catch(r){e(e=>({agentChatByAgent:{...e.agentChatByAgent,[n]:{...e.agentChatByAgent[n]??q,loading:!1}}})),t().showError(`Chat Load Failed`,r.message)}}},async loadOlder(n){if(!n)return;let r=t().agentChatByAgent[n];if(!r?.loadedInitial){await t().loadAgentChat(n);return}if(!(r.loading||!r.hasMore||r.oldestLoadedId===null)){e(e=>({agentChatByAgent:{...e.agentChatByAgent,[n]:{...r,loading:!0}}}));try{let i=await c(`GET`,Nt(n,{before:r.oldestLoadedId,limit:K})),a=Pt(n,i),o=t().agentChatByAgent[n]??r,s=W(o.messages,[...a,...o.messages].sort((e,t)=>e.id-t.id));e(e=>({agentChatByAgent:{...e.agentChatByAgent,[n]:{messages:s,oldestLoadedId:J(s),hasMore:i.length===K,loading:!1,loadedInitial:!0}}}))}catch(i){e(e=>({agentChatByAgent:{...e.agentChatByAgent,[n]:{...e.agentChatByAgent[n]??r,loading:!1}}})),t().showError(`Chat Load Failed`,i.message)}}},async gapFillAgentChat(e){if(!e)return;let n=t().agentChatByAgent[e];if(!n?.loadedInitial||n.messages.length===0)return;let r=n.messages[n.messages.length-1].id;try{for(;;){let i=r,a=await c(`GET`,Nt(e,{since:r,limit:K}));if(a.length===0||(t().appendChatTail(e,a.filter(e=>e.id>i)),r=a[a.length-1].id,r<=i)||a.length<K)return;n=t().agentChatByAgent[e];let o=n?.messages[n.messages.length-1]?.id;o&&o>r&&(r=o)}}catch(t){console.warn(`[chat] gap-fill skipped for ${e}: ${t.message}`)}},appendChatTail(n,r){if(!n||r.length===0)return;let i=Pt(n,r);if(i.length===0)return;let a=t().agentChatByAgent[n]??q,o=Ft(It(a.messages,i),i);e({agentChatByAgent:{...t().agentChatByAgent,[n]:{...a,messages:o,oldestLoadedId:J(o)}}})},async fetchThreadHistory(n){if(n)try{let r=await c(`GET`,`/messages?for=`+encodeURIComponent(n)+`&limit=500`);e({threadHistory:{...t().threadHistory,[n]:r}})}catch{}},async fetchChatHistoryImports(){try{e({chatHistoryImports:await c(`GET`,`/chat/history-imports?limit=500`)})}catch{}},async fetchInboxState(){try{let n=await c(`GET`,`/inbox/state?operatorId=user`),r={},i={},a={};for(let e of n?.threads||[])e.readCursorMessageId&&(r[e.peerId]=e.readCursorMessageId),e.archivedAtMessageId&&(i[e.peerId]=e.archivedAtMessageId);for(let e of n?.drafts||[])e.body&&(a[e.peerId]=e.body);let o=t().inboxDrafts;e({inboxReadCursors:r,inboxArchivedThreads:i,...Object.keys(o).length>0?{}:{inboxDrafts:a}})}catch{}},openCompose(){e({composeOpen:!0,compose:{...m,from:E}})},openComposeToAgent(t){e({replyTo:null,compose:{...m,from:E,to:t.id},composeOpen:!0})},async doSend(){let n=t();if(!n.compose.from||!n.compose.to||!n.compose.body){t().showError(`Validation`,`From, To, and Message are required.`);return}try{let r={from:n.compose.from,to:n.compose.to,body:n.compose.body};n.compose.channel&&(r.channel=n.compose.channel),n.compose.subject&&(r.subject=n.compose.subject),n.replyTo&&(r.replyTo=n.replyTo.id),n.compose.claimable&&(r.claimable=!0,r.kind=`task`,r.payload={title:n.compose.subject||`Claimable task`}),await c(`POST`,`/messages`,r),e({composeOpen:!1,replyTo:null,compose:{...m,from:E}}),await t().fetchMessages()}catch(e){t().showError(`Send Failed`,e.message)}},async doClaim(e){let n=t(),r=n.compose.from||n.selectedAgent;if(!r){t().showError(`Validation`,`Select an agent first.`);return}try{let n=await c(`POST`,`/messages/`+e+`/claim`,{agentId:r});n.ok||t().showError(`Claim Failed`,n.error||`unknown`),n.ok&&await Promise.all([t().fetchMessages(),t().fetchTasks()])}catch(e){t().showError(`Claim Failed`,e.message)}},async doDeliveryAction(e,n,r){try{await c(`POST`,`/messages/`+e+`/delivery/actions`,{action:n,reason:r,agentId:t().compose.from||t().selectedAgent||`user`}),await t().fetchMessages()}catch(e){t().showError(`Delivery Update Failed`,e.message)}},async doDeleteMessage(n){try{await c(`DELETE`,`/messages/`+n),e({messages:t().messages.filter(e=>e.id!==n)})}catch(e){t().showError(`Delete Failed`,e.message)}},applyChatMessageUpdate(n){let r=t().agentChatByAgent,i={};for(let[e,t]of Object.entries(r))t.messages.some(e=>e.id===n.id)&&(i[e]={...t,messages:t.messages.map(e=>e.id===n.id?n:e)});Object.keys(i).length!==0&&e({agentChatByAgent:{...r,...i}})},async reactToMessage(n,r){try{let i=(n.reactions||[]).some(e=>e.actorId===`user`&&e.emoji===r),a=await c(`POST`,`/messages/`+n.id+`/reactions`,{actorId:E,emoji:r,action:i?`remove`:`add`});e({messages:U(t().messages,a)}),t().applyChatMessageUpdate(a)}catch(e){t().showError(`Reaction Failed`,e.message)}},startReply(t){let n=t.from===`user`?t.to:t.from;e({replyTo:{id:t.id,from:t.from},compose:{...m,from:E,to:n,channel:t.channel||``},composeOpen:!0})},cancelReply(){e({replyTo:null})},async openThread(n){e({threadMessages:[],threadOpen:!0});try{e({threadMessages:await c(`GET`,`/messages/`+n+`/thread`)})}catch(e){t().showError(`Thread Load Failed`,e.message)}},openInboxThread(n,r=[]){e({selectedInboxThread:n}),r.length&&t().markInboxThreadRead(n,r),t().loadAgentChat(n)},async sendChatMessage(n,r,i=[]){if(!n.trim()&&i.length===0||t().chatSending)return;let a=r.peer;e({chatSending:!0});let o=t().inboxDrafts[a],s={...t().inboxDrafts};delete s[a],e({inboxDrafts:s});let l=-Date.now(),u={id:l,from:E,to:a,kind:`chat`,body:n.trim()||`Attachment`,...r.lastMessage?.channel?{channel:r.lastMessage.channel}:{},payload:i.length?{attachments:i}:{},readBy:[E],createdAt:Date.now()};e(e=>{let t=e.agentChatByAgent[a]??q,n=[...t.messages,u];return{agentChatByAgent:{...e.agentChatByAgent,[a]:{...t,messages:n,oldestLoadedId:J(n)}}}});try{let o=t().agentsById[a]?.providerCapabilities?.liveSession?.inject,s=null;if(o)await c(`POST`,`/agents/`+encodeURIComponent(a)+`/prompt`,{body:n.trim()||`Attachment`,...i.length?{attachments:i}:{}});else{let e={from:E,to:a,body:n.trim()||`Attachment`};r.lastMessage?.channel&&(e.channel=r.lastMessage.channel),r.lastMessage?.id&&(e.replyTo=r.lastMessage.id),i.length&&(e.payload={attachments:i}),s=await c(`POST`,`/messages`,e)}e(e=>{let t=e.agentChatByAgent[a];if(!t)return{};let n=t.messages.filter(e=>e.id!==l);if(s){let r=n.some(e=>e.id===s.id)?n:Ft(n,[s]);return{agentChatByAgent:{...e.agentChatByAgent,[a]:{...t,messages:r,oldestLoadedId:J(r)}}}}return{agentChatByAgent:{...e.agentChatByAgent,[a]:{...t,messages:n,oldestLoadedId:J(n)}}}}),c(`DELETE`,`/inbox/drafts?operatorId=`+encodeURIComponent(C)+`&peerId=`+encodeURIComponent(a)).catch(()=>{}),Promise.all([t().fetchMessages(),t().loadAgentChat(a)])}catch(n){o!==void 0&&e(e=>e.inboxDrafts[a]===void 0?{inboxDrafts:{...e.inboxDrafts,[a]:o}}:{}),e(e=>{let t=e.agentChatByAgent[a];if(!t)return{};let n=t.messages.filter(e=>e.id!==l);return{agentChatByAgent:{...e.agentChatByAgent,[a]:{...t,messages:n,oldestLoadedId:J(n)}}}}),t().showError(`Send Failed`,n.message)}e({chatSending:!1})},async sendPermissionDecision(e,n,r,i){try{await c(`POST`,`/agents/`+encodeURIComponent(e)+`/permission-decision`,{approvalId:n,decision:r,...i?{answers:i}:{}});let a=r===`approve`?`Approved`:r===`approve-session`?`Approved for session`:r===`abort`?`Aborted`:r===`answer`?`Answer sent for`:`Denied`;t().showNotification(`${a} ${r===`answer`?`Claude's question`:`permission request`}`),await t().fetchAgents()}catch(e){t().showError(`Permission Failed`,e.message)}},markInboxThreadReadTo(n,r){!n||r<=(t().inboxReadCursors[n]||0)||(e({inboxReadCursors:{...t().inboxReadCursors,[n]:r}}),c(`PATCH`,`/inbox/threads`,{operatorId:C,peerId:n,readCursorMessageId:r}).catch(()=>{}))},markInboxThreadRead(e,n){!e||!n.length||t().markInboxThreadReadTo(e,yt(n))},markInboxThreadUnread(n){let r={...t().inboxReadCursors};delete r[n],e({inboxReadCursors:r}),c(`PATCH`,`/inbox/threads`,{operatorId:C,peerId:n,readCursorMessageId:null}).catch(()=>{})},archiveInboxThread(n,r){e({inboxArchivedThreads:{...t().inboxArchivedThreads,[n]:r}}),t().selectedInboxThread===n&&e({selectedInboxThread:``}),c(`PATCH`,`/inbox/threads`,{operatorId:C,peerId:n,archivedAtMessageId:r}).catch(()=>{})},unarchiveInboxThread(n){let r={...t().inboxArchivedThreads};delete r[n],e({inboxArchivedThreads:r}),c(`PATCH`,`/inbox/threads`,{operatorId:C,peerId:n,archivedAtMessageId:null}).catch(()=>{})},setReplyDraft(n,r){let i={...t().inboxDrafts};r?i[n]=r:delete i[n],e({inboxDrafts:i}),r?c(`PUT`,`/inbox/drafts`,{operatorId:C,peerId:n,body:r}).catch(()=>{}):c(`DELETE`,`/inbox/drafts?operatorId=`+encodeURIComponent(C)+`&peerId=`+encodeURIComponent(n)).catch(()=>{})},async sendInboxReply(n,r){let i=(t().inboxDrafts[n]||``).trim();if(!i||t().chatSending){i||t().showError(`Validation`,`Reply body is required.`);return}e({chatSending:!0});try{let a={from:E,to:n,body:i};r?.channel&&(a.channel=r.channel),r?.id&&(a.replyTo=r.id),await c(`POST`,`/messages`,a);let o={...t().inboxDrafts};delete o[n],e({inboxDrafts:o}),c(`DELETE`,`/inbox/drafts?operatorId=`+encodeURIComponent(C)+`&peerId=`+encodeURIComponent(n)).catch(()=>{}),await t().fetchMessages()}catch(e){t().showError(`Reply Failed`,e.message)}e({chatSending:!1})},toggleChatChildrenCollapsed(n){let r=t().chatCollapsedChildren;e({chatCollapsedChildren:r.includes(n)?r.filter(e=>e!==n):[...r,n]})},setFeedObserveAll(t){e({feedObserveAll:t})},toggleCoordinatorFollow(n){let r=t().coordinatorFollows,i=t().coordinatorMutes;r.includes(n)?e({coordinatorFollows:r.filter(e=>e!==n)}):e({coordinatorFollows:[...r,n],coordinatorMutes:i.filter(e=>e!==n)})},toggleCoordinatorMute(n){let r=t().coordinatorMutes,i=t().coordinatorFollows;r.includes(n)?e({coordinatorMutes:r.filter(e=>e!==n)}):e({coordinatorMutes:[...r,n],coordinatorFollows:i.filter(e=>e!==n)})},async doSendInboxCompose(){let n=t().inboxCompose,r=n.to;if(r){if(n.toMode===`tag`?r=`tag:`+r:n.toMode===`cap`&&(r=`cap:`+r),!n.body){t().showError(`Validation`,`Message is required.`);return}try{let i={from:E,to:r,body:n.body};n.channel&&(i.channel=n.channel),n.subject&&(i.subject=n.subject),n.claimable&&(i.claimable=!0,i.kind=`task`,i.payload={title:n.subject||`Claimable task`}),await c(`POST`,`/messages`,i),e({inboxCompose:{...S,toMode:n.toMode,to:n.to}}),await t().fetchMessages()}catch(e){t().showError(`Send Failed`,e.message)}}}});function X(e,t){return JSON.stringify([String(e),t||``])}function Z(e,t){return JSON.stringify([`team`,e,t||``])}function Vt(e){return{threadId:String(e.threadId),...e.channel?{channel:e.channel}:{}}}function Ht(e){return e.teamId?{teamId:e.teamId,...e.channel?{channel:e.channel}:{}}:null}function Ut(e){return`teamId`in e?Z(e.teamId,e.channel):X(e.threadId,e.channel)}function Wt(e){let t=new URLSearchParams(`teamId`in e?{teamId:e.teamId}:{threadId:String(e.threadId)});return e.channel&&t.set(`channel`,e.channel),`/plans?${t.toString()}`}var Gt=(e,t)=>({plansById:{},plansByThread:{},plansByTeam:{},planLookups:{},planLoading:{},planCollapsed:null,sessionTasksCollapsed:!1,setPlanCollapsed(t){e({planCollapsed:t})},setSessionTasksCollapsed(t){e({sessionTasksCollapsed:t})},async fetchPlan(n){let r=`teamId`in n?{teamId:n.teamId,...n.channel?{channel:n.channel}:{}}:{threadId:String(n.threadId),...n.channel?{channel:n.channel}:{}},i=Ut(r);e({planLookups:{...t().planLookups,[i]:r},planLoading:{...t().planLoading,[i]:!0}});try{let n=await c(`GET`,Wt(r)),a=Vt(n),o=X(a.threadId,a.channel),s=Ht(n),l=s?Z(s.teamId,s.channel):``,u=!(`teamId`in r),d=`teamId`in r;e({plansById:{...t().plansById,[n.id]:n},plansByThread:{...t().plansByThread,...u?{[i]:n}:{},[o]:n},plansByTeam:s?{...t().plansByTeam,...d?{[i]:n}:{},[l]:n}:t().plansByTeam,planLookups:{...t().planLookups,[i]:r,[o]:a,...s?{[l]:s}:{}},planLoading:{...t().planLoading,[i]:!1,[o]:!1,...s?{[l]:!1}:{}}}),t().hydrateIssueRefsForPlan(n)}catch(n){let a=typeof n.status==`number`?n.status:0;e({plansByThread:a===404&&!(`teamId`in r)?{...t().plansByThread,[i]:null}:t().plansByThread,plansByTeam:a===404&&`teamId`in r?{...t().plansByTeam,[i]:null}:t().plansByTeam,planLoading:{...t().planLoading,[i]:!1}}),a&&a!==404&&t().showError(`Plan Load Failed`,n.message)}},async refreshPlans(){let e=Object.values(t().planLookups);await Promise.all(e.map(e=>t().fetchPlan(e)))},async setPlanArchived(e,n){try{let r=await c(`PATCH`,`/plans/${encodeURIComponent(e)}/archive`,{archived:n});t().upsertPlan(r)}catch(e){t().showError(n?`Plan Archive Failed`:`Plan Unarchive Failed`,e.message)}},upsertPlan(n){let r=Vt(n),i=X(r.threadId,r.channel),a=Ht(n),o=a?Z(a.teamId,a.channel):``;e({plansById:{...t().plansById,[n.id]:n},plansByThread:{...t().plansByThread,[i]:n},plansByTeam:a?{...t().plansByTeam,[o]:n}:t().plansByTeam,planLookups:{...t().planLookups,[i]:r,...a?{[o]:a}:{}},planLoading:{...t().planLoading,[i]:!1,...a?{[o]:!1}:{}}}),t().hydrateIssueRefsForPlan(n)},removePlan(n){let r=typeof n==`string`?n:n.id,i={...t().plansById};delete i[r],e({plansById:i,plansByThread:Object.fromEntries(Object.entries(t().plansByThread).filter(([,e])=>e?.id!==r)),plansByTeam:Object.fromEntries(Object.entries(t().plansByTeam).filter(([,e])=>e?.id!==r)),planLookups:Object.fromEntries(Object.entries(t().planLookups).filter(([e])=>t().plansByThread[e]?.id!==r&&t().plansByTeam[e]?.id!==r))})}}),Kt=(e,t)=>({teams:[],teamsLoading:!1,teamsError:null,teamOutcomeAggregates:null,teamOutcomeAggregatesLoading:!1,teamOutcomeAggregatesError:null,async fetchTeams(){e({teamsLoading:!0,teamsError:null});try{let n=await c(`GET`,`/teams`),r=W(t().teams,n.teams);return e({teams:r,teamsLoading:!1,teamsError:null}),r}catch(n){return e({teamsLoading:!1,teamsError:p(n)}),t().teams}},async fetchTeamOutcomeAggregates(){e({teamOutcomeAggregatesLoading:!0,teamOutcomeAggregatesError:null});try{let t=await c(`GET`,`/teams/outcomes`);return e({teamOutcomeAggregates:t,teamOutcomeAggregatesLoading:!1,teamOutcomeAggregatesError:null}),t}catch(n){return e({teamOutcomeAggregatesLoading:!1,teamOutcomeAggregatesError:p(n)}),t().teamOutcomeAggregates}},upsertTeam(n){let r=U(t().teams,n);r!==t().teams&&e({teams:r})},markTeamDissolved(n){let r=Date.now();e({teams:t().teams.map(e=>e.id===n.teamId?{...e,status:`dissolved`,updatedAt:r,dissolvedAt:e.dissolvedAt??r,zeroMembersSince:void 0,...n.outcomeStatus?{outcomeStatus:n.outcomeStatus}:{},...n.reason?{outcomeSummary:n.reason}:{}}:e)})},async dissolveTeam(e){try{let n=await c(`POST`,`/teams/${encodeURIComponent(e)}/dissolve`,{});t().upsertTeam(n),t().showNotification(`Team dissolved`),await Promise.all([t().fetchTeams(),t().fetchTeamOutcomeAggregates(),t().fetchActivityEvents()])}catch(e){t().showError(`Dissolve Failed`,p(e))}}});function qt(e,t){return JSON.stringify([e,t])}function Jt(e){return[...new Set(e.nodes.map(e=>e.refs?.issueId).filter(e=>!!e))]}function Q(e,t){let n=!1,r={...e};for(let i of t){let t=e[i.id];(!t||JSON.stringify(t)!==JSON.stringify(i))&&(r[i.id]=i,n=!0)}return n?r:e}var Yt=(e,t)=>({issueRefsById:{},issuesByEntity:{},issueActivityByAgent:{},issueLoading:{},issueErrors:{},async fetchAllIssueRefs(){try{let n=await c(`GET`,`/issue-refs?limit=500`);e({issueRefsById:Q(t().issueRefsById,n.issueRefs)})}catch{}},async fetchIssueRef(n){let r=`ref:${n}`;e({issueLoading:{...t().issueLoading,[r]:!0},issueErrors:{...t().issueErrors,[r]:null}});try{let i=await c(`GET`,`/issue-refs/${encodeURIComponent(n)}`);return e({issueRefsById:Q(t().issueRefsById,[i.issueRef]),issueLoading:{...t().issueLoading,[r]:!1}}),i.issueRef}catch(i){return e({issueLoading:{...t().issueLoading,[r]:!1},issueErrors:{...t().issueErrors,[r]:p(i)}}),t().issueRefsById[n]??null}},async fetchIssuesForEntity(n,r){let i=qt(n,r);e({issueLoading:{...t().issueLoading,[i]:!0},issueErrors:{...t().issueErrors,[i]:null}});try{let a=await c(`GET`,`/issue-associations/entities/${encodeURIComponent(n)}/${encodeURIComponent(r)}/issues`);return e({issuesByEntity:{...t().issuesByEntity,[i]:a.issues},issueRefsById:Q(t().issueRefsById,a.issues.map(e=>e.issueRef)),issueLoading:{...t().issueLoading,[i]:!1}}),a.issues}catch(n){return e({issueLoading:{...t().issueLoading,[i]:!1},issueErrors:{...t().issueErrors,[i]:p(n)}}),t().issuesByEntity[i]??[]}},async fetchAgentIssueActivity(n){let r=`agent:${n}`;e({issueLoading:{...t().issueLoading,[r]:!0},issueErrors:{...t().issueErrors,[r]:null}});try{let i=await c(`GET`,`/issue-activity/agents/${encodeURIComponent(n)}`);return e({issueActivityByAgent:{...t().issueActivityByAgent,[n]:i.issues},issueRefsById:Q(t().issueRefsById,i.issues.map(e=>e.issueRef)),issueLoading:{...t().issueLoading,[r]:!1}}),i.issues}catch(i){return e({issueLoading:{...t().issueLoading,[r]:!1},issueErrors:{...t().issueErrors,[r]:p(i)}}),t().issueActivityByAgent[n]??[]}},async hydrateIssueRefsForPlan(e){let n=Jt(e).filter(e=>!t().issueRefsById[e]);await Promise.all(n.map(e=>t().fetchIssueRef(e)))},async refreshIssueRefs(){let e=Object.keys(t().issueRefsById).map(e=>t().fetchIssueRef(e)),n=Object.keys(t().issuesByEntity).map(e=>{try{let[n,r]=JSON.parse(e);return t().fetchIssuesForEntity(n,r)}catch{return Promise.resolve([])}});await Promise.all([...e,...n])},upsertIssueRef(n){let r=Q(t().issueRefsById,[n]);r!==t().issueRefsById&&e({issueRefsById:r})}}),Xt={title:``,intent:``,doneWhen:``,issueRefs:``,dependsOn:``,dispatchComplexity:``,dispatchType:``,dispatchFootprint:``,dispatchCriticality:``},Zt=(e,t)=>({pairs:[],tasks:[],taskEvents:[],taskEventCache:{},taskEventsOpen:!1,pairInviteOpen:!1,pairMessageOpen:!1,pairInvite:{...D},deliverableTasks:[],deliverableStatusFilter:``,deliverableStageFilter:``,deliverableProjectFilter:``,taskDetailById:{},taskMemoryById:{},taskHistoryById:{},taskDetailOpen:!1,taskDetailId:null,taskCreateOpen:!1,taskCreateForm:{...Xt},taskDispatchResultById:{},taskDispatchLoadingId:null,pairMessage:{...w},pairStatusFilter:`open`,taskStatusFilter:``,taskSourceFilter:``,async fetchPairs(){try{let n=t(),r;if(n.view===`activity`)r=await c(`GET`,`/pairs`);else if(n.pairStatusFilter===`open`){let[e,t]=await Promise.all([c(`GET`,`/pairs?status=active`),c(`GET`,`/pairs?status=pending`)]);r=[...e,...t]}else r=n.pairStatusFilter?await c(`GET`,`/pairs?status=`+encodeURIComponent(n.pairStatusFilter)):await c(`GET`,`/pairs`);let i=r.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime()),a=W(t().pairs,i);a!==t().pairs&&e({pairs:a})}catch{}},async fetchTasks(){try{let n=t(),r=new URLSearchParams({limit:`100`});n.taskStatusFilter&&r.set(`status`,n.taskStatusFilter),n.taskSourceFilter&&r.set(`source`,n.taskSourceFilter);let i=W(t().tasks,await c(`GET`,`/tasks?`+r.toString()));i!==t().tasks&&e({tasks:i})}catch{}},async fetchDeliverableTasks(n){try{let r=t(),i=new URLSearchParams({kind:`deliverable`,limit:`200`});n?.unfiltered||(r.deliverableStatusFilter&&i.set(`status`,r.deliverableStatusFilter),r.deliverableStageFilter&&i.set(`deliverableStage`,r.deliverableStageFilter),r.deliverableProjectFilter&&i.set(`projectId`,r.deliverableProjectFilter));let a=await c(`GET`,`/tasks?`+i.toString()),o=W(t().deliverableTasks,a);o!==t().deliverableTasks&&e({deliverableTasks:o})}catch{}},async fetchTaskDetail(n){try{let r=await c(`GET`,`/tasks/`+n+`/detail`);e({taskDetailById:{...t().taskDetailById,[n]:r}})}catch{}},async fetchTaskMemory(n){try{let r=await c(`GET`,`/tasks/`+n+`/memory`);e({taskMemoryById:{...t().taskMemoryById,[n]:r}})}catch{}},async fetchTaskHistory(n){try{let r=await c(`GET`,`/tasks/`+n+`/history`);e({taskHistoryById:{...t().taskHistoryById,[n]:r}})}catch{}},openTaskDetail(n){e({taskDetailOpen:!0,taskDetailId:n.id}),t().fetchTaskDetail(n.id),t().fetchTaskMemory(n.id),t().fetchTaskHistory(n.id)},openTaskDetailById(n){e({taskDetailOpen:!0,taskDetailId:n}),t().fetchTaskDetail(n),t().fetchTaskMemory(n),t().fetchTaskHistory(n)},closeTaskDetail(){e({taskDetailOpen:!1,taskDetailId:null})},async doClaimTask(e){let n=t(),r=n.compose.from||n.selectedAgent;if(!r){t().showError(`Validation`,`Select an agent first.`);return}try{let n=await c(`POST`,`/tasks/`+e+`/claim`,{agentId:r});n.ok?await Promise.all([t().fetchTasks(),t().fetchMessages()]):t().showError(`Claim Failed`,n.error||`unknown`)}catch(e){t().showError(`Claim Failed`,e.message)}},async doUpdateTaskStatus(n,r){if(!(!n||!r||r===n.status))try{let i={status:r},a=n.claimedBy||t().compose.from||t().selectedAgent;a&&(i.agentId=a);let o=await c(`PATCH`,`/tasks/`+n.id+`/status`,i),s=o.task||o;if(e({tasks:t().tasks.map(e=>e.id===n.id?s:e)}),o.memoryEvent){let r=t().taskEventCache[n.id]||[];e({taskEventCache:{...t().taskEventCache,[n.id]:[...r,o.memoryEvent]},...t().taskEventsOpen?{taskEvents:[...t().taskEvents,o.memoryEvent]}:{}})}o.memory&&t().showNotification(`Memory captured: ${o.memory.title}`)}catch(e){t().showError(`Status Update Failed`,e.message),await t().fetchTasks()}},async openTaskEvents(n){e({taskEvents:[],taskEventsOpen:!0});try{let r=await c(`GET`,`/tasks/`+n.id+`/events`);e({taskEvents:r,taskEventCache:{...t().taskEventCache,[n.id]:r}})}catch(e){t().showError(`Task Events Failed`,e.message)}},openTaskCreate(){e({taskCreateOpen:!0,taskCreateForm:{...Xt}})},closeTaskCreate(){e({taskCreateOpen:!1})},setTaskCreateForm(n){e({taskCreateForm:{...t().taskCreateForm,...n}})},async doCreateTask(){let{taskCreateForm:n}=t(),r=n.title.trim();if(!r){t().showError(`Validation`,`Title is required.`);return}let i=n.intent.trim()||r,a={};n.dispatchComplexity&&(a.complexity=n.dispatchComplexity),n.dispatchType&&(a.type=n.dispatchType),n.dispatchFootprint&&(a.contextFootprint=n.dispatchFootprint),n.dispatchCriticality&&(a.criticality=n.dispatchCriticality);let o=n.issueRefs.split(`,`).map(e=>e.trim()).filter(Boolean),s=n.dependsOn.split(`,`).map(e=>Number(e.trim())).filter(e=>Number.isInteger(e)&&e>0);try{await c(`POST`,`/tasks`,{title:r,intent:i,...n.doneWhen.trim()?{doneWhen:n.doneWhen.trim()}:{},...o.length?{issueRefs:o}:{},...s.length?{dependsOn:s}:{},...Object.keys(a).length?{dispatch:a}:{}}),e({taskCreateOpen:!1,taskCreateForm:{...Xt}}),await t().fetchDeliverableTasks()}catch(e){t().showError(`Create Task Failed`,e.message)}},async doEditTask(n,r){try{let i=await c(`PATCH`,`/tasks/`+n,r);e({taskDetailById:{...t().taskDetailById,[n]:i},deliverableTasks:t().deliverableTasks.map(e=>e.id===n?{...e,...i}:e)})}catch(e){t().showError(`Edit Task Failed`,e.message)}},async doDispatchTask(n,r){e({taskDispatchLoadingId:n});try{let i={};r&&Object.keys(r).length&&(i.pin=r);let a=await c(`POST`,`/tasks/`+n+`/dispatch`,i);e({taskDispatchResultById:{...t().taskDispatchResultById,[n]:a},taskDispatchLoadingId:null})}catch(n){e({taskDispatchLoadingId:null}),t().showError(`Dispatch Failed`,n.message)}},async doSpawnWithTask(e,n){let r=t().spawnOrchId;try{let i={provider:n.provider,taskId:e};n.model&&(i.model=n.model),n.effort&&(i.effort=n.effort),r&&(i.orchestratorId=r),await c(`POST`,`/agents/spawn`,i),t().showNotification(`Worker spawning for T${e} (${n.provider})`)}catch(e){t().showError(`Spawn Failed`,e.message)}},openPairInvite(n){e({pairInvite:{...D,requesterId:n||t().selectedAgent||``},pairInviteOpen:!0})},closePairInvite(){e({pairInviteOpen:!1,pairInvite:{...D}})},async doCreatePair(){let n=t();if(!n.pairInvite.requesterId||!n.pairInvite.targetId){t().showError(`Validation`,`Requester and Target are required.`);return}if(n.pairInvite.requesterId===n.pairInvite.targetId){t().showError(`Validation`,`Requester and Target must be different.`);return}try{let r={from:n.pairInvite.requesterId,target:n.pairInvite.targetId};n.pairInvite.objective&&(r.objective=n.pairInvite.objective),await c(`POST`,`/pairs`,r),e({pairInviteOpen:!1,pairInvite:{...D}}),await Promise.all([t().fetchPairs(),t().fetchMessages()])}catch(e){t().showError(`Pair Invite Failed`,e.message)}},openPairMessage(t,n){e({pairMessage:{...w,pairId:t.id,from:n||t.requesterId},pairMessageOpen:!0})},closePairMessage(){e({pairMessageOpen:!1,pairMessage:{...w}})},async doSendPairMessage(){let n=t();if(!n.pairMessage.pairId||!n.pairMessage.from||!n.pairMessage.body){t().showError(`Validation`,`Pair, From, and Message are required.`);return}try{let r={from:n.pairMessage.from,body:n.pairMessage.body};n.pairMessage.subject&&(r.subject=n.pairMessage.subject),await c(`POST`,`/pairs/`+encodeURIComponent(n.pairMessage.pairId)+`/messages`,r),e({pairMessageOpen:!1,pairMessage:{...w}}),await Promise.all([t().fetchPairs(),t().fetchMessages()])}catch(e){t().showError(`Pair Message Failed`,e.message)}},async doAcceptPair(e){try{await c(`POST`,`/pairs/`+encodeURIComponent(e.id)+`/accept`,{agentId:e.targetId}),await Promise.all([t().fetchPairs(),t().fetchMessages()])}catch(e){t().showError(`Accept Failed`,e.message)}},async doRejectPair(e){try{await c(`POST`,`/pairs/`+encodeURIComponent(e.id)+`/reject`,{agentId:e.targetId}),await Promise.all([t().fetchPairs(),t().fetchMessages()])}catch(e){t().showError(`Reject Failed`,e.message)}},async doHangupPair(e,n){try{await c(`POST`,`/pairs/`+encodeURIComponent(e.id)+`/hangup`,{agentId:n||e.requesterId}),await Promise.all([t().fetchPairs(),t().fetchMessages()])}catch(e){t().showError(`Hang Up Failed`,e.message)}}}),Qt=(e,t)=>({orchestrators:[],providerCatalog:[],orchestratorSpawnOpen:!1,orchestratorInstallOpen:!1,spawnOrchId:``,spawnProvider:L(void 0),spawnModel:z(L(void 0)),spawnEffort:``,spawnProfile:`default-relay`,spawnCwd:``,spawnLabel:``,spawnApproval:`guarded`,spawnWorkspaceMode:`inherit`,spawnPrompt:``,spawnSystemPromptAppend:``,spawnCount:1,spawnCwdHistory:[],isSpawning:!1,spawnDirBrowser:{open:!1,loading:!1,path:``,parent:``,baseDir:``,entries:[],error:``},pendingForkImport:null,async fetchOrchestrators(){try{let n=W(t().orchestrators,await c(`GET`,`/orchestrators`));n!==t().orchestrators&&e({orchestrators:n})}catch{}},async fetchProviderCatalog(){try{e({providerCatalog:(await c(`GET`,`/providers`)).catalog})}catch{}},async refreshOrchestratorProviders(e){try{await c(`GET`,`/orchestrators/`+encodeURIComponent(e)+`/providers?refresh=1`),await t().fetchOrchestrators(),t().showNotification(`Provider status refreshed`)}catch(e){t().showError(`Provider Refresh Failed`,e.message)}},openAgentSpawn(){t().openOrchestratorSpawn()},closeAgentSpawn(){e({orchestratorSpawnOpen:!1})},async doSpawnAgent(){await t().submitOrchestratorSpawn()},openOrchestratorSpawn(){t().openOrchestratorSpawnAt()},openOrchestratorSpawnAt(n={}){let r=t().orchestrators.filter(e=>e.status===`online`);if(!r.length){t().showError(`No Orchestrators`,`No orchestrators are currently online.`);return}t().fetchProviderCatalog();let i=t(),a=n.orchestratorId?r.find(e=>e.id===n.orchestratorId):void 0;if(n.orchestratorId&&!a){t().showError(`Orchestrator Offline`,`The selected orchestrator is not online.`);return}let o=n.cwd?.trim()||i.spawnCwd,s=o?r.find(e=>v(o,e.baseDir)):void 0,c=i.spawnOrchId?r.find(e=>e.id===i.spawnOrchId):void 0,l=a?.id||s?.id||c?.id||r[0].id,u=r.find(e=>e.id===l),d=i.spawnProvider&&u.providers.includes(i.spawnProvider)?i.spawnProvider:L(u),f=i.spawnProvider===d&&i.spawnModel&&R(d,i.providerCatalog).some(e=>e.alias===i.spawnModel)?i.spawnModel:z(d,i.providerCatalog),p=o&&v(o,u.baseDir)?o:u.baseDir||``;e({spawnOrchId:l,spawnProvider:d,spawnModel:f,spawnEffort:i.spawnProvider===d&&i.spawnModel===f?i.spawnEffort:``,spawnProfile:i.spawnProfile||`default-relay`,spawnCwd:p,spawnLabel:``,spawnWorkspaceMode:`inherit`,spawnPrompt:``,spawnSystemPromptAppend:``,spawnCount:1,pendingForkImport:null,orchestratorSpawnOpen:!0})},forkFromAgent(n,r){let i=t(),a=i.agentsById[n];if(!a){t().showError(`Fork`,`Agent not found.`);return}let o=i.orchestrators.filter(e=>e.status===`online`);if(!o.length){t().showError(`No Orchestrators`,`No orchestrators are currently online.`);return}t().fetchProviderCatalog();let s=a.providerCapabilities,c=s?.model?.provider||(typeof a.meta?.provider==`string`?a.meta.provider:``),l=s?.model?.alias||s?.model?.id||``,f=(c?I(c,i.providerCatalog):void 0)?.models.find(e=>e.alias===l||e.providerModel===l)?.alias||``,p=s?.model?.effort||``,m=a.meta?.workspace,h=u(m)?m:{},g=d(h.repoRoot)||d(h.sourceCwd)||(typeof a.meta?.cwd==`string`?a.meta.cwd:``),_=d(h.mode),y=_===`isolated`?`isolated`:_===`shared`?`shared`:`inherit`,b=s?.session?.approvalMode||(typeof a.meta?.approvalMode==`string`?a.meta.approvalMode:`guarded`),ee=a.label?`${a.label} (fork)`:``,x=o.find(e=>e.hostname===a.machine)||o.find(e=>v(g,e.baseDir))||o[0],S=te(a),C=[];for(let e of r){let t=ne(e).trim();if(!t)continue;let n=e.from===`user`?`user`:`agent`;C.push(`[${n}]: ${t}`)}let w=C.join(`
|
|
6
|
-
`),T=14e3,re=`You are continuing work from a previous agent session (${S}). Below is the conversation history. Treat it as context for your work, not as your own actions.\n\n${w.length>T?`...
|
|
7
|
-
`+w.slice(w.length-T):w}`,E=r.filter(e=>typeof e.id==`number`&&e.id>0).map(e=>e.id);e({spawnOrchId:x.id,spawnProvider:c||L(x),spawnModel:f||z(c||L(x)),spawnEffort:p,spawnProfile:i.spawnProfile||`default-relay`,spawnCwd:g||x.baseDir||``,spawnLabel:ee,spawnApproval:b,spawnWorkspaceMode:y,spawnPrompt:`Continue from this previous session.`,spawnSystemPromptAppend:re,spawnCount:1,pendingForkImport:{sourcePeerId:a.id,sourceAgentId:a.id,sourceThreadId:a.id,sourceAgentLabel:S,messageIds:E},orchestratorSpawnOpen:!0})},openOrchestratorInstall(){e({orchestratorInstallOpen:!0})},openOrchestratorSpawnFor(n){let r=t(),i=r.orchestrators.find(e=>e.id===n),a=L(i),o=z(a,r.providerCatalog),s=r.spawnProvider===a&&r.spawnModel===o?r.spawnEffort:``,c=r.spawnCwd&&v(r.spawnCwd,i?.baseDir)?r.spawnCwd:i?.baseDir||``;e({spawnOrchId:n,spawnProvider:a,spawnModel:o,spawnEffort:s,spawnProfile:r.spawnProfile||`default-relay`,spawnCwd:c,spawnLabel:``,spawnWorkspaceMode:`inherit`,spawnPrompt:``,spawnSystemPromptAppend:``,spawnCount:1,pendingForkImport:null,orchestratorSpawnOpen:!0})},selectSpawnHistory(n,r){let i=t(),a=i.orchestrators.find(e=>e.id===n&&e.status===`online`);if(!a){t().showError(`Unavailable`,`That orchestrator is no longer online.`);return}if(n===i.spawnOrchId){e({spawnCwd:r});return}let o=i.spawnProvider&&a.providers.includes(i.spawnProvider)?i.spawnProvider:L(a),s=i.spawnProvider===o&&i.spawnModel&&R(o,i.providerCatalog).some(e=>e.alias===i.spawnModel)?i.spawnModel:z(o,i.providerCatalog);e({spawnOrchId:n,spawnProvider:o,spawnModel:s,spawnEffort:i.spawnProvider===o&&i.spawnModel===s?i.spawnEffort:``,spawnCwd:r})},async submitOrchestratorSpawn(){let n=t();if(n.isSpawning)return;if(!n.spawnOrchId){t().showError(`Validation`,`Select an orchestrator.`);return}let r=n.orchestrators.find(e=>e.id===n.spawnOrchId);if(!r){t().showError(`Validation`,`Selected orchestrator is not available.`);return}let i=n.spawnCwd.trim();if(!i){t().showError(`Validation`,`Select a working directory.`);return}if(!v(i,r.baseDir)){t().showError(`Validation`,`Working directory must be under ${r.baseDir}.`);return}let a=n.pendingForkImport,o=a?1:Math.max(1,Math.min(10,Math.round(n.spawnCount)||1));e({isSpawning:!0});try{for(let e=0;e<o;e++){let t={provider:n.spawnProvider,orchestratorId:n.spawnOrchId,approvalMode:n.spawnApproval,workspaceMode:n.spawnWorkspaceMode||`inherit`};n.spawnModel&&(t.model=n.spawnModel),n.spawnEffort&&(t.effort=n.spawnEffort),n.spawnProfile&&(t.profile=n.spawnProfile),t.cwd=i,n.spawnLabel&&(t.label=o>1?`${n.spawnLabel} ${e+1}`:n.spawnLabel),n.spawnPrompt&&(t.prompt=n.spawnPrompt),n.spawnSystemPromptAppend&&(t.systemPromptAppend=n.spawnSystemPromptAppend);let r=(await c(`POST`,`/agents/spawn`,t)).command?.params?.spawnRequestId;a&&r&&a.messageIds.length>0&&await c(`POST`,`/chat/history-imports`,{targetSpawnRequestId:r,sourcePeerId:a.sourcePeerId,sourceAgentId:a.sourceAgentId,sourceThreadId:a.sourceThreadId,sourceAgentLabel:a.sourceAgentLabel,importedBy:C,messageIds:a.messageIds})}e({orchestratorSpawnOpen:!1,pendingForkImport:null,isSpawning:!1,spawnCwdHistory:[{orchId:n.spawnOrchId,cwd:i},...n.spawnCwdHistory.filter(e=>!(e.orchId===n.spawnOrchId&&e.cwd===i))].slice(0,5)}),await Promise.all([t().fetchAgents(),t().fetchOrchestrators(),t().fetchActivityEvents(),t().fetchChatHistoryImports()])}catch(n){e({isSpawning:!1}),t().showError(`Spawn Failed`,n.message)}},orchestratorAction(e,n,r,i){let a=n===`restart`?`Restart`:`Shutdown`,o=r?`agent "${r}"`:`all agents`;t().openConfirm(`${a} Agent`,`${a} ${o} on orchestrator "${e}"?`,async()=>{try{await c(`POST`,`/orchestrators/`+encodeURIComponent(e)+`/actions`,{action:n,agentId:r,...i?{surface:{component:i}}:{}}),await Promise.all([t().fetchOrchestrators(),t().fetchActivityEvents()])}catch(e){t().showError(`${a} Failed`,e.message)}})},upgradeOrchestrator(e,n){let r=n?` to v${n}`:` to match the relay`;t().openConfirm(`Upgrade Orchestrator`,`Upgrade "${e}"${r}? It will install the new version and restart itself.`,async()=>{try{await c(`POST`,`/orchestrators/`+encodeURIComponent(e)+`/actions`,{action:`upgrade`,...n?{targetVersion:n}:{}}),await Promise.all([t().fetchOrchestrators(),t().fetchActivityEvents()])}catch(e){t().showError(`Upgrade Failed`,e.message)}})},deleteOrchestrator(e){t().openConfirm(`Remove Orchestrator`,`Remove orchestrator "${e}"?`,async()=>{try{await c(`DELETE`,`/orchestrators/`+encodeURIComponent(e)),await Promise.all([t().fetchOrchestrators(),t().fetchActivityEvents()])}catch(e){t().showError(`Delete Failed`,e.message)}})},async browseSpawnDirectory(n){let r=t().spawnOrchId;if(!r)return;let i=t().spawnDirBrowser;e({spawnDirBrowser:{...i,loading:!0,error:``}});try{let i=n?`?path=`+encodeURIComponent(n):``,a=await c(`GET`,`/orchestrators/`+encodeURIComponent(r)+`/directories`+i);e({spawnDirBrowser:{open:!0,loading:!1,path:a.path||``,parent:a.parent||``,baseDir:a.baseDir||``,entries:a.entries||[],error:``},spawnCwd:a.path||t().spawnCwd})}catch(n){e({spawnDirBrowser:{...t().spawnDirBrowser,loading:!1,error:n.message}})}},selectSpawnDirectory(n){e({spawnCwd:n||t().spawnDirBrowser.path,spawnDirBrowser:{...t().spawnDirBrowser,open:!1}})}}),$t=(e,t)=>({managedPolicies:[],policyModal:{open:!1,editing:``,name:``,description:``,orchestratorId:``,cwd:``,enabled:void 0,provider:L(void 0),rig:``,model:z(L(void 0)),effort:``,profile:`default-relay`,providerArgs:``,prompt:``,tags:``,capabilities:``,label:``,mode:`always-on`,permissionMode:`guarded`,restartOnUpdate:!0,scheduledDailyRestart:!1,keepaliveSeconds:`300`,backoffSchedule:`5,15,60,300`,backoffResetAfterSeconds:`600`,channelId:``},policyDirBrowser:{open:!1,loading:!1,path:``,parent:``,baseDir:``,entries:[],error:``},agentProfiles:[],toolGroupCatalog:[],toolGroupCatalogStatus:{loading:!1,loaded:!1,error:null},profileModal:{open:!1,mode:`create`,profile:{name:``,description:``,provider:`any`,base:`host`,instructions:{system:``,append:[],repoInstructions:`allow`,globalInstructions:`allow`},relay:{context:!0,skills:!0,plugins:!0,statusLine:!0,mcp:!0},skills:[],plugins:[],mcp:{mode:`host`},hooks:{mode:`host`},permissions:{filesystem:`host`},env:{},providerOptions:{}},relayToolsMode:`full`},async fetchManagedPolicies(){try{e({managedPolicies:await c(`GET`,`/spawn-policies/health`)})}catch{}},async fetchAgentProfiles(){try{e({agentProfiles:(await c(`GET`,`/agent-profiles`)).map(e=>e.value)})}catch{}},async fetchToolGroupCatalog(){e({toolGroupCatalogStatus:{loading:!0,loaded:t().toolGroupCatalogStatus.loaded,error:null}});try{e({toolGroupCatalog:await c(`GET`,`/agent-profiles/tool-groups`),toolGroupCatalogStatus:{loading:!1,loaded:!0,error:null}})}catch(t){e({toolGroupCatalog:[],toolGroupCatalogStatus:{loading:!1,loaded:!0,error:p(t)}})}},openPolicyCreate(){let n=t().orchestrators.filter(e=>e.status===`online`);if(!n.length){t().showError(`No Orchestrators`,`No orchestrators are currently online.`);return}t().fetchProviderCatalog(),e({policyModal:{open:!0,editing:``,name:``,description:``,orchestratorId:n[0].id,cwd:``,enabled:void 0,provider:L(n[0]),rig:``,model:z(L(n[0]),t().providerCatalog),effort:``,profile:`default-relay`,providerArgs:``,prompt:``,tags:``,capabilities:``,label:``,mode:`always-on`,permissionMode:`guarded`,restartOnUpdate:!0,scheduledDailyRestart:!1,keepaliveSeconds:`300`,backoffSchedule:`5,15,60,300`,backoffResetAfterSeconds:`600`,channelId:``},policyDirBrowser:{open:!1,loading:!1,path:``,parent:``,baseDir:``,entries:[],error:``}})},openPolicyEdit(n){t().fetchProviderCatalog(),e({policyModal:{open:!0,editing:n.name,name:n.name,enabled:n.enabled,description:n.description||``,orchestratorId:n.orchestratorId,cwd:n.cwd,provider:n.provider,rig:n.rig||``,model:n.model||z(n.provider,t().providerCatalog),effort:n.effort||``,profile:n.profile||`default-relay`,providerArgs:(n.providerArgs||[]).join(` `),prompt:n.prompt||``,tags:(n.tags||[]).join(`, `),capabilities:(n.capabilities||[]).join(`, `),label:n.label||``,mode:n.mode,permissionMode:n.permissionMode,restartOnUpdate:n.restartOnUpdate,scheduledDailyRestart:n.scheduledDailyRestart,keepaliveSeconds:String(n.onDemand?.keepaliveSeconds??300),backoffSchedule:(n.backoff?.schedule||[5,15,60,300]).join(`, `),backoffResetAfterSeconds:String(n.backoff?.resetAfterSeconds??600),channelId:n.binding?.channelId||``},policyDirBrowser:{open:!1,loading:!1,path:``,parent:``,baseDir:``,entries:[],error:``}})},async submitPolicy(){let n=t().policyModal;if(!n.name.trim()){t().showError(`Validation`,`Policy name is required.`);return}if(!n.orchestratorId){t().showError(`Validation`,`Select an orchestrator.`);return}if(!n.cwd.trim()){t().showError(`Validation`,`Working directory is required.`);return}let r=e=>e.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean),i={name:n.name.trim(),...n.description.trim()?{description:n.description.trim()}:{},...n.enabled===void 0?{}:{enabled:n.enabled},orchestratorId:n.orchestratorId,cwd:n.cwd.trim(),provider:n.provider,...n.rig.trim()?{rig:n.rig.trim()}:{},...n.model?{model:n.model}:{},...n.effort?{effort:n.effort}:{},...n.profile?{profile:n.profile}:{},providerArgs:n.providerArgs.trim()?n.providerArgs.trim().split(/\s+/):[],...n.prompt.trim()?{prompt:n.prompt.trim()}:{},tags:r(n.tags),capabilities:r(n.capabilities),...n.label.trim()?{label:n.label.trim()}:{},mode:n.mode,permissionMode:n.permissionMode,restartOnUpdate:n.restartOnUpdate,scheduledDailyRestart:n.scheduledDailyRestart,...n.mode===`on-demand`?{onDemand:{keepaliveSeconds:Number(n.keepaliveSeconds)||300,idleDefinition:`no-activity`}}:{},backoff:{schedule:r(n.backoffSchedule).map(Number).filter(e=>e>0),resetAfterSeconds:Number(n.backoffResetAfterSeconds)||600},...n.channelId.trim()?{binding:{type:`channel`,channelId:n.channelId.trim()}}:{}};i.backoff.schedule.length||(i.backoff.schedule=[5,15,60,300]);try{await c(`PUT`,`/spawn-policy/`+encodeURIComponent(i.name),i),e({policyModal:{...n,open:!1}}),await t().fetchManagedPolicies()}catch(e){t().showError(`Save Failed`,e.message)}},deletePolicy(e){t().openConfirm(`Delete Policy`,`Delete managed agent policy "${e}"? This will stop any running agent.`,async()=>{try{await c(`DELETE`,`/spawn-policy/`+encodeURIComponent(e)),await t().fetchManagedPolicies()}catch(e){t().showError(`Delete Failed`,e.message)}})},async browsePolicyDirectory(n){let r=t().policyModal.orchestratorId;if(!r)return;let i=t().policyDirBrowser;e({policyDirBrowser:{...i,loading:!0,error:``}});try{let i=n?`?path=`+encodeURIComponent(n):``,a=await c(`GET`,`/orchestrators/`+encodeURIComponent(r)+`/directories`+i);e({policyDirBrowser:{open:!0,loading:!1,path:a.path||``,parent:a.parent||``,baseDir:a.baseDir||``,entries:a.entries||[],error:``},policyModal:{...t().policyModal,cwd:a.path||t().policyModal.cwd}})}catch(n){e({policyDirBrowser:{...t().policyDirBrowser,loading:!1,error:n.message}})}},selectPolicyDirectory(n){e({policyModal:{...t().policyModal,cwd:n||t().policyDirBrowser.path},policyDirBrowser:{...t().policyDirBrowser,open:!1}})},openProfileModal(n,r){t().fetchToolGroupCatalog();let i={name:``,description:``,provider:`any`,base:`host`,instructions:{system:``,append:[],repoInstructions:`allow`,globalInstructions:`allow`},relay:{context:!0,skills:!0,plugins:!0,statusLine:!0,mcp:!0},skills:[],plugins:[],mcp:{mode:`host`},hooks:{mode:`host`},permissions:{filesystem:`host`},env:{},providerOptions:{}},a;r&&n===`duplicate`?(a=JSON.parse(JSON.stringify(r)),a.name=r.name+`-copy`,delete a.builtIn):a=r&&(n===`edit`||n===`view`)?JSON.parse(JSON.stringify(r)):i;let o=(a.relay.tools?.groups?.length??0)>0?`custom`:`full`;e({profileModal:{open:!0,mode:n,profile:a,relayToolsMode:o}})},closeProfileModal(){e({profileModal:{...t().profileModal,open:!1}})},updateProfileModal(n){let r=t().profileModal.profile;e({profileModal:{...t().profileModal,profile:{...r,...n}}})},setRelayToolsMode(n){if(e({profileModal:{...t().profileModal,relayToolsMode:n}}),n===`full`){let{profile:n}=t().profileModal;e({profileModal:{...t().profileModal,profile:{...n,relay:{...n.relay,tools:void 0}}}})}},async saveProfile(){let{mode:n,profile:r}=t().profileModal;if(!r.name.trim()){t().showError(`Validation`,`Profile name is required.`);return}if(n!==`view`)try{await c(`PUT`,`/agent-profiles/`+encodeURIComponent(r.name.trim()),r),e({profileModal:{...t().profileModal,open:!1}}),await t().fetchAgentProfiles(),t().showNotification(`Profile "${r.name}" saved`)}catch(e){t().showError(`Save Failed`,e.message)}},deleteProfile(e){let n=typeof e==`string`?t().agentProfiles.find(t=>t.name===e):e,r=typeof e==`string`?e:e.name,i=n?.builtIn===!0;t().openConfirm(i?`Reset Profile`:`Delete Profile`,i?`Reset built-in profile "${r}" to its default?`:`Delete agent profile "${r}"?`,async()=>{try{await c(`DELETE`,`/agent-profiles/`+encodeURIComponent(r)),await t().fetchAgentProfiles(),t().showNotification(i?`Profile "${r}" reset to default`:`Profile "${r}" deleted`)}catch(e){t().showError(`Delete Failed`,e.message)}})}}),en=(e,t)=>({operatorActivity:[],recordOperatorActivity(n){let r={id:Date.now(),kind:`operator`,title:n.title||`Activity`,body:n.body,meta:n.meta,icon:n.icon,view:n.view,peer:n.peer,messageId:n.messageId,pairId:n.pairId,taskId:n.taskId,agentId:n.agentId,ts:Date.now(),clientId:`op-`+Date.now(),createdAt:Date.now()};e({operatorActivity:[r,...t().operatorActivity.slice(0,79)]}),c(`POST`,`/activity`,{operatorId:C,clientId:r.clientId,kind:r.kind,title:r.title,body:r.body,meta:r.meta,icon:r.icon,view:r.view,peer:r.peer,messageId:r.messageId,pairId:r.pairId,taskId:r.taskId,agentId:r.agentId}).catch(()=>{})},async openActivityItem(e){if(e.view&&await t().switchView(e.view===`inbox`?`chat`:e.view),e.peer&&t().openInboxThread(e.peer),e.agentId){let n=t().agentsById[e.agentId];n&&t().openAgentDetail(n)}e.taskId&&t().openTaskDetailById(e.taskId)}});function tn(e){return re(e.createdAt??e.ts)}function nn(e,t){let n=[`# Agent Relay Timeline`,``,`Exported: ${t}`,`Events: ${e.length}`,``];for(let t of e){let e=new Date(tn(t)).toISOString();n.push(`## ${t.title||t.kind||`Event`}`),n.push(`- When: ${e}`),t.kind&&n.push(`- Kind: ${t.kind}`),t.agentId&&n.push(`- Agent: ${t.agentId}`),t.peer&&n.push(`- Peer: ${t.peer}`),t.body&&n.push(``,t.body),n.push(``)}return n.join(`
|
|
8
|
-
`)}var rn=(e,t)=>({activityEvents:[],activityFilter:``,async fetchActivityEvents(){try{e({activityEvents:await c(`GET`,`/activity?limit=200`)})}catch{}},exportActivity(e){let n=t(),r=[...n.operatorActivity,...n.activityEvents].sort((e,t)=>tn(t)-tn(e)),i=new Date().toISOString(),a=`agent-relay-timeline-${i.slice(0,10)}.${e===`json`?`json`:`md`}`;e===`json`?T(a,JSON.stringify({title:`Agent Relay Timeline`,exportedAt:i,events:r},null,2),`application/json`):T(a,nn(r,i),`text/markdown`)},exportThread(e,t){let n=`agent-relay-thread-${ee(e.peer)}.${t===`json`?`json`:`md`}`,r={title:`Thread: `+e.peer,importedHistory:e.importedHistory||[],messages:e.messages,exportedAt:new Date().toISOString()};T(n,JSON.stringify(r,null,2),t===`json`?`application/json`:`text/markdown`)},exportPair(e,t){let n=`agent-relay-pair-${ee(e.id)}.${t===`json`?`json`:`md`}`,r={title:`Pair: `+e.id,pair:e,exportedAt:new Date().toISOString()};T(n,JSON.stringify(r,null,2),t===`json`?`application/json`:`text/markdown`)},async exportTask(n,r){let i=t().taskEventCache[n.id]||[];if(!i.length)try{i=await c(`GET`,`/tasks/`+n.id+`/events`),e({taskEventCache:{...t().taskEventCache,[n.id]:i}})}catch{}let a=`agent-relay-task-${n.id}.${r===`json`?`json`:`md`}`,o={title:`Task: `+(n.title||`T`+n.id),task:n,events:i,exportedAt:new Date().toISOString()};T(a,JSON.stringify(o,null,2),r===`json`?`application/json`:`text/markdown`)}}),an=(e,t)=>({channels:[],connectors:[],integrations:[],automations:[],automationRuns:[],health:null,maintenanceJobs:[],analyticsPeriod:`24h`,analyticsData:null,async fetchChannels(){try{e({channels:await c(`GET`,`/channels`)})}catch{}},async fetchConnectors(){try{e({connectors:await c(`GET`,`/connectors`)})}catch{}},async fetchIntegrations(){try{e({integrations:await c(`GET`,`/integrations`)})}catch{}},async fetchAutomations(){try{e({automations:await c(`GET`,`/automations`)})}catch{}},async fetchAutomationRuns(t){try{let n=new URLSearchParams({limit:`100`});t&&n.set(`automationId`,t),e({automationRuns:await c(`GET`,`/automation-runs?`+n.toString())})}catch{}},async fetchHealth(){try{e({health:await c(`GET`,`/health`)})}catch{}},async fetchMaintenanceJobs(){try{e({maintenanceJobs:await c(`GET`,`/maintenance/jobs`)})}catch{}},async runMaintenanceJob(n){try{let r=await c(`POST`,`/maintenance/jobs/`+encodeURIComponent(n)+`/run`,{});return e({maintenanceJobs:r.jobs}),t().showNotification(r.run.status===`succeeded`?`Maintenance job completed`:`Maintenance job skipped`),r.run}catch(e){return t().showError(`Maintenance Job Failed`,e.message),await t().fetchMaintenanceJobs(),null}},async runHealthAction(n){if(n.preset&&e({agentPresetFilter:n.preset,showOffline:!0}),n.api&&n.path&&(await c(n.api,n.path),await t().refreshLiveData()),n.view&&await t().switchView(n.view),n.copy)try{await navigator.clipboard?.writeText(n.copy)}catch{}},async runConnectorAction(e,n){try{let r=await c(`POST`,`/connectors/`+encodeURIComponent(e)+`/actions`,{action:n});if(await t().fetchConnectors(),!r.ok)throw Error(r.stderr||`${n} failed`);return r}catch(e){throw t().showError(`Connector Action Failed`,e.message),e}},async fetchAnalytics(){try{e({analyticsData:await c(`GET`,`/stats/analytics?period=`+t().analyticsPeriod)})}catch{}},setAnalyticsPeriod(n){e({analyticsPeriod:n}),t().fetchAnalytics()}}),on=(e,t)=>({workspaces:[],workspaceFocusId:null,workspaceGitState:{},workspaceMergePreview:{},workspaceDiff:{},workspaceOrphans:[],async openWorkspaceFocus(n){e({workspaceFocusId:n}),await t().switchView(`workspaces`)},async fetchWorkspaces(){try{e({workspaces:await c(`GET`,`/workspaces`)})}catch{}},async fetchWorkspaceGitState(t){try{let n=await c(`GET`,`/workspaces/`+encodeURIComponent(t)+`/git-state`);e(e=>({workspaceGitState:{...e.workspaceGitState,[t]:n}}))}catch(n){e(e=>({workspaceGitState:{...e.workspaceGitState,[t]:{available:!1,reason:n.message}}}))}},async fetchWorkspaceMergePreview(t){try{let n=await c(`GET`,`/workspaces/`+encodeURIComponent(t)+`/merge-preview`);e(e=>({workspaceMergePreview:{...e.workspaceMergePreview,[t]:n}}))}catch(n){e(e=>({workspaceMergePreview:{...e.workspaceMergePreview,[t]:{available:!1,reason:n.message}}}))}},async fetchWorkspaceDiff(t){try{let n=await c(`GET`,`/workspaces/`+encodeURIComponent(t)+`/diff`);e(e=>({workspaceDiff:{...e.workspaceDiff,[t]:n}}))}catch(n){e(e=>({workspaceDiff:{...e.workspaceDiff,[t]:{available:!1,reason:n.message}}}))}},async fetchWorkspaceOrphans(){try{e({workspaceOrphans:(await c(`GET`,`/workspaces/orphans`)).orphans??[]})}catch{}},async reclaimWorkspaceOrphan(e){t().openConfirm(`Reclaim Orphan Worktree`,`Remove the orphaned worktree "${e.branch||e.worktreePath}" from disk? It has no live agent.`,async()=>{try{await c(`POST`,`/workspaces/orphans/reclaim`,{worktreePath:e.worktreePath,repoRoot:e.repoRoot,branch:e.branch}),t().showNotification(`Orphan reclaim dispatched`),await Promise.all([t().fetchWorkspaceOrphans(),t().fetchActivityEvents()])}catch(e){t().showError(`Reclaim Failed`,e.message)}})},async workspaceAction(e,n){let r=n===`ready`?`Mark ready`:n===`request-review`?`Request review`:n===`merge-plan`?`Mark merge planned`:n===`merge`?`Merge`:n===`abandon`?`Abandon`:`Cleanup`,i=async()=>{try{await c(`POST`,`/workspaces/`+encodeURIComponent(e)+`/actions`,{action:n}),t().showNotification(n===`cleanup`?`Workspace cleanup requested`:n===`merge`?`Workspace merge dispatched`:`Workspace updated: ${r}`),await Promise.all([t().fetchWorkspaces(),t().fetchOrchestrators(),t().fetchActivityEvents()])}catch(e){t().showError(`Workspace Action Failed`,e.message)}};if(n===`cleanup`||n===`abandon`||n===`merge`){let r=t().workspaces.find(t=>t.id===e),a=r?.branch||r?.worktreePath||e;if(n===`merge`){let n=t().workspaceMergePreview[e],r=n&&n.available!==!1?` — ${n.strategy===`pr`?`opens a PR`:`rebases & fast-forwards into ${n.baseRef||`base`}, then deletes the branch`}.`:` — lands the work and deletes the branch.`;t().openConfirm(`Merge Workspace`,`Merge workspace "${a}"?${r}`,i);return}if(n===`cleanup`){await t().fetchWorkspaceGitState(e);let n=t().workspaceGitState[e],r=``;if(n&&n.available!==!1&&!n.missing){let e=n.ahead??0,t=n.dirtyCount??0;(e>0||t>0)&&(r=` ⚠ This destroys ${[e>0?`${e} unmerged commit(s)`:``,t>0?`${t} uncommitted change(s)`:``].filter(Boolean).join(` and `)}.`)}t().openConfirm(`Cleanup Workspace`,`Remove the worktree for "${a}" on the host?${r}`,i);return}t().openConfirm(`Abandon Workspace`,`Abandon workspace "${a}"?`,i);return}await i()},async purgeWorkspace(e){let n=t().workspaces.find(t=>t.id===e),r=n?.branch||n?.worktreePath||e;t().openConfirm(`Purge Workspace Record`,`Permanently remove the record for "${r}"? This only clears the dashboard row — it does not touch disk.`,async()=>{try{await c(`DELETE`,`/workspaces/`+encodeURIComponent(e)),t().showNotification(`Workspace record purged`),await Promise.all([t().fetchWorkspaces(),t().fetchActivityEvents()])}catch(e){t().showError(`Purge Failed`,e.message)}})}}),sn=(e,t)=>({memories:[],memoryTotal:0,memoryBrokerInfo:null,memoryStats:null,memoryFilters:{search:``,type:``,scope:``,tags:``,visibility:``,minRelevance:`0`},selectedMemoryId:``,memoryLoading:!1,async refreshMemory(){await Promise.all([t().fetchMemoryBroker(),t().fetchMemoryStats(),t().fetchMemories()])},async fetchMemoryBroker(){try{e({memoryBrokerInfo:await c(`GET`,`/memories/broker`)})}catch(e){t().showError(`Memory Broker Failed`,e.message)}},async fetchMemoryStats(){try{e({memoryStats:await c(`GET`,`/memories/stats`)})}catch{}},async fetchMemories(){let n=t().memoryFilters,r={limit:100};if(n.type&&(r.type=n.type),n.scope.trim()&&(r.scope=n.scope.trim()),n.visibility&&(r.visibility=n.visibility),n.tags.trim()&&(r.tags=n.tags.split(`,`).map(e=>e.trim()).filter(Boolean)),n.minRelevance.trim()!==``){let e=Number(n.minRelevance);Number.isFinite(e)&&(r.minRelevance=Math.max(0,Math.min(1,e)))}e({memoryLoading:!0});try{let n=await c(`POST`,`/memories/search`,r),i=n.memories.some(e=>e.id===t().selectedMemoryId)?t().selectedMemoryId:n.memories[0]?.id||``;e({memories:n.memories,memoryTotal:n.total,selectedMemoryId:i})}catch(e){t().showError(`Memory Search Failed`,e.message)}finally{e({memoryLoading:!1})}},async saveMemory(n,r){try{e({selectedMemoryId:(r?await c(`PATCH`,`/memories/`+encodeURIComponent(r),n):await c(`POST`,`/memories`,n)).id}),await Promise.all([t().fetchMemories(),t().fetchMemoryStats()]),t().showNotification(r?`Memory updated`:`Memory created`)}catch(e){t().showError(`Memory Save Failed`,e.message)}},deleteMemory(n){t().openConfirm(`Delete Memory`,`Delete memory "${n}"?`,async()=>{try{await c(`DELETE`,`/memories/`+encodeURIComponent(n)),e({selectedMemoryId:``}),await Promise.all([t().fetchMemories(),t().fetchMemoryStats()]),t().showNotification(`Memory deleted`)}catch(e){t().showError(`Delete Failed`,e.message)}})},async injectMemory(e){try{let n=await c(`POST`,`/memories/inject`,e);return t().showNotification(`Memory inject command sent to ${e.agentId}`),n}catch(e){return t().showError(`Memory Inject Failed`,e.message),null}}}),cn=(e,t)=>({projectFocusId:null,projectByCwd:{},async openProjectFocus(n){e({projectFocusId:n}),await t().switchView(`projects`)},consumeProjectFocus(){t().projectFocusId!==null&&e({projectFocusId:null})},async fetchProjectForCwd(n){if(!(!n||n in t().projectByCwd))try{let t=await c(`GET`,`/projects/resolve?cwd=`+encodeURIComponent(n));e(e=>({projectByCwd:{...e.projectByCwd,[n]:t.project??null}}))}catch{}}});function ln(){return $.persist.hasHydrated()?Promise.resolve():new Promise(e=>{let t=$.persist.onFinishHydration(()=>{t(),e()})})}var $=ue()(pe((...e)=>({...At({waitForHydration:ln})(...e),...jt(...e),...Mt(...e),...Bt(...e),...Gt(...e),...Kt(...e),...Yt(...e),...Zt(...e),...Qt(...e),...$t(...e),...Et(...e),...en(...e),...rn(...e),...Dt(...e),...an(...e),...on(...e),...sn(...e),...cn(...e)}),{name:`agent-relay-dashboard`,partialize:e=>({theme:e.theme,view:e.view,showOffline:e.showOffline,showBuiltIns:e.showBuiltIns,showReasoning:e.showReasoning,autoRefresh:e.autoRefresh,voiceTtsEnabled:e.voiceTtsEnabled,voiceTtsLang:e.voiceTtsLang,voiceTtsMode:e.voiceTtsMode,voiceTtsKokoroVoice:e.voiceTtsKokoroVoice,voiceTtsBrowserVoice:e.voiceTtsBrowserVoice,voiceInputMode:e.voiceInputMode,agentSort:e.agentSort,agentSortDir:e.agentSortDir,agentPresetFilter:e.agentPresetFilter,agentStatusFilter:e.agentStatusFilter,agentTagFilter:e.agentTagFilter,agentHostFilter:e.agentHostFilter,pairStatusFilter:e.pairStatusFilter,inboxSort:e.inboxSort,inboxSortDir:e.inboxSortDir,inboxShowArchived:e.inboxShowArchived,chatAgentProviderFilter:e.chatAgentProviderFilter,chatAgentStatusFilter:e.chatAgentStatusFilter,chatAgentTagFilter:e.chatAgentTagFilter,chatAgentCapFilter:e.chatAgentCapFilter,chatAgentHostFilter:e.chatAgentHostFilter,chatAgentSort:e.chatAgentSort,chatAgentSortDir:e.chatAgentSortDir,chatAgentGroupBy:e.chatAgentGroupBy,chatAgentFiltersCollapsed:e.chatAgentFiltersCollapsed,chatCollapsedChildren:e.chatCollapsedChildren,feedObserveAll:e.feedObserveAll,coordinatorFollows:e.coordinatorFollows,coordinatorMutes:e.coordinatorMutes,planCollapsed:e.planCollapsed,sessionTasksCollapsed:e.sessionTasksCollapsed,activityFilter:e.activityFilter,analyticsPeriod:e.analyticsPeriod,memoryFilters:e.memoryFilters,authToken:e.authToken,inboxReadCursors:e.inboxReadCursors,inboxArchivedThreads:e.inboxArchivedThreads,inboxDrafts:e.inboxDrafts,chatStatusEvents:e.chatStatusEvents,operatorActivity:e.operatorActivity,notifications:e.notifications,notificationUnread:e.notificationUnread,notificationSettings:e.notificationSettings,spawnOrchId:e.spawnOrchId,spawnProvider:e.spawnProvider,spawnModel:e.spawnModel,spawnEffort:e.spawnEffort,spawnProfile:e.spawnProfile,spawnCwd:e.spawnCwd,spawnApproval:e.spawnApproval,spawnWorkspaceMode:e.spawnWorkspaceMode,spawnCwdHistory:e.spawnCwdHistory})}));$.subscribe(kt);export{De as _,Ze as a,z as c,N as d,je as f,Ee as g,ke as h,Z as i,L as l,we as m,qt as n,Qe as o,Me as p,X as r,R as s,$ as t,ze as u,Ae as v,M as y};
|
|
9
|
-
//# sourceMappingURL=store-BuuJUn70.js.map
|