@suveren/gateway 0.3.4 → 0.3.5
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.
|
@@ -66,7 +66,7 @@ Watch out — What should the agent avoid or be careful about?`;function Vv(e,t,
|
|
|
66
66
|
.profile-grid .card { display: flex; flex-direction: column; height: 100%; margin-top: 0 !important; }
|
|
67
67
|
@media (max-width: 900px) { .profile-grid { grid-template-columns: repeat(2, 1fr); } }
|
|
68
68
|
@media (max-width: 560px) { .profile-grid { grid-template-columns: 1fr; } }
|
|
69
|
-
`}),f?a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem"},children:"Loading..."}):g.length===0?a.jsxs("div",{className:"card",style:{padding:"2rem",textAlign:"center"},children:[a.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9rem",marginBottom:"1rem"},children:"No integrations set up yet. Connect a service first."}),a.jsx(Je,{to:"/integrations",className:"btn btn-primary btn-sm",onClick:()=>e==null?void 0:e(),children:"Go to Integrations"})]}):a.jsx("div",{className:"profile-grid",children:g.map(k=>{const N=S(k.id),C=k.id.replace(/@.*$/,"").split("/").pop()??k.id,T=h.get(C),H=m.get(C),W=(H==null?void 0:H.running)===!0;return a.jsxs("div",{className:"card",style:W?void 0:{opacity:.7},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.125rem"},children:[a.jsx("h3",{className:"card-title",style:{margin:0},children:Ee(k.id,k.name)}),N?a.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Team"}):a.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--bg-main)",color:"var(--text-tertiary)",fontWeight:600,border:"1px solid var(--border)"},children:"Personal"})]}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"1rem",flex:1},children:k.description}),W?a.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>P(k.id),children:"Authorize"}):a.jsxs(Je,{to:`/integrations?setup=${(T==null?void 0:T.id)??""}`,className:"btn btn-secondary btn-sm",style:{textDecoration:"none",textAlign:"center"},onClick:()=>e==null?void 0:e(),children:["Set up ",(T==null?void 0:T.name)??"integration"]})]},k.id)})})]})}const ny={active:"Active",pending:"Pending",expired:"Expired",revoked:"Revoked"};function ry({status:e,label:t}){return a.jsx("span",{className:`status-badge status-${e}`,children:t||ny[e]})}function oy({domain:e,attested:t}){const n=t===!0?"domain-attested":t===!1?"domain-missing":"";return a.jsx("span",{className:`domain-badge ${n}`,style:{fontSize:"0.75rem"},children:e})}const yn=86400,Nr=3600,Po=60,ay=30*yn;function sy(e){if(e<=0)return"Expired";if(e>90*yn){const t=Math.floor(e/ay);return`${t} ${t===1?"month":"months"} remaining`}if(e>7*yn){const t=Math.floor(e/yn);return`${t} ${t===1?"day":"days"} remaining`}if(e>=2*yn){const t=Math.floor(e/yn),n=Math.floor(e%yn/Nr);return`${t} ${t===1?"day":"days"} ${n}h remaining`}if(e>=2*Nr){const t=Math.floor(e/Nr),n=Math.floor(e%Nr/Po);return`${t}h ${String(n).padStart(2,"0")}m remaining`}if(e>=Po){const t=Math.floor(e/Po),n=Math.floor(e%Po);return`${t}m ${String(n).padStart(2,"0")}s remaining`}return`${Math.floor(e)}s remaining`}function iy({expiresAt:e}){const[t,n]=d.useState(()=>e-Date.now()/1e3),r=t<2*Nr;d.useEffect(()=>{const s=setInterval(()=>n(e-Date.now()/1e3),r?1e3:6e4);return()=>clearInterval(s)},[e,r]);const o=t<300;return a.jsx("span",{className:`ttl-badge ${o?"ttl-warn":"ttl-ok"}`,children:sy(t)})}function Bf({icon:e,title:t,text:n,children:r}){return a.jsxs("div",{className:"empty-state",children:[e&&a.jsx("div",{className:"empty-state-icon",children:e}),a.jsx("div",{className:"empty-state-title",children:t}),n&&a.jsx("div",{className:"empty-state-text",children:n}),r]})}function ly(e){const t=Math.floor(e/86400);if(t>=1)return`${t} day${t===1?"":"s"}`;const n=Math.floor(e/3600);if(n>=1)return`${n} hour${n===1?"":"s"}`;const r=Math.ceil(e/60);return`${r} minute${r===1?"":"s"}`}const cy=[{label:"30m",seconds:1800},{label:"1h",seconds:3600},{label:"2h",seconds:7200},{label:"4h",seconds:14400},{label:"8h",seconds:28800},{label:"24h",seconds:86400},{label:"7d",seconds:604800},{label:"30d",seconds:2592e3},{label:"1y",seconds:31536e3}];function uy({item:e,onClose:t,onSuccess:n}){var h;const{user:r,activeDomain:o,groupId:s}=ze(),i=e.remaining_seconds??0,l=cy.filter(m=>m.seconds>i),c=((h=l[0])==null?void 0:h.seconds)??2592e3,[u,p]=d.useState(c),[f,v]=d.useState(!1),[y,x]=d.useState(""),w=Object.entries(e.frame).filter(([m])=>m!=="profile"&&m!=="path"),j=async()=>{var m;if(r){v(!0),x("");try{const g=e.authorization_id,S=await O.getGateContent(g);if(!S)throw new Error("Gate content not found locally. The MCP server may have restarted. Please re-authorize through the full wizard instead.");const E=await O.getProfile(e.profile_id),P=e.frame,k=S.context??{},N=e.attested_domains[0]||o||"owner",C=await Ho(P,E),T=await Ff(k,E),[H,W]=await Promise.all([va(S.gateContent.intent),va(JSON.stringify({profile:e.profile_id,path:e.path,domain:N}))]);if(!s)throw new Error("No active group; cannot extend authorization.");const D=(((m=e.deferred_commitment_domains)==null?void 0:m.length)??0)>0?"review":"automatic",_=await O.attest({authorization_id:e.authorization_id,renew:!0,profile_id:e.profile_id,bounds:P,bounds_hash:C,context_hash:T,domain:N,did:r.did,gate_content_hashes:{intent:H},execution_context_hash:W,group_id:s,commitment_mode:D,ttl:u});await O.pushGateContent(Of(_,{boundsHash:C,contextHash:T,context:k,path:e.path,gateContent:S.gateContent})),n()}catch(g){x(g instanceof Error?g.message:"Extension failed")}finally{v(!1)}}};return a.jsx("div",{className:"modal-backdrop",onClick:m=>m.target===m.currentTarget&&t(),children:a.jsxs("div",{className:"modal",children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h3",{className:"modal-title",children:"Extend Authorization"}),a.jsx("button",{className:"modal-close",onClick:t,children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsxs("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:[Ee(e.profile_id)," / ",e.path]}),w.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:w.map(([m,g])=>`${m}=${g}`).join(" · ")})]}),a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.5rem"},children:"New duration"}),i>0&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["Currently valid for ",ly(i),". Only longer durations are shown."]}),a.jsx("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:l.length===0?a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This authorization is already on the longest available duration. Nothing to extend."}):l.map(m=>a.jsx("button",{className:`btn ${u===m.seconds?"btn-primary":"btn-secondary"}`,onClick:()=>p(m.seconds),style:{minWidth:"3.5rem"},children:m.label},m.seconds))})]}),a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Same bounds, context, and gate content will be re-attested with a new TTL (measured from now)."}),y&&a.jsx("div",{className:"error-message",children:y})]}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-secondary",onClick:t,disabled:f,children:"Cancel"}),a.jsx("button",{className:"btn btn-primary",onClick:j,disabled:f,children:f?"Extending...":"Extend"})]})]})})}function dy(e,t,n){return[...e].sort((r,o)=>{if(n){if(r.authorization_id===n&&o.authorization_id!==n)return-1;if(o.authorization_id===n&&r.authorization_id!==n)return 1}const s=Ct(r,{revokedSet:t}),i=Ct(o,{revokedSet:t}),l={active:0,pending:1,expired:2,revoked:3};return l[s]!==l[i]?l[s]-l[i]:new Date(o.created_at).getTime()-new Date(r.created_at).getTime()})}function fy({item:e,revokedSet:t,expandedHash:n,gateCache:r,gateLoading:o,copiedHash:s,revokingHash:i,copyingHash:l,profileConfigCache:c,mode:u,ownerLabel:p,isAdmin:f,onExpand:v,onCopyHash:y,onCopy:x,onRevoke:w,onExtend:j,highlightHash:h}){var $;const m=Ct(e,{revokedSet:t}),g=n===e.authorization_id,S=r[e.authorization_id],E=m==="active"||m==="pending"||m==="expired",P=Object.entries(e.frame).filter(([L])=>L!=="profile"&&L!=="path"),k=c.get(e.profile_id)??null,N=((($=k==null?void 0:k.approvers)==null?void 0:$.length)??0)>0,C=new Map;if(k!=null&&k.caps&&u==="team")for(const[L,V]of P){const ee=k.caps[L];ee!==void 0&&Number(V)>ee&&C.set(L,{authorized:Number(V),cap:ee})}const T=C.size>0,H=e.approvers_frozen??[],W=(k==null?void 0:k.approvers)??[],D=u==="team"&&H.length>0&&W.length>0&&(H.length!==W.length||H.some(L=>!W.includes(L))||W.some(L=>!H.includes(L))),_=Array.from(C.entries()).map(([L,V])=>`${L}: ${V.authorized} (cap ${V.cap})`).join(", "),B=Array.from(C.entries()).map(([L,V])=>`${L}: ${V.authorized} → ${V.cap}`).join(", "),X=T?N?C.size===1?`Above team cap: ${_} — actions require approval`:`Above team cap (${C.size}): ${_} — actions require approval`:C.size===1?`Reduced by hard cap: ${B}`:`Reduced by hard cap (${C.size}): ${B}`:"",se=T?N?"Above-cap actions under this authority require per-action approval from the profile's approvers. Bounds remain authorized at their original values.":"No approvers are configured for this profile, so the team cap is a hard ceiling. Bounds above the cap are effectively reduced to the cap. Ask the admin to raise the cap or add approvers, or copy this authorization to reissue within the cap.":void 0,z=Ee(e.profile_id),R=h!=null&&e.authorization_id===h;return a.jsxs("div",{className:`card${R?" card-highlight":""}`,style:{marginBottom:0},children:[p&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner: ",a.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:p})]}),a.jsxs("div",{className:"auth-card-header",children:[a.jsx("span",{style:{fontWeight:700,fontSize:"1rem",color:"var(--text-primary)",letterSpacing:"0.01em"},children:z}),e.title&&a.jsx("span",{style:{fontWeight:500,fontSize:"0.85rem",color:"var(--text-secondary)"},children:e.title}),a.jsx(ry,{status:m}),m==="active"&&e.earliest_expiry&&a.jsx(iy,{expiresAt:new Date(e.earliest_expiry).getTime()/1e3}),m==="expired"&&a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:new Date(e.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem",alignItems:"center"},children:[e.required_domains.map(L=>a.jsx(oy,{domain:L,attested:e.attested_domains.includes(L)},L)),e.deferred_commitment_domains.length>0&&a.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Review Mode"}),T&&a.jsx("span",{title:se,style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:N?"var(--accent-subtle)":"var(--danger-subtle)",color:N?"var(--accent)":"var(--danger)",fontWeight:600,cursor:"help"},children:X}),D&&a.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.65rem",padding:"0.15rem 0.5rem",borderRadius:"0.25rem",background:"var(--warning-subtle, rgba(234,179,8,0.12))",color:"var(--warning, #ca8a04)",fontWeight:600,border:"1px solid var(--warning-border, rgba(234,179,8,0.3))",cursor:"pointer",lineHeight:1.4},onClick:()=>x(e),disabled:l===e.authorization_id,title:"The approver list for this profile has changed since this authority was created. Copy to reissue with the current approvers.",children:l===e.authorization_id?"Copying...":"Approver list updated · Copy with new approvers"})]}),P.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:P.map(([L,V],ee)=>{const J=C.get(L);return a.jsxs("span",{children:[ee>0&&" · ",J?N?a.jsxs("span",{title:`Team cap on ${L} is ${J.cap}. Actions exceeding the cap require per-action approval. Bound remains authorized at ${J.authorized}.`,children:[a.jsxs("span",{style:{color:"var(--text-tertiary)"},children:[L,"=",String(V)]}),a.jsxs("span",{style:{color:"var(--accent)",marginLeft:"0.25rem",fontWeight:600},children:["↑ approval at ",J.cap]})]}):a.jsxs("span",{title:`Team cap on ${L} is ${J.cap} with no approvers configured (hard cap). Authorized for ${J.authorized}; effective ${J.cap}.`,children:[a.jsxs("span",{style:{textDecoration:"line-through",color:"var(--text-tertiary)"},children:[L,"=",String(V)]}),a.jsxs("span",{style:{color:"var(--danger)",marginLeft:"0.25rem",fontWeight:600},children:["→"," ",J.cap]})]}):a.jsxs("span",{children:[L,"=",String(V)]})]},L)})}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>v(e),children:g?"▲ Hide Details":"▼ Details"})}),g&&a.jsxs("div",{style:{borderTop:"1px solid var(--border)",marginTop:"0.75rem",paddingTop:"0.75rem"},children:[P.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Bounds"}),a.jsx("dl",{className:"review-grid",children:P.map(([L,V])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:L}),a.jsx("dd",{children:String(V)})]},L))})]}),(S==null?void 0:S.context)&&Object.keys(S.context).length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Context"}),a.jsx("dl",{className:"review-grid",children:Object.entries(S.context).map(([L,V])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:L}),a.jsx("dd",{children:String(V)})]},L))})]}),a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Intent"}),o===e.authorization_id?a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Loading gate content..."}):S?a.jsx("div",{className:"gate-content-block",children:a.jsx("div",{className:"gate-content-item",children:a.jsx("div",{className:"gate-content-text",children:S.gateContent.intent})})}):a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Gate content not available."}),a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"1rem"},children:["Created: ",new Date(e.created_at).toLocaleString(),e.earliest_expiry&&` · Expires: ${new Date(e.earliest_expiry).toLocaleString()}`]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all"},children:e.authorization_id}),a.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.7rem",padding:"0.125rem 0.375rem"},onClick:()=>y(e.authorization_id),children:s===e.authorization_id?"copied":"copy"})]}),a.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.75rem"},children:[!p&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),disabled:l===e.authorization_id,title:"Start a new authorization pre-filled with these bounds, context, and intent",children:l===e.authorization_id?"Copying…":"⧉ Copy"}),!p&&E&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>j(e),children:"↻ Extend"}),p&&f&&m!=="revoked"?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>w(e.authorization_id,p,z),disabled:i===e.authorization_id,children:i===e.authorization_id?"Revoking…":"Revoke"}):!p&&(m==="active"||m==="pending")?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>w(e.authorization_id),disabled:i===e.authorization_id,children:i===e.authorization_id?"Revoking…":"Revoke"}):null]})]})]},e.authorization_id)}function my(){const[e,t]=d.useState([]),[n,r]=d.useState(!0),[o,s]=d.useState([]),[i,l]=d.useState(!1),[c,u]=d.useState("mine"),[p,f]=d.useState("active"),[v,y]=d.useState(null),[x,w]=d.useState(null),[j,h]=zf(),[m,g]=d.useState(()=>j.get("new")==="1"),[S,E]=d.useState(()=>j.get("highlight")),[P,k]=d.useState(null),[N,C]=d.useState({}),[T,H]=d.useState(null),[W,D]=d.useState(null),[_,B]=d.useState(null),[X,se]=d.useState(new Set),[z,R]=d.useState(null),[$,L]=d.useState(null),V=Wt(),{group:ee,groupId:J,domain:je,mode:b,activeTeam:U}=ze(),A=(U==null?void 0:U.isAdmin)===!0,[I,Y]=d.useState(()=>new Map),xe=d.useCallback(()=>{r(!0),O.getMyAttestations().then(t).catch(()=>{}).finally(()=>r(!1))},[]),Pe=d.useCallback(()=>{J&&(l(!0),O.listTeamAuthorizations(J).then(s).catch(()=>{}).finally(()=>l(!1)))},[J]);fe("attestation-changed",()=>{xe(),A&&J&&Pe()}),d.useEffect(()=>{if(!S)return;j.get("highlight")&&(j.delete("highlight"),h(j,{replace:!0}));const G=window.setTimeout(()=>E(null),3e3);return()=>window.clearTimeout(G)},[]),$t(xe,3e5),d.useEffect(()=>{c==="team"&&A&&J&&o.length===0&&!i&&Pe()},[c,A,J,o.length,i,Pe]),d.useEffect(()=>{if(b!=="team"||!J)return;const G=c==="mine"?e:o;if(G.length===0)return;const F=[...new Set(G.map(Q=>Q.profile_id))].filter(Q=>!I.has(Q));if(F.length!==0){Y(Q=>{const q=new Map(Q);for(const oe of F)q.set(oe,null);return q});for(const Q of F)O.getTeamProfileConfig(J,Q).then(q=>{Y(oe=>new Map(oe).set(Q,q))}).catch(()=>{})}},[e,o,c,J,b,I]);const ke=async G=>{if(P===G.authorization_id){k(null);return}k(G.authorization_id);const F=G.authorization_id;if(!(F in N)){H(G.authorization_id);try{const Q=await O.getGateContent(F);C(q=>({...q,[F]:Q}))}catch{C(Q=>({...Q,[F]:null}))}finally{H(null)}}},mn=G=>{navigator.clipboard.writeText(G).then(()=>{B(G),setTimeout(()=>B(null),2e3)})},Rn=async G=>{var F;if(!J){alert("No active group; cannot copy authorization.");return}L(G.authorization_id);try{const Q=G.authorization_id;let q=N[Q]??null;Q in N||(q=await O.getGateContent(Q),C(_e=>({..._e,[Q]:q})));const oe=Object.fromEntries(Object.entries(G.frame).filter(([_e])=>_e!=="profile"&&_e!=="path")),pn=(q==null?void 0:q.context)??{},Ye=((F=q==null?void 0:q.gateContent)==null?void 0:F.intent)??"",mt=G.deferred_commitment_domains.length>0?"review":"automatic",Tt=G.attested_domains[0]||je||"owner";sessionStorage.setItem("agentAuth",JSON.stringify({profileId:G.profile_id,groupId:J,groupName:(ee==null?void 0:ee.name)??null,domain:Tt})),sessionStorage.setItem("agentGate",JSON.stringify({bounds:oe,context:pn,gateContent:{intent:Ye},templateMode:mt})),V("/agent/gate")}catch(Q){alert(Q instanceof Error?Q.message:"Failed to copy authorization")}finally{L(null)}},Pt=async(G,F,Q)=>{const q=F&&Q?`Revoke ${F}'s ${Q} authorization? This cannot be undone.`:"Revoke this authorization? The agent will no longer be able to execute actions under this attestation.";if(confirm(q)){R(G);try{await O.revokeAttestation(G),se(oe=>new Set(oe).add(G)),F&&J&&Pe()}catch(oe){alert(oe instanceof Error?oe.message:"Failed to revoke authorization")}finally{R(null)}}},Ue=c==="mine"?e:o,dr=c==="mine"?n:i,Ht={active:Ue.filter(G=>Ct(G,{revokedSet:X})==="active").length,pending:Ue.filter(G=>Ct(G,{revokedSet:X})==="pending").length,expired:Ue.filter(G=>Ct(G,{revokedSet:X})==="expired").length,revoked:Ue.filter(G=>Ct(G,{revokedSet:X})==="revoked").length},ne=(()=>{const G=new Map;for(const F of Ue){if(Ct(F,{revokedSet:X})!==p)continue;const Q=G.get(F.profile_id)??{count:0,review:!1};Q.count+=1,F.deferred_commitment_domains.length>0&&(Q.review=!0),G.set(F.profile_id,Q)}return Array.from(G.entries()).map(([F,Q])=>({profileId:F,...Q})).sort((F,Q)=>Ee(F.profileId).localeCompare(Ee(Q.profileId)))})(),ft=dy(Ue.filter(G=>{if(Ct(G,{revokedSet:X})!==p||v!==null&&G.profile_id!==v)return!1;if(x!==null){const F=G.deferred_commitment_domains.length>0;if(x==="review"&&!F||x==="auto"&&F)return!1}return!0}),X,S),lo={revokedSet:X,expandedHash:P,gateCache:N,gateLoading:T,copiedHash:_,revokingHash:z,copyingHash:$,profileConfigCache:I,mode:b,activeDomain:je,group:ee,groupId:J,onExpand:ke,onCopyHash:mn,onCopy:Rn,onRevoke:Pt,onExtend:D,highlightHash:S};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("h1",{className:"page-title",children:"Authorizations"}),a.jsx("p",{className:"page-subtitle",children:"Active, pending, and expired agent authorizations."})]}),a.jsx("button",{className:"btn btn-primary",onClick:()=>g(!0),children:"+ New authorization"})]}),m&&a.jsx("div",{className:"modal-backdrop",onClick:()=>{g(!1),j.get("new")&&(j.delete("new"),h(j,{replace:!0}))},children:a.jsxs("div",{className:"modal",onClick:G=>G.stopPropagation(),style:{maxWidth:"960px",width:"90vw"},children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h2",{className:"modal-title",children:"New authorization"}),a.jsx("button",{className:"modal-close",onClick:()=>{g(!1),j.get("new")&&(j.delete("new"),h(j,{replace:!0}))},children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem",marginTop:0,marginBottom:"1rem"},children:"What should your agent be able to do? Pick a profile, set limits, then authorize."}),a.jsx(ty,{onDismiss:()=>g(!1)})]})]})}),A&&a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"0.5rem"},children:[a.jsx("button",{className:`nav-tab${c==="mine"?" active":""}`,onClick:()=>{u("mine"),f("active"),y(null),w(null),k(null)},children:"Mine"}),a.jsx("button",{className:`nav-tab${c==="team"?" active":""}`,onClick:()=>{u("team"),f("active"),y(null),w(null),k(null)},children:"Team"})]}),a.jsx("div",{className:"nav-tabs",children:["active","pending","expired","revoked"].map(G=>a.jsxs("button",{className:`nav-tab${p===G?" active":""}`,onClick:()=>{f(G),y(null),w(null)},children:[G.charAt(0).toUpperCase()+G.slice(1)," (",Ht[G],")"]},G))}),ne.length>0&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center",marginTop:"-0.25rem",marginBottom:"1rem"},children:[ne.map(G=>{const F=v===G.profileId;return a.jsx("button",{className:`btn btn-sm ${F?"btn-primary":"btn-secondary"}`,onClick:()=>y(F?null:G.profileId),children:Ee(G.profileId)},G.profileId)}),a.jsx("span",{"aria-hidden":"true",style:{color:"var(--border)",fontSize:"1.1rem",padding:"0 0.25rem",userSelect:"none"},children:"|"}),["auto","review"].map(G=>{const F=x===G;return a.jsx("button",{className:`btn btn-sm ${F?"btn-primary":"btn-secondary"}`,onClick:()=>w(F?null:G),children:G==="auto"?"Auto":"Review"},G)})]}),dr&&Ue.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):ft.length===0?a.jsx(Bf,{icon:"☰",title:"No authorizations",text:`No ${p} authorizations found.`}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:ft.map(G=>{const F=c==="team"?G:null,Q=F!=null&&F.owner?F.owner.name??F.owner.email??F.owner.userId:void 0;return a.jsx(fy,{item:G,ownerLabel:Q,isAdmin:A,...lo},G.authorization_id)})}),W&&a.jsx(uy,{item:W,onClose:()=>D(null),onSuccess:()=>{D(null),xe()}})]})}function Df({profileId:e}){return a.jsx("span",{className:"profile-badge",children:Ee(e)})}function py(e){return new Date(e*1e3).toLocaleString()}function hy(e,t){if(t==="all")return!0;const n=t==="1d"?1:t==="7d"?7:30,r=Math.floor(Date.now()/1e3)-n*86400;return e.timestamp>=r}function gy(e,t){if(!t)return!0;const n=t.toLowerCase();return e.profileId.toLowerCase().includes(n)||Ee(e.profileId).toLowerCase().includes(n)||e.path.toLowerCase().includes(n)||e.action.toLowerCase().includes(n)||e.attestationHash.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||JSON.stringify(e.executionContext).toLowerCase().includes(n)}function Vc(e,t){const n=new Map(e.map(r=>[r.id,r]));for(const r of t)n.set(r.id,r);return[...n.values()].sort((r,o)=>o.timestamp-r.timestamp)}function vy(){const{activeTeam:e,groupId:t}=ze(),n=(e==null?void 0:e.isAdmin)===!0,[r,o]=d.useState("mine"),[s,i]=d.useState([]),[l,c]=d.useState(!0),[u,p]=d.useState({}),[f,v]=d.useState(new Set),[y,x]=d.useState(""),[w,j]=d.useState(new Set),[h,m]=d.useState(new Set),[g,S]=d.useState("all"),[E,P]=d.useState(!1),[k,N]=d.useState(null),[C,T]=d.useState(!1),[H,W]=d.useState(!1),D=d.useRef(""),_=d.useCallback(b=>r==="team"&&n&&t?O.listTeamReceiptsPage(t,{before:b,limit:200}):O.getMyReceiptsPage({before:b,limit:200}),[r,n,t]),B=d.useCallback(()=>{const b=r==="team"?`team:${t}`:"mine",U=D.current!==b;D.current=b,c(!0),W(!1),_().then(A=>{i(I=>U?A.receipts:Vc(I,A.receipts)),N(I=>U?A.nextBefore:I??A.nextBefore)}).catch(()=>{U&&i([]),W(!0)}).finally(()=>c(!1))},[_,r,t]),X=d.useCallback(()=>{!k||C||(T(!0),W(!1),_(k).then(b=>{i(U=>Vc(U,b.receipts)),N(b.nextBefore)}).catch(()=>W(!0)).finally(()=>T(!1)))},[k,C,_]);$t(B,12e4),d.useEffect(()=>{r!=="team"||Object.keys(u).length>0||O.listUsers().then(b=>{const U={};for(const A of b)U[A.id]={name:A.name,email:A.email};p(U)}).catch(()=>{})},[r,u]);const se=d.useMemo(()=>{const b=new Set;for(const U of s)b.add(Ee(U.profileId));return[...b].sort()},[s]),z=d.useMemo(()=>{const b=new Set;for(const U of s)b.add(U.action);return[...b].sort()},[s]),R=d.useMemo(()=>{if(r!=="team")return[];const b=new Set;for(const U of s)U.userId&&b.add(U.userId);return[...b].map(U=>{var A;return{id:U,label:(A=u[U])!=null&&A.name?`${u[U].name} (${u[U].email})`:U}}).sort((U,A)=>U.label.localeCompare(A.label))},[r,s,u]),$=d.useMemo(()=>s.filter(b=>!(!gy(b,y)||w.size>0&&!w.has(Ee(b.profileId))||h.size>0&&!h.has(b.action)||f.size>0&&b.userId&&!f.has(b.userId)||!hy(b,g))),[s,y,w,h,f,g]),L=w.size>0||h.size>0||f.size>0||g!=="all";function V(b){j(U=>{const A=new Set(U);return A.has(b)?A.delete(b):A.add(b),A})}function ee(b){m(U=>{const A=new Set(U);return A.has(b)?A.delete(b):A.add(b),A})}function J(b){v(U=>{const A=new Set(U);return A.has(b)?A.delete(b):A.add(b),A})}function je(){j(new Set),m(new Set),v(new Set),S("all"),x("")}return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"Receipts"}),a.jsx("p",{className:"page-subtitle",children:"Execution history for agent actions."})]}),n&&a.jsx("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"1rem",borderBottom:"1px solid var(--border)"},children:["mine","team"].map(b=>a.jsx("button",{onClick:()=>o(b),className:"btn btn-ghost",style:{borderRadius:0,padding:"0.5rem 0.875rem",borderBottom:r===b?"2px solid var(--accent)":"2px solid transparent",color:r===b?"var(--text-primary)":"var(--text-tertiary)",fontWeight:r===b?600:500},children:b==="mine"?"Mine":"Team"},b))}),a.jsxs("div",{className:"search-filter-bar",children:[a.jsxs("div",{className:"search-input-wrap",children:[a.jsx("span",{className:"search-icon",children:"⌕"}),a.jsx("input",{type:"text",className:"form-input search-input",placeholder:"Search by profile, action, path, or hash\\u2026",value:y,onChange:b=>x(b.target.value)}),y&&a.jsx("button",{className:"search-clear",onClick:()=>x(""),children:"×"})]}),a.jsxs("button",{className:`btn btn-sm btn-secondary${E?" active":""}`,onClick:()=>P(!E),children:["Filters",L?` (${w.size+h.size+(g!=="all"?1:0)})`:""]})]}),E&&a.jsxs("div",{className:"filter-panel",children:[se.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Profile"}),a.jsx("div",{className:"filter-chips",children:se.map(b=>a.jsx("button",{className:`filter-chip${w.has(b)?" selected":""}`,onClick:()=>V(b),children:b},b))})]}),z.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Action"}),a.jsx("div",{className:"filter-chips",children:z.map(b=>a.jsx("button",{className:`filter-chip${h.has(b)?" selected":""}`,onClick:()=>ee(b),children:b},b))})]}),r==="team"&&R.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Owner"}),a.jsx("div",{className:"filter-chips",children:R.map(b=>a.jsx("button",{className:`filter-chip${f.has(b.id)?" selected":""}`,onClick:()=>J(b.id),children:b.label},b.id))})]}),a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Time range"}),a.jsx("div",{className:"filter-chips",children:[["1d","Today"],["7d","7 days"],["30d","30 days"],["all","All time"]].map(([b,U])=>a.jsx("button",{className:`filter-chip${g===b?" selected":""}`,onClick:()=>S(b),children:U},b))})]})]}),L&&a.jsxs("div",{className:"active-filters",children:[[...w].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>V(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...h].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>ee(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...f].map(b=>{const U=u[b],A=U?U.name:b;return a.jsxs("span",{className:"active-chip",onClick:()=>J(b),children:[A," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)}),g!=="all"&&a.jsxs("span",{className:"active-chip",onClick:()=>S("all"),children:[g==="1d"?"Today":g==="7d"?"7 days":"30 days"," ",a.jsx("span",{className:"chip-remove",children:"×"})]}),a.jsx("button",{className:"clear-filters",onClick:je,children:"Clear all"})]}),H&&a.jsx("div",{className:"card",style:{borderColor:"var(--danger, #c0392b)",marginBottom:"0.75rem"},children:a.jsx("span",{style:{color:"var(--danger, #c0392b)",fontSize:"0.85rem"},children:"Couldn’t load receipts — your session may have expired. Try signing out and back in."})}),l&&s.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):$.length===0?a.jsx(Bf,{icon:"⌕",title:s.length===0?"No receipts in the last 30 days":"No matching receipts",text:s.length===0?"Execution receipts appear here after an agent uses an authorized tool. Older receipts can be loaded below.":"Try adjusting your search or filters."}):a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:$.length===s.length?`${s.length} receipt${s.length!==1?"s":""}`:`${$.length} of ${s.length} receipts`}),a.jsx("div",{className:"timeline",children:$.map(b=>{var U;return a.jsx("div",{className:"timeline-event",children:a.jsxs("div",{className:"card",style:{marginBottom:0},children:[a.jsxs("div",{className:"auth-card-header",children:[a.jsx(Df,{profileId:b.profileId}),a.jsx("span",{className:"auth-card-path",children:b.path}),a.jsx("span",{className:"receipt-action",children:b.action}),a.jsx("span",{className:"auth-card-time",children:py(b.timestamp)})]}),r==="team"&&b.userId&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner:"," ",a.jsx("span",{style:{color:"var(--text-secondary)"},children:(U=u[b.userId])!=null&&U.name?`${u[b.userId].name} (${u[b.userId].email})`:b.userId})]}),Object.keys(b.executionContext).length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:Object.entries(b.executionContext).map(([A,I])=>`${A}=${I}`).join(" · ")}),a.jsxs("div",{style:{display:"flex",gap:"1rem",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:[a.jsxs("span",{children:["Daily: ",b.cumulativeState.daily.count," calls, $",b.cumulativeState.daily.amount]}),a.jsxs("span",{children:["Monthly: ",b.cumulativeState.monthly.count," calls, $",b.cumulativeState.monthly.amount]})]}),a.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all",marginTop:"0.375rem"},children:b.attestationHash})]})},b.id)})})]}),k&&a.jsx("div",{style:{textAlign:"center",marginTop:"1rem"},children:a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:X,disabled:C,children:C?"Loading…":"Load older"})})]})}const Kc={ollama:{provider:"ollama",endpoint:"http://localhost:11434",models:["gemma4:e4b","gemma4:e2b","gemma4:26b","gemma4:31b","llama3.2","llama3.1","mistral","qwen2.5"]},openrouter:{provider:"openai-compatible",endpoint:"https://openrouter.ai/api/v1",models:["google/gemma-4-31b-it","qwen/qwen3.6-plus:free","stepfun/step-3.5-flash:free","google/gemini-2.5-flash","openai/gpt-4o-mini","anthropic/claude-haiku-4"]},openai:{provider:"openai-compatible",endpoint:"https://api.openai.com/v1",models:["gpt-4o-mini","gpt-4o","o3-mini"]},groq:{provider:"openai-compatible",endpoint:"https://api.groq.com/openai/v1",models:["llama-3.1-8b-instant","llama-3.3-70b-versatile","gemma2-9b-it"]},together:{provider:"openai-compatible",endpoint:"https://api.together.xyz/v1",models:["meta-llama/Llama-3-8b-chat-hf","meta-llama/Llama-3-70b-chat-hf"]}};function yy(){const[e,t]=d.useState(""),[n,r]=d.useState("openrouter"),[o,s]=d.useState("openai-compatible"),[i,l]=d.useState("https://openrouter.ai/api/v1"),[c,u]=d.useState("google/gemma-4-31b-it"),[p,f]=d.useState(""),[v,y]=d.useState(!1),[x,w]=d.useState(!1),[j,h]=d.useState(!1),[m,g]=d.useState(null),S=d.useCallback(C=>{t(C),setTimeout(()=>t(""),3e3)},[]),E=d.useCallback(async()=>{try{const C=await O.getCredential("ai-config");if(y(C.configured),C.configured&&C.fields){C.fields.provider&&s(C.fields.provider),C.fields.endpoint&&l(C.fields.endpoint),C.fields.model&&u(C.fields.model);const T=C.fields.endpoint??"";T.includes("openai.com")?r("openai"):T.includes("groq.com")?r("groq"):T.includes("together.xyz")?r("together"):T.includes("openrouter.ai")?r("openrouter"):r("ollama")}}catch{}},[]);d.useEffect(()=>{E()},[E]);const P=C=>{r(C);const T=Kc[C];T&&(s(T.provider),l(T.endpoint),u(T.models[0]))},k=async()=>{w(!0);try{await O.setCredential("ai-config",{provider:o,endpoint:i,model:c,...p?{apiKey:p}:{}}),y(!0),S("AI configuration saved!")}catch{S("Failed to save AI config")}finally{w(!1)}},N=async()=>{h(!0),g(null);try{const C=await O.aiTest(p?{provider:o,endpoint:i,model:c,apiKey:p}:{});g(C.ok?`OK: ${C.message}`:`Failed: ${C.message}`)}catch(C){g(`Error: ${C instanceof Error?C.message:"Unknown"}`)}finally{h(!1)}};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"AI Assistant"}),a.jsx("p",{className:"page-subtitle",children:"Advisory AI to help you think through intent when authorizing agents."})]}),e&&a.jsx("div",{className:"alert alert-success",children:e}),a.jsxs("div",{className:"card",children:[a.jsx("h3",{className:"card-title",children:"Configuration"}),a.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Connect a trusted AI model that has access to your intent — problem, objective, and tradeoffs — to help you think through authorizations. Keys are encrypted in your vault."}),v&&a.jsxs("div",{className:"status-banner status-banner-success",style:{marginBottom:"1rem",fontSize:"0.8rem"},children:[a.jsx("span",{className:"status-banner-icon",children:"✓"}),a.jsx("span",{className:"status-banner-text",children:"AI configured"})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsx("label",{className:"form-label",children:"Provider Preset"}),a.jsxs("select",{className:"form-input",value:n,onChange:C=>P(C.target.value),children:[a.jsx("option",{value:"openrouter",children:"OpenRouter (recommended)"}),a.jsx("option",{value:"ollama",children:"Ollama (local)"}),a.jsx("option",{value:"openai",children:"OpenAI"}),a.jsx("option",{value:"groq",children:"Groq"}),a.jsx("option",{value:"together",children:"Together"})]})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsx("label",{className:"form-label",children:"Model"}),(()=>{var H;const C=((H=Kc[n])==null?void 0:H.models)??[],T=C.includes(c);return a.jsxs(a.Fragment,{children:[a.jsxs("select",{className:"form-input",value:T?c:"__custom__",onChange:W=>{W.target.value==="__custom__"?u(""):u(W.target.value)},style:{marginBottom:T?void 0:"0.375rem"},children:[C.map(W=>a.jsx("option",{value:W,children:W},W)),a.jsx("option",{value:"__custom__",children:"Custom model..."})]}),!T&&a.jsx("input",{className:"form-input",value:c,onChange:W=>u(W.target.value),placeholder:"Enter model name"})]})})()]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"1rem"},children:[a.jsx("label",{className:"form-label",children:"API Key (if required)"}),a.jsx("input",{className:"form-input",type:"password",value:p,onChange:C=>f(C.target.value),placeholder:v?"••••••••••••••••":"sk-... (not needed for Ollama)"})]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[a.jsx("button",{className:"btn btn-primary",onClick:k,disabled:x,children:x?"Saving...":"Save & Encrypt"}),v&&a.jsx("button",{className:"btn btn-ghost",onClick:N,disabled:j,children:j?"Testing...":"Test Connection"})]}),m&&a.jsx("div",{className:`alert ${m.startsWith("OK")?"alert-success":"alert-error"}`,style:{marginTop:"0.75rem"},children:m})]}),a.jsx(xy,{}),a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,marginBottom:"1rem"},children:"Security"}),a.jsxs("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.7},children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"What the gateway protects"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"Every tool call verified against your authorization bounds"}),a.jsx("li",{children:"Credentials never exposed to agents through MCP"}),a.jsx("li",{children:"Every action produces a signed receipt"})]})]}),a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"Your responsibility"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"If your AI agent has full access to your computer, it could bypass the gateway"}),a.jsx("li",{children:"For best security, run agents in sandboxed environments"}),a.jsx("li",{children:"The gateway secures what agents do through tools — not what they do on your machine"})]})]})]})]})]})}function xy(){const[e,t]=d.useState(null),[n,r]=d.useState({intent:"",context:""}),[o,s]=d.useState(null),[i,l]=d.useState(null),[c,u]=d.useState(null),[p,f]=d.useState(!1),v=d.useCallback(async()=>{if(!p)try{const w=await O.getAIPrompts();t(w),r({intent:w.intent.current,context:w.context.current}),f(!0)}catch(w){l(w instanceof Error?w.message:"Failed to load prompts")}},[p]),y=async w=>{if(e){s(w),l(null);try{const j=n[w],h=j.trim()===e[w].default.trim()?"":j;await O.setAIPrompt(w,h);const m=await O.getAIPrompts();t(m),r({intent:m.intent.current,context:m.context.current}),u(w),setTimeout(()=>u(null),2e3)}catch(j){l(j instanceof Error?j.message:"Save failed")}finally{s(null)}}},x=async w=>{if(confirm(`Revert ${w} prompt to the built-in default?`)){s(w),l(null);try{await O.setAIPrompt(w,"");const j=await O.getAIPrompts();t(j),r({intent:j.intent.current,context:j.context.current})}catch(j){l(j instanceof Error?j.message:"Revert failed")}finally{s(null)}}};return a.jsxs("details",{className:"card",style:{padding:"1.5rem",marginTop:"1rem"},onToggle:w=>{w.currentTarget.open&&v()},children:[a.jsx("summary",{style:{fontSize:"1rem",fontWeight:700,cursor:"pointer",listStyle:"revert",userSelect:"none"},children:"Advanced — AI assistant prompts"}),a.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",margin:"0.75rem 0 1rem 0",lineHeight:1.55},children:"These are the system prompts the AI assistant sees when helping you write Intent (per-authorization) or Context (your standing-orders brief). Edit with care — changes apply on the next chat turn."}),i&&a.jsx("div",{className:"alert alert-error",style:{marginBottom:"0.75rem"},children:i}),!p&&!i&&a.jsx("p",{style:{color:"var(--text-muted)",fontSize:"0.85rem"},children:"Loading prompts…"}),e&&a.jsxs(a.Fragment,{children:[a.jsx(Gc,{kind:"intent",label:"Intent — per-authorization",description:"Used on the Intent gate when creating a new authorization.",state:e.intent,draft:n.intent,onChange:w=>r(j=>({...j,intent:w})),onSave:()=>y("intent"),onRevert:()=>x("intent"),saving:o==="intent",justSaved:c==="intent"}),a.jsx(Gc,{kind:"context",label:"Context — standing-orders brief",description:"Used on the Brief page when refining your context.md.",state:e.context,draft:n.context,onChange:w=>r(j=>({...j,context:w})),onSave:()=>y("context"),onRevert:()=>x("context"),saving:o==="context",justSaved:c==="context"})]})]})}function Gc({kind:e,label:t,description:n,state:r,draft:o,onChange:s,onSave:i,onRevert:l,saving:c,justSaved:u}){const p=o!==r.current;return a.jsxs("section",{style:{marginBottom:"1.5rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"0.25rem",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,fontSize:"0.9rem"},children:t}),a.jsx("div",{style:{fontSize:"0.78rem",color:"var(--text-secondary)"},children:n})]}),r.overridden&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Custom"})]}),a.jsx("textarea",{className:"form-textarea",value:o,onChange:f=>s(f.target.value),rows:12,spellCheck:!1,style:{width:"100%",fontFamily:"'SF Mono', Monaco, 'Cascadia Code', monospace",fontSize:"0.82rem",lineHeight:1.55,resize:"vertical",minHeight:"14rem",marginTop:"0.5rem"},"aria-label":`${t} system prompt`}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",marginTop:"0.5rem",flexWrap:"wrap"},children:[a.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:i,disabled:c||!p,children:c?"Saving…":"Save"}),r.overridden&&a.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:l,disabled:c,title:"Discard the override and use the built-in default",children:"Revert to default"}),u&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--success)"},children:"Saved"}),p&&!c&&!u&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"Unsaved changes"})]}),a.jsxs("details",{style:{marginTop:"0.5rem"},children:[a.jsx("summary",{style:{fontSize:"0.78rem",color:"var(--text-muted)",cursor:"pointer"},children:"Show built-in default"}),a.jsx("pre",{style:{marginTop:"0.5rem",padding:"0.75rem 1rem",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.5rem",fontSize:"0.78rem",lineHeight:1.55,whiteSpace:"pre-wrap",maxHeight:"20rem",overflowY:"auto"},children:r.default})]}),a.jsx("span",{style:{display:"none"},children:e})]})}function wy(e){return e.proposalId?"review":"automatic"}function Yc(e,t,n={}){const r=n.status??"pending",o=n.includeAutonomous??!1,s=[];for(const i of e)r==="pending"&&i.status!=="pending"||n.profile&&i.profileId!==n.profile||s.push({kind:"proposal",id:i.id,sortTimestamp:i.createdAt,commitmentMode:"review",profileId:i.profileId,proposal:i});if(r==="all")for(const i of t){const l=wy(i);!o&&l==="automatic"||n.profile&&i.profileId!==n.profile||s.push({kind:"receipt",id:i.id,sortTimestamp:i.timestamp,commitmentMode:l,profileId:i.profileId,receipt:i})}return s.sort((i,l)=>l.sortTimestamp-i.sortTimestamp),typeof n.limit=="number"&&n.limit>0?s.slice(0,n.limit):s}const Sy={pending:"Pending",committed:"Approved",executed:"Executed",rejected:"Rejected",expired:"Expired"},jy={pending:"status-pending",committed:"status-active",executed:"status-active",rejected:"status-revoked",expired:"status-expired"};function ky(e){const t=Date.now()-e*1e3,n=t/36e5;return n<48?n<1?`${Math.max(1,Math.round(t/6e4))}m ago`:`${Math.round(n)}h ago`:new Date(e*1e3).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Cy(e){return e.split("__").pop()??e}function by(e){const t=e.toLowerCase();return t.includes("delete")||t.includes("refund")||t.includes("cancel")||t.includes("revoke")}const Ny=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]),Ey=/^(image|img|photo|picture|thumbnail)(_?url)?$/i;function zy(e,t){return typeof t!="string"?!1:/^data:image\//i.test(t)?!0:Ey.test(e)?/^https?:\/\//.test(t):/^https?:\/\/.+\.(jpe?g|png|gif|webp|svg|avif)(\?|$)/i.test(t)}function gi(e){if(e==null)return"—";if(typeof e=="string")return e.length>160?e.slice(0,157)+"…":e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>gi(t)).join(", ");try{const t=JSON.stringify(e);return t.length>160?t.slice(0,157)+"…":t}catch{return String(e)}}function Qc({item:e,onApprove:t,onReject:n,resolving:r}){const o=e.kind==="proposal",s=o?e.proposal.status:"executed",i=o?e.proposal.tool:e.receipt.action,l=Cy(i),c=by(i),u=o?e.proposal.toolArgs:null,p=o?e.proposal.executionContext:e.receipt.executionContext,f=o?null:e.receipt.cumulativeState,v=u?Object.entries(u).filter(([x])=>!Ny.has(x)):[],y=Object.entries(p??{});return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",flexWrap:"wrap"},children:[a.jsx(Df,{profileId:e.profileId}),a.jsx("code",{style:{fontSize:"0.85rem"},children:l}),e.commitmentMode==="automatic"&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"autonomous"}),a.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[a.jsx("span",{className:`status-badge ${jy[s]}`,children:Sy[s]}),a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:ky(e.sortTimestamp)})]})]}),c&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem",fontSize:"0.8rem",color:"var(--warning)",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.375rem",padding:"0.4rem 0.6rem",marginBottom:"0.75rem"},children:[a.jsx("span",{children:"⚠"}),a.jsx("span",{children:"Irreversible action"})]}),o&&typeof(u==null?void 0:u._imagePreview)=="string"&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Preview"}),a.jsx("img",{src:u._imagePreview,alt:typeof(u==null?void 0:u.altText)=="string"?u.altText:"local image preview",style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"}})]}),o&&v.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:v.map(([x,w])=>a.jsxs(d.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:x}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word"},children:zy(x,w)?a.jsx("img",{src:w,alt:typeof(u==null?void 0:u.altText)=="string"?u.altText:x,style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"},onError:j=>{const h=j.currentTarget,m=h.parentElement;if(!m)return;h.style.display="none";const g=document.createElement("span");g.textContent=w,g.style.color="var(--text-tertiary)",m.appendChild(g)}}):gi(w)})]},x))})]}),y.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",fontSize:"0.8rem",color:"var(--text-secondary)"},children:y.map(([x,w])=>`${x}=${gi(w)}`).join(" · ")}),f&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["After this action · today: ",f.daily.count," action",f.daily.count===1?"":"s",f.daily.amount>0?`, ${f.daily.amount}`:""," · ","this month: ",f.monthly.count,f.monthly.amount>0?`, ${f.monthly.amount}`:""]}),o&&s==="pending"&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:()=>t==null?void 0:t(e.id),disabled:r,children:r?"Approving…":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:()=>n==null?void 0:n(e.id),disabled:r,children:"Reject"})]}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:[o?"Proposal":"Receipt",": ",e.id]})]})}const Py=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]);function vi(e){if(e==null)return"—";if(typeof e=="string")return e.length>200?e.slice(0,197)+"...":e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>vi(t)).join(", ");try{const t=JSON.stringify(e);return t.length>200?t.slice(0,197)+"...":t}catch{return String(e)}}function Ty(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Iy({proposal:e,currentUserId:t,onAction:n,onMessage:r}){const[o,s]=d.useState(!1),[i,l]=d.useState(!1),[c,u]=d.useState(null),[p,f]=d.useState(!1),[v,y]=d.useState(null),[x,w]=d.useState(!1),j=e.tool.split("__").pop()??e.tool,h=Object.entries(e.toolArgs).filter(([D])=>!Py.has(D)),m=Object.entries(e.executionContext),g=e.pendingApprovers??[],S=e.approvedBy??{},E=Object.keys(S).length,P=g.filter(D=>!(D in S)).length,k=t in S,N=async()=>{if(c===null){f(!0),y(null);try{const D=await O.getAttestationIntent(e.authorizationId);if(!D){y("Intent not available or you are not an authorized approver.");return}const _=await O.decryptIntent({intentCiphertext:D.intentCiphertext,encryptedKey:D.encryptedKey,approverId:t});u(_)}catch(D){y(D instanceof Error?D.message:"Failed to decrypt intent")}finally{f(!1)}}},C=async()=>{x?w(!1):(w(!0),await N())},T=async()=>{s(!0),r("");try{await O.approveProposal(e.id);try{if(c===null){const D=await O.getAttestationIntent(e.authorizationId);if(D){const _=await O.decryptIntent({intentCiphertext:D.intentCiphertext,encryptedKey:D.encryptedKey,approverId:t});u(_),await O.storeApprovedIntent(e.authorizationId,_)}}else await O.storeApprovedIntent(e.authorizationId,c)}catch{}r(`Approved. ${P-1>0?`${P-1} more approver(s) still needed.`:"All approvers signed off — action is ready to execute."}`),n()}catch(D){r(D instanceof Error?D.message:"Approval failed")}finally{s(!1)}},H=async()=>{const D=prompt("Rejection reason (optional):");if(D!==null){l(!0),r("");try{await O.rejectProposal(e.id,D||void 0),r("Action rejected."),n()}catch(_){r(_ instanceof Error?_.message:"Rejection failed")}finally{l(!1)}}},W=o||i;return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:Ee(e.profileId)}),a.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),a.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Ty(e.createdAt)})]}),a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[E," of ",g.length," approver",g.length===1?"":"s"," signed off",g.map(D=>{const _=D in S;return a.jsxs("span",{style:{marginLeft:"0.5rem",color:_?"var(--success, green)":"var(--text-tertiary)"},children:[_?"✓":"○"," ",D===t?"You":D]},D)})]}),a.jsxs("div",{style:{marginBottom:"0.5rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Proposed action"}),a.jsx("code",{style:{fontSize:"0.85rem"},children:j})]}),h.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:h.map(([D,_])=>a.jsxs(d.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:D}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word"},children:vi(_)})]},D))})]}),m.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:m.map(([D,_])=>`${D}=${vi(_)}`).join(" · ")}),a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsxs("button",{className:"btn btn-ghost btn-sm",style:{padding:"0.2rem 0",fontSize:"0.75rem"},onClick:C,disabled:p,children:[x?"▲ Hide intent":"▼ Show intent",p&&" (decrypting...)"]}),x&&a.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"var(--bg-main)",borderRadius:"0.375rem",border:"1px solid var(--border)"},children:v?a.jsx("p",{style:{color:"var(--danger)",fontSize:"0.8rem",margin:0},children:v}):c!==null?a.jsx("p",{style:{fontSize:"0.85rem",margin:0,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:c}):a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.8rem",margin:0},children:"No intent available for this authority."})})]}),!k&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:T,disabled:W,children:o?"Approving...":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:H,disabled:W,children:i?"Rejecting...":"Reject"})]}),k&&a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"You approved this action. Waiting on other approvers."}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["Proposal: ",e.id]})]})}function Ry(){const{domain:e,user:t}=ze(),n=(t==null?void 0:t.id)??"",[r,o]=d.useState("awaiting-me"),[s,i]=d.useState([]),[l,c]=d.useState(!0),[u,p]=d.useState(""),f=d.useCallback(async()=>{try{const A=await O.getProposalsForApprover();i(A)}catch{}finally{c(!1)}},[]);fe("proposal-added",f),fe("proposal-approved",f),fe("proposal-rejected",f),fe("proposal-resolved",f),$t(f,3e4);const[v,y]=d.useState([]),x=d.useCallback(async()=>{try{const A=await O.getProposals(e||"owner");y(A)}catch{}},[e]);fe("proposal-added",x),fe("proposal-approved",x),fe("proposal-rejected",x),fe("proposal-resolved",x),$t(x,3e4,e);const w=d.useMemo(()=>v.filter(A=>{var I;return A.status==="pending"&&(((I=A.pendingApprovers)==null?void 0:I.length)??0)===0}),[v]),j=d.useMemo(()=>Yc(w,[],{status:"pending"}),[w]),[h,m]=d.useState([]),g=d.useCallback(async()=>{if(n)try{const I=(await O.getProposals(e||"owner")).filter(Y=>Y.status==="pending"&&Y.pendingApprovers&&Y.pendingApprovers.includes(n)&&Y.approvedBy&&n in Y.approvedBy);m(I)}catch{}},[n,e]);fe("proposal-approved",g),fe("proposal-rejected",g),$t(g,3e4,`${n}:${e}`),d.useEffect(()=>{f(),x(),g()},[]);const[S,E]=d.useState([]),[P,k]=d.useState([]),[N,C]=d.useState(!0),[T,H]=d.useState(null),[W,D]=d.useState(""),[_,B]=d.useState("pending"),[X,se]=d.useState(null),[z,R]=d.useState(!1),$=d.useCallback(async()=>{try{const{proposals:A,receipts:I}=await O.getThread({domain:e,status:_,sinceDays:7});E(A),k(I)}catch{}finally{C(!1)}},[e,_]);$t($,3e4,`${e}:${_}`);const L=async(A,I)=>{H(A),D("");try{const Y=e||"owner",xe=await O.resolveProposal(A,I,Y);D(I==="commit"?`Action approved. Status: ${xe.status}`:"Action rejected."),await Promise.all([$(),x()])}catch(Y){D(Y instanceof Error?Y.message:"Failed")}finally{H(null)}},V=d.useMemo(()=>{const A=new Set;for(const I of S)A.add(I.profileId);for(const I of P)A.add(I.profileId);return Array.from(A).sort()},[S,P]),ee=d.useMemo(()=>Yc(S,P,{status:_,profile:X??void 0,includeAutonomous:z}),[S,P,_,X,z]),J=d.useCallback(()=>{f(),g()},[f,g]),je=d.useMemo(()=>{const A=new Set,I=[];for(const Y of h)A.has(Y.id)||(A.add(Y.id),I.push(Y));return I.sort((Y,xe)=>xe.createdAt-Y.createdAt)},[h]),b=s.length+j.length,U=je.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"Pending Approvals"}),a.jsx("p",{className:"page-subtitle",children:"Actions awaiting approval, plus recent activity from the last 7 days."})]}),a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"1rem"},children:[a.jsxs("button",{className:`nav-tab${r==="awaiting-me"?" active":""}`,onClick:()=>o("awaiting-me"),children:["Awaiting me ",b>0&&a.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--warning)",color:"var(--bg-elevated)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:b})]}),a.jsxs("button",{className:`nav-tab${r==="awaiting-others"?" active":""}`,onClick:()=>o("awaiting-others"),children:["Awaiting others ",U>0&&a.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--border)",color:"var(--text-secondary)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:U})]}),a.jsx("button",{className:`nav-tab${r==="all"?" active":""}`,onClick:()=>{o("all"),$()},children:"All"})]}),r==="awaiting-me"&&a.jsx(a.Fragment,{children:l&&b===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):b===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions awaiting your approval."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Review-mode actions and above-cap actions you must approve will appear here."})]}):a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[(u||W)&&a.jsx("div",{className:"alert alert-success",children:u||W}),j.map(A=>a.jsx(Qc,{item:A,onApprove:I=>L(I,"commit"),onReject:I=>L(I,"reject"),resolving:T===A.id},A.id)),s.map(A=>a.jsx(Iy,{proposal:A,currentUserId:n,onAction:J,onMessage:p},A.id))]})}),r==="awaiting-others"&&a.jsx(a.Fragment,{children:je.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions waiting on others."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Actions you proposed or approved that are pending other approvers will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:je.map(A=>a.jsx(Ay,{proposal:A,currentUserId:n,onCancel:async()=>{try{await O.rejectProposal(A.id,"cancelled by creator"),g(),x()}catch(I){alert(I instanceof Error?I.message:"Cancel failed")}}},A.id))})}),r==="all"&&a.jsxs(a.Fragment,{children:[W&&a.jsx("div",{className:"alert alert-success",style:{marginBottom:"1rem"},children:W}),a.jsxs("div",{className:"filter-chips",style:{marginBottom:"1rem"},children:[a.jsx("button",{className:`filter-chip ${_==="pending"?"selected":""}`,onClick:()=>B("pending"),children:"Pending"}),a.jsx("button",{className:`filter-chip ${_==="all"?"selected":""}`,onClick:()=>B("all"),children:"All"}),V.length>0&&a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),V.map(A=>a.jsx("button",{className:`filter-chip ${X===A?"selected":""}`,onClick:()=>se(X===A?null:A),children:Ee(A)},A)),_==="all"&&a.jsxs(a.Fragment,{children:[a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),a.jsxs("button",{className:`filter-chip ${z?"selected":""}`,onClick:()=>R(!z),title:"Include actions executed without human review (automatic commitment mode)",children:[z?"✓ ":"","Autonomous actions"]})]})]}),N&&ee.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):ee.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:_==="pending"?"No actions awaiting your approval.":"Nothing here yet."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:_==="pending"?"Your agents are operating within their authorizations. Switch to All to see recent activity.":"When an agent calls a gated tool, activity will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:ee.map(A=>a.jsx(Qc,{item:A,onApprove:I=>L(I,"commit"),onReject:I=>L(I,"reject"),resolving:T===A.id},A.id))})]})]})}function _y(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ay({proposal:e,currentUserId:t,onCancel:n}){var u;const[r,o]=d.useState(!1),s=Object.keys(e.approvedBy??{}),i=(e.pendingApprovers??[]).filter(p=>!(p in(e.approvedBy??{}))),l=(((u=e.pendingApprovers)==null?void 0:u.length)??0)>0,c=async()=>{if(confirm("Cancel this action? All approvers will be notified.")){o(!0);try{await n()}finally{o(!1)}}};return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:Ee(e.profileId)}),l&&a.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),a.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:_y(e.createdAt)})]}),a.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:a.jsx("code",{children:e.tool.split("__").pop()??e.tool})}),l&&a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[s.map(p=>a.jsx("span",{style:{marginRight:"0.75rem",color:"var(--success, green)"},children:p===t?"You approved":`${p} approved`},p)),i.map(p=>a.jsxs("span",{style:{marginRight:"0.75rem",color:"var(--text-tertiary)"},children:["Waiting on ",p===t?"you":p]},p))]}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--danger)"},onClick:c,disabled:r,children:r?"Cancelling...":"Cancel"})})]})}const $y=`# Agent Brief
|
|
69
|
+
`}),f?a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem"},children:"Loading..."}):g.length===0?a.jsxs("div",{className:"card",style:{padding:"2rem",textAlign:"center"},children:[a.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9rem",marginBottom:"1rem"},children:"No integrations set up yet. Connect a service first."}),a.jsx(Je,{to:"/integrations",className:"btn btn-primary btn-sm",onClick:()=>e==null?void 0:e(),children:"Go to Integrations"})]}):a.jsx("div",{className:"profile-grid",children:g.map(k=>{const N=S(k.id),C=k.id.replace(/@.*$/,"").split("/").pop()??k.id,T=h.get(C),H=m.get(C),W=(H==null?void 0:H.running)===!0;return a.jsxs("div",{className:"card",style:W?void 0:{opacity:.7},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.125rem"},children:[a.jsx("h3",{className:"card-title",style:{margin:0},children:Ee(k.id,k.name)}),N?a.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Team"}):a.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--bg-main)",color:"var(--text-tertiary)",fontWeight:600,border:"1px solid var(--border)"},children:"Personal"})]}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"1rem",flex:1},children:k.description}),W?a.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>P(k.id),children:"Authorize"}):a.jsxs(Je,{to:`/integrations?setup=${(T==null?void 0:T.id)??""}`,className:"btn btn-secondary btn-sm",style:{textDecoration:"none",textAlign:"center"},onClick:()=>e==null?void 0:e(),children:["Set up ",(T==null?void 0:T.name)??"integration"]})]},k.id)})})]})}const ny={active:"Active",pending:"Pending",expired:"Expired",revoked:"Revoked"};function ry({status:e,label:t}){return a.jsx("span",{className:`status-badge status-${e}`,children:t||ny[e]})}function oy({domain:e,attested:t}){const n=t===!0?"domain-attested":t===!1?"domain-missing":"";return a.jsx("span",{className:`domain-badge ${n}`,style:{fontSize:"0.75rem"},children:e})}const yn=86400,Nr=3600,Po=60,ay=30*yn;function sy(e){if(e<=0)return"Expired";if(e>90*yn){const t=Math.floor(e/ay);return`${t} ${t===1?"month":"months"} remaining`}if(e>7*yn){const t=Math.floor(e/yn);return`${t} ${t===1?"day":"days"} remaining`}if(e>=2*yn){const t=Math.floor(e/yn),n=Math.floor(e%yn/Nr);return`${t} ${t===1?"day":"days"} ${n}h remaining`}if(e>=2*Nr){const t=Math.floor(e/Nr),n=Math.floor(e%Nr/Po);return`${t}h ${String(n).padStart(2,"0")}m remaining`}if(e>=Po){const t=Math.floor(e/Po),n=Math.floor(e%Po);return`${t}m ${String(n).padStart(2,"0")}s remaining`}return`${Math.floor(e)}s remaining`}function iy({expiresAt:e}){const[t,n]=d.useState(()=>e-Date.now()/1e3),r=t<2*Nr;d.useEffect(()=>{const s=setInterval(()=>n(e-Date.now()/1e3),r?1e3:6e4);return()=>clearInterval(s)},[e,r]);const o=t<300;return a.jsx("span",{className:`ttl-badge ${o?"ttl-warn":"ttl-ok"}`,children:sy(t)})}function Bf({icon:e,title:t,text:n,children:r}){return a.jsxs("div",{className:"empty-state",children:[e&&a.jsx("div",{className:"empty-state-icon",children:e}),a.jsx("div",{className:"empty-state-title",children:t}),n&&a.jsx("div",{className:"empty-state-text",children:n}),r]})}function ly(e){const t=Math.floor(e/86400);if(t>=1)return`${t} day${t===1?"":"s"}`;const n=Math.floor(e/3600);if(n>=1)return`${n} hour${n===1?"":"s"}`;const r=Math.ceil(e/60);return`${r} minute${r===1?"":"s"}`}const cy=[{label:"30m",seconds:1800},{label:"1h",seconds:3600},{label:"2h",seconds:7200},{label:"4h",seconds:14400},{label:"8h",seconds:28800},{label:"24h",seconds:86400},{label:"7d",seconds:604800},{label:"30d",seconds:2592e3},{label:"1y",seconds:31536e3}];function uy({item:e,onClose:t,onSuccess:n}){var h;const{user:r,activeDomain:o,groupId:s}=ze(),i=e.remaining_seconds??0,l=cy.filter(m=>m.seconds>i),c=((h=l[0])==null?void 0:h.seconds)??2592e3,[u,p]=d.useState(c),[f,v]=d.useState(!1),[y,x]=d.useState(""),w=Object.entries(e.frame).filter(([m])=>m!=="profile"&&m!=="path"),j=async()=>{var m;if(r){v(!0),x("");try{const g=e.authorization_id,S=await O.getGateContent(g);if(!S)throw new Error("Gate content not found locally. The MCP server may have restarted. Please re-authorize through the full wizard instead.");const E=await O.getProfile(e.profile_id),P=e.frame,k=S.context??{},N=e.attested_domains[0]||o||"owner",C=await Ho(P,E),T=await Ff(k,E),[H,W]=await Promise.all([va(S.gateContent.intent),va(JSON.stringify({profile:e.profile_id,path:e.path,domain:N}))]);if(!s)throw new Error("No active group; cannot extend authorization.");const D=(((m=e.deferred_commitment_domains)==null?void 0:m.length)??0)>0?"review":"automatic",_=await O.attest({authorization_id:e.authorization_id,renew:!0,profile_id:e.profile_id,bounds:P,bounds_hash:C,context_hash:T,domain:N,did:r.did,gate_content_hashes:{intent:H},execution_context_hash:W,group_id:s,commitment_mode:D,ttl:u});await O.pushGateContent(Of(_,{boundsHash:C,contextHash:T,context:k,path:e.path,gateContent:S.gateContent})),n()}catch(g){x(g instanceof Error?g.message:"Extension failed")}finally{v(!1)}}};return a.jsx("div",{className:"modal-backdrop",onClick:m=>m.target===m.currentTarget&&t(),children:a.jsxs("div",{className:"modal",children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h3",{className:"modal-title",children:"Extend Authorization"}),a.jsx("button",{className:"modal-close",onClick:t,children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsxs("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:[Ee(e.profile_id)," / ",e.path]}),w.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:w.map(([m,g])=>`${m}=${g}`).join(" · ")})]}),a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.5rem"},children:"New duration"}),i>0&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["Currently valid for ",ly(i),". Only longer durations are shown."]}),a.jsx("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:l.length===0?a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This authorization is already on the longest available duration. Nothing to extend."}):l.map(m=>a.jsx("button",{className:`btn ${u===m.seconds?"btn-primary":"btn-secondary"}`,onClick:()=>p(m.seconds),style:{minWidth:"3.5rem"},children:m.label},m.seconds))})]}),a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Same bounds, context, and gate content will be re-attested with a new TTL (measured from now)."}),y&&a.jsx("div",{className:"error-message",children:y})]}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-secondary",onClick:t,disabled:f,children:"Cancel"}),a.jsx("button",{className:"btn btn-primary",onClick:j,disabled:f,children:f?"Extending...":"Extend"})]})]})})}function dy(e,t,n){return[...e].sort((r,o)=>{if(n){if(r.authorization_id===n&&o.authorization_id!==n)return-1;if(o.authorization_id===n&&r.authorization_id!==n)return 1}const s=Ct(r,{revokedSet:t}),i=Ct(o,{revokedSet:t}),l={active:0,pending:1,expired:2,revoked:3};return l[s]!==l[i]?l[s]-l[i]:new Date(o.created_at).getTime()-new Date(r.created_at).getTime()})}function fy({item:e,revokedSet:t,expandedHash:n,gateCache:r,gateLoading:o,copiedHash:s,revokingHash:i,copyingHash:l,profileConfigCache:c,mode:u,ownerLabel:p,isAdmin:f,onExpand:v,onCopyHash:y,onCopy:x,onRevoke:w,onExtend:j,highlightHash:h}){var $;const m=Ct(e,{revokedSet:t}),g=n===e.authorization_id,S=r[e.authorization_id],E=m==="active"||m==="pending"||m==="expired",P=Object.entries(e.frame).filter(([L])=>L!=="profile"&&L!=="path"),k=c.get(e.profile_id)??null,N=((($=k==null?void 0:k.approvers)==null?void 0:$.length)??0)>0,C=new Map;if(k!=null&&k.caps&&u==="team")for(const[L,V]of P){const ee=k.caps[L];ee!==void 0&&Number(V)>ee&&C.set(L,{authorized:Number(V),cap:ee})}const T=C.size>0,H=e.approvers_frozen??[],W=(k==null?void 0:k.approvers)??[],D=u==="team"&&H.length>0&&W.length>0&&(H.length!==W.length||H.some(L=>!W.includes(L))||W.some(L=>!H.includes(L))),_=Array.from(C.entries()).map(([L,V])=>`${L}: ${V.authorized} (cap ${V.cap})`).join(", "),B=Array.from(C.entries()).map(([L,V])=>`${L}: ${V.authorized} → ${V.cap}`).join(", "),X=T?N?C.size===1?`Above team cap: ${_} — actions require approval`:`Above team cap (${C.size}): ${_} — actions require approval`:C.size===1?`Reduced by hard cap: ${B}`:`Reduced by hard cap (${C.size}): ${B}`:"",se=T?N?"Above-cap actions under this authority require per-action approval from the profile's approvers. Bounds remain authorized at their original values.":"No approvers are configured for this profile, so the team cap is a hard ceiling. Bounds above the cap are effectively reduced to the cap. Ask the admin to raise the cap or add approvers, or copy this authorization to reissue within the cap.":void 0,z=Ee(e.profile_id),R=h!=null&&e.authorization_id===h;return a.jsxs("div",{className:`card${R?" card-highlight":""}`,style:{marginBottom:0},children:[p&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner: ",a.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:p})]}),a.jsxs("div",{className:"auth-card-header",children:[a.jsx("span",{style:{fontWeight:700,fontSize:"1rem",color:"var(--text-primary)",letterSpacing:"0.01em"},children:z}),e.title&&a.jsx("span",{style:{fontWeight:500,fontSize:"0.85rem",color:"var(--text-secondary)"},children:e.title}),a.jsx(ry,{status:m}),m==="active"&&e.earliest_expiry&&a.jsx(iy,{expiresAt:new Date(e.earliest_expiry).getTime()/1e3}),m==="expired"&&a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:new Date(e.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem",alignItems:"center"},children:[e.required_domains.map(L=>a.jsx(oy,{domain:L,attested:e.attested_domains.includes(L)},L)),e.deferred_commitment_domains.length>0&&a.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Review Mode"}),T&&a.jsx("span",{title:se,style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:N?"var(--accent-subtle)":"var(--danger-subtle)",color:N?"var(--accent)":"var(--danger)",fontWeight:600,cursor:"help"},children:X}),D&&a.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.65rem",padding:"0.15rem 0.5rem",borderRadius:"0.25rem",background:"var(--warning-subtle, rgba(234,179,8,0.12))",color:"var(--warning, #ca8a04)",fontWeight:600,border:"1px solid var(--warning-border, rgba(234,179,8,0.3))",cursor:"pointer",lineHeight:1.4},onClick:()=>x(e),disabled:l===e.authorization_id,title:"The approver list for this profile has changed since this authority was created. Copy to reissue with the current approvers.",children:l===e.authorization_id?"Copying...":"Approver list updated · Copy with new approvers"})]}),P.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:P.map(([L,V],ee)=>{const J=C.get(L);return a.jsxs("span",{children:[ee>0&&" · ",J?N?a.jsxs("span",{title:`Team cap on ${L} is ${J.cap}. Actions exceeding the cap require per-action approval. Bound remains authorized at ${J.authorized}.`,children:[a.jsxs("span",{style:{color:"var(--text-tertiary)"},children:[L,"=",String(V)]}),a.jsxs("span",{style:{color:"var(--accent)",marginLeft:"0.25rem",fontWeight:600},children:["↑ approval at ",J.cap]})]}):a.jsxs("span",{title:`Team cap on ${L} is ${J.cap} with no approvers configured (hard cap). Authorized for ${J.authorized}; effective ${J.cap}.`,children:[a.jsxs("span",{style:{textDecoration:"line-through",color:"var(--text-tertiary)"},children:[L,"=",String(V)]}),a.jsxs("span",{style:{color:"var(--danger)",marginLeft:"0.25rem",fontWeight:600},children:["→"," ",J.cap]})]}):a.jsxs("span",{children:[L,"=",String(V)]})]},L)})}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>v(e),children:g?"▲ Hide Details":"▼ Details"})}),g&&a.jsxs("div",{style:{borderTop:"1px solid var(--border)",marginTop:"0.75rem",paddingTop:"0.75rem"},children:[P.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Bounds"}),a.jsx("dl",{className:"review-grid",children:P.map(([L,V])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:L}),a.jsx("dd",{children:String(V)})]},L))})]}),(S==null?void 0:S.context)&&Object.keys(S.context).length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Context"}),a.jsx("dl",{className:"review-grid",children:Object.entries(S.context).map(([L,V])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:L}),a.jsx("dd",{children:String(V)})]},L))})]}),a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Intent"}),o===e.authorization_id?a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Loading gate content..."}):S?a.jsx("div",{className:"gate-content-block",children:a.jsx("div",{className:"gate-content-item",children:a.jsx("div",{className:"gate-content-text",children:S.gateContent.intent})})}):a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Gate content not available."}),a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"1rem"},children:["Created: ",new Date(e.created_at).toLocaleString(),e.earliest_expiry&&` · Expires: ${new Date(e.earliest_expiry).toLocaleString()}`]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all"},children:e.authorization_id}),a.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.7rem",padding:"0.125rem 0.375rem"},onClick:()=>y(e.authorization_id),children:s===e.authorization_id?"copied":"copy"})]}),a.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.75rem"},children:[!p&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),disabled:l===e.authorization_id,title:"Start a new authorization pre-filled with these bounds, context, and intent",children:l===e.authorization_id?"Copying…":"⧉ Copy"}),!p&&E&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>j(e),children:"↻ Extend"}),p&&f&&m!=="revoked"?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>w(e.authorization_id,p,z),disabled:i===e.authorization_id,children:i===e.authorization_id?"Revoking…":"Revoke"}):!p&&(m==="active"||m==="pending")?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>w(e.authorization_id),disabled:i===e.authorization_id,children:i===e.authorization_id?"Revoking…":"Revoke"}):null]})]})]},e.authorization_id)}function my(){const[e,t]=d.useState([]),[n,r]=d.useState(!0),[o,s]=d.useState([]),[i,l]=d.useState(!1),[c,u]=d.useState("mine"),[p,f]=d.useState("active"),[v,y]=d.useState(null),[x,w]=d.useState(null),[j,h]=zf(),[m,g]=d.useState(()=>j.get("new")==="1"),[S,E]=d.useState(()=>j.get("highlight")),[P,k]=d.useState(null),[N,C]=d.useState({}),[T,H]=d.useState(null),[W,D]=d.useState(null),[_,B]=d.useState(null),[X,se]=d.useState(new Set),[z,R]=d.useState(null),[$,L]=d.useState(null),V=Wt(),{group:ee,groupId:J,domain:je,mode:b,activeTeam:U}=ze(),A=(U==null?void 0:U.isAdmin)===!0,[I,Y]=d.useState(()=>new Map),xe=d.useCallback(()=>{r(!0),O.getMyAttestations().then(t).catch(()=>{}).finally(()=>r(!1))},[]),Pe=d.useCallback(()=>{J&&(l(!0),O.listTeamAuthorizations(J).then(s).catch(()=>{}).finally(()=>l(!1)))},[J]);fe("attestation-changed",()=>{xe(),A&&J&&Pe()}),d.useEffect(()=>{if(!S)return;j.get("highlight")&&(j.delete("highlight"),h(j,{replace:!0}));const G=window.setTimeout(()=>E(null),3e3);return()=>window.clearTimeout(G)},[]),$t(xe,3e5),d.useEffect(()=>{c==="team"&&A&&J&&o.length===0&&!i&&Pe()},[c,A,J,o.length,i,Pe]),d.useEffect(()=>{if(b!=="team"||!J)return;const G=c==="mine"?e:o;if(G.length===0)return;const F=[...new Set(G.map(Q=>Q.profile_id))].filter(Q=>!I.has(Q));if(F.length!==0){Y(Q=>{const q=new Map(Q);for(const oe of F)q.set(oe,null);return q});for(const Q of F)O.getTeamProfileConfig(J,Q).then(q=>{Y(oe=>new Map(oe).set(Q,q))}).catch(()=>{})}},[e,o,c,J,b,I]);const ke=async G=>{if(P===G.authorization_id){k(null);return}k(G.authorization_id);const F=G.authorization_id;if(!(F in N)){H(G.authorization_id);try{const Q=await O.getGateContent(F);C(q=>({...q,[F]:Q}))}catch{C(Q=>({...Q,[F]:null}))}finally{H(null)}}},mn=G=>{navigator.clipboard.writeText(G).then(()=>{B(G),setTimeout(()=>B(null),2e3)})},Rn=async G=>{var F;if(!J){alert("No active group; cannot copy authorization.");return}L(G.authorization_id);try{const Q=G.authorization_id;let q=N[Q]??null;Q in N||(q=await O.getGateContent(Q),C(_e=>({..._e,[Q]:q})));const oe=Object.fromEntries(Object.entries(G.frame).filter(([_e])=>_e!=="profile"&&_e!=="path")),pn=(q==null?void 0:q.context)??{},Ye=((F=q==null?void 0:q.gateContent)==null?void 0:F.intent)??"",mt=G.deferred_commitment_domains.length>0?"review":"automatic",Tt=G.attested_domains[0]||je||"owner";sessionStorage.setItem("agentAuth",JSON.stringify({profileId:G.profile_id,groupId:J,groupName:(ee==null?void 0:ee.name)??null,domain:Tt})),sessionStorage.setItem("agentGate",JSON.stringify({bounds:oe,context:pn,gateContent:{intent:Ye},templateMode:mt})),V("/agent/gate")}catch(Q){alert(Q instanceof Error?Q.message:"Failed to copy authorization")}finally{L(null)}},Pt=async(G,F,Q)=>{const q=F&&Q?`Revoke ${F}'s ${Q} authorization? This cannot be undone.`:"Revoke this authorization? The agent will no longer be able to execute actions under this attestation.";if(confirm(q)){R(G);try{await O.revokeAttestation(G),se(oe=>new Set(oe).add(G)),F&&J&&Pe()}catch(oe){alert(oe instanceof Error?oe.message:"Failed to revoke authorization")}finally{R(null)}}},Ue=c==="mine"?e:o,dr=c==="mine"?n:i,Ht={active:Ue.filter(G=>Ct(G,{revokedSet:X})==="active").length,pending:Ue.filter(G=>Ct(G,{revokedSet:X})==="pending").length,expired:Ue.filter(G=>Ct(G,{revokedSet:X})==="expired").length,revoked:Ue.filter(G=>Ct(G,{revokedSet:X})==="revoked").length},ne=(()=>{const G=new Map;for(const F of Ue){if(Ct(F,{revokedSet:X})!==p)continue;const Q=G.get(F.profile_id)??{count:0,review:!1};Q.count+=1,F.deferred_commitment_domains.length>0&&(Q.review=!0),G.set(F.profile_id,Q)}return Array.from(G.entries()).map(([F,Q])=>({profileId:F,...Q})).sort((F,Q)=>Ee(F.profileId).localeCompare(Ee(Q.profileId)))})(),ft=dy(Ue.filter(G=>{if(Ct(G,{revokedSet:X})!==p||v!==null&&G.profile_id!==v)return!1;if(x!==null){const F=G.deferred_commitment_domains.length>0;if(x==="review"&&!F||x==="auto"&&F)return!1}return!0}),X,S),lo={revokedSet:X,expandedHash:P,gateCache:N,gateLoading:T,copiedHash:_,revokingHash:z,copyingHash:$,profileConfigCache:I,mode:b,activeDomain:je,group:ee,groupId:J,onExpand:ke,onCopyHash:mn,onCopy:Rn,onRevoke:Pt,onExtend:D,highlightHash:S};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("h1",{className:"page-title",children:"Authorizations"}),a.jsx("p",{className:"page-subtitle",children:"Active, pending, and expired agent authorizations."})]}),a.jsx("button",{className:"btn btn-primary",onClick:()=>g(!0),children:"+ New authorization"})]}),m&&a.jsx("div",{className:"modal-backdrop",onClick:()=>{g(!1),j.get("new")&&(j.delete("new"),h(j,{replace:!0}))},children:a.jsxs("div",{className:"modal",onClick:G=>G.stopPropagation(),style:{maxWidth:"960px",width:"90vw"},children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h2",{className:"modal-title",children:"New authorization"}),a.jsx("button",{className:"modal-close",onClick:()=>{g(!1),j.get("new")&&(j.delete("new"),h(j,{replace:!0}))},children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem",marginTop:0,marginBottom:"1rem"},children:"What should your agent be able to do? Pick a profile, set limits, then authorize."}),a.jsx(ty,{onDismiss:()=>g(!1)})]})]})}),A&&a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"0.5rem"},children:[a.jsx("button",{className:`nav-tab${c==="mine"?" active":""}`,onClick:()=>{u("mine"),f("active"),y(null),w(null),k(null)},children:"Mine"}),a.jsx("button",{className:`nav-tab${c==="team"?" active":""}`,onClick:()=>{u("team"),f("active"),y(null),w(null),k(null)},children:"Team"})]}),a.jsx("div",{className:"nav-tabs",children:["active","pending","expired","revoked"].map(G=>a.jsxs("button",{className:`nav-tab${p===G?" active":""}`,onClick:()=>{f(G),y(null),w(null)},children:[G.charAt(0).toUpperCase()+G.slice(1)," (",Ht[G],")"]},G))}),ne.length>0&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center",marginTop:"-0.25rem",marginBottom:"1rem"},children:[ne.map(G=>{const F=v===G.profileId;return a.jsx("button",{className:`btn btn-sm ${F?"btn-primary":"btn-secondary"}`,onClick:()=>y(F?null:G.profileId),children:Ee(G.profileId)},G.profileId)}),a.jsx("span",{"aria-hidden":"true",style:{color:"var(--border)",fontSize:"1.1rem",padding:"0 0.25rem",userSelect:"none"},children:"|"}),["auto","review"].map(G=>{const F=x===G;return a.jsx("button",{className:`btn btn-sm ${F?"btn-primary":"btn-secondary"}`,onClick:()=>w(F?null:G),children:G==="auto"?"Auto":"Review"},G)})]}),dr&&Ue.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):ft.length===0?a.jsx(Bf,{icon:"☰",title:"No authorizations",text:`No ${p} authorizations found.`}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:ft.map(G=>{const F=c==="team"?G:null,Q=F!=null&&F.owner?F.owner.name??F.owner.email??F.owner.userId:void 0;return a.jsx(fy,{item:G,ownerLabel:Q,isAdmin:A,...lo},G.authorization_id)})}),W&&a.jsx(uy,{item:W,onClose:()=>D(null),onSuccess:()=>{D(null),xe()}})]})}function Df({profileId:e}){return a.jsx("span",{className:"profile-badge",children:Ee(e)})}function py(e){return new Date(e*1e3).toLocaleString()}function hy(e,t){if(t==="all")return!0;const n=t==="1d"?1:t==="7d"?7:30,r=Math.floor(Date.now()/1e3)-n*86400;return e.timestamp>=r}function gy(e,t){if(!t)return!0;const n=t.toLowerCase();return e.profileId.toLowerCase().includes(n)||Ee(e.profileId).toLowerCase().includes(n)||e.path.toLowerCase().includes(n)||e.action.toLowerCase().includes(n)||e.attestationHash.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||JSON.stringify(e.executionContext).toLowerCase().includes(n)}function Vc(e,t){const n=new Map(e.map(r=>[r.id,r]));for(const r of t)n.set(r.id,r);return[...n.values()].sort((r,o)=>o.timestamp-r.timestamp)}function vy(){const{activeTeam:e,groupId:t}=ze(),n=(e==null?void 0:e.isAdmin)===!0,[r,o]=d.useState("mine"),[s,i]=d.useState([]),[l,c]=d.useState(!0),[u,p]=d.useState({}),[f,v]=d.useState(new Set),[y,x]=d.useState(""),[w,j]=d.useState(new Set),[h,m]=d.useState(new Set),[g,S]=d.useState("all"),[E,P]=d.useState(!1),[k,N]=d.useState(null),[C,T]=d.useState(!1),[H,W]=d.useState(!1),D=d.useRef(""),_=d.useCallback(b=>r==="team"&&n&&t?O.listTeamReceiptsPage(t,{before:b,limit:200}):O.getMyReceiptsPage({before:b,limit:200}),[r,n,t]),B=d.useCallback(()=>{const b=r==="team"?`team:${t}`:"mine",U=D.current!==b;D.current=b,c(!0),W(!1),_().then(A=>{i(I=>U?A.receipts:Vc(I,A.receipts)),N(I=>U?A.nextBefore:I??A.nextBefore)}).catch(()=>{U&&i([]),W(!0)}).finally(()=>c(!1))},[_,r,t]),X=d.useCallback(()=>{!k||C||(T(!0),W(!1),_(k).then(b=>{i(U=>Vc(U,b.receipts)),N(b.nextBefore)}).catch(()=>W(!0)).finally(()=>T(!1)))},[k,C,_]);$t(B,12e4),d.useEffect(()=>{r!=="team"||Object.keys(u).length>0||O.listUsers().then(b=>{const U={};for(const A of b)U[A.id]={name:A.name,email:A.email};p(U)}).catch(()=>{})},[r,u]);const se=d.useMemo(()=>{const b=new Set;for(const U of s)b.add(Ee(U.profileId));return[...b].sort()},[s]),z=d.useMemo(()=>{const b=new Set;for(const U of s)b.add(U.action);return[...b].sort()},[s]),R=d.useMemo(()=>{if(r!=="team")return[];const b=new Set;for(const U of s)U.userId&&b.add(U.userId);return[...b].map(U=>{var A;return{id:U,label:(A=u[U])!=null&&A.name?`${u[U].name} (${u[U].email})`:U}}).sort((U,A)=>U.label.localeCompare(A.label))},[r,s,u]),$=d.useMemo(()=>s.filter(b=>!(!gy(b,y)||w.size>0&&!w.has(Ee(b.profileId))||h.size>0&&!h.has(b.action)||f.size>0&&b.userId&&!f.has(b.userId)||!hy(b,g))),[s,y,w,h,f,g]),L=w.size>0||h.size>0||f.size>0||g!=="all";function V(b){j(U=>{const A=new Set(U);return A.has(b)?A.delete(b):A.add(b),A})}function ee(b){m(U=>{const A=new Set(U);return A.has(b)?A.delete(b):A.add(b),A})}function J(b){v(U=>{const A=new Set(U);return A.has(b)?A.delete(b):A.add(b),A})}function je(){j(new Set),m(new Set),v(new Set),S("all"),x("")}return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"Receipts"}),a.jsx("p",{className:"page-subtitle",children:"Execution history for agent actions."})]}),n&&a.jsx("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"1rem",borderBottom:"1px solid var(--border)"},children:["mine","team"].map(b=>a.jsx("button",{onClick:()=>o(b),className:"btn btn-ghost",style:{borderRadius:0,padding:"0.5rem 0.875rem",borderBottom:r===b?"2px solid var(--accent)":"2px solid transparent",color:r===b?"var(--text-primary)":"var(--text-tertiary)",fontWeight:r===b?600:500},children:b==="mine"?"Mine":"Team"},b))}),a.jsxs("div",{className:"search-filter-bar",children:[a.jsxs("div",{className:"search-input-wrap",children:[a.jsx("span",{className:"search-icon",children:"⌕"}),a.jsx("input",{type:"text",className:"form-input search-input",placeholder:"Search by profile, action, path, or hash\\u2026",value:y,onChange:b=>x(b.target.value)}),y&&a.jsx("button",{className:"search-clear",onClick:()=>x(""),children:"×"})]}),a.jsxs("button",{className:`btn btn-sm btn-secondary${E?" active":""}`,onClick:()=>P(!E),children:["Filters",L?` (${w.size+h.size+(g!=="all"?1:0)})`:""]})]}),E&&a.jsxs("div",{className:"filter-panel",children:[se.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Profile"}),a.jsx("div",{className:"filter-chips",children:se.map(b=>a.jsx("button",{className:`filter-chip${w.has(b)?" selected":""}`,onClick:()=>V(b),children:b},b))})]}),z.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Action"}),a.jsx("div",{className:"filter-chips",children:z.map(b=>a.jsx("button",{className:`filter-chip${h.has(b)?" selected":""}`,onClick:()=>ee(b),children:b},b))})]}),r==="team"&&R.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Owner"}),a.jsx("div",{className:"filter-chips",children:R.map(b=>a.jsx("button",{className:`filter-chip${f.has(b.id)?" selected":""}`,onClick:()=>J(b.id),children:b.label},b.id))})]}),a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Time range"}),a.jsx("div",{className:"filter-chips",children:[["1d","Today"],["7d","7 days"],["30d","30 days"],["all","All time"]].map(([b,U])=>a.jsx("button",{className:`filter-chip${g===b?" selected":""}`,onClick:()=>S(b),children:U},b))})]})]}),L&&a.jsxs("div",{className:"active-filters",children:[[...w].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>V(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...h].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>ee(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...f].map(b=>{const U=u[b],A=U?U.name:b;return a.jsxs("span",{className:"active-chip",onClick:()=>J(b),children:[A," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)}),g!=="all"&&a.jsxs("span",{className:"active-chip",onClick:()=>S("all"),children:[g==="1d"?"Today":g==="7d"?"7 days":"30 days"," ",a.jsx("span",{className:"chip-remove",children:"×"})]}),a.jsx("button",{className:"clear-filters",onClick:je,children:"Clear all"})]}),H&&a.jsx("div",{className:"card",style:{borderColor:"var(--danger, #c0392b)",marginBottom:"0.75rem"},children:a.jsx("span",{style:{color:"var(--danger, #c0392b)",fontSize:"0.85rem"},children:"Couldn’t load receipts — your session may have expired. Try signing out and back in."})}),l&&s.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):$.length===0?a.jsx(Bf,{icon:"⌕",title:s.length===0?"No receipts in the last 30 days":"No matching receipts",text:s.length===0?"Execution receipts appear here after an agent uses an authorized tool. Older receipts can be loaded below.":"Try adjusting your search or filters."}):a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:$.length===s.length?`${s.length} receipt${s.length!==1?"s":""}`:`${$.length} of ${s.length} receipts`}),a.jsx("div",{className:"timeline",children:$.map(b=>{var U;return a.jsx("div",{className:"timeline-event",children:a.jsxs("div",{className:"card",style:{marginBottom:0},children:[a.jsxs("div",{className:"auth-card-header",children:[a.jsx(Df,{profileId:b.profileId}),a.jsx("span",{className:"auth-card-path",children:b.path}),a.jsx("span",{className:"receipt-action",children:b.action}),a.jsx("span",{className:"auth-card-time",children:py(b.timestamp)})]}),r==="team"&&b.userId&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner:"," ",a.jsx("span",{style:{color:"var(--text-secondary)"},children:(U=u[b.userId])!=null&&U.name?`${u[b.userId].name} (${u[b.userId].email})`:b.userId})]}),Object.keys(b.executionContext).length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:Object.entries(b.executionContext).map(([A,I])=>`${A}=${I}`).join(" · ")}),a.jsxs("div",{style:{display:"flex",gap:"1rem",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:[a.jsxs("span",{children:["Daily: ",b.cumulativeState.daily.count," calls, $",b.cumulativeState.daily.amount]}),a.jsxs("span",{children:["Monthly: ",b.cumulativeState.monthly.count," calls, $",b.cumulativeState.monthly.amount]})]}),a.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all",marginTop:"0.375rem"},children:b.attestationHash})]})},b.id)})})]}),k&&a.jsx("div",{style:{textAlign:"center",marginTop:"1rem"},children:a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:X,disabled:C,children:C?"Loading…":"Load older"})})]})}const Kc={ollama:{provider:"ollama",endpoint:"http://localhost:11434",models:["gemma4:e4b","gemma4:e2b","gemma4:26b","gemma4:31b","llama3.2","llama3.1","mistral","qwen2.5"]},openrouter:{provider:"openai-compatible",endpoint:"https://openrouter.ai/api/v1",models:["google/gemma-4-31b-it","qwen/qwen3.6-plus:free","stepfun/step-3.5-flash:free","google/gemini-2.5-flash","openai/gpt-4o-mini","anthropic/claude-haiku-4"]},openai:{provider:"openai-compatible",endpoint:"https://api.openai.com/v1",models:["gpt-4o-mini","gpt-4o","o3-mini"]},groq:{provider:"openai-compatible",endpoint:"https://api.groq.com/openai/v1",models:["llama-3.1-8b-instant","llama-3.3-70b-versatile","gemma2-9b-it"]},together:{provider:"openai-compatible",endpoint:"https://api.together.xyz/v1",models:["meta-llama/Llama-3-8b-chat-hf","meta-llama/Llama-3-70b-chat-hf"]}};function yy(){const[e,t]=d.useState(""),[n,r]=d.useState("openrouter"),[o,s]=d.useState("openai-compatible"),[i,l]=d.useState("https://openrouter.ai/api/v1"),[c,u]=d.useState("google/gemma-4-31b-it"),[p,f]=d.useState(""),[v,y]=d.useState(!1),[x,w]=d.useState(!1),[j,h]=d.useState(!1),[m,g]=d.useState(null),S=d.useCallback(C=>{t(C),setTimeout(()=>t(""),3e3)},[]),E=d.useCallback(async()=>{try{const C=await O.getCredential("ai-config");if(y(C.configured),C.configured&&C.fields){C.fields.provider&&s(C.fields.provider),C.fields.endpoint&&l(C.fields.endpoint),C.fields.model&&u(C.fields.model);const T=C.fields.endpoint??"";T.includes("openai.com")?r("openai"):T.includes("groq.com")?r("groq"):T.includes("together.xyz")?r("together"):T.includes("openrouter.ai")?r("openrouter"):r("ollama")}}catch{}},[]);d.useEffect(()=>{E()},[E]);const P=C=>{r(C);const T=Kc[C];T&&(s(T.provider),l(T.endpoint),u(T.models[0]))},k=async()=>{w(!0);try{await O.setCredential("ai-config",{provider:o,endpoint:i,model:c,...p?{apiKey:p}:{}}),y(!0),S("AI configuration saved!")}catch{S("Failed to save AI config")}finally{w(!1)}},N=async()=>{h(!0),g(null);try{const C=await O.aiTest(p?{provider:o,endpoint:i,model:c,apiKey:p}:{});g(C.ok?`OK: ${C.message}`:`Failed: ${C.message}`)}catch(C){g(`Error: ${C instanceof Error?C.message:"Unknown"}`)}finally{h(!1)}};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"AI Assistant"}),a.jsx("p",{className:"page-subtitle",children:"Advisory AI to help you think through intent when authorizing agents."})]}),e&&a.jsx("div",{className:"alert alert-success",children:e}),a.jsxs("div",{className:"card",children:[a.jsx("h3",{className:"card-title",children:"Configuration"}),a.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Connect a trusted AI model that has access to your intent — problem, objective, and tradeoffs — to help you think through authorizations. Keys are encrypted in your vault."}),v&&a.jsxs("div",{className:"status-banner status-banner-success",style:{marginBottom:"1rem",fontSize:"0.8rem"},children:[a.jsx("span",{className:"status-banner-icon",children:"✓"}),a.jsx("span",{className:"status-banner-text",children:"AI configured"})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsx("label",{className:"form-label",children:"Provider Preset"}),a.jsxs("select",{className:"form-input",value:n,onChange:C=>P(C.target.value),children:[a.jsx("option",{value:"openrouter",children:"OpenRouter (recommended)"}),a.jsx("option",{value:"ollama",children:"Ollama (local)"}),a.jsx("option",{value:"openai",children:"OpenAI"}),a.jsx("option",{value:"groq",children:"Groq"}),a.jsx("option",{value:"together",children:"Together"})]})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsx("label",{className:"form-label",children:"Model"}),(()=>{var H;const C=((H=Kc[n])==null?void 0:H.models)??[],T=C.includes(c);return a.jsxs(a.Fragment,{children:[a.jsxs("select",{className:"form-input",value:T?c:"__custom__",onChange:W=>{W.target.value==="__custom__"?u(""):u(W.target.value)},style:{marginBottom:T?void 0:"0.375rem"},children:[C.map(W=>a.jsx("option",{value:W,children:W},W)),a.jsx("option",{value:"__custom__",children:"Custom model..."})]}),!T&&a.jsx("input",{className:"form-input",value:c,onChange:W=>u(W.target.value),placeholder:"Enter model name"})]})})()]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"1rem"},children:[a.jsx("label",{className:"form-label",children:"API Key (if required)"}),a.jsx("input",{className:"form-input",type:"password",value:p,onChange:C=>f(C.target.value),placeholder:v?"••••••••••••••••":"sk-... (not needed for Ollama)"})]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[a.jsx("button",{className:"btn btn-primary",onClick:k,disabled:x,children:x?"Saving...":"Save & Encrypt"}),v&&a.jsx("button",{className:"btn btn-ghost",onClick:N,disabled:j,children:j?"Testing...":"Test Connection"})]}),m&&a.jsx("div",{className:`alert ${m.startsWith("OK")?"alert-success":"alert-error"}`,style:{marginTop:"0.75rem"},children:m})]}),a.jsx(xy,{}),a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,marginBottom:"1rem"},children:"Security"}),a.jsxs("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.7},children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"What the gateway protects"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"Every tool call verified against your authorization bounds"}),a.jsx("li",{children:"Credentials never exposed to agents through MCP"}),a.jsx("li",{children:"Every action produces a signed receipt"})]})]}),a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"Your responsibility"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"If your AI agent has full access to your computer, it could bypass the gateway"}),a.jsx("li",{children:"For best security, run agents in sandboxed environments"}),a.jsx("li",{children:"The gateway secures what agents do through tools — not what they do on your machine"})]})]})]})]})]})}function xy(){const[e,t]=d.useState(null),[n,r]=d.useState({intent:"",context:""}),[o,s]=d.useState(null),[i,l]=d.useState(null),[c,u]=d.useState(null),[p,f]=d.useState(!1),v=d.useCallback(async()=>{if(!p)try{const w=await O.getAIPrompts();t(w),r({intent:w.intent.current,context:w.context.current}),f(!0)}catch(w){l(w instanceof Error?w.message:"Failed to load prompts")}},[p]),y=async w=>{if(e){s(w),l(null);try{const j=n[w],h=j.trim()===e[w].default.trim()?"":j;await O.setAIPrompt(w,h);const m=await O.getAIPrompts();t(m),r({intent:m.intent.current,context:m.context.current}),u(w),setTimeout(()=>u(null),2e3)}catch(j){l(j instanceof Error?j.message:"Save failed")}finally{s(null)}}},x=async w=>{if(confirm(`Revert ${w} prompt to the built-in default?`)){s(w),l(null);try{await O.setAIPrompt(w,"");const j=await O.getAIPrompts();t(j),r({intent:j.intent.current,context:j.context.current})}catch(j){l(j instanceof Error?j.message:"Revert failed")}finally{s(null)}}};return a.jsxs("details",{className:"card",style:{padding:"1.5rem",marginTop:"1rem"},onToggle:w=>{w.currentTarget.open&&v()},children:[a.jsx("summary",{style:{fontSize:"1rem",fontWeight:700,cursor:"pointer",listStyle:"revert",userSelect:"none"},children:"Advanced — AI assistant prompts"}),a.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",margin:"0.75rem 0 1rem 0",lineHeight:1.55},children:"These are the system prompts the AI assistant sees when helping you write Intent (per-authorization) or Context (your standing-orders brief). Edit with care — changes apply on the next chat turn."}),i&&a.jsx("div",{className:"alert alert-error",style:{marginBottom:"0.75rem"},children:i}),!p&&!i&&a.jsx("p",{style:{color:"var(--text-muted)",fontSize:"0.85rem"},children:"Loading prompts…"}),e&&a.jsxs(a.Fragment,{children:[a.jsx(Gc,{kind:"intent",label:"Intent — per-authorization",description:"Used on the Intent gate when creating a new authorization.",state:e.intent,draft:n.intent,onChange:w=>r(j=>({...j,intent:w})),onSave:()=>y("intent"),onRevert:()=>x("intent"),saving:o==="intent",justSaved:c==="intent"}),a.jsx(Gc,{kind:"context",label:"Context — standing-orders brief",description:"Used on the Brief page when refining your context.md.",state:e.context,draft:n.context,onChange:w=>r(j=>({...j,context:w})),onSave:()=>y("context"),onRevert:()=>x("context"),saving:o==="context",justSaved:c==="context"})]})]})}function Gc({kind:e,label:t,description:n,state:r,draft:o,onChange:s,onSave:i,onRevert:l,saving:c,justSaved:u}){const p=o!==r.current;return a.jsxs("section",{style:{marginBottom:"1.5rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"0.25rem",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,fontSize:"0.9rem"},children:t}),a.jsx("div",{style:{fontSize:"0.78rem",color:"var(--text-secondary)"},children:n})]}),r.overridden&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Custom"})]}),a.jsx("textarea",{className:"form-textarea",value:o,onChange:f=>s(f.target.value),rows:12,spellCheck:!1,style:{width:"100%",fontFamily:"'SF Mono', Monaco, 'Cascadia Code', monospace",fontSize:"0.82rem",lineHeight:1.55,resize:"vertical",minHeight:"14rem",marginTop:"0.5rem"},"aria-label":`${t} system prompt`}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",marginTop:"0.5rem",flexWrap:"wrap"},children:[a.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:i,disabled:c||!p,children:c?"Saving…":"Save"}),r.overridden&&a.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:l,disabled:c,title:"Discard the override and use the built-in default",children:"Revert to default"}),u&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--success)"},children:"Saved"}),p&&!c&&!u&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"Unsaved changes"})]}),a.jsxs("details",{style:{marginTop:"0.5rem"},children:[a.jsx("summary",{style:{fontSize:"0.78rem",color:"var(--text-muted)",cursor:"pointer"},children:"Show built-in default"}),a.jsx("pre",{style:{marginTop:"0.5rem",padding:"0.75rem 1rem",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.5rem",fontSize:"0.78rem",lineHeight:1.55,whiteSpace:"pre-wrap",maxHeight:"20rem",overflowY:"auto"},children:r.default})]}),a.jsx("span",{style:{display:"none"},children:e})]})}function wy(e){return e.proposalId?"review":"automatic"}function Yc(e,t,n={}){const r=n.status??"pending",o=n.includeAutonomous??!1,s=[];for(const i of e)r==="pending"&&i.status!=="pending"||n.profile&&i.profileId!==n.profile||s.push({kind:"proposal",id:i.id,sortTimestamp:i.createdAt,commitmentMode:"review",profileId:i.profileId,proposal:i});if(r==="all")for(const i of t){const l=wy(i);!o&&l==="automatic"||n.profile&&i.profileId!==n.profile||s.push({kind:"receipt",id:i.id,sortTimestamp:i.timestamp,commitmentMode:l,profileId:i.profileId,receipt:i})}return s.sort((i,l)=>l.sortTimestamp-i.sortTimestamp),typeof n.limit=="number"&&n.limit>0?s.slice(0,n.limit):s}const Sy={pending:"Pending",committed:"Approved",executed:"Executed",rejected:"Rejected",expired:"Expired"},jy={pending:"status-pending",committed:"status-active",executed:"status-active",rejected:"status-revoked",expired:"status-expired"};function ky(e){const t=Date.now()-e*1e3,n=t/36e5;return n<48?n<1?`${Math.max(1,Math.round(t/6e4))}m ago`:`${Math.round(n)}h ago`:new Date(e*1e3).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Cy(e){return e.split("__").pop()??e}function by(e){const t=e.toLowerCase();return t.includes("delete")||t.includes("refund")||t.includes("cancel")||t.includes("revoke")}const Ny=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]),Ey=/^(image|img|photo|picture|thumbnail)(_?url)?$/i;function zy(e,t){return typeof t!="string"?!1:/^data:image\//i.test(t)?!0:Ey.test(e)?/^https?:\/\//.test(t):/^https?:\/\/.+\.(jpe?g|png|gif|webp|svg|avif)(\?|$)/i.test(t)}function gi(e){if(e==null)return"—";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>gi(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Qc({item:e,onApprove:t,onReject:n,resolving:r}){const o=e.kind==="proposal",s=o?e.proposal.status:"executed",i=o?e.proposal.tool:e.receipt.action,l=Cy(i),c=by(i),u=o?e.proposal.toolArgs:null,p=o?e.proposal.executionContext:e.receipt.executionContext,f=o?null:e.receipt.cumulativeState,v=u?Object.entries(u).filter(([x])=>!Ny.has(x)):[],y=Object.entries(p??{});return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",flexWrap:"wrap"},children:[a.jsx(Df,{profileId:e.profileId}),a.jsx("code",{style:{fontSize:"0.85rem"},children:l}),e.commitmentMode==="automatic"&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"autonomous"}),a.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[a.jsx("span",{className:`status-badge ${jy[s]}`,children:Sy[s]}),a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:ky(e.sortTimestamp)})]})]}),c&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem",fontSize:"0.8rem",color:"var(--warning)",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.375rem",padding:"0.4rem 0.6rem",marginBottom:"0.75rem"},children:[a.jsx("span",{children:"⚠"}),a.jsx("span",{children:"Irreversible action"})]}),o&&typeof(u==null?void 0:u._imagePreview)=="string"&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Preview"}),a.jsx("img",{src:u._imagePreview,alt:typeof(u==null?void 0:u.altText)=="string"?u.altText:"local image preview",style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"}})]}),o&&v.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:v.map(([x,w])=>a.jsxs(d.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:x}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:zy(x,w)?a.jsx("img",{src:w,alt:typeof(u==null?void 0:u.altText)=="string"?u.altText:x,style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"},onError:j=>{const h=j.currentTarget,m=h.parentElement;if(!m)return;h.style.display="none";const g=document.createElement("span");g.textContent=w,g.style.color="var(--text-tertiary)",m.appendChild(g)}}):gi(w)})]},x))})]}),y.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",fontSize:"0.8rem",color:"var(--text-secondary)"},children:y.map(([x,w])=>`${x}=${gi(w)}`).join(" · ")}),f&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["After this action · today: ",f.daily.count," action",f.daily.count===1?"":"s",f.daily.amount>0?`, ${f.daily.amount}`:""," · ","this month: ",f.monthly.count,f.monthly.amount>0?`, ${f.monthly.amount}`:""]}),o&&s==="pending"&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:()=>t==null?void 0:t(e.id),disabled:r,children:r?"Approving…":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:()=>n==null?void 0:n(e.id),disabled:r,children:"Reject"})]}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:[o?"Proposal":"Receipt",": ",e.id]})]})}const Py=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]);function vi(e){if(e==null)return"—";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>vi(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ty(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Iy({proposal:e,currentUserId:t,onAction:n,onMessage:r}){const[o,s]=d.useState(!1),[i,l]=d.useState(!1),[c,u]=d.useState(null),[p,f]=d.useState(!1),[v,y]=d.useState(null),[x,w]=d.useState(!1),j=e.tool.split("__").pop()??e.tool,h=Object.entries(e.toolArgs).filter(([D])=>!Py.has(D)),m=Object.entries(e.executionContext),g=e.pendingApprovers??[],S=e.approvedBy??{},E=Object.keys(S).length,P=g.filter(D=>!(D in S)).length,k=t in S,N=async()=>{if(c===null){f(!0),y(null);try{const D=await O.getAttestationIntent(e.authorizationId);if(!D){y("Intent not available or you are not an authorized approver.");return}const _=await O.decryptIntent({intentCiphertext:D.intentCiphertext,encryptedKey:D.encryptedKey,approverId:t});u(_)}catch(D){y(D instanceof Error?D.message:"Failed to decrypt intent")}finally{f(!1)}}},C=async()=>{x?w(!1):(w(!0),await N())},T=async()=>{s(!0),r("");try{await O.approveProposal(e.id);try{if(c===null){const D=await O.getAttestationIntent(e.authorizationId);if(D){const _=await O.decryptIntent({intentCiphertext:D.intentCiphertext,encryptedKey:D.encryptedKey,approverId:t});u(_),await O.storeApprovedIntent(e.authorizationId,_)}}else await O.storeApprovedIntent(e.authorizationId,c)}catch{}r(`Approved. ${P-1>0?`${P-1} more approver(s) still needed.`:"All approvers signed off — action is ready to execute."}`),n()}catch(D){r(D instanceof Error?D.message:"Approval failed")}finally{s(!1)}},H=async()=>{const D=prompt("Rejection reason (optional):");if(D!==null){l(!0),r("");try{await O.rejectProposal(e.id,D||void 0),r("Action rejected."),n()}catch(_){r(_ instanceof Error?_.message:"Rejection failed")}finally{l(!1)}}},W=o||i;return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:Ee(e.profileId)}),a.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),a.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Ty(e.createdAt)})]}),a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[E," of ",g.length," approver",g.length===1?"":"s"," signed off",g.map(D=>{const _=D in S;return a.jsxs("span",{style:{marginLeft:"0.5rem",color:_?"var(--success, green)":"var(--text-tertiary)"},children:[_?"✓":"○"," ",D===t?"You":D]},D)})]}),a.jsxs("div",{style:{marginBottom:"0.5rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Proposed action"}),a.jsx("code",{style:{fontSize:"0.85rem"},children:j})]}),h.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:h.map(([D,_])=>a.jsxs(d.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:D}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:vi(_)})]},D))})]}),m.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:m.map(([D,_])=>`${D}=${vi(_)}`).join(" · ")}),a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsxs("button",{className:"btn btn-ghost btn-sm",style:{padding:"0.2rem 0",fontSize:"0.75rem"},onClick:C,disabled:p,children:[x?"▲ Hide intent":"▼ Show intent",p&&" (decrypting...)"]}),x&&a.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"var(--bg-main)",borderRadius:"0.375rem",border:"1px solid var(--border)"},children:v?a.jsx("p",{style:{color:"var(--danger)",fontSize:"0.8rem",margin:0},children:v}):c!==null?a.jsx("p",{style:{fontSize:"0.85rem",margin:0,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:c}):a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.8rem",margin:0},children:"No intent available for this authority."})})]}),!k&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:T,disabled:W,children:o?"Approving...":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:H,disabled:W,children:i?"Rejecting...":"Reject"})]}),k&&a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"You approved this action. Waiting on other approvers."}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["Proposal: ",e.id]})]})}function Ry(){const{domain:e,user:t}=ze(),n=(t==null?void 0:t.id)??"",[r,o]=d.useState("awaiting-me"),[s,i]=d.useState([]),[l,c]=d.useState(!0),[u,p]=d.useState(""),f=d.useCallback(async()=>{try{const A=await O.getProposalsForApprover();i(A)}catch{}finally{c(!1)}},[]);fe("proposal-added",f),fe("proposal-approved",f),fe("proposal-rejected",f),fe("proposal-resolved",f),$t(f,3e4);const[v,y]=d.useState([]),x=d.useCallback(async()=>{try{const A=await O.getProposals(e||"owner");y(A)}catch{}},[e]);fe("proposal-added",x),fe("proposal-approved",x),fe("proposal-rejected",x),fe("proposal-resolved",x),$t(x,3e4,e);const w=d.useMemo(()=>v.filter(A=>{var I;return A.status==="pending"&&(((I=A.pendingApprovers)==null?void 0:I.length)??0)===0}),[v]),j=d.useMemo(()=>Yc(w,[],{status:"pending"}),[w]),[h,m]=d.useState([]),g=d.useCallback(async()=>{if(n)try{const I=(await O.getProposals(e||"owner")).filter(Y=>Y.status==="pending"&&Y.pendingApprovers&&Y.pendingApprovers.includes(n)&&Y.approvedBy&&n in Y.approvedBy);m(I)}catch{}},[n,e]);fe("proposal-approved",g),fe("proposal-rejected",g),$t(g,3e4,`${n}:${e}`),d.useEffect(()=>{f(),x(),g()},[]);const[S,E]=d.useState([]),[P,k]=d.useState([]),[N,C]=d.useState(!0),[T,H]=d.useState(null),[W,D]=d.useState(""),[_,B]=d.useState("pending"),[X,se]=d.useState(null),[z,R]=d.useState(!1),$=d.useCallback(async()=>{try{const{proposals:A,receipts:I}=await O.getThread({domain:e,status:_,sinceDays:7});E(A),k(I)}catch{}finally{C(!1)}},[e,_]);$t($,3e4,`${e}:${_}`);const L=async(A,I)=>{H(A),D("");try{const Y=e||"owner",xe=await O.resolveProposal(A,I,Y);D(I==="commit"?`Action approved. Status: ${xe.status}`:"Action rejected."),await Promise.all([$(),x()])}catch(Y){D(Y instanceof Error?Y.message:"Failed")}finally{H(null)}},V=d.useMemo(()=>{const A=new Set;for(const I of S)A.add(I.profileId);for(const I of P)A.add(I.profileId);return Array.from(A).sort()},[S,P]),ee=d.useMemo(()=>Yc(S,P,{status:_,profile:X??void 0,includeAutonomous:z}),[S,P,_,X,z]),J=d.useCallback(()=>{f(),g()},[f,g]),je=d.useMemo(()=>{const A=new Set,I=[];for(const Y of h)A.has(Y.id)||(A.add(Y.id),I.push(Y));return I.sort((Y,xe)=>xe.createdAt-Y.createdAt)},[h]),b=s.length+j.length,U=je.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"Pending Approvals"}),a.jsx("p",{className:"page-subtitle",children:"Actions awaiting approval, plus recent activity from the last 7 days."})]}),a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"1rem"},children:[a.jsxs("button",{className:`nav-tab${r==="awaiting-me"?" active":""}`,onClick:()=>o("awaiting-me"),children:["Awaiting me ",b>0&&a.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--warning)",color:"var(--bg-elevated)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:b})]}),a.jsxs("button",{className:`nav-tab${r==="awaiting-others"?" active":""}`,onClick:()=>o("awaiting-others"),children:["Awaiting others ",U>0&&a.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--border)",color:"var(--text-secondary)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:U})]}),a.jsx("button",{className:`nav-tab${r==="all"?" active":""}`,onClick:()=>{o("all"),$()},children:"All"})]}),r==="awaiting-me"&&a.jsx(a.Fragment,{children:l&&b===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):b===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions awaiting your approval."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Review-mode actions and above-cap actions you must approve will appear here."})]}):a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[(u||W)&&a.jsx("div",{className:"alert alert-success",children:u||W}),j.map(A=>a.jsx(Qc,{item:A,onApprove:I=>L(I,"commit"),onReject:I=>L(I,"reject"),resolving:T===A.id},A.id)),s.map(A=>a.jsx(Iy,{proposal:A,currentUserId:n,onAction:J,onMessage:p},A.id))]})}),r==="awaiting-others"&&a.jsx(a.Fragment,{children:je.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions waiting on others."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Actions you proposed or approved that are pending other approvers will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:je.map(A=>a.jsx(Ay,{proposal:A,currentUserId:n,onCancel:async()=>{try{await O.rejectProposal(A.id,"cancelled by creator"),g(),x()}catch(I){alert(I instanceof Error?I.message:"Cancel failed")}}},A.id))})}),r==="all"&&a.jsxs(a.Fragment,{children:[W&&a.jsx("div",{className:"alert alert-success",style:{marginBottom:"1rem"},children:W}),a.jsxs("div",{className:"filter-chips",style:{marginBottom:"1rem"},children:[a.jsx("button",{className:`filter-chip ${_==="pending"?"selected":""}`,onClick:()=>B("pending"),children:"Pending"}),a.jsx("button",{className:`filter-chip ${_==="all"?"selected":""}`,onClick:()=>B("all"),children:"All"}),V.length>0&&a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),V.map(A=>a.jsx("button",{className:`filter-chip ${X===A?"selected":""}`,onClick:()=>se(X===A?null:A),children:Ee(A)},A)),_==="all"&&a.jsxs(a.Fragment,{children:[a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),a.jsxs("button",{className:`filter-chip ${z?"selected":""}`,onClick:()=>R(!z),title:"Include actions executed without human review (automatic commitment mode)",children:[z?"✓ ":"","Autonomous actions"]})]})]}),N&&ee.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):ee.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:_==="pending"?"No actions awaiting your approval.":"Nothing here yet."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:_==="pending"?"Your agents are operating within their authorizations. Switch to All to see recent activity.":"When an agent calls a gated tool, activity will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:ee.map(A=>a.jsx(Qc,{item:A,onApprove:I=>L(I,"commit"),onReject:I=>L(I,"reject"),resolving:T===A.id},A.id))})]})]})}function _y(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ay({proposal:e,currentUserId:t,onCancel:n}){var u;const[r,o]=d.useState(!1),s=Object.keys(e.approvedBy??{}),i=(e.pendingApprovers??[]).filter(p=>!(p in(e.approvedBy??{}))),l=(((u=e.pendingApprovers)==null?void 0:u.length)??0)>0,c=async()=>{if(confirm("Cancel this action? All approvers will be notified.")){o(!0);try{await n()}finally{o(!1)}}};return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:Ee(e.profileId)}),l&&a.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),a.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:_y(e.createdAt)})]}),a.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:a.jsx("code",{children:e.tool.split("__").pop()??e.tool})}),l&&a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[s.map(p=>a.jsx("span",{style:{marginRight:"0.75rem",color:"var(--success, green)"},children:p===t?"You approved":`${p} approved`},p)),i.map(p=>a.jsxs("span",{style:{marginRight:"0.75rem",color:"var(--text-tertiary)"},children:["Waiting on ",p===t?"you":p]},p))]}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--danger)"},onClick:c,disabled:r,children:r?"Cancelling...":"Cancel"})})]})}const $y=`# Agent Brief
|
|
70
70
|
|
|
71
71
|
You act on my behalf through Suveren — the gateway that gates every
|
|
72
72
|
privileged tool call you make. Suveren implements the bounded-authority
|
package/dist/ui/index.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Suveren</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-Ui0cpzkh.js"></script>
|
|
8
8
|
<link rel="stylesheet" crossorigin href="/assets/index-BUgn3e63.css">
|
|
9
9
|
</head>
|
|
10
10
|
<body>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@suveren/gateway",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.5",
|
|
4
4
|
"description": "Suveren gateway — local agent gateway built in compliance with the Human Agency Protocol (HAP). Runs the UI, control plane, and MCP server in one Node process.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "server.js",
|