l(e=>!e),children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:c?`▾`:`▸`}),` `,o(`tasks.completed`)]}):(0,H.jsxs)(`strong`,{children:[(0,H.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-done`}),o(`tasks.completed`)]}),(0,H.jsx)(`span`,{children:m})]}),(0,H.jsxs)(`div`,{id:s,hidden:!u,"aria-label":o(`tasks.completed`),className:`personal-task-lane-scroll`,ref:O,role:`region`,tabIndex:0,onScroll:e=>T({top:e.currentTarget.scrollTop,height:e.currentTarget.clientHeight}),children:[(0,H.jsx)(`div`,{className:`personal-completed-window`,style:{height:f.length*d},children:N.map(t=>{let n=f[t];return(0,H.jsx)(`div`,{className:`personal-task-card personal-completed-row`,style:{top:t*d,height:d},children:(0,H.jsxs)(`button`,{type:`button`,onFocus:()=>D(t),onBlur:()=>D(null),onClick:()=>a({kind:`todo`,item:{...n,goalId:e.goalId,goalTitle:e.title,ownerLabel:n.claimedBy??e.agentLabel??e.agentId}}),children:[(0,H.jsx)(`span`,{className:`is-done`,children:`✓`}),(0,H.jsx)(`strong`,{children:n.text}),(0,H.jsx)(`small`,{children:n.claimedBy??e.agentLabel??e.agentId})]})},n.todoId)})}),(0,H.jsx)(`div`,{className:`personal-completed-footer`,role:`status`,children:v?o(`tasks.historyLoading`):b?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{children:o(S?`tasks.historyExpired`:`tasks.historyError`)}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>{S&&(_(void 0),O.current&&(O.current.scrollTop=0)),C(!1),x(!1),te(e=>e+1)},children:o(`tasks.historyRetry`)})]}):r?g===null?o(`tasks.historyEnd`):(0,H.jsx)(`button`,{type:`button`,onClick:()=>{O.current&&(O.current.scrollTop=f.length*d)},children:o(`tasks.historyMore`)}):o(`tasks.historyLocalOnly`)})]})]})}function kb({children:e,count:t,label:n,tone:r,listView:i=!1}){let a=(0,V.useId)(),o=(0,V.useRef)(null),s=(0,V.useRef)([]),c=(0,V.useRef)(null),[l,u]=(0,V.useState)({after:!1,before:!1}),d=(0,V.useCallback)(()=>{let e=o.current;if(!e)return;let t={after:Math.max(0,e.scrollHeight-e.clientHeight)-e.scrollTop>1,before:e.scrollTop>1};u(e=>e.after===t.after&&e.before===t.before?e:t)},[]);return(0,V.useEffect)(()=>{let e=o.current;if(!e)return;let t=new ResizeObserver(d);return c.current=t,t.observe(e),e.addEventListener(`scroll`,d,{passive:!0}),d(),()=>{t.disconnect(),c.current=null,s.current=[],e.removeEventListener(`scroll`,d)}},[i,d]),(0,V.useEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;for(let e of s.current)t.unobserve(e);let n=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(let e of n)t.observe(e);s.current=n,d()},[e,t,i,d]),i?!t&&r!==`done`?null:(0,H.jsxs)(`details`,{className:`personal-task-group tone-${r}`,open:!0,children:[(0,H.jsxs)(`summary`,{children:[(0,H.jsx)(nm,{size:16}),(0,H.jsx)(`strong`,{children:n}),(0,H.jsx)(`span`,{children:t})]}),(0,H.jsx)(`div`,{className:`personal-task-list-rows`,children:e})]}):(0,H.jsxs)(`section`,{className:`personal-object-list personal-task-lane`,children:[(0,H.jsxs)(`header`,{id:a,children:[(0,H.jsxs)(`strong`,{children:[(0,H.jsx)(`i`,{"aria-hidden":`true`,className:`personal-kanban-dot tone-${r}`}),n]}),(0,H.jsx)(`span`,{children:t})]}),(0,H.jsx)(`div`,{"aria-labelledby":a,className:`personal-task-lane-scroll${l.before?` has-overflow-before`:``}${l.after?` has-overflow-after`:``}`,ref:o,role:`region`,tabIndex:t>0?0:-1,children:e})]})}function Ab({historyEnabled:e=!1,goal:t,items:n,onDraftTaskFromMessage:r,onOpenChat:i,onQuickComplete:a,quickCompletingTodoIds:o,onSelect:s,selectedTodoId:c=null,userTodos:l}){let{t:u}=qi(),[d,f]=(0,V.useState)(!1),[p,m]=(0,V.useState)({goalId:``,laneId:`all`}),h=(0,V.useRef)(null);(0,V.useEffect)(()=>{if(!c)return;let e=window.requestAnimationFrame(()=>h.current?.scrollIntoView({block:`nearest`,inline:`nearest`}));return()=>window.cancelAnimationFrame(e)},[c]);let g=l.filter(e=>e.goalId===t.goalId).map(e=>({...e,goalTitle:t.title})),_=e=>e.priority===`P0`?0:e.priority===`P1`?1:e.priority===`P2`?2:3,v=(0,V.useMemo)(()=>{let e=new Map((t.agentLanes??[]).map(e=>[e.agentId,e]));for(let n of t.agentTodos)n.claimedBy&&!e.has(n.claimedBy)&&e.set(n.claimedBy,{agentId:n.claimedBy,label:n.claimedBy});return[...e.values()]},[t.agentLanes,t.agentTodos]),y=p.goalId===t.goalId&&v.some(e=>e.agentId===p.laneId)?p.laneId:`all`,b=e=>y===`all`||e===y,x=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&!e.done).filter(e=>b(e.claimedBy)).sort((e,t)=>_(e)-_(t)),S=t.agentTodos.filter(e=>e.taskClass!==`continuous_monitor`&&e.done).filter(e=>b(e.claimedBy)),C=n.filter(e=>e.kind===`schedule`&&b(e.schedule.agentId)),w=n.filter(e=>e.kind===`run`&&!!e.run.todoId&&b(e.run.agentId)),T=!g.length&&!x.length&&!S.length&&!C.length,E=n.filter(e=>e.kind===`message`&&(e.message.role===`user`||e.message.role===`assistant`)),D=E.reduce((e,t,n)=>t.message.role===`user`?n:e,-1),O=D>=0?E[D]?.message:null,k=D>=0?E.slice(D+1).reverse().find(e=>e.message.role===`assistant`)?.message:null,ee=D>=0&&E.slice(D+1).some(e=>e.message.role===`assistant`&&e.message.pending);return(0,H.jsxs)(`section`,{"aria-label":u(`header.tasks`),className:`personal-task-board${d?` is-list-view`:``}`,children:[(0,H.jsxs)(`header`,{className:`personal-task-view-toolbar`,children:[(0,H.jsx)(`div`,{children:(0,H.jsx)(`strong`,{children:u(`header.tasks`)})}),(0,H.jsxs)(`div`,{className:`personal-task-view-switch`,role:`group`,"aria-label":u(`tasks.viewLabel`),children:[(0,H.jsx)(`button`,{type:`button`,"aria-pressed":d,onClick:()=>f(!0),children:u(`tasks.listView`)}),(0,H.jsx)(`button`,{type:`button`,"aria-pressed":!d,onClick:()=>f(!1),children:u(`tasks.boardView`)})]})]}),v.length>1?(0,H.jsxs)(`section`,{"aria-label":u(`tasks.agentLaneFilter`),className:`personal-task-lane-filter`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(Qp,{size:15}),(0,H.jsx)(`span`,{children:(0,H.jsx)(`strong`,{children:u(`tasks.agentLane`)})})]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{className:`sr-only`,children:u(`tasks.agentLaneFilter`)}),(0,H.jsxs)(`select`,{"aria-label":u(`tasks.agentLaneFilter`),onChange:e=>m({goalId:t.goalId,laneId:e.target.value}),value:y,children:[(0,H.jsx)(`option`,{value:`all`,children:u(`tasks.allAgentLanes`,{count:v.length})}),v.map(e=>(0,H.jsx)(`option`,{value:e.agentId,children:e.label},e.agentId))]}),(0,H.jsx)(nm,{"aria-hidden":!0,size:14})]})]}):null,O?(0,H.jsxs)(`section`,{"aria-label":u(`tasks.chatRecent`),className:`personal-task-chat-receipt`,children:[(0,H.jsx)(`span`,{className:`personal-task-chat-icon`,children:(0,H.jsx)(Om,{size:18})}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`header`,{children:[(0,H.jsx)(`strong`,{children:u(ee?`tasks.chatPending`:k?`tasks.chatAgentReplied`:`tasks.chatRecent`)}),(0,H.jsx)(`small`,{children:t.agentLabel??t.agentId})]}),(0,H.jsxs)(`p`,{className:`is-user`,children:[(0,H.jsx)(`b`,{children:u(`common.you`)}),O.text]}),k&&!k.pending?(0,H.jsxs)(`p`,{className:`is-assistant`,children:[(0,H.jsx)(`b`,{children:u(`common.agent`)}),k.text]}):null,(0,H.jsx)(`small`,{children:u(ee?`tasks.chatPendingDescription`:`tasks.chatUnchangedDescription`)})]}),(0,H.jsxs)(`footer`,{children:[(0,H.jsxs)(`button`,{onClick:i,type:`button`,children:[(0,H.jsx)(Om,{size:14}),u(`tasks.chatViewReply`)]}),k&&!ee&&r?(0,H.jsxs)(`button`,{onClick:()=>r(k.text),type:`button`,children:[(0,H.jsx)(Cm,{size:14}),u(`tasks.convertToTask`)]}):null]})]}):null,(0,H.jsxs)(`div`,{className:d?`personal-task-grouped-list`:`personal-task-kanban`,children:[(0,H.jsxs)(kb,{listView:d,count:g.length,label:u(`timeline.waitingConfirmation`),tone:`attention`,children:[g.map(e=>{let t=Xi(e.updatedAt,u);return(0,H.jsxs)(`button`,{onClick:()=>s({item:e,kind:`attention`}),type:`button`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,className:`is-attention`,children:`!`}),(0,H.jsx)(`strong`,{children:e.text}),(0,H.jsxs)(`small`,{children:[(0,H.jsx)(`span`,{className:`personal-row-status ${e.blocking?`is-blocking`:`is-pending`}`,children:e.blocking?u(`tasks.blocked`):u(`tasks.pending`)}),t?(0,H.jsx)(`span`,{className:`personal-task-age`,children:u(`tasks.waitingAge`,{age:t})}):null]})]},e.todoId)}),g.length?null:(0,H.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyConfirm`)})]}),(0,H.jsxs)(kb,{listView:d,count:x.length,label:u(`tasks.pendingAndRunning`),tone:`progress`,children:[x.map(e=>{let n={...e,goalId:t.goalId,goalTitle:t.title,ownerLabel:e.claimedBy??t.agentLabel??t.agentId},r=w.find(t=>t.run.todoId===e.todoId)?.run;return(0,H.jsxs)(`div`,{className:`personal-task-card${r?` has-session`:``}${c===e.todoId?` is-selected`:``}`,ref:c===e.todoId?e=>{h.current=e}:void 0,children:[(0,H.jsxs)(`button`,{"aria-pressed":c===e.todoId,onClick:()=>s({item:n,kind:`todo`}),type:`button`,children:[(0,H.jsx)(`span`,{children:`○`}),(0,H.jsx)(`strong`,{children:e.text}),(0,H.jsxs)(`small`,{children:[e.priority?(0,H.jsx)(`span`,{className:`personal-priority-badge is-${e.priority.toLowerCase()}`,children:e.priority}):null,e.status===`blocked`?(0,H.jsx)(`span`,{className:`personal-priority-badge is-blocked`,children:u(`tasks.blocked`)}):null,r?(0,H.jsx)(`span`,{className:`personal-task-session-status`,children:r.status===`running`||r.status===`queued`?u(`runs.running`):r.status===`failed`?u(`tasks.sessionError`):u(`common.waiting`)}):null,e.status===`deferred`?(0,H.jsx)(`span`,{className:`personal-task-session-status`,children:u(`drawer.taskStatusDeferred`)}):r?null:(0,H.jsx)(`span`,{className:`personal-task-session-status`,children:u(`tasks.waiting`)}),e.claimedBy??t.agentLabel??t.agentId]})]}),(0,H.jsxs)(`div`,{className:`personal-task-card-actions`,children:[r?(0,H.jsxs)(`button`,{className:`personal-task-session-link`,"aria-label":u(`tasks.openExecution`,{name:e.text}),onClick:()=>s({item:r,kind:`run`}),title:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`),type:`button`,children:[(0,H.jsx)(pm,{size:14}),(0,H.jsx)(`span`,{children:r.status===`completed`?u(`tasks.viewResult`):u(`tasks.viewExecution`)})]}):null,a?(0,H.jsx)(`button`,{"aria-busy":o?.has(e.todoId)||void 0,"aria-label":u(`tasks.markComplete`,{name:e.text}),disabled:o?.has(e.todoId),onClick:()=>void a(n),title:u(`tasks.completed`),type:`button`,children:o?.has(e.todoId)?(0,H.jsx)(wm,{className:`personal-spin`,size:14}):(0,H.jsx)(tm,{size:14})}):null,(0,H.jsx)(`button`,{"aria-label":u(`tasks.moreActions`,{name:e.text}),onClick:()=>s({item:n,kind:`todo`}),title:u(`common.actions`),type:`button`,children:(0,H.jsx)(fm,{size:14})})]})]},e.todoId)}),x.length?null:(0,H.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyRunning`)})]}),(0,H.jsxs)(kb,{listView:d,count:C.length,label:u(`tasks.scheduled`),tone:`schedule`,children:[C.map(e=>(0,H.jsxs)(`button`,{onClick:()=>s({item:e.schedule,kind:`schedule`}),type:`button`,children:[(0,H.jsx)(`span`,{children:`◷`}),(0,H.jsx)(`strong`,{children:e.schedule.label}),(0,H.jsx)(`small`,{children:e.schedule.status===`paused`?u(`schedule.paused`):u(`schedule.active`)})]},e.id)),C.length?null:(0,H.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptySchedules`)})]}),(0,H.jsx)(Ob,{goal:t,agentId:y,seed:S,enabled:e,listView:d,onSelect:s},`${t.goalId}:${y}:${e}`)]}),T?(0,H.jsx)(`p`,{className:`personal-task-empty`,children:u(`tasks.emptyGoal`)}):null]})}function jb(e,t){return{live_steering:{label:t(`lark.ingressSteering`),detail:t(`lark.ingressSteeringDescription`)},session_queue:{label:t(`lark.ingressQueue`),detail:t(`lark.ingressQueueDescription`)},async_inbox:{label:t(`lark.ingressAsync`),detail:t(`lark.ingressAsyncDescription`)},direct_session:{label:t(`lark.ingressLegacy`),detail:t(`lark.ingressLegacyDescription`)}}[e]}function Mb(e,t){return e.listener_status===`starting`?{label:t(`lark.health.starting`),detail:t(`lark.health.startingDetail`),state:`not_ready`}:e.listener_status===`retrying`&&e.listener_error_code===`lark_event_source_disconnected`?{label:t(`lark.health.sourceDisconnected`),detail:t(`lark.health.sourceDisconnectedDetail`),state:`not_ready`}:e.listener_status===`retrying`?{label:t(`lark.health.retrying`),detail:t(`lark.health.retryingDetail`),state:`not_ready`}:e.listener_status===`stopped`||e.listener_status===null?{label:t(`lark.health.notStarted`),detail:t(`lark.health.notStartedDetail`),state:`not_ready`}:e.last_event_status===`message_context_permission_required`?{label:t(`lark.health.messageContextPermission`),detail:t(`lark.health.messageContextPermissionDetail`),state:`not_ready`}:e.last_event_status===`processing_failed`?{label:t(`lark.health.processingFailed`),detail:t(`lark.health.processingFailedDetail`),state:`not_ready`}:e.health_error_code===`invalid_routing_state`?{label:t(`lark.health.invalidRouting`),detail:t(`lark.health.invalidRoutingDetail`),state:`not_ready`}:e.last_event_status===`queued_for_agent`?{label:t(`lark.health.queued`),detail:t(`lark.health.queuedDetail`,{agent:e.agent_id??t(`lark.targetAgent`)}),state:`ready`}:e.last_event_status===`context_only_captured`||e.last_event_status===`context_only_already_captured`?{label:t(`lark.health.contextCaptured`),detail:t(`lark.health.contextCapturedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`not_addressed`?{label:t(`lark.health.notAddressed`),detail:t(`lark.health.notAddressedDetail`),state:`ready`}:e.last_event_status===`ignored`&&e.last_event_reason===`self_message`?{label:t(`lark.health.listening`),detail:t(`lark.health.ignoredSelf`),state:`ready`}:e.health_error_code===`lark_event_route_mismatch`||[`chat_mismatch`,`topic_mismatch`,`route_ambiguous`].includes(e.last_event_reason??``)?{label:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguous`):t(`lark.health.routeMismatch`),detail:e.last_event_reason===`route_ambiguous`?t(`lark.health.routeAmbiguousDetail`):t(`lark.health.routeMismatchDetail`),state:`not_ready`}:[`invalid_event`,`binding_unavailable`].includes(e.last_event_reason??``)?{label:t(`lark.health.routeUnavailable`),detail:t(`lark.health.routeUnavailableDetail`),state:`not_ready`}:e.last_event_status===`replied_and_acknowledged`?{label:t(`lark.health.listening`),detail:t(`lark.health.eventProcessed`,{events:e.event_count,replies:e.replied_count}),state:`ready`}:e.health_error_code===`lark_event_delivery_unverified`||e.event_count===0?{label:t(`lark.health.eventUnverified`),detail:t(`lark.health.eventUnverifiedDetail`),state:`unverified`}:{label:e.reply_ready?t(`lark.health.listening`):t(`lark.health.unavailable`),detail:t(`lark.health.lastStatus`,{status:e.last_event_status??t(`lark.health.waiting`)}),state:e.reply_ready?`ready`:`not_ready`}}function Nb(e){return e.history_permission_guidance?.api_document_url??null}function Pb(e,t,n){if(e instanceof Eh){let t=String(e.payload.error_code??``);return{lark_cli_not_installed:n(`lark.error.cliMissing`),lark_cli_not_executable:n(`lark.error.cliExecutable`),lark_cli_start_failed:n(`lark.error.cliStart`),lark_message_permissions_required:n(`lark.error.messagePermissions`),lark_app_required:n(`lark.error.appRequired`),invalid_lark_app:n(`lark.error.invalidApp`),lark_group_lookup_failed:n(`lark.error.groupLookup`),provider_api_failed:n(`lark.error.provider`)}[t]??e.message}return e instanceof Error?e.message:t}function Fb({embedded:e=!1,focusGoalConnection:t=!1,goals:n,initialGoalId:r,onChanged:i,onClose:a}){let{t:o}=qi(),[s,c]=(0,V.useState)(`connections`),[l,u]=(0,V.useState)([]),[d,f]=(0,V.useState)([]),[p,m]=(0,V.useState)(!0),[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)(``),[y,b]=(0,V.useState)(t),[x,S]=(0,V.useState)(``),[C,w]=(0,V.useState)(r??n[0]?.goalId??``),[T,E]=(0,V.useState)(``),[D,O]=(0,V.useState)([]),[k,ee]=(0,V.useState)(``),[te,A]=(0,V.useState)(!1),[j,M]=(0,V.useState)(null),[N,P]=(0,V.useState)(`addressed_only`),[F,ne]=(0,V.useState)(t&&r?`goal`:`manager`),[re,I]=(0,V.useState)(`async_inbox`),[L,ie]=(0,V.useState)(`topic_reply`),[R,ae]=(0,V.useState)(``),[oe,se]=(0,V.useState)(!1),[ce,le]=(0,V.useState)({}),[ue,z]=(0,V.useState)(!1),[de,fe]=(0,V.useState)(null),[pe,me]=(0,V.useState)(null),[he,ge]=(0,V.useState)(null),[_e,ve]=(0,V.useState)(null),[ye,be]=(0,V.useState)(!1),[xe,Se]=(0,V.useState)(`loopx-workspace-bot`),[Ce,we]=(0,V.useState)(`feishu`),[Te,B]=(0,V.useState)(null),[Ee,De]=(0,V.useState)(!1),[Oe,ke]=(0,V.useState)(null),Ae=(0,V.useRef)(null),je=(0,V.useRef)(null),Me=(0,V.useRef)(!1);async function Ne(){m(!0),g(null);try{let[e,t]=await Promise.all([zg(),Jg()]);u(e),f(t),S(t=>t||e.find(e=>e.reply_ready)?.app_ref||e.find(e=>e.ready)?.app_ref||e[0]?.app_ref||``)}catch(e){g(Pb(e,o(`lark.error.configuration`),o))}finally{m(!1)}}(0,V.useEffect)(()=>{Ne()},[]),(0,V.useEffect)(()=>{if(!t||p||Me.current||!r)return;Me.current=!0;let e=d.find(e=>e.goal_id===r);e?qe(e):Ke(n.find(e=>e.goalId===r))},[d,t,n,r,p]),(0,V.useEffect)(()=>{if(!y||!x||he){O([]),ee(``),A(!1),M(null);return}let e=!1;A(!0),M(null);let t=window.setTimeout(()=>{Kg(x,T).then(t=>{e||(O(t),ee(e=>t.some(t=>t.chat_id===e)?e:t[0]?.chat_id??``))}).catch(t=>{e||(O([]),ee(``),M(Pb(t,o(`lark.error.groupLoad`),o)))}).finally(()=>{e||A(!1)})},180);return()=>{e=!0,window.clearTimeout(t)}},[x,T,y,he]),(0,V.useEffect)(()=>{if(!ye||!Te||[`ready`,`failed`,`cancelled`].includes(Te.status))return;let e=!1,t=window.setTimeout(()=>{Hg(Te.setup_id).then(async t=>{e||(B(t),t.verification_url&&je.current!==t.verification_url&&(je.current=t.verification_url,Ae.current&&!Ae.current.closed&&(Ae.current.location.href=t.verification_url)),t.status===`ready`&&(await Ne(),S(t.app_ref),le({}),be(!1)),t.status===`failed`&&ke(t.error??o(`lark.error.appCreate`)))}).catch(t=>{e||ke(Pb(t,o(`lark.error.setupPoll`),o))})},650);return()=>{e=!0,window.clearTimeout(t)}},[ye,Te]);let Pe=n.find(e=>e.goalId===C),Fe=Pe?.agentId?[{agentId:Pe.agentId,label:Pe.agentLabel??Pe.agentId}]:[],Ie=Pe?.agentLanes?.length?Pe.agentLanes:Fe,Le=Ie.some(e=>e.agentId===R),Re=[];oe?Re=Ie.map(e=>({agentId:e.agentId,appRef:ce[e.agentId]??x})):Le&&(Re=[{agentId:R,appRef:x}]);let ze=Re.map(e=>e.agentId),Be=!!he||Re.length>0&&Re.every(e=>l.some(t=>t.app_ref===e.appRef&&t.reply_ready)),Ve=o(`lark.connect`);pe?Ve=o(`lark.saveConnection`):oe&&(Ve=o(`lark.connectAllAgentsAction`,{count:ze.length}));let He=l.find(e=>e.app_ref===x),Ue=D.find(e=>e.chat_id===k),We=(0,V.useMemo)(()=>{let e=_.trim().toLocaleLowerCase();return e?d.filter(t=>[t.app_label,t.chat_name,t.goal_title,t.topic_name].some(t=>t.toLocaleLowerCase().includes(e))):d},[d,_]),Ge=(0,V.useMemo)(()=>d.filter(e=>Mb(e,o).state===`unverified`).length,[d,o]);function Ke(e){let i=e??n.find(e=>e.goalId===r)??n[0];me(null),ge(null),ne(e||t?`goal`:`manager`),S(l.some(e=>e.app_ref===x)?x:l.find(e=>e.reply_ready)?.app_ref??l[0]?.app_ref??``),ee(``),w(i?.goalId??``),ae(i?.agentId??``),se(!1),le({}),P(`addressed_only`),I(`async_inbox`),ie(`topic_reply`),E(``),fe(null),b(!0)}function qe(e){me(e.goal_id),ge(e),ne(e.conversation_kind??`goal`),S(e.app_ref),w(e.goal_id);let t=n.find(t=>t.goalId===e.goal_id),r=t?.agentLanes?.length?t.agentLanes:t?.agentId?[{agentId:t.agentId}]:[];ae(e.agent_id??(r.length===1?r[0].agentId:``)),se(!1),le({}),P(e.capture_scope),I(e.ingress_mode===`direct_session`?`async_inbox`:e.ingress_mode),ie(e.reply_mode),E(e.chat_name),fe(null),b(!0)}function Je(){B(null),ke(null),je.current=null,be(!0)}async function Ye(){if(!(Ee||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(xe))){De(!0),ke(null),je.current=null,Ae.current=window.open(window.location.href,`_blank`);try{let e=await Vg({appRef:xe,brand:Ce});B(e)}catch(e){Ae.current?.close(),ke(Pb(e,o(`lark.error.setupStart`),o))}finally{De(!1)}}}async function Xe(){let e=Te;if(be(!1),Ae.current?.close(),e&&![`ready`,`failed`,`cancelled`].includes(e.status))try{await Ug(e.setup_id)}catch{}}async function Ze(){if(!(!x||!C||!he&&!Ue||F===`goal`&&ze.length===0||ue)){z(!0),fe(null);try{let e={...F===`manager`?{...he?{connectionId:he.connection_id}:{appRef:x,chatId:Ue.chat_id,chatName:Ue.chat_name}}:he?{connectionId:he.connection_id,agentId:R}:{agentBindings:Re,chatId:Ue.chat_id,chatName:Ue.chat_name},conversationKind:F,captureScope:F===`manager`?`addressed_only`:N,goalId:C,incomingMode:N===`configured_chat_all`?`all`:`mentions`,ingressMode:F===`manager`?`session_queue`:re,replyMode:L},t=await Yg({...e,execute:!1});if(!t.ok)throw new Eh(t.public_summary??t.blocker??o(`lark.error.bindPreview`),{error_code:t.blocker??`provider_api_failed`});let n=await Yg({...e,execute:!0});if(!n.ok)throw new Eh(n.public_summary??n.blocker??o(`lark.error.bind`),{error_code:n.blocker??`provider_api_failed`});b(!1),await Ne(),i?.()}catch(e){fe(Pb(e,o(`lark.error.bind`),o))}finally{z(!1)}}}async function Qe(e,t){if(_e!==t){ve(t);return}try{await Xg(e,t),ve(null),await Ne(),i?.()}catch(e){g(Pb(e,o(`lark.error.disconnect`),o))}}return(0,H.jsxs)(`section`,{className:`personal-lark-settings${e?` is-embedded`:``}`,"aria-label":o(`lark.configuration`),children:[e?null:(0,H.jsxs)(`header`,{className:`personal-lark-header`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`small`,{children:o(`settings.goalConnections`)}),(0,H.jsx)(`h1`,{children:`Lark`})]}),(0,H.jsx)(`button`,{"aria-label":o(`lark.closeSettings`),className:`personal-icon-button`,onClick:a,type:`button`,children:(0,H.jsx)(eh,{size:18})})]}),(0,H.jsxs)(`nav`,{className:`personal-lark-tabs`,"aria-label":o(`lark.management`),children:[(0,H.jsxs)(`button`,{"aria-current":s===`apps`?`page`:void 0,onClick:()=>c(`apps`),type:`button`,children:[o(`lark.apps`),` `,(0,H.jsx)(`span`,{children:p?`…`:l.length})]}),(0,H.jsxs)(`button`,{"aria-current":s===`connections`?`page`:void 0,onClick:()=>c(`connections`),type:`button`,children:[o(`lark.connections`),` `,(0,H.jsx)(`span`,{children:p?`…`:d.length})]})]}),h?(0,H.jsx)(`p`,{className:`personal-notification-error`,children:h}):null,p?(0,H.jsxs)(`div`,{className:`personal-lark-loading`,children:[(0,H.jsx)(wm,{className:`is-spinning`,size:18}),o(`lark.loading`)]}):null,!p&&s===`apps`?(0,H.jsxs)(`div`,{className:`personal-lark-apps`,children:[(0,H.jsxs)(`div`,{className:`personal-lark-app-toolbar`,children:[(0,H.jsx)(`span`,{children:o(`lark.reusableApps`,{count:l.length})}),(0,H.jsxs)(`button`,{className:`personal-primary-action`,onClick:Je,type:`button`,children:[(0,H.jsx)(Fm,{size:16}),o(`lark.newApp`)]})]}),(0,H.jsxs)(`div`,{className:`personal-lark-app-grid`,children:[l.map(e=>(0,H.jsxs)(`article`,{className:`personal-lark-app-card`,children:[(0,H.jsx)(`span`,{className:`personal-lark-app-avatar`,children:(0,H.jsx)(Qp,{size:19})}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:e.label}),(0,H.jsxs)(`small`,{children:[e.brand,` · lark-cli profile`]})]}),(0,H.jsx)(`em`,{className:e.reply_ready?`is-ready`:`is-off`,children:e.reply_ready?o(`lark.autoReplyReady`):e.ready?o(`lark.needsMessagePermissions`):o(`lark.needsSetup`)}),(0,H.jsxs)(`p`,{children:[o(`lark.goalConnections`,{count:d.filter(t=>t.app_ref===e.app_ref).length}),e.ready&&!e.reply_ready?` · ${o(`lark.autoReplyUnavailable`)}`:``]})]},e.app_ref)),l.length===0?(0,H.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noProfiles`)}):null]})]}):null,!p&&s===`connections`?(0,H.jsxs)(`div`,{className:`personal-lark-connections`,children:[Ge>0?(0,H.jsxs)(`p`,{className:`personal-lark-route-readiness`,role:`status`,children:[(0,H.jsx)(Om,{size:15}),o(`lark.routesUnverified`,{count:Ge})]}):null,(0,H.jsxs)(`div`,{className:`personal-lark-toolbar`,children:[(0,H.jsxs)(`label`,{children:[(0,H.jsx)(Bm,{size:16}),(0,H.jsx)(`input`,{"aria-label":o(`lark.searchConnections`),onChange:e=>v(e.target.value),placeholder:o(`lark.searchPlaceholder`),type:`search`,value:_})]}),(0,H.jsxs)(`button`,{className:`personal-primary-action`,disabled:l.length===0||n.length===0,onClick:()=>Ke(),type:`button`,children:[(0,H.jsx)(Fm,{size:16}),o(`lark.connectApp`)]})]}),(0,H.jsxs)(`div`,{className:`personal-lark-table`,role:`table`,"aria-label":o(`lark.goalTopicConnections`),children:[(0,H.jsxs)(`div`,{className:`personal-lark-table-head`,role:`row`,children:[(0,H.jsx)(`span`,{children:o(`lark.connection`)}),(0,H.jsx)(`span`,{children:o(`common.goal`)}),(0,H.jsx)(`span`,{children:o(`lark.capture`)}),(0,H.jsx)(`span`,{children:o(`lark.processing`)}),(0,H.jsx)(`span`,{children:o(`common.actions`)})]}),We.map(e=>{let t=Mb(e,o);return(0,H.jsxs)(`div`,{className:`personal-lark-table-row`,role:`row`,children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:e.chat_name}),(0,H.jsxs)(`small`,{children:[e.app_label,` · `,t.label]}),(0,H.jsx)(`small`,{children:t.detail}),t.state===`unverified`?(0,H.jsxs)(`a`,{href:`https://open.feishu.cn/document/server-docs/im-v1/message/events/receive?lang=zh-CN`,rel:`noreferrer`,target:`_blank`,children:[(0,H.jsx)(pm,{size:12}),o(`lark.openEventSettings`)]}):null,Nb(e)?(0,H.jsxs)(`a`,{href:Nb(e)??void 0,rel:`noreferrer`,target:`_blank`,children:[(0,H.jsx)(pm,{size:12}),o(`lark.historyPermission`)]}):null]}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:e.goal_title}),(0,H.jsxs)(`small`,{children:[`# `,e.topic_name]})]}),(0,H.jsx)(`span`,{children:e.capture_scope===`addressed_only`?o(`lark.mentionsOnly`):o(`lark.allTopicMessages`)}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:e.conversation_kind===`manager`?o(`lark.managerConversation`):jb(e.ingress_mode,o).label}),(0,H.jsx)(`small`,{children:e.conversation_kind===`manager`?o(`lark.managerConversationDescription`):e.agent_id??jb(e.ingress_mode,o).detail})]}),(0,H.jsxs)(`span`,{className:`personal-lark-row-actions`,children:[(0,H.jsx)(`button`,{"aria-label":o(`lark.settingsConfigure`,{goal:e.goal_title}),onClick:()=>qe(e),type:`button`,children:(0,H.jsx)(Wm,{size:15})}),(0,H.jsxs)(`button`,{"aria-label":o(`lark.settingsDisconnect`,{goal:e.goal_title}),className:_e===e.connection_id?`is-confirm`:``,onClick:()=>void Qe(e.goal_id,e.connection_id),type:`button`,children:[(0,H.jsx)($m,{size:15}),_e===e.connection_id?o(`common.confirm`):null]})]})]},e.connection_id)}),We.length===0?(0,H.jsx)(`p`,{className:`personal-lark-empty`,children:o(`lark.noConnections`)}):null]})]}):null,y?(0,H.jsx)(`div`,{className:`personal-lark-modal-backdrop`,role:`presentation`,children:(0,H.jsxs)(`section`,{"aria-labelledby":`connect-lark-title`,"aria-modal":`true`,className:`personal-lark-modal`,role:`dialog`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`small`,{children:`Goal Topic connection`}),(0,H.jsx)(`h2`,{id:`connect-lark-title`,children:o(pe?`lark.editConnection`:`lark.connectApp`)})]}),(0,H.jsx)(`button`,{"aria-label":o(`lark.closeConnection`),onClick:()=>b(!1),type:`button`,children:(0,H.jsx)(eh,{size:18})})]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.conversationKind`)}),(0,H.jsxs)(`select`,{"aria-label":o(`lark.conversationKind`),disabled:!!he,value:F,onChange:e=>ne(e.target.value),children:[(0,H.jsx)(`option`,{value:`manager`,children:o(`lark.managerConversation`)}),(0,H.jsx)(`option`,{value:`goal`,children:o(`lark.workerConversation`)})]})]}),F===`manager`?(0,H.jsx)(`p`,{children:o(`lark.managerConversationDescription`)}):null,he?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,H.jsx)(`div`,{children:he.app_label})]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,H.jsx)(`div`,{children:he.chat_name})]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,H.jsx)(`div`,{children:he.goal_title})]}),(0,H.jsx)(`small`,{children:o(`lark.editPreservesIdentity`)})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.appProfile`)}),(0,H.jsx)(`select`,{"aria-label":o(`lark.appProfile`),disabled:p,onChange:e=>{e.target.value===`__register__`?Je():(S(e.target.value),le({}))},value:x,children:p?(0,H.jsx)(`option`,{value:``,children:o(`lark.appLoading`)}):(0,H.jsxs)(H.Fragment,{children:[l.map(e=>(0,H.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref)),(0,H.jsx)(`option`,{value:`__register__`,children:o(`lark.registerAnother`)})]})}),(0,H.jsx)(`small`,{children:o(`lark.defaultAgentAppDescription`)})]}),He?.ready&&!He.reply_ready?(0,H.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.appPermissions`)}):null,(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.groupChat`)}),(0,H.jsx)(`input`,{"aria-label":o(`lark.groupSearch`),onChange:e=>E(e.target.value),placeholder:o(`lark.groupSearch`),type:`search`,value:T}),te?(0,H.jsxs)(`div`,{className:`personal-lark-group-state`,role:`status`,children:[(0,H.jsx)(wm,{className:`is-spinning`,size:15}),o(`lark.groupLoading`)]}):null,!te&&j?(0,H.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:j}):null,!te&&!j&&D.length===0?(0,H.jsx)(`div`,{className:`personal-lark-group-state`,role:`status`,children:o(`lark.groupEmpty`)}):null,!te&&!j&&D.length>0?(0,H.jsx)(`select`,{"aria-label":o(`lark.groupChat`),onChange:e=>ee(e.target.value),value:k,children:D.map(e=>(0,H.jsx)(`option`,{value:e.chat_id,children:e.chat_name},e.chat_id))}):null]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.bindGoal`)}),(0,H.jsx)(`select`,{"aria-label":o(`lark.bindGoal`),onChange:e=>{let t=e.target.value;w(t),ae(n.find(e=>e.goalId===t)?.agentId??``),le({})},value:C,children:n.map(e=>(0,H.jsx)(`option`,{value:e.goalId,children:e.title},e.goalId))})]})]}),(0,H.jsxs)(`label`,{className:`personal-lark-check`,children:[(0,H.jsx)(`input`,{checked:!0,readOnly:!0,type:`checkbox`}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:o(`lark.createAutomatically`)}),(0,H.jsx)(`small`,{children:o(`lark.createAutomaticallyDescription`)})]})]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.topicPreview`)}),(0,H.jsxs)(`div`,{className:`personal-lark-topic-preview`,children:[(0,H.jsx)(Om,{size:15}),`# `,Pe?.title??Pe?.goalId??`Goal`]})]}),F===`goal`?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.captureScope`)}),(0,H.jsxs)(`select`,{"aria-label":o(`lark.captureScope`),disabled:he?.ingress_mode===`direct_session`,onChange:e=>P(e.target.value),value:N,children:[(0,H.jsx)(`option`,{value:`addressed_only`,children:o(`lark.captureAddressed`)}),(0,H.jsx)(`option`,{value:`configured_chat_all`,children:o(`lark.captureAll`)})]}),(0,H.jsx)(`small`,{children:o(`lark.captureScopeDescription`)})]}),(0,H.jsxs)(`fieldset`,{"aria-label":o(`lark.agentIngress`),className:`personal-lark-ingress`,children:[(0,H.jsx)(`legend`,{children:o(`lark.agentIngress`)}),(0,H.jsx)(`div`,{children:[`live_steering`,`session_queue`,`async_inbox`].map(e=>{let t=jb(e,o);return(0,H.jsxs)(`label`,{className:re===e?`is-active`:``,children:[(0,H.jsx)(`input`,{"aria-label":t.label,checked:re===e,name:`lark-agent-ingress`,onChange:()=>I(e),type:`radio`,value:e}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:t.label}),(0,H.jsx)(`small`,{children:t.detail})]})]},e)})})]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.targetAgent`)}),(0,H.jsxs)(`select`,{"aria-label":o(`lark.targetAgent`),disabled:!!he?.agent_id,onChange:e=>ae(e.target.value),value:R,children:[Le?null:(0,H.jsx)(`option`,{disabled:!0,value:R,children:R?o(`lark.agentUnavailable`,{agent:R}):o(`lark.noAgentConfigured`)}),Ie.map(e=>(0,H.jsx)(`option`,{value:e.agentId,children:e.label===e.agentId?e.agentId:`${e.label} · ${e.agentId}`},e.agentId))]}),(0,H.jsx)(`small`,{children:o(`lark.targetAgentDescription`)})]}),!pe&&Ie.length>1?(0,H.jsxs)(`label`,{"aria-label":o(`lark.connectAllAgents`),className:`personal-lark-check`,children:[(0,H.jsx)(`input`,{checked:oe,onChange:e=>se(e.target.checked),type:`checkbox`}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:o(`lark.connectAllAgents`)}),(0,H.jsx)(`small`,{children:o(`lark.connectAllAgentsDescription`,{count:Ie.length})})]})]}):null,!pe&&oe&&Ie.length>1?(0,H.jsxs)(`fieldset`,{"aria-label":o(`lark.agentApps`),className:`personal-lark-agent-apps`,children:[(0,H.jsx)(`legend`,{children:o(`lark.agentApps`)}),(0,H.jsx)(`small`,{children:o(`lark.agentAppsDescription`)}),(0,H.jsx)(`div`,{children:Ie.map(e=>(0,H.jsxs)(`label`,{children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:e.label}),(0,H.jsx)(`small`,{children:e.agentId})]}),(0,H.jsx)(`select`,{"aria-label":o(`lark.agentAppSelection`,{agent:e.label}),onChange:t=>le(n=>({...n,[e.agentId]:t.target.value})),value:ce[e.agentId]??x,children:l.map(e=>(0,H.jsxs)(`option`,{disabled:!e.ready,value:e.app_ref,children:[e.label,e.reply_ready?``:e.ready?` · ${o(`lark.needsMessagePermissions`)}`:` · ${o(`lark.needsSetup`)}`]},e.app_ref))})]},e.agentId))})]}):null,oe&&Re.length>0&&!Be?(0,H.jsx)(`div`,{className:`personal-lark-group-state is-error`,role:`alert`,children:o(`lark.agentAppPermissions`)}):null,ze.length===0?(0,H.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:o(`lark.selectRegisteredAgent`)}):null]}):null,(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.replyMode`)}),(0,H.jsx)(`select`,{"aria-label":o(`lark.replyMode`),onChange:e=>ie(e.target.value),value:L,children:(0,H.jsx)(`option`,{value:`topic_reply`,children:o(`lark.topicReply`)})}),(0,H.jsx)(`small`,{children:o(`lark.replyModeDescription`)})]}),(0,H.jsxs)(`p`,{className:`personal-lark-cardinality`,children:[(0,H.jsx)(tm,{size:15}),o(`lark.cardinality`)]}),de?(0,H.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:de}):null,(0,H.jsxs)(`footer`,{children:[(0,H.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>b(!1),type:`button`,children:o(`lark.cancel`)}),(0,H.jsxs)(`button`,{className:`personal-primary-action`,disabled:p||!x||!he&&(!He?.reply_ready||!k)||F===`goal`&&(!Be||ze.length===0)||!C||ue,onClick:()=>void Ze(),type:`button`,children:[ue?(0,H.jsx)(wm,{className:`is-spinning`,size:15}):null,Ve]})]})]})}):null,ye?(0,H.jsx)(`div`,{className:`personal-lark-modal-backdrop is-setup`,role:`presentation`,children:(0,H.jsxs)(`section`,{"aria-labelledby":`new-lark-app-title`,"aria-modal":`true`,className:`personal-lark-modal personal-lark-setup-modal`,role:`dialog`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`small`,{children:o(`lark.reusableWorkspaceApp`)}),(0,H.jsx)(`h2`,{id:`new-lark-app-title`,children:o(`lark.newApp`)})]}),(0,H.jsx)(`button`,{"aria-label":o(`lark.closeCreate`),onClick:()=>void Xe(),type:`button`,children:(0,H.jsx)(eh,{size:18})})]}),Te?(0,H.jsxs)(`div`,{className:`personal-lark-setup-progress`,children:[(0,H.jsx)(`span`,{className:`personal-lark-setup-icon is-${Te.status}`,children:Te.status===`ready`?(0,H.jsx)(tm,{size:22}):(0,H.jsx)(wm,{className:Te.status===`failed`?``:`is-spinning`,size:22})}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:Te.status===`ready`?o(`lark.appCreated`):Te.status===`failed`?o(`lark.appCreateFailed`):o(`lark.waitingFeishu`)}),(0,H.jsx)(`p`,{children:Te.status===`waiting_for_feishu`?o(`lark.waitingFeishuDescription`):Te.status===`starting`?o(`lark.waitingLink`):Te.error})]}),Te.verification_url?(0,H.jsxs)(`a`,{href:Te.verification_url,rel:`noreferrer`,target:`_blank`,children:[(0,H.jsx)(pm,{size:15}),o(`lark.reopenFeishu`)]}):null]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{className:`personal-lark-setup-copy`,children:o(`lark.setupCopy`)}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.profileName`)}),(0,H.jsx)(`input`,{"aria-label":o(`lark.profileName`),autoComplete:`off`,onChange:e=>Se(e.target.value),placeholder:`loopx-workspace-bot`,value:xe})]}),(0,H.jsxs)(`label`,{children:[(0,H.jsx)(`span`,{children:o(`lark.region`)}),(0,H.jsxs)(`select`,{"aria-label":o(`lark.region`),onChange:e=>we(e.target.value),value:Ce,children:[(0,H.jsx)(`option`,{value:`feishu`,children:`Feishu`}),(0,H.jsx)(`option`,{value:`lark`,children:`Lark`})]})]}),xe&&!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(xe)?(0,H.jsx)(`p`,{className:`personal-notification-error`,children:o(`lark.profileValidation`)}):null]}),Oe?(0,H.jsx)(`p`,{className:`personal-notification-error`,children:Oe}):null,(0,H.jsxs)(`footer`,{children:[(0,H.jsx)(`button`,{className:`personal-secondary-action`,onClick:()=>void Xe(),type:`button`,children:o(`lark.cancel`)}),Te?null:(0,H.jsxs)(`button`,{className:`personal-primary-action`,disabled:Ee||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(xe),onClick:()=>void Ye(),type:`button`,children:[Ee?(0,H.jsx)(wm,{className:`is-spinning`,size:15}):(0,H.jsx)(pm,{size:15}),o(`lark.continueFeishu`)]})]})]})}):null]})}function Ib(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Lb(e,t,n){let r=Ib(t),i=Ib(n);return Object.fromEntries(e.fields.flatMap(({key:e,nullable:t})=>{let n=r[e],a=i[e];return Object.hasOwn(r,e)&&(n!=null||t&&n===null)?[[e,n]]:Object.hasOwn(i,e)&&a!=null?[[e,a]]:[]}))}function Rb(e,t){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=new Set(e.fields.map(e=>e.key));return Object.keys(n).some(e=>!r.has(e))?null:n}function zb(e,t,n){let r={...e,[t]:n},i=e.schedule;return t===`timezone`&&i&&typeof i==`object`&&`schema_version`in i&&i.schema_version===`periodic_report_schedule_v0`&&(r.schedule={...i,timezone:n}),r}function Bb({id:e,value:t,timezone:n,onChange:r}){let{locale:i}=qi(),a=i===`zh-CN`,o=t&&typeof t==`object`&&!Array.isArray(t)?t:null,s=String(o?.rrule??``).split(`;`).map(e=>e.split(`=`)),c=Object.fromEntries(s.filter(e=>e.length===2)),l=[`MO`,`TU`,`WE`,`TH`,`FR`,`SA`,`SU`],u=(e,t)=>e!==void 0&&/^\d+$/.test(e)&&Number(e)<=t,d=!o||o.schema_version===`periodic_report_schedule_v0`&&[`DAILY`,`WEEKLY`].includes(c.FREQ)&&o.timezone===n&&s.every(e=>e.length===2&&[`FREQ`,`BYDAY`,`BYHOUR`,`BYMINUTE`,`INTERVAL`].includes(e[0]))&&new Set(s.map(([e])=>e)).size===s.length&&u(c.BYHOUR,23)&&u(c.BYMINUTE??`0`,59)&&(c.FREQ===`WEEKLY`?l.includes(c.BYDAY):!c.BYDAY)&&(!c.INTERVAL||c.INTERVAL===`1`),f=a?[`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`]:[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`];function p(e){let t={FREQ:`WEEKLY`,BYDAY:`MO`,BYHOUR:`9`,BYMINUTE:`0`,...c,...e};r?.({schema_version:`periodic_report_schedule_v0`,schedule_id:o?.schedule_id??`report-schedule`,timezone:n,rrule:[`FREQ=${t.FREQ}`,...t.FREQ===`WEEKLY`?[`BYDAY=${t.BYDAY}`]:[],`BYHOUR=${t.BYHOUR}`,`BYMINUTE=${t.BYMINUTE}`].join(`;`)})}return(0,H.jsxs)(`div`,{className:`personal-report-schedule`,children:[(0,H.jsxs)(`label`,{className:`is-boolean`,htmlFor:e,children:[(0,H.jsx)(`span`,{children:a?`按日历汇报`:`Calendar reports`}),(0,H.jsx)(`input`,{id:e,type:`checkbox`,role:`switch`,checked:!!o,disabled:!r,onChange:e=>e.target.checked?p({}):r?.(null)})]}),o?(0,H.jsxs)(H.Fragment,{children:[d?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`label`,{htmlFor:`${e}-frequency`,children:[(0,H.jsx)(`span`,{children:a?`频率`:`Frequency`}),(0,H.jsxs)(`select`,{id:`${e}-frequency`,value:c.FREQ,disabled:!r,onChange:e=>p({FREQ:e.target.value}),children:[(0,H.jsx)(`option`,{value:`DAILY`,children:a?`每天`:`Daily`}),(0,H.jsx)(`option`,{value:`WEEKLY`,children:a?`每周`:`Weekly`})]})]}),c.FREQ===`WEEKLY`&&(0,H.jsxs)(`label`,{htmlFor:`${e}-day`,children:[(0,H.jsx)(`span`,{children:a?`星期`:`Weekday`}),(0,H.jsx)(`select`,{id:`${e}-day`,value:c.BYDAY,disabled:!r,onChange:e=>p({BYDAY:e.target.value}),children:l.map((e,t)=>(0,H.jsx)(`option`,{value:e,children:f[t]},e))})]}),(0,H.jsxs)(`label`,{htmlFor:`${e}-time`,children:[(0,H.jsxs)(`span`,{children:[a?`当地时间`:`Local time`,` (`,n,`)`]}),(0,H.jsx)(`input`,{id:`${e}-time`,type:`time`,required:!0,disabled:!r,value:`${(c.BYHOUR??`9`).padStart(2,`0`)}:${(c.BYMINUTE??`0`).padStart(2,`0`)}`,onChange:e=>{if(!/^\d{2}:\d{2}$/.test(e.target.value))return;let[t,n]=e.target.value.split(`:`);p({BYHOUR:t,BYMINUTE:n})}})]})]}):(0,H.jsx)(`p`,{role:`alert`,children:a?`此计划需在 JSON 模式中编辑;当前内容已保留。`:`Edit this schedule in JSON mode; its current value is preserved.`}),(0,H.jsx)(`p`,{children:a?`由现有唤醒检查到期计划;实际送达以回执为准。`:`Existing wakes check the schedule; delivery is confirmed by its receipt.`})]}):(0,H.jsx)(`p`,{children:a?`未设置日历计划;保持阶段结束时汇报。`:`No calendar schedule; report at validated stage boundaries.`})]})}function Vb({copy:e,field:t,id:n,onChange:r,value:i,timezone:a}){let o=e[t.key]?.label??t.label,s=!r;if(t.input_kind===`periodic_report_schedule`)return(0,H.jsx)(Bb,{id:n,value:i,timezone:a,onChange:r?e=>r(t.key,e):void 0});if(t.input_kind===`boolean`)return(0,H.jsxs)(`label`,{className:`is-boolean`,htmlFor:n,children:[(0,H.jsx)(`span`,{children:o}),(0,H.jsx)(`input`,{checked:i===!0,id:n,onChange:r?e=>r(t.key,e.target.checked):void 0,readOnly:s,role:`switch`,type:`checkbox`})]});if(t.input_kind===`select`)return(0,H.jsxs)(`label`,{htmlFor:n,children:[(0,H.jsx)(`span`,{children:o}),(0,H.jsxs)(`select`,{id:n,onChange:r?e=>r(t.key,e.target.value):void 0,value:typeof i==`string`?i:``,children:[(0,H.jsx)(`option`,{value:``}),(t.options??[]).map(e=>(0,H.jsx)(`option`,{value:e,children:e},e))]})]});if(t.input_kind===`string_list`)return(0,H.jsxs)(`label`,{htmlFor:n,children:[(0,H.jsx)(`span`,{children:o}),(0,H.jsx)(`textarea`,{id:n,onChange:r?e=>r(t.key,e.target.value.split(/\r?\n/u).filter(Boolean)):void 0,readOnly:s,rows:4,value:Array.isArray(i)?i.join(`
-`):``})]});let c=t.input_kind===`number`;return(0,H.jsxs)(`label`,{htmlFor:n,children:[(0,H.jsx)(`span`,{children:o}),(0,H.jsx)(`input`,{id:n,max:t.maximum,min:t.minimum,onChange:r?e=>r(t.key,c?Number(e.target.value):e.target.value):void 0,readOnly:s,required:t.required,type:c?`number`:`text`,value:typeof i==`number`||typeof i==`string`?i:``})]})}function Hb({copy:e={},disabled:t=!1,editor:n,enabledAction:r,omitKeys:i=[],onChange:a,value:o}){let s=(0,V.useId)(),c=new Set(i);return(0,H.jsx)(`fieldset`,{className:`personal-capability-fields`,disabled:t,children:n.fields.filter(e=>!c.has(e.key)).map(t=>{let n=(0,H.jsx)(Vb,{copy:e,field:t,id:`${s}-${t.key.replace(/[^a-z0-9_-]/gi,`-`)}`,onChange:a,value:o[t.key],timezone:String(o.timezone??`UTC`)},t.key);return t.key===`enabled`&&t.input_kind===`boolean`?(0,H.jsxs)(`div`,{className:`personal-capability-enabled-row`,children:[n,r]},t.key):n})})}var Ub={en:{manager_runtime:{displayName:`Manager runtime`,description:`Selects the persistent host-tool profile used by owner manager conversations.`},todo_replan_cadence:{displayName:`Goal review cadence`,description:`Configures the Goal review cadence.`},change_quality_qualification:{displayName:`Change quality qualification`,description:`Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.`},explore_graph:{displayName:`Explore Graph`,description:`Organizes bounded exploration as a typed evidence graph so branches, findings, and synthesis remain inspectable.`},explore_harness:{displayName:`Explore Harness`,description:`Selects a capability-owned planning and research harness profile for bounded multi-step exploration.`},lark_event_inbox:{displayName:`Lark event inbox`,description:`Receives provider events through a local-private inbox binding before LoopX projects them into governed work.`,readOnlyReason:`This capability requires a local-private inbox binding. Manage it in Lark settings or through the capability CLI.`},lark_kanban_heartbeat_sync:{displayName:`Lark Kanban heartbeat sync`,description:`Synchronizes accepted LoopX work state to the configured Lark Kanban heartbeat surface.`},local_authority_shadow:{displayName:`Local authority shadow`,description:`Observes post-commit Todo and task-lease state through the shared authority contract without taking write authority.`},multi_subagent:{displayName:`Adaptive child capacity`,description:`Sets bounded child-agent capacity and the public-safe responsibility domains in which parallel work may be delegated.`},peer_task_coordination:{displayName:`Registered-peer task coordination`,description:`Routes explicitly scoped peer-owned work to one registered coordinator without granting cross-owner mutation authority.`},periodic_report:{displayName:`Periodic reports`,description:`Turns validated Goal stage progress into a frozen report and automatically delivers it through the configured Goal Channel with exact readback.`},pull_request_review:{displayName:`Pull-request review`,description:`Ranks the public GitHub PR review queue with a machine-level default; it never grants GitHub, Todo, push, or merge authority.`},reward_memory:{displayName:`Reward Memory experiment`,description:`Configures a reviewed local-private provider binding for Goal-scoped Agent recall and evidence-backed outcome learning.`}},"zh-CN":{manager_runtime:{displayName:`管家 Runtime`,description:`选择管家会话持续生效的宿主工具模式。`},todo_replan_cadence:{displayName:`Goal 复核周期`,description:`配置 Goal 的复核周期。`},change_quality_qualification:{displayName:`变更质量验证`,description:`生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。`},explore_graph:{displayName:`探索图谱`,description:`把有界探索组织为 typed 证据图,让探索分支、发现与综合结论都可检查、可追溯。`},explore_harness:{displayName:`探索 Harness`,description:`为有界的多步探索选择由能力负责的规划与研究 Harness profile。`},lark_event_inbox:{displayName:`飞书事件收件箱`,description:`通过本机私有收件箱接收 Provider 事件,再由 LoopX 将其投影为受治理的工作。`,readOnlyReason:`此能力依赖本机私有的收件箱绑定,请在飞书设置或 capability CLI 中管理。`},lark_kanban_heartbeat_sync:{displayName:`飞书看板心跳同步`,description:`把 LoopX 已接受的工作状态同步到配置好的飞书看板心跳界面。`},local_authority_shadow:{displayName:`本地 Authority 影子观测`,description:`通过共享 Authority contract 观测提交后的 Todo 与 task lease 状态,但不取得写入权。`},multi_subagent:{displayName:`自适应子 Agent 容量`,description:`限定子 Agent 容量与可公开的职责域,只有落在这些边界内的工作才能并行委派。`},peer_task_coordination:{displayName:`已注册 Peer 任务协调`,description:`把明确限定的 Peer 工作路由给一个已注册协调者,不授予跨 Owner 修改权限。`},periodic_report:{displayName:`周期报告`,description:`把经过验证的 Goal 阶段进展整理为冻结报告,并通过配置的 Goal Channel 自动发送和精确回读。`},pull_request_review:{displayName:`Pull-request Review`,description:`配置公开 GitHub PR 审阅队列的本机默认排序;不会授予 GitHub、Todo、push 或 merge 权限。`},reward_memory:{displayName:`Reward Memory 实验`,description:`为 Goal 内 Agent 的召回与证据化结果学习配置经过审阅的本机私有 Provider 绑定。`}}},Wb={en:{runtime_profile:{label:`Runtime profile`,description:`Restricted keeps scoped LoopX reads only. Trusted owner enables normal host tools while protected operations retain separate checks.`},completed_todos:{label:`Completed Todos between Goal reviews`,description:`Machine default or explicit Goal override, from 1 to 5.`},allowed_domains:{label:`Allowed responsibility domains`,description:`Enter one bounded, public-safe domain per line.`},coordinator_agent_id:{label:`Coordinator Agent`,description:`Use an already registered Agent id; leave blank to disable coordination.`},enabled:{label:`Enabled`},model:{label:`Child model`,description:`For example gpt-5.6-luna. Blank clears the child model preference.`},reasoning_effort:{label:`Child reasoning effort`,description:`For example max; the host must support this model and effort.`},max_children:{label:`Maximum children`,description:`Hard upper bound for concurrently delegated child work.`},profile:{label:`Planner profile`,description:`Select one registered Explore Harness profile.`},profile_preset:{label:`Report profile`,description:`Capability-owned report profile, such as weekly-progress.`},wait_for_ci:{label:`Wait for CI`,description:`Disable to use local validation without querying or waiting for CI. Merge authority is unchanged.`},review_priority:{label:`Review priority`,description:`Choose whether other developers' PRs or the authenticated reviewer's own PRs are ranked first.`},route_ref:{label:`Goal Channel route`,description:`Public route alias only; credentials and provider identifiers stay outside this form.`},safe_fix:{label:`Allow one bounded safe-fix pass`},strict_receipt:{label:`Require an exact-diff receipt`},timezone:{label:`Timezone`,description:`Use an IANA timezone, for example Asia/Shanghai.`},schedule:{label:`Calendar reports`,description:`Optional daily or weekly reports; no schedule preserves stage-only delivery.`},config_path:{label:`Local-private configuration path`,description:`Repo-relative ignored JSON under .loopx/config/. Leave blank to retain the current binding; the path is never returned.`},enabled_agents:{label:`Enabled Goal Agents`,description:`Enter one registered Goal-local Agent id per line. A private binding currently accepts exactly one Agent.`}},"zh-CN":{runtime_profile:{label:`运行模式`,description:`restricted 仅使用受限 LoopX 读取;trusted_owner 开放常规宿主工具,但受保护操作仍单独校验。`},completed_todos:{label:`两次 Goal 复核间的已完成 Todo 数`,description:`可设置 1–5;机器默认值可被 Goal 显式覆盖。`},allowed_domains:{label:`允许的职责域`,description:`每行填写一个有边界、可公开的职责域。`},coordinator_agent_id:{label:`协调 Agent`,description:`填写一个已经注册的 Agent ID;留空表示关闭协调。`},enabled:{label:`启用`},model:{label:`子 Agent 模型`,description:`例如 gpt-5.6-luna;留空清除模型偏好。`},reasoning_effort:{label:`子 Agent 推理档位`,description:`例如 max;宿主须支持所选模型与档位。`},max_children:{label:`最大子 Agent 数`,description:`可同时委派的子任务硬上限。`},profile:{label:`规划 Profile`,description:`选择一个已注册的 Explore Harness profile。`},profile_preset:{label:`报告 Profile`,description:`由该能力管理的报告 profile,例如 weekly-progress。`},wait_for_ci:{label:`等待 CI`,description:`关闭后使用本地验证,不查询或等待 CI;不改变合并权限。`},review_priority:{label:`审阅优先级`,description:`选择先排其他开发者的 PR,还是先排当前已认证审阅者自己的 PR。`},route_ref:{label:`Goal Channel 路由`,description:`只填写公开 route alias;凭据与 Provider 标识不会进入此表单。`},safe_fix:{label:`允许一次有界安全修复`},strict_receipt:{label:`要求精确 diff 回执`},timezone:{label:`时区`,description:`使用 IANA 时区,例如 Asia/Shanghai。`},schedule:{label:`日历汇报`,description:`可选每日或每周计划;未设置时保持阶段结束汇报。`},config_path:{label:`本机私有配置路径`,description:`填写 .loopx/config/ 下、相对仓库且被忽略的 JSON;留空保留当前绑定,路径不会被回传。`},enabled_agents:{label:`已启用的 Goal Agent`,description:`每行填写一个已注册的 Goal 内 Agent ID;私有绑定当前只接受一个 Agent。`}}};function Gb(e,t){let n=Ub[t][e.capability_id];return n?{...e,display_name:n.displayName,description:n.description,configuration_editor:{...e.configuration_editor,...n.readOnlyReason?{read_only_reason:n.readOnlyReason}:{}}}:e}function Kb(e){return Wb[e]}Object.freeze(Object.keys(Ub.en).sort());function qb(e,t){return e.available_scopes.includes(t)&&(t!==`machine`||!!e.machine_namespace)&&e.configuration_editor.editable&&e.configuration_editor.writable_scopes.includes(t)}function Jb({values:e,t}){return(0,H.jsxs)(`details`,{className:`personal-capability-raw-values`,children:[(0,H.jsx)(`summary`,{children:t(`capabilities.rawJson`)}),(0,H.jsx)(`div`,{className:`personal-capability-value-grid`,children:e.map(({label:e,value:t})=>(0,H.jsxs)(`section`,{children:[(0,H.jsx)(`strong`,{children:e}),(0,H.jsx)(`pre`,{children:t?JSON.stringify(t,null,2):`—`})]},e))})]})}function Yb({source:e,t}){return e?(0,H.jsxs)(`p`,{className:`personal-capability-effective-source`,children:[(0,H.jsx)(Gm,{"aria-hidden":!0,size:15}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:t(`capabilities.effectiveSource`)}),t(`capabilities.source.${e}`)]})]}):null}function Xb({available:e,description:t,t:n}){return e?null:(0,H.jsxs)(`section`,{className:`personal-capability-editor-status is-read-only`,children:[(0,H.jsx)(Qm,{"aria-hidden":!0,size:18}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:n(`capabilities.readOnly`)}),(0,H.jsx)(`p`,{children:t})]})]})}function Zb(e){return e.availability?.includes(`experimental`)?4:e.capability_id===`multi_subagent`?3:e.configuration_editor.writable_scopes.length===0||e.availability===`supported_explicit_opt_in`?2:e.availability===`supported_explicit_override`?0:1}function Qb(e,t){return[...e].sort((e,n)=>{let r=Zb(e)-Zb(n);if(r!==0)return r;let i=Gb(e,t),a=Gb(n,t);return i.display_name.localeCompare(a.display_name,t)||e.capability_id.localeCompare(n.capability_id)})}function $b({capabilities:e,locale:t,onSelect:n,scope:r,selectedCapabilityId:i,t:a}){return(0,H.jsx)(`nav`,{"aria-label":a(r===`goal`?`capabilities.catalog`:`machine.capabilityCatalog`),className:`personal-capability-list`,tabIndex:0,children:Qb(e,t).map(e=>{let o=Gb(e,t);return(0,H.jsxs)(`button`,{"aria-current":i===o.capability_id?`page`:void 0,onClick:()=>n(o.capability_id),type:`button`,children:[(0,H.jsx)(`span`,{children:(0,H.jsx)(`strong`,{children:o.display_name})}),(0,H.jsx)(`em`,{children:a(o.available_scopes.includes(r)?r===`goal`?`capabilities.goalScope`:`capabilities.machineScope`:r===`machine`?`capabilities.goalScope`:`capabilities.machineScope`)})]},o.capability_id)})})}function ex({capability:e,locale:t,source:n}){let{t:r}=qi(),i=Gb(e,t);return(0,H.jsxs)(`header`,{children:[(0,H.jsx)(`span`,{className:`personal-settings-icon`,children:(0,H.jsx)(Km,{"aria-hidden":!0,size:18})}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`personal-capability-heading-row`,children:[(0,H.jsx)(`h2`,{children:i.display_name}),(0,H.jsx)(Yb,{source:n,t:r})]}),e.context_contribution&&(0,H.jsxs)(`details`,{className:`personal-capability-help`,"data-testid":`capability-context-phases`,children:[(0,H.jsx)(`summary`,{children:t===`zh-CN`?`主 Agent 协作指导`:`Coordinator workflow guidance`}),(0,H.jsx)(`p`,{children:t===`zh-CN`?`随能力开启。支持以下阶段;此处展示能力范围,不能证明某次运行已读取或采纳。`:`Enabled with this capability. These are supported phases, not proof that a run read or adopted the guidance.`}),(0,H.jsx)(`dl`,{children:e.context_contribution.supported_phases.map(e=>(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:(0,H.jsx)(`code`,{children:e})}),(0,H.jsx)(`dd`,{children:tx[e][t===`zh-CN`?`zh`:`en`]})]},e))}),(0,H.jsx)(`p`,{children:t===`zh-CN`?`LoopX Turn 在请求与结果中提供上下文;原生工具入口由 LoopX skill 调用同一只读接口。执行与采纳需另看运行证据。`:`LoopX Turn includes context in requests and results. For native tools, the LoopX skill reads the same interface. Execution and adoption require run evidence.`})]}),(0,H.jsxs)(`details`,{className:`personal-capability-help`,children:[(0,H.jsx)(`summary`,{children:t===`zh-CN`?`配置说明`:`Configuration help`}),(0,H.jsx)(`p`,{children:i.description}),(0,H.jsx)(`dl`,{children:e.configuration_editor.fields.map(e=>{let n=Kb(t)[e.key],r=n?.description??e.description;return r?(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:n?.label??e.label}),(0,H.jsx)(`dd`,{children:r})]},e.key):null})})]},e.capability_id)]})]})}var tx={before_plan:{zh:`规划前:识别独立问题并保留主 Agent 的核验与整合职责。`,en:`Before planning: identify independent questions and retain coordinator validation and integration.`},before_delegate:{zh:`委派前:明确子任务边界、模型偏好及预期证据。`,en:`Before delegation: specify task boundaries, model preferences and expected evidence.`},after_delegate_result:{zh:`回收后:核验结果,说明采纳决定并关联计划与成果。`,en:`After results: validate evidence, explain acceptance and link plans and deliverables.`}};function nx({callbacks:e,goalId:t,notification:n,onChanged:r}){let{t:i}=qi(),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(null);async function l(n){if(e.onToggleGoalAutoNotify){o(!0),c(null);try{let a=await e.onToggleGoalAutoNotify({autoNotify:n,goalId:t});if(!a.ok){c(a.public_summary??a.blocker??i(`notifications.setupFailed`));return}r()}catch(e){c(e instanceof Error?e.message:i(`notifications.setupFailed`))}finally{o(!1)}}}return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`label`,{className:`personal-notification-toggle`,children:[(0,H.jsx)(`input`,{checked:n?.humanGateAutoNotifyEnabled??!1,disabled:a||n?.configured!==!0||!e.onToggleGoalAutoNotify,onChange:e=>void l(e.target.checked),type:`checkbox`}),(0,H.jsx)(`span`,{children:i(`notifications.autoNotify`)}),a?(0,H.jsx)(wm,{"aria-hidden":!0,className:`is-spinning`,size:14}):null]}),s?(0,H.jsx)(`p`,{className:`personal-notification-error`,role:`alert`,children:s}):null]})}function rx({goalId:e,onApplied:t,selected:n,t:r}){let[i,a]=(0,V.useState)({busy:null,draft:{},partialWrite:null,preview:null}),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)(`guided`),[u,d]=(0,V.useState)(``),f=(0,V.useMemo)(()=>n?Rb(n.configuration_editor,u):null,[n,u]),p=c===`guided`||f!==null;(0,V.useEffect)(()=>{l(`guided`),d(``),a({busy:null,draft:Lb(n?.configuration_editor??{fields:[]},n?.current??n?.effective_configuration?.configuration??n?.default,n?.default),partialWrite:null,preview:null}),s(null)},[n]);async function m(t){if(!(!n||i.busy||!p)){a(e=>({...e,busy:`preview`,partialWrite:null})),s(null);try{let r=await Og(e,n.capability_id,t);a(e=>({...e,preview:r}))}catch(e){s(e instanceof Error?e.message:r(`capabilities.previewFailed`))}finally{a(e=>({...e,busy:null}))}}}async function h(){if(!(!n||!i.preview||i.busy||!p)){a(e=>({...e,busy:`apply`})),s(null);try{let r=Lb(n.configuration_editor,i.draft,n.default),o=await kg(e,n.capability_id,i.preview.action===`delete`?null:r,i.preview.plan_revision);a(e=>({...e,partialWrite:o.status===`partial_write`?o:null,preview:null})),o.status!==`partial_write`&&t()}catch(e){a(e=>({...e,preview:null})),s(e instanceof Error?e.message:r(`capabilities.applyFailed`))}finally{a(e=>({...e,busy:null}))}}}function g(e,t){a(r=>({...r,draft:n?.capability_id===`periodic_report`?zb(r.draft,e,t):{...r.draft,[e]:t},preview:null})),s(null)}function _(e){if(!n||i.busy)return;d(e);let t=Rb(n.configuration_editor,e);a(e=>({...e,preview:null,draft:t?Lb(n.configuration_editor,t,n.default):e.draft})),s(null)}function v(){i.busy||!p||(c===`guided`&&d(JSON.stringify(i.draft,null,2)),l(c===`guided`?`json`:`guided`),a(e=>({...e,preview:null})))}return{apply:h,changeDraft:g,changeJson:_,changeMode:v,editorMode:c,jsonDraft:u,jsonValid:p,error:o,mutation:i,preview:m}}function ix({mutationError:e,onApplied:t,partialWrite:n,preview:r}){let{t:i}=qi();return(0,H.jsxs)(H.Fragment,{children:[e?(0,H.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:e}):null,n?(0,H.jsxs)(`section`,{"aria-live":`polite`,className:`personal-capability-recovery`,children:[(0,H.jsx)(Qm,{"aria-hidden":!0,size:18}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:i(`capabilities.partialWrite`)}),(0,H.jsx)(`p`,{children:i(`capabilities.partialWriteDescription`)}),(0,H.jsx)(`small`,{children:n.recommended_action})]}),(0,H.jsxs)(`button`,{onClick:t,type:`button`,children:[(0,H.jsx)(Lm,{"aria-hidden":!0,size:15}),i(`capabilities.refreshSource`)]})]}):null,r?(0,H.jsxs)(`section`,{className:`personal-capability-preview`,"aria-label":i(`capabilities.preview`),children:[(0,H.jsx)(`strong`,{children:i(`capabilities.preview`)}),(0,H.jsx)(`span`,{children:i(`machine.action.${r.action}`)}),(0,H.jsx)(`small`,{children:i(`capabilities.previewLocked`)})]}):null]})}function ax({callbacks:e,catalog:t,goalId:n,notification:r,onApplied:i,onNotificationChanged:a}){let{locale:o,t:s}=qi(),c=(0,V.useMemo)(()=>Qb(t.capabilities,o),[t.capabilities,o]),[l,u]=(0,V.useState)(()=>c[0]?.capability_id??``),d=(0,V.useMemo)(()=>c.find(e=>e.capability_id===l)??c[0],[c,l]),f=(0,V.useMemo)(()=>d?Gb(d,o):void 0,[o,d]),{apply:p,changeDraft:m,changeJson:h,changeMode:g,editorMode:_,jsonDraft:v,jsonValid:y,error:b,mutation:x,preview:S}=rx({goalId:n,onApplied:i,selected:f,t:s}),{busy:C,draft:w,partialWrite:T,preview:E}=x;if(!d||!f)return(0,H.jsx)(`p`,{className:`personal-capability-empty`,children:s(`capabilities.empty`)});let D=f.available_scopes.includes(`goal`),O=qb(f,`goal`),k=f.configuration_editor.read_only_reason??s(D?`capabilities.previewOnly`:`capabilities.machineOnly`);async function ee(){if(!f||!O||C||!y)return;let e=Lb(f.configuration_editor,w,f.default);await S(e)}async function te(){!O||C||await S(null)}return(0,H.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,H.jsx)($b,{capabilities:t.capabilities,locale:o,onSelect:u,scope:`goal`,selectedCapabilityId:f.capability_id,t:s}),(0,H.jsxs)(`article`,{"aria-label":f.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,H.jsx)(ex,{capability:d,locale:o,source:f.effective_configuration?.source}),(0,H.jsx)(Xb,{available:O,t:s,description:k}),f.capability_id===`lark_event_inbox`?(0,H.jsxs)(`section`,{className:`personal-capability-linked-setting`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:s(`capabilities.larkInboxNotificationSetting`)}),(0,H.jsx)(`p`,{children:s(`capabilities.larkInboxNotificationDescription`)})]}),(0,H.jsx)(nx,{callbacks:e,goalId:n,notification:r,onChanged:a})]}):null,O?(0,H.jsxs)(H.Fragment,{children:[_===`json`||!f.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,H.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,H.jsxs)(`button`,{disabled:!!C||!y,onClick:g,type:`button`,children:[(0,H.jsx)(cm,{"aria-hidden":!0,size:14}),s(_===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,_===`guided`?(0,H.jsx)(`section`,{className:`personal-capability-field-summary`,children:(0,H.jsx)(Hb,{disabled:!!C,copy:Kb(o),editor:f.configuration_editor,onChange:m,value:w,enabledAction:(0,H.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:g,type:`button`,children:[(0,H.jsx)(cm,{"aria-hidden":!0,size:14}),s(`machine.editJson`)]})})}):(0,H.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`goal-configuration-json`,children:[(0,H.jsx)(`span`,{children:s(`capabilities.jsonConfiguration`)}),(0,H.jsx)(`textarea`,{id:`goal-configuration-json`,"aria-describedby":`goal-configuration-json-help`,disabled:!!C,onChange:e=>h(e.target.value),rows:12,spellCheck:!1,value:v}),(0,H.jsx)(`small`,{id:`goal-configuration-json-help`,children:s(`capabilities.jsonHelp`)}),y?null:(0,H.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:s(`capabilities.jsonInvalid`)})]})]}):null,(0,H.jsx)(ix,{mutationError:b,onApplied:i,partialWrite:T,preview:E}),O?(0,H.jsxs)(`footer`,{className:`personal-capability-actions`,children:[f.current&&f.available_scopes.includes(`machine`)?(0,H.jsx)(`button`,{disabled:!!C||!y,onClick:()=>void te(),type:`button`,children:s(`capabilities.restoreInheritance`)}):null,(0,H.jsx)(`button`,{disabled:!!C||!y,onClick:()=>void ee(),type:`button`,children:s(C===`preview`?`common.loading`:`capabilities.previewChanges`)}),(0,H.jsx)(`button`,{className:`is-primary`,disabled:!!C||!E||!y,onClick:()=>void p(),type:`button`,children:s(C===`apply`?`common.loading`:`capabilities.applyPreview`)})]}):null,(0,H.jsx)(Jb,{values:[{label:s(`capabilities.goalValue`),value:f.current},{label:s(f.machine_current?`capabilities.machineValue`:`capabilities.defaultValue`),value:f.machine_current??f.default}],t:s},d.capability_id)]})]})}function ox({callbacks:e,goalId:t,notification:n,onChanged:r}){let{t:i}=qi(),[a,o]=(0,V.useState)(null),[s,c]=(0,V.useState)(null),[l,u]=(0,V.useState)(!1);function d(){t&&(u(!0),c(null),Dg(t).then(o).catch(e=>c(e instanceof Error?e.message:i(`capabilities.loadFailed`))).finally(()=>u(!1)))}return(0,V.useEffect)(d,[t]),t?l&&!a?(0,H.jsxs)(`p`,{"aria-live":`polite`,className:`personal-capability-empty`,children:[(0,H.jsx)(wm,{className:`personal-spin`,size:18}),i(`capabilities.loading`)]}):s?(0,H.jsxs)(`section`,{className:`personal-capability-error`,role:`alert`,children:[(0,H.jsx)(Qm,{"aria-hidden":!0,size:18}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:i(`capabilities.loadFailed`)}),(0,H.jsx)(`small`,{children:s})]}),(0,H.jsxs)(`button`,{onClick:d,type:`button`,children:[(0,H.jsx)(Lm,{"aria-hidden":!0,size:15}),i(`capabilities.retry`)]})]}):a?(0,H.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":a.revision,children:[(0,H.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,H.jsxs)(`summary`,{children:[(0,H.jsx)(Gm,{"aria-hidden":!0,size:17}),i(`capabilities.atomicOverride`)]}),(0,H.jsx)(`p`,{children:i(`capabilities.atomicOverrideDescription`)})]}),(0,H.jsx)(ax,{callbacks:e,catalog:a.capability_catalog,goalId:t,notification:n,onApplied:d,onNotificationChanged:r})]}):null:(0,H.jsx)(`p`,{className:`personal-capability-empty`,children:i(`capabilities.chooseGoal`)})}function sx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function cx(e,t){let n=t?.machine_namespace;return n?e?.machine_configuration?.namespaces[n]:void 0}function lx(e,t,n){return{...sx(e.default),...sx(t),...n}}function ux(e,t){for(let n of e.configuration_editor.fields){let e=t[n.key];if(n.required&&(e==null||e===``))return!1}return e.capability_id===`periodic_report`&&t.enabled===!0?!!(String(t.profile_preset??``).trim()&&String(t.route_ref??``).trim()&&String(t.timezone??``).trim()):!0}function dx(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function fx(e){return e?e===`absent`?e:e.replace(/^sha256:/,``).slice(0,12):`—`}function px(){let{locale:e,t}=qi(),[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)({}),[c,l]=(0,V.useState)(`{}`),[u,d]=(0,V.useState)(`guided`),[f,p]=(0,V.useState)(null),[m,h]=(0,V.useState)(`upsert`),[g,_]=(0,V.useState)(null),[v,y]=(0,V.useState)(null),[b,x]=(0,V.useState)(`load`),[S,C]=(0,V.useState)(null),[w,T]=(0,V.useState)(null),E=(0,V.useMemo)(()=>Qb(n?.capability_catalog.capabilities??[],e),[n,e]),D=n?.invalid_namespaces[0],O=E.find(e=>e.capability_id===i)??(D?E.find(e=>e.machine_namespace===D):void 0)??E.find(e=>qb(e,`machine`))??E[0],k=O?Gb(O,e):void 0,ee=cx(n,k),te=!!(k?.machine_namespace&&ee),A=!!(k&&qb(k,`machine`)),j=(0,V.useMemo)(()=>dx(c),[c]),M=k?u===`json`?j:lx(k,ee,o):null,N=!!(k&&(u===`json`?j:ux(k,M??{})));async function P(){r(await Eg())}(0,V.useEffect)(()=>{let e=!0;return Eg().then(t=>{e&&r(t)}).catch(n=>{e&&C(n instanceof Error?n.message:t(`machine.loadError`))}).finally(()=>{e&&x(null)}),()=>{e=!1}},[t]),(0,V.useEffect)(()=>{if(!k)return;let e=cx(n,k),t=Lb(k.configuration_editor,e??k.default,k.default),r=lx(k,e,t);s(t),l(JSON.stringify(r,null,2)),d(A?`guided`:`json`),p(null),h(`upsert`),y(null)},[n,i,e]);function F(e,t){s(n=>k?.capability_id===`periodic_report`?zb(n,e,t):{...n,[e]:t}),p(null),h(`upsert`),C(null),T(null)}function ne(e){if(k){if(e===`json`)l(JSON.stringify(lx(k,ee,o),null,2));else if(j)s(Lb(k.configuration_editor,j,k.default));else{C(t(`machine.jsonInvalid`));return}d(e),p(null),h(`upsert`),C(null)}}async function re(){if(!(!A||!k?.machine_namespace||!M||!N||b)){x(`preview`),C(null),T(null);try{h(`upsert`),p(await Ag(k.machine_namespace,M))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function I(){if(!(!A||!k?.machine_namespace||!te||b)){x(`preview`),C(null),T(null);try{h(`remove`),p(await Mg(k.machine_namespace))}catch(e){C(e instanceof Error?e.message:t(`machine.previewError`))}finally{x(null)}}}async function L(){if(!A||!k?.machine_namespace||!f||b||m===`upsert`&&!M)return;x(`apply`),C(null);let e=m;try{let n=e===`remove`?await Ng(k.machine_namespace,f.plan_revision):await jg(k.machine_namespace,M,f.plan_revision);_(n),p(null),h(`upsert`),y(null),await P(),T(n.status===`applied`?t(e===`remove`?`machine.removed`:`machine.applied`):t(`machine.unchanged`))}catch(e){p(null),h(`upsert`),C(e instanceof Error?e.message:t(`machine.applyError`))}finally{x(null)}}async function ie(){if(!(!g?.transaction_id||b)){x(`rollback-preview`),C(null);try{y(await Pg(g.transaction_id))}catch(e){C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}async function R(){if(!(!g?.transaction_id||!v||b)){x(`rollback`),C(null);try{await Fg(g.transaction_id,v.plan_revision),_(null),y(null),p(null),await P(),T(t(`machine.rolledBack`))}catch(e){y(null),C(e instanceof Error?e.message:t(`machine.rollbackError`))}finally{x(null)}}}return b===`load`?(0,H.jsx)(`div`,{className:`personal-machine-loading`,role:`status`,children:t(`common.loading`)}):k?(0,H.jsxs)(`section`,{className:`personal-capability-settings`,"data-revision":n?.revision,children:[(0,H.jsxs)(`details`,{className:`personal-capability-scope-note`,children:[(0,H.jsxs)(`summary`,{children:[(0,H.jsx)(Gm,{"aria-hidden":!0,size:17}),t(`machine.liveDefault`)]}),(0,H.jsx)(`p`,{children:t(`machine.liveDefaultDescription`)})]}),n?.status===`invalid`?(0,H.jsxs)(`section`,{className:`personal-machine-error`,"data-testid":`machine-invalid-repair`,role:`alert`,children:[(0,H.jsx)(`strong`,{children:t(`machine.invalidStoredConfiguration`)}),(0,H.jsx)(`p`,{children:t(`machine.invalidStoredConfigurationDescription`)})]}):null,(0,H.jsxs)(`div`,{className:`personal-capability-layout`,children:[(0,H.jsx)($b,{capabilities:E,locale:e,onSelect:a,scope:`machine`,selectedCapabilityId:k.capability_id,t}),(0,H.jsxs)(`article`,{"aria-label":k.display_name,className:`personal-capability-detail`,tabIndex:0,children:[(0,H.jsx)(ex,{capability:O,locale:e,source:k.available_scopes.includes(`machine`)?te?`machine_default`:`capability_default`:void 0}),(0,H.jsx)(Xb,{available:A,t,description:k.available_scopes.includes(`machine`)?t(`machine.editorUnavailableDescription`):t(`machine.goalOnly`)}),k.capability_id===`periodic_report`?(0,H.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,H.jsx)(Gm,{"aria-hidden":!0,size:18}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:ee?.schedule?e===`zh-CN`?`日历与阶段汇报`:`Calendar and stage reports`:t(`machine.periodicReportActivation`)}),(0,H.jsx)(`p`,{children:ee?.schedule?ee.enabled===!0?e===`zh-CN`?`已配置日历计划,由现有唤醒检查;是否送达请核对报告回执。`:`A calendar schedule is configured and checked by existing wakes. Verify delivery in the report receipt.`:e===`zh-CN`?`日历计划已保存;启用此能力后才会检查和投递。`:`The schedule is saved; enable this capability to check and deliver reports.`:t(`machine.periodicReportActivationDescription`)})]})]}):null,k.capability_id===`change_quality_qualification`?(0,H.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,H.jsx)(Gm,{"aria-hidden":!0,size:18}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:t(`machine.changeQualityActivation`)}),(0,H.jsx)(`p`,{children:t(`machine.changeQualityActivationDescription`)})]})]}):null,k.capability_id===`todo_replan_cadence`?(0,H.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,H.jsx)(Gm,{"aria-hidden":!0,size:18}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:t(`machine.replanCadenceActivation`)}),(0,H.jsx)(`p`,{children:t(`machine.replanCadenceActivationDescription`)})]})]}):null,k.capability_id===`pull_request_review`?(0,H.jsxs)(`section`,{className:`personal-capability-behavior-note`,children:[(0,H.jsx)(Gm,{"aria-hidden":!0,size:18}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:e===`zh-CN`?`只改变队列排序`:`Queue ordering only`}),(0,H.jsx)(`p`,{children:e===`zh-CN`?`默认先审阅其他开发者的 PR;选择 owner-first 才会优先当前已认证审阅者自己的 PR。此配置不会发布 review、写 Todo、push 或 merge。`:`The default reviews other developers' PRs first; choose owner-first only when the authenticated reviewer's own PRs should lead. This setting never posts a review, writes Todos, pushes, or merges.`})]})]}):null,A?(0,H.jsxs)(H.Fragment,{children:[u===`json`||!k.configuration_editor.fields.some(e=>e.key===`enabled`&&e.input_kind===`boolean`)?(0,H.jsx)(`div`,{className:`personal-capability-editor-mode`,children:(0,H.jsxs)(`button`,{onClick:()=>ne(u===`guided`?`json`:`guided`),type:`button`,children:[(0,H.jsx)(cm,{"aria-hidden":!0,size:14}),t(u===`guided`?`machine.editJson`:`machine.backToForm`)]})}):null,u===`guided`?(0,H.jsxs)(`section`,{className:`personal-capability-field-summary`,children:[(0,H.jsx)(Hb,{copy:Kb(e),disabled:!!b,editor:k.configuration_editor,onChange:F,value:o,enabledAction:(0,H.jsxs)(`button`,{className:`personal-capability-edit-json`,onClick:()=>ne(`json`),type:`button`,children:[(0,H.jsx)(cm,{"aria-hidden":!0,size:14}),t(`machine.editJson`)]})}),N?null:(0,H.jsx)(`p`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.requiredFields`)})]}):(0,H.jsxs)(`label`,{className:`personal-capability-json-editor`,htmlFor:`machine-configuration-json`,children:[(0,H.jsx)(`span`,{children:t(`machine.jsonConfiguration`)}),(0,H.jsx)(`textarea`,{"aria-describedby":`machine-configuration-json-help`,disabled:!!b,id:`machine-configuration-json`,onChange:e=>{l(e.target.value),p(null),C(null)},rows:12,spellCheck:!1,value:c}),(0,H.jsx)(`small`,{id:`machine-configuration-json-help`,children:t(`machine.jsonConfigurationHelp`)}),j?null:(0,H.jsx)(`span`,{className:`personal-machine-validation`,role:`alert`,children:t(`machine.jsonInvalid`)})]})]}):null,S?(0,H.jsx)(`p`,{className:`personal-machine-error`,role:`alert`,children:S}):null,w?(0,H.jsxs)(`p`,{className:`personal-machine-notice`,role:`status`,"aria-live":`polite`,children:[(0,H.jsx)(tm,{"aria-hidden":!0,size:16}),w]}):null,f?(0,H.jsxs)(`section`,{"aria-label":t(`machine.preview`),className:`personal-machine-preview`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsx)(`strong`,{children:t(`machine.preview`)}),(0,H.jsx)(`span`,{children:t(`machine.action.${f.action}`)})]}),(0,H.jsxs)(`dl`,{children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:t(`machine.currentRevision`)}),(0,H.jsx)(`dd`,{title:f.current_revision,children:fx(f.current_revision)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:t(`machine.desiredRevision`)}),(0,H.jsx)(`dd`,{title:f.desired_revision,children:fx(f.desired_revision)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:t(`machine.changedNamespaces`)}),(0,H.jsx)(`dd`,{children:f.changed_namespaces.join(`, `)||t(`common.none`)})]})]}),(0,H.jsx)(`p`,{children:t(`machine.previewLocked`)})]}):null,g?.rollback_available&&g.transaction_id?(0,H.jsxs)(`section`,{className:`personal-machine-rollback`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:t(`machine.rollbackAvailable`)}),(0,H.jsx)(`p`,{children:t(v?`machine.rollbackPreviewDescription`:`machine.rollbackDescription`)})]}),(0,H.jsxs)(`button`,{className:`personal-secondary-action`,disabled:!!b||!!(v&&!v.rollback_allowed),onClick:()=>void(v?R():ie()),type:`button`,children:[(0,H.jsx)(Rm,{"aria-hidden":!0,size:15}),t(b===`rollback`||b===`rollback-preview`?`common.loading`:v?`machine.confirmRollback`:`machine.previewRollback`)]})]}):null,A?(0,H.jsxs)(`footer`,{className:`personal-capability-actions`,children:[te?(0,H.jsxs)(`button`,{className:`is-danger`,disabled:!!b,onClick:()=>void I(),type:`button`,children:[(0,H.jsx)(Zm,{"aria-hidden":!0,size:15}),t(`machine.previewRemoval`)]}):null,(0,H.jsx)(`button`,{disabled:!!b||!N,onClick:()=>void re(),type:`button`,children:t(b===`preview`?`common.loading`:`machine.previewChanges`)}),(0,H.jsx)(`button`,{className:`is-primary`,disabled:!!b||!f,onClick:()=>void L(),type:`button`,children:t(b===`apply`?`common.loading`:`machine.applyPreview`)})]}):null,k.available_scopes.includes(`machine`)?(0,H.jsx)(Jb,{values:[{label:t(`machine.currentValue`),value:ee},{label:t(`capabilities.defaultValue`),value:k.default}],t},k.capability_id):null]})]})]}):(0,H.jsx)(`p`,{className:`personal-capability-empty`,children:t(`machine.capabilityEmpty`)})}var mx={appearance:jm,capabilities:Km,language:xm,lark:Wm,machine:Hm};function hx({callbacks:e,focusGoalConnection:t=!1,goals:n,initialGoalId:r,initialTab:i=`lark`,goalNotifications:a,onChanged:o,onClose:s,onThemeChange:c,theme:l}){let{locale:u,setLocale:d,t:f}=qi(),[p,m]=(0,V.useState)(i),h=[...r?[{key:`capabilities`,label:f(`capabilities.title`)}]:[],{key:`machine`,label:f(`machine.title`)},{key:`lark`,label:`Lark`},{key:`appearance`,label:f(`settings.appearance`)},{key:`language`,label:f(`settings.language`)}],g=[{label:f(`settings.languageEnglish`),value:`en`},{label:f(`settings.languageSimplifiedChinese`),value:`zh-CN`}],_={appearance:{title:f(`settings.appearance`)},capabilities:{title:f(`capabilities.title`)},language:{title:f(`settings.language`)},lark:{title:`Lark`},machine:{title:f(`machine.title`)}}[p];return(0,H.jsxs)(`section`,{"aria-label":f(`settings.title`),className:`personal-settings-page`,"data-pw-theme":l,children:[(0,H.jsxs)(`aside`,{className:`personal-settings-sidebar`,children:[(0,H.jsxs)(`button`,{className:`personal-settings-back`,onClick:s,type:`button`,children:[(0,H.jsx)(Kp,{size:17}),(0,H.jsx)(`span`,{children:f(`settings.back`)})]}),(0,H.jsxs)(`div`,{className:`personal-settings-title`,children:[(0,H.jsx)(`small`,{children:f(`settings.eyebrow`)}),(0,H.jsx)(`strong`,{children:f(`settings.title`)})]}),(0,H.jsx)(`nav`,{"aria-label":f(`settings.categories`),className:`personal-settings-tabs`,children:h.map(e=>{let t=mx[e.key];return(0,H.jsxs)(`button`,{"aria-current":p===e.key?`page`:void 0,onClick:()=>m(e.key),type:`button`,children:[(0,H.jsx)(t,{size:17}),(0,H.jsx)(`span`,{children:(0,H.jsx)(`strong`,{children:e.label})})]},e.key)})})]}),(0,H.jsxs)(`main`,{className:`personal-settings-body`,children:[(0,H.jsx)(`header`,{className:`personal-settings-header`,children:(0,H.jsx)(`div`,{children:(0,H.jsx)(`h1`,{children:_.title})})}),p===`lark`?(0,H.jsx)(Fb,{embedded:!0,focusGoalConnection:t,goals:n,initialGoalId:r,onChanged:o,onClose:s}):null,p===`machine`?(0,H.jsx)(px,{}):null,p===`capabilities`?(0,H.jsx)(ox,{callbacks:e,goalId:r,notification:a.find(e=>e.goalId===r),onChanged:o}):null,p===`appearance`?(0,H.jsxs)(`section`,{className:`personal-detail-card personal-appearance-settings`,children:[(0,H.jsx)(`small`,{children:f(`settings.workspaceDisplay`)}),(0,H.jsx)(`h3`,{children:f(`settings.appearance`)}),(0,H.jsxs)(`div`,{className:`personal-settings-choice-group`,role:`radiogroup`,"aria-label":f(`settings.workspaceTheme`),children:[(0,H.jsxs)(`button`,{"aria-checked":l===`loopx`,onClick:()=>c(`loopx`),role:`radio`,type:`button`,children:[(0,H.jsx)(`span`,{className:`personal-settings-theme-swatch is-loopx`}),(0,H.jsx)(`strong`,{children:f(`settings.themeLoopx`)})]}),(0,H.jsxs)(`button`,{"aria-checked":l===`paper`,onClick:()=>c(`paper`),role:`radio`,type:`button`,children:[(0,H.jsx)(`span`,{className:`personal-settings-theme-swatch is-paper`}),(0,H.jsx)(`strong`,{children:f(`settings.themeDefault`)})]}),(0,H.jsxs)(`button`,{"aria-checked":l===`brutal`,onClick:()=>c(`brutal`),role:`radio`,type:`button`,children:[(0,H.jsx)(`span`,{className:`personal-settings-theme-swatch is-brutal`}),(0,H.jsx)(`strong`,{children:f(`settings.themeHighContrast`)})]})]})]}):null,p===`language`?(0,H.jsxs)(`section`,{className:`personal-settings-card`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsx)(`span`,{className:`personal-settings-icon`,children:(0,H.jsx)(xm,{size:18})}),(0,H.jsx)(`div`,{children:(0,H.jsx)(`h2`,{children:f(`settings.language`)})})]}),(0,H.jsx)(`div`,{"aria-label":f(`settings.language`),className:`personal-language-options`,role:`radiogroup`,children:g.map(e=>(0,H.jsxs)(`button`,{"aria-checked":u===e.value,className:u===e.value?`is-selected`:``,onClick:()=>d(e.value),role:`radio`,type:`button`,children:[(0,H.jsx)(`span`,{children:(0,H.jsx)(`strong`,{children:e.label})}),u===e.value?(0,H.jsx)(tm,{"aria-hidden":!0,size:17}):null]},e.value))})]}):null]})]})}var gx=`loopx-pw-theme`,_x=`loopx`;function vx(){try{let e=window.localStorage.getItem(gx);return e===`loopx`||e===`paper`||e===`brutal`?e:_x}catch{return _x}}function yx(e){try{window.localStorage.setItem(gx,e)}catch{}}function bx({drawer:e,drawerMode:t=`panel`,drawerOpen:n,main:r,mobileSidebarOpen:i=!1,onCloseMobileSidebar:a,sidebar:o,theme:s=`loopx`}){let{t:c}=qi(),l=(0,V.useRef)(null),u=(0,V.useRef)(null);return(0,V.useEffect)(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let e=l.current?.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])`);e?.[0]?.focus();function t(t){if(t.key!==`Tab`||!e?.length)return;let n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())}return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),u.current?.focus(),u.current=null}},[i]),(0,H.jsxs)(`section`,{className:`personal-workspace-shell${n?` has-drawer`:``}${n&&t.startsWith(`inspector`)?` has-task-inspector`:``}${t===`inspector-full`?` is-task-inspector-full`:``}${i?` mobile-sidebar-open`:``}`,"data-pw-theme":s,children:[i?(0,H.jsx)(`button`,{"aria-hidden":!0,className:`personal-sidebar-backdrop`,onClick:a,tabIndex:-1,type:`button`}):null,(0,H.jsx)(`aside`,{"aria-label":i?c(`header.goalNavigation`):void 0,"aria-modal":i?!0:void 0,className:`personal-workspace-sidebar`,"data-workspace-sidebar":!0,ref:l,role:i?`dialog`:void 0,children:(0,H.jsxs)(`div`,{className:`personal-workspace-sidebar-inner`,children:[i?(0,H.jsxs)(`button`,{className:`personal-sr-only`,onClick:a,type:`button`,children:[c(`common.close`),` `,c(`header.goalNavigation`)]}):null,o]})}),(0,H.jsx)(`main`,{"aria-hidden":i||void 0,className:`personal-workspace-main`,inert:i||void 0,children:r}),n?(0,H.jsx)(`aside`,{className:`personal-workspace-drawer`,"data-context-drawer":!0,"data-drawer-mode":t,children:e}):null]})}function xx(e){let t=e.match(/(?:下一步|建议|行动项|待办)[::\s]*([^\n]+)/u),n=t?t[1]:e;n=n.replace(/```[\s\S]*?```/g,``).replace(/`([^`]+)`/g,`$1`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).replace(/[#*~_>]/g,``).replace(/^[-*•\d+.\s]+/u,``).replace(/^(好的|没问题|收到|建议如下|任务如下|分析如下|结论[::])[\s,,::]*/u,``);let r=(n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)[0]||n).replace(/\s+/gu,` `).trim();return Array.from(r).slice(0,120).join(``)}function Sx(e){let t=new Map;return e.forEach(e=>{let n=e.fields.find(e=>e.key===`todo_id`)?.value??``,r=[e.actionKind,e.goalId??``,n,e.title].join(`:`);t.set(r,e)}),[...t.values()]}function Cx(e,t,n){if(!e)return n(`home.noFirstActivity`);let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let i=new Date,a=new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.toDateString()===i.toDateString()?n(`home.todayAt`,{time:a}):new Intl.DateTimeFormat(t,{month:`numeric`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r)}function wx({goals:e,onSelectGoal:t,onRetry:n,systemHealth:r}){let{locale:i,t:a}=qi(),o=e.filter(e=>e.activationState===`active`),s=o.filter(e=>e.loadState===`error`).length,c=[{key:`needs_you`,label:a(`home.lane.needsYou`)},{key:`running`,label:a(`home.lane.running`)},{key:`observing`,label:a(`home.lane.observing`)},{key:`scheduled`,label:a(`home.lane.scheduled`)}],l=Object.fromEntries(c.map(e=>[e.key,[]])),u=[],d=[];e.filter(e=>!e.loadState).forEach(e=>{let t=by(e);t===`history`?u.push(e):t===`stopped`?d.push(e):l[t].push(e)});let f=e=>(0,H.jsxs)(`button`,{className:`personal-home-goal-card`,"data-goal-state":e.loadState??e.state,"data-load-error":e.loadError,onClick:()=>t(e.goalId),type:`button`,children:[(0,H.jsxs)(`span`,{className:`personal-home-goal-meta`,children:[(0,H.jsx)(`i`,{}),e.agentLaneCount&&e.agentLaneCount>1?a(`header.workAgentCount`,{count:e.agentLaneCount}):e.agentLabel??e.agentId]}),(0,H.jsx)(`strong`,{children:e.title}),(0,H.jsx)(`p`,{children:e.loadError?a(`startup.error.${e.loadError}`):e.needsYou??e.nextSentence}),(0,H.jsxs)(`footer`,{children:[(0,H.jsx)(`span`,{children:e.loadState?a(e.loadState===`error`?`startup.goalError`:`startup.goalLoading`):Ji(e.state,i)}),(0,H.jsx)(`small`,{title:e.latestActivity,children:e.loadState?``:e.latestActivity?Cx(e.latestActivity,i,a):e.agentTodos.length?a(`home.taskCount`,{count:e.agentTodos.length}):a(`home.noActivity`)})]})]},e.goalId);return(0,H.jsxs)(`section`,{"aria-label":a(`home.workspace`),className:`personal-home-board`,children:[r&&(!r.ok||r.issues.length>0||r.freshnessWarning)?(0,H.jsxs)(`div`,{className:`personal-system-health-banner`,role:`alert`,children:[(0,H.jsxs)(`div`,{className:`personal-system-health-header`,children:[(0,H.jsx)(am,{size:15}),(0,H.jsx)(`strong`,{children:a(`home.systemHealth`,{summary:r.summary})}),r.freshnessWarning?(0,H.jsxs)(`small`,{children:[`(`,r.freshnessWarning,`)`]}):null]}),r.issues.length>0?(0,H.jsx)(`ul`,{className:`personal-system-health-issues`,children:r.issues.map((e,t)=>(0,H.jsx)(`li`,{children:e},t))}):null]}):null,o.some(e=>e.loadState)?(0,H.jsxs)(`section`,{className:`personal-home-lane`,"aria-live":`polite`,children:[(0,H.jsx)(`header`,{children:a(`startup.progress`,{loaded:o.filter(e=>!e.loadState).length,total:o.length})}),s?(0,H.jsxs)(`div`,{className:`personal-stopped-goal-error`,role:`status`,children:[(0,H.jsx)(`span`,{children:a(`startup.failedCount`,{count:s})}),(0,H.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,onClick:n,type:`button`,children:a(`startup.retryFailed`)})]}):null,o.filter(e=>e.loadState).map(f)]}):null,(0,H.jsx)(`div`,{className:`personal-home-lanes`,children:c.map(e=>(0,H.jsxs)(`section`,{className:`personal-home-lane is-${e.key}`,"data-testid":`personal-home-lane-${e.key}`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`i`,{}),e.label]}),(0,H.jsx)(`b`,{children:l[e.key].length})]}),(0,H.jsx)(`div`,{className:`personal-home-lane-list`,children:l[e.key].length?l[e.key].map(f):(0,H.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.empty`)})})]},e.key))}),(0,H.jsxs)(`details`,{className:`personal-home-history`,children:[(0,H.jsxs)(`summary`,{children:[(0,H.jsx)(`span`,{children:a(`home.history`)}),(0,H.jsx)(`b`,{children:u.length}),(0,H.jsx)(`small`,{children:a(`home.completedGoals`)})]}),(0,H.jsx)(`div`,{children:u.length?u.map(f):(0,H.jsx)(`span`,{className:`personal-home-empty`,children:a(`home.noCompletedGoals`)})})]}),d.length?(0,H.jsxs)(`details`,{className:`personal-home-history is-stopped`,children:[(0,H.jsxs)(`summary`,{children:[(0,H.jsx)(`span`,{children:a(`home.stopped`)}),(0,H.jsx)(`b`,{children:d.length}),(0,H.jsx)(`small`,{children:a(`home.preservedState`)})]}),(0,H.jsx)(`div`,{children:d.map(f)})]}):null]})}function Tx({items:e,onSelect:t,reportState:n}){let{locale:r,t:i}=qi();return(0,H.jsxs)(`section`,{className:`personal-object-list personal-files-list`,"data-testid":`personal-goal-outputs`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsx)(`strong`,{children:i(`files.title`)}),(0,H.jsx)(`span`,{children:e.length})]}),n?.loading?(0,H.jsxs)(`p`,{className:`personal-object-list-state`,role:`status`,children:[(0,H.jsx)(Lm,{className:`is-spinning`,size:14}),i(`files.loadingReports`)]}):null,n?.error?(0,H.jsxs)(`p`,{className:`personal-object-list-state is-error`,role:`alert`,children:[(0,H.jsx)(am,{size:14}),i(`files.reportLoadFailed`),`: `,n.error]}):null,!n?.loading&&!n?.error&&e.length===0?(0,H.jsxs)(`p`,{className:`personal-object-list-state`,children:[(0,H.jsx)(_m,{size:14}),i(`files.empty`)]}):null,e.map(e=>(0,H.jsxs)(`button`,{"data-output-kind":e.output.kind,onClick:()=>t({item:e.output,kind:`output`}),type:`button`,children:[(0,H.jsx)(`span`,{className:`personal-file-icon`,children:(0,H.jsx)(_m,{size:16})}),(0,H.jsx)(`strong`,{children:e.output.title}),e.output.report?(0,H.jsx)(`em`,{children:i(`files.reportDelta`,{added:e.output.report.addedCount,changed:e.output.report.changedCount})}):null,(0,H.jsx)(`p`,{children:e.output.summary??e.output.safePreview??e.output.kind??i(`files.emptySummary`)}),(0,H.jsx)(`small`,{title:e.output.createdAt,children:[e.output.goalTitle,e.output.kind===`report`?i(`files.verifiedReport`):null,e.output.todoId?`${i(`common.task`)} ${e.output.todoId}`:null,Cx(e.output.createdAt,r,i)].filter(Boolean).join(` · `)})]},e.id))]})}function Ex({agentLabel:e,messages:t,onClose:n,onDraftTask:r,onOpenConversation:i,title:a}){let{t:o}=qi(),s=t.reduce((e,t,n)=>t.role===`user`?n:e,0),c=t.slice(Math.max(0,s)).slice(-3),l=c.filter(e=>e.role===`assistant`&&!e.pending).at(-1);return(0,V.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,H.jsxs)(`aside`,{"aria-label":o(`conversation.receipt`),className:`personal-manager-conversation-tray`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(Qp,{size:16}),(0,H.jsx)(`strong`,{children:a??o(`conversation.title`)}),(0,H.jsx)(`small`,{children:t.at(-1)?.pending?o(`conversation.replying`):o(`common.recently`)})]}),(0,H.jsxs)(`div`,{className:`personal-manager-conversation-actions`,children:[r&&l?(0,H.jsxs)(`button`,{className:`personal-manager-conversation-btn`,onClick:()=>r(l.text),title:o(`conversation.convertHint`),type:`button`,children:[(0,H.jsx)(Cm,{size:13}),(0,H.jsx)(`span`,{children:o(`conversation.toTask`)})]}):null,(0,H.jsx)(`button`,{className:`personal-manager-conversation-link`,onClick:i,type:`button`,children:o(`conversation.full`)}),n?(0,H.jsx)(`button`,{"aria-label":o(`conversation.close`),className:`personal-manager-conversation-close`,onClick:n,title:o(`conversation.close`),type:`button`,children:(0,H.jsx)(eh,{size:14})}):null]})]}),(0,H.jsx)(`div`,{"aria-live":`polite`,className:`personal-manager-conversation-messages`,children:c.map(t=>(0,H.jsxs)(`article`,{className:`is-${t.role}`,children:[(0,H.jsx)(`strong`,{children:t.role===`user`?o(`common.you`):t.agentLabel??e??o(`header.manager`)}),(0,H.jsxs)(`div`,{className:`personal-manager-conversation-bubble`,children:[t.role===`user`?(0,H.jsx)(`p`,{children:t.text}):(0,H.jsx)(Fy,{text:t.text}),t.pending?(0,H.jsx)(`small`,{children:o(`conversation.agentPending`)}):null,(0,H.jsx)(By,{delivery:t.returnDelivery})]})]},t.id))})]})}function Dx({onClose:e,onOpenDetails:t,run:n}){let{t:r}=qi();return(0,H.jsxs)(`section`,{"aria-label":r(`session.record`),className:`personal-session-record`,children:[(0,H.jsxs)(`header`,{children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(Qp,{size:17}),r(`session.record`)]}),(0,H.jsx)(`button`,{"aria-label":r(`session.closeRecord`),onClick:e,type:`button`,children:(0,H.jsx)(eh,{size:15})})]}),(0,H.jsx)(`div`,{children:(0,H.jsx)(`strong`,{children:n.title})}),(0,H.jsxs)(`dl`,{children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Agent`}),(0,H.jsx)(`dd`,{children:n.agentLabel})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:r(`common.status`)}),(0,H.jsx)(`dd`,{children:Yi(n.sessionStatus??n.status,r)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Session`}),(0,H.jsx)(`dd`,{title:n.sessionId,children:n.sessionId})]})]}),(0,H.jsx)(`button`,{className:`personal-secondary-action`,onClick:t,type:`button`,children:r(`session.details`)})]})}function Ox(e,t,n){let r=[];if(t===null)return e.userTodos.slice(0,4).forEach(t=>r.push({attention:{...t,goalTitle:t.goalTitle??yy(e,t.goalId)},id:`attention:${t.todoId}`,kind:`attention`})),e.goals.filter(e=>by(e)===`running`).slice(0,4).forEach(e=>r.push({id:`run:${e.goalId}`,kind:`run`,run:{agentId:e.agentId,agentLabel:e.agentLabel??e.agentId,completedSteps:e.doneTodoCount??e.agentTodos.filter(e=>e.done).length,goalId:e.goalId,goalTitle:e.title,latestActivity:e.agentSentence,runId:`goal:${e.goalId}`,status:`running`,title:e.nextSentence,totalSteps:Math.max((e.doneTodoCount??0)+e.agentTodos.filter(e=>!e.done).length,1)}})),r;let i=e.goals.find(e=>e.goalId===t);if(!i)return r;if(i.needsYou){let t=e.userTodos.find(e=>e.goalId===i.goalId);r.push({attention:t?{...t,goalTitle:i.title}:{blocking:i.needsYouBlocking??!1,goalId:i.goalId,goalTitle:i.title,text:i.needsYou,todoId:`${i.goalId}:attention`},id:`attention:${i.goalId}`,kind:`attention`})}r.push({id:`run:${i.goalId}`,kind:`run`,run:{agentId:i.agentId,agentLabel:i.agentLabel??i.agentId,completedSteps:i.doneTodoCount??i.agentTodos.filter(e=>e.done).length,goalId:i.goalId,goalTitle:i.title,latestActivity:i.agentSentence,runId:`goal:${i.goalId}`,status:i.state===`推进中`?`running`:i.state===`需修复`?`failed`:`waiting`,title:i.nextSentence,totalSteps:Math.max((i.doneTodoCount??0)+i.agentTodos.filter(e=>!e.done).length,1)}}),i.agentTodos.filter(e=>e.taskClass===`continuous_monitor`).forEach(t=>{let a=e.timeline?.find(e=>e.kind===`run`&&e.run.goalId===i.goalId&&e.run.todoId===t.todoId&&!!e.run.sessionId);r.push({id:`schedule:${i.goalId}:${t.todoId}`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:a?[{label:a.run.latestActivity||a.run.title,runId:a.run.runId,status:a.run.status===`waiting`||a.run.status===`queued`?`running`:a.run.status,timestamp:i.latestActivity||n(`common.recently`)}]:[],goalId:i.goalId,label:t.text,schedule:t.evidence??n(`schedule.summary`),scheduleId:t.todoId,scheduleKind:`monitor`,sessionId:a?.run.sessionId,status:t.done||t.status===`paused`?`paused`:`active`,stopCondition:n(`drawer.scheduleDefaultStop`),target:t.text,timezone:`Asia/Shanghai`}})});let a=e.timeline?.find(e=>e.kind===`proposal`&&e.proposal.actionKind===`heartbeat.bind`&&e.proposal.goalId===i.goalId);if(a){let e=e=>a.proposal.fields.find(t=>t.key===e)?.value;r.push({id:`schedule:${i.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:i.agentId,executionHistory:[],goalId:i.goalId,label:`${n(`schedule.heartbeat`)} · ${i.title}`,nextRunAt:n(`drawer.schedulePending`),notificationRule:n(`drawer.scheduleDefaultNotification`),schedule:e(`cadence`)??n(`schedule.summary`),scheduleId:`${i.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:a.proposal.status===`applied`?`active`:`draft`,stopCondition:e(`stop_condition`)??n(`drawer.scheduleDefaultStop`),timezone:e(`timezone`)??`Asia/Shanghai`}})}return r}function kx(e){return e===`preview_ready`?`ready`:e===`cancelled`?`draft`:e===`failed`?`error`:e}function Ax(e,t){let n={agent_id:t(`proposal.field.agentId`),cadence:t(`proposal.field.cadence`),completion_criteria:t(`proposal.field.completionCriteria`),execution_boundary:t(`proposal.field.executionBoundary`),goal_id:t(`proposal.field.goalId`),heartbeat:t(`proposal.field.heartbeat`),initial_todos:t(`proposal.field.initialTodos`),objective:t(`proposal.field.objective`),operation:t(`proposal.field.operation`),permission:t(`proposal.field.permission`),reason:t(`proposal.field.reason`),stop_condition:t(`proposal.field.stopCondition`),target:t(`proposal.field.target`),timezone:t(`proposal.field.timezone`),title:t(`proposal.field.title`),workspace_ref:t(`proposal.field.workspace`)},r=[`title`,`objective`,`completion_criteria`,`execution_boundary`,`permission`,`agent_id`,`workspace_ref`,`initial_todos`,`heartbeat`,`stop_condition`,`goal_id`];return Object.entries(e).sort(([e],[t])=>{let n=r.indexOf(e),i=r.indexOf(t);return(n<0?r.length:n)-(i<0?r.length:i)}).slice(0,10).map(([e,r])=>({key:e,label:n[e]??e.replaceAll(`_`,` `),value:e===`workspace_ref`?r===`current`?t(`proposal.workspace.current`):t(`proposal.workspace.named`,{workspace:String(r??`current`)}):Array.isArray(r)?r.join(` · `):typeof r==`object`&&r?JSON.stringify(r):String(r??`—`)}))}function jx(e,t,n){let r=t.operationFrame,i=r?.content.fields.map((e,t)=>({key:`projection:${t}`,label:e.label,value:e.value})).slice(0,8)??[];return[{key:`operation_state`,label:n(`proposal.field.operationState`),value:r?.lifecycleState??e.status},...r?.kind===`result`?[{key:`result_delivery`,label:n(`proposal.field.resultDelivery`),value:r.resultDeliveryVerified?n(`proposal.resultDelivery.verified`):n(`proposal.resultDelivery.pending`)}]:[],...i,...r?[{key:`warning`,label:n(`proposal.field.confirmationBoundary`),value:r.content.warning}]:[],...r?[{key:`expires_at`,label:n(`proposal.field.expiresAt`),value:r.expiresAt}]:[]].slice(0,10)}function Mx(e){if(e.action_kind!==`goal.lifecycle`)return;let t=e.normalized_parameters.operation;return t===`stop`||t===`resume`||t===`delete`?t:void 0}function Nx(e,t){let n=Mx(e),r=gy(e),i=typeof e.normalized_parameters.title==`string`?e.normalized_parameters.title:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:``,a=typeof e.normalized_parameters.target==`string`?e.normalized_parameters.target:``,o=r.operationFrame,s=o?.content.title??e.summary,c=e.action_kind===`operation.execute`?s:e.action_kind===`goal.create`?t(`proposal.summary.goalCreate`,{title:i}):e.action_kind===`heartbeat.bind`?t(`proposal.summary.heartbeat`):e.action_kind===`monitor.create`?t(`proposal.summary.monitor`,{target:a}):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.summary.lifecycleStop`,{title:i}):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.summary.lifecycleDelete`,{title:i}):e.action_kind===`goal.lifecycle`?t(`proposal.summary.lifecycleResume`,{title:i}):e.summary;return{actionKind:e.action_kind,reviewPlan:r,fields:e.action_kind===`operation.execute`?jx(e,r,t):Ax(e.normalized_parameters,t),goalId:typeof e.normalized_parameters.goal_id==`string`?e.normalized_parameters.goal_id:void 0,impact:e.action_kind===`operation.execute`?t(`proposal.impact.operation`):e.action_kind===`goal.create`?t(`proposal.impact.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.impact.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.impact.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.impact.lifecycleResume`):e.permission_classification===`protected`?t(`proposal.impact.protected`):t(`proposal.impact.default`),previewId:e.proposal_id,lifecycleOperation:n,gate:e.gate?{kind:String(e.gate.kind??`protected_action`),nextAction:typeof e.gate.next_action==`string`?e.gate.next_action:void 0,summary:String(e.gate.summary??t(`proposal.gate.default`))}:void 0,primaryLabel:e.action_kind===`operation.execute`?o?.kind===`result`?o.resultDeliveryVerified?t(`proposal.primary.operationResultVerified`):t(`proposal.primary.operationResultPending`):t(`proposal.primary.operationGroup`):e.action_kind===`goal.create`?t(`proposal.primary.goalCreate`):e.action_kind===`goal.lifecycle`&&n===`stop`?t(`proposal.primary.lifecycleStop`):e.action_kind===`goal.lifecycle`&&n===`delete`?t(`proposal.primary.lifecycleDelete`):e.action_kind===`goal.lifecycle`?t(`proposal.primary.lifecycleResume`):e.action_kind===`todo.create`&&e.normalized_parameters.start_execution===!0?t(`proposal.primary.todoStart`):t(`proposal.primary.apply`),status:e.status===`applied`&&e.action_kind!==`operation.execute`&&r.interaction!==`completed`?`error`:kx(e.status),title:c}}function Px(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,42);if(t)return t;let n=2166136261;for(let t of e)n^=t.codePointAt(0)??0,n=Math.imul(n,16777619);return`goal-${(n>>>0).toString(36)}`}function Fx(e,t){let n=e.match(/[「“"]([^」”"]{2,80})[」”"]/u)?.[1];return n?n.trim():e.replace(/^(请|帮我|我想|给我|创建|新建|设置|please|i want to|create|set up)+/iu,``).replace(/(一个|新的)?\s*(goal|目标)/giu,``).replace(/[,。!?].*$/u,``).trim().slice(0,80)||t(`goal.defaultTitle`)}function Ix(e,t){for(let n of e.split(/\r?\n/u)){let e=n.trim();for(let n of t){let t=e.match(RegExp(`^${n.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}\\s*[::]\\s*(.*)$`,`iu`));if(t?.[1]?.trim())return t[1].trim()}}return``}function Lx(e,t){let n=Ix(e,[`目标`,`Objective`]),r=Ix(e,[`完成标准`,`Completion criteria`]),i=Ix(e,[`执行边界(可选)`,`执行边界`,`边界`,`Execution boundary (optional)`,`Execution boundary`,`Boundary`]),a=(n||Fx(e,t)).split(/[。;;\n]/u)[0].trim().slice(0,80)||t(`goal.defaultTitle`),o=[n||a,r?t(`goal.objectiveCompletion`,{criteria:r}):``,i?t(`goal.objectiveBoundary`,{boundary:i}):``].filter(Boolean).join(`
-`),s=/(只读|不调用外部工具|不修改(?:仓库|代码|状态)|read.?only|do not (?:call|use) external tools|do not modify (?:repositories|repository|code|state))/iu.test(i||e);return{completionCriteria:r,executionBoundary:i,initialTodos:r?[t(`goal.initialTodo`,{criteria:r})]:[],objective:o,permission:s?`read_only`:`workspace_write_on_confirmation`,title:a}}function Rx(e){let t=e.match(/(?:每|every)\s*(\d{1,3})\s*(?:分钟|minutes?)/iu)?.[1];if(t)return`${t}m`;let n=e.match(/(?:每|every)\s*(\d{1,2})\s*(?:小时|hours?)/iu)?.[1];return n?`${n}h`:/每小时|every hour|hourly/iu.test(e)?`1h`:(/每天|每日|早上|上午|daily|every day/iu.test(e),`1d`)}function zx(e,t){return/(每周|星期|周[一二三四五六日天]|weekly|every\s+(?:mon|tues|wednes|thurs|fri|satur|sun)day|\d{1,2}\s*[::]\s*\d{2})/iu.test(e)?t(`schedule.unsupportedCalendar`):null}function Bx(e,t){return Ix(e,[`检查内容`,`监控内容`,`目标`,`Check target`,`Monitor target`,`Target`])||e.replace(/^(?:为当前 Goal |for the current Goal )?(?:添加|配置|创建|add|configure|create)?\s*(?:定时检查|监控|scheduled check|monitor)[::]?/iu,``).split(/\r?\n/u)[0].trim()||t(`schedule.defaultTarget`)}function Vx(e){return/(mr|pr).{0,8}(合并|merge)/iu.test(e)?`pr_merged`:/发布完成|上线完成|release (?:is )?complete|deployment (?:is )?complete/iu.test(e)?`release_complete`:`goal_complete`}function Hx(e,t){let n=e.toLowerCase();return t.find(e=>n.includes(e.agentId.toLowerCase())||n.includes(e.label.toLowerCase()))}function Ux(e){let t=Ix(e,[`标题`,`任务标题`,`Todo 标题`]),n=Ix(e,[`内容`,`任务内容`,`Todo 内容`]);if(t)return[t,n].filter(Boolean).join(`:`).slice(0,400);let r=e.match(/[「“"]([^」”"]{2,200})[」”"]/u)?.[1];return r?r.trim():e.replace(/^(请|帮我|给我|为当前 Goal |新增|新建|创建|添加|加上|加一个|记一个)+/u,``).replace(/^(一个\s*)?(普通\s*)?(todo|待办|任务)(?:\s*到\s*Tasks?)?[::\s]*/iu,``).replace(/[。;;,,]\s*(?:不要|不需要|无需|禁止|别|暂不).{0,80}(?:heartbeat|心跳|定时|监控|执行).*$/iu,``).replace(/[,,]\s*(并且|然后|再)?\s*(交给|分配给|让).+$/u,``).replace(/\s*(交给|分配给|让)\s+.+$/u,``).trim().slice(0,400)||`推进当前 Goal 的下一项工作`}var Wx=new Set([`image/png`,`image/jpeg`,`image/webp`,`image/gif`]),Gx=5242880,Kx=4;function qx(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onerror=()=>r(Error(t(`composer.imageReadError`,{name:e.name}))),i.onload=()=>n({dataUrl:String(i.result??``),id:crypto.randomUUID(),mimeType:e.type,name:e.name,size:e.size}),i.readAsDataURL(e)})}function Jx({agents:e=[{agentId:`codex`,available:!0,capability:`代码与项目执行`,label:`Codex`}],callbacks:t={},goalArchiveLoadState:n={error:null,phase:`ready`},managerRuntime:r,model:i,readOnly:a=!1,selectedAgentId:o,selectedGoalId:s,statusSourceControl:c}){let{locale:l,t:u}=qi(),[d,f]=(0,V.useState)(s??null),[p,m]=(0,V.useState)(o??e.find(e=>e.available)?.agentId??`codex`),[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)(!1),[y,b]=(0,V.useState)(null),[x,S]=(0,V.useState)({}),[C,w]=(0,V.useState)(`chat`),[T,E]=(0,V.useState)(!1),[D,O]=(0,V.useState)(!1),[k,ee]=(0,V.useState)(!1),[te,A]=(0,V.useState)(()=>{try{let e=window.sessionStorage.getItem(`loopx-pw-composer-drafts`),t=e?JSON.parse(e):{};return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}),[j,M]=(0,V.useState)(!1),[N,P]=(0,V.useState)([]),[F,ne]=(0,V.useState)(null),[re,I]=(0,V.useState)(null),[L,ie]=(0,V.useState)(()=>new Set),[R,ae]=(0,V.useState)(()=>new Set),[oe,se]=(0,V.useState)(`idle`),[ce,le]=(0,V.useState)([]),[ue,z]=(0,V.useState)(!1),[de,fe]=(0,V.useState)(vx),[pe,me]=(0,V.useState)({}),[he,ge]=(0,V.useState)([]),_e=(0,V.useRef)(!1),ve=(0,V.useRef)(NaN),ye=(0,V.useRef)(null),be=(0,V.useRef)(null),xe=(0,V.useRef)(null),Se=(0,V.useRef)(new Set),Ce=(0,V.useRef)(new Set),[we,Te]=(0,V.useState)(null),B=s===void 0?d:s,Ee=o??p,De=`${B??`manager`}:${Ee}`,Oe=te[De]??``;(0,V.useEffect)(()=>{P([]),ne(null)},[De]);function ke(e,t){A(n=>{let r={...n};t?r[e]=t:delete r[e];try{window.sessionStorage.setItem(`loopx-pw-composer-drafts`,JSON.stringify(r))}catch{}return r})}function Ae(e){ke(De,e)}function je(e){let t=te[De]?.trimEnd();Ae(t?`${t}\n${e}`:e),window.requestAnimationFrame(()=>ye.current?.focus())}(0,V.useEffect)(()=>{let e=ye.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)},[Oe]);let Me=(0,V.useMemo)(()=>i.goals.map(e=>{let t=pe[e.goalId];return t?{...e,repository:{branch:t.branch,identity:t.identity,label:t.label,readOnly:!0}}:e}),[pe,i.goals]),Ne=(0,V.useMemo)(()=>Me.filter(e=>by(e)===`needs_you`).length,[Me]),Pe=(0,V.useMemo)(()=>Me.filter(e=>by(e)===`needs_you`&&(e.needsYouBlocking||e.state===`等你`)).length,[Me]),Fe=Me.find(e=>e.goalId===B)??null,Ie=h?.kind===`settings`,Le=B,Re=(0,V.useMemo)(()=>{let e=Object.values(x).filter(e=>e.actionKind===`heartbeat.bind`&&e.goalId&&e.status===`applied`).map(e=>({id:`schedule:${e.goalId}:heartbeat`,kind:`schedule`,schedule:{agentId:Ee,executionHistory:[],goalId:e.goalId,label:e.title,nextRunAt:u(`drawer.schedulePending`),notificationRule:u(`drawer.scheduleDefaultNotification`),schedule:e.fields.find(e=>e.key===`cadence`)?.value??u(`schedule.summary`),scheduleId:`${e.goalId}:heartbeat`,scheduleKind:`heartbeat`,status:e.status===`applied`?`active`:`draft`,stopCondition:e.fields.find(e=>e.key===`stop_condition`)?.value??u(`drawer.scheduleDefaultStop`),timezone:e.fields.find(e=>e.key===`timezone`)?.value??`Asia/Shanghai`}})),t=[...Ox(i,Le,u),...i.timeline??[],...e,...Sx(Object.values(x)).filter(e=>e.actionKind!==`heartbeat.bind`||e.status!==`applied`).map(e=>({id:`proposal:${e.previewId}`,kind:`proposal`,proposal:e}))];return[...new Map(t.map(e=>[e.id,e])).values()].filter(e=>e.kind!==`proposal`||![`stale`,`error`].includes(e.proposal.status)||ce.includes(e.proposal.previewId)).filter(e=>!B||e.kind===`message`?!0:e.kind===`proposal`?!e.proposal.goalId||e.proposal.goalId===B:e.kind===`attention`?e.attention.goalId===B:e.kind===`run`?e.run.goalId===B:e.kind===`schedule`?e.schedule.goalId===B:e.output.goalId===B)},[Le,i,x,Ee,B,ce,u]),ze=(0,V.useMemo)(()=>y?Re.filter(e=>e.kind===`message`?!0:e.kind===`run`?e.run.runId===y.runId:e.kind===`output`&&e.output.runId===y.runId):Re,[y,Re]);(0,V.useEffect)(()=>{if(!y)return;let e=Re.find(e=>e.kind===`run`&&e.run.runId===y.runId);!e||e.kind!==`run`||JSON.stringify({completedSteps:y.completedSteps,latestActivity:y.latestActivity,messages:y.sessionMessages,sessionStatus:y.sessionStatus,status:y.status,totalSteps:y.totalSteps})!==JSON.stringify({completedSteps:e.run.completedSteps,latestActivity:e.run.latestActivity,messages:e.run.sessionMessages,sessionStatus:e.run.sessionStatus,status:e.run.status,totalSteps:e.run.totalSteps})&&b(e.run)},[y,Re]);let Be=(0,V.useMemo)(()=>Re.flatMap(e=>e.kind===`message`?[e.message]:[]),[Re]),Ve=(0,V.useMemo)(()=>Fe?Re.flatMap(e=>e.kind===`message`?[e.message]:[]):[],[Re,Fe]);(0,V.useEffect)(()=>{Fe||T||Be.some(e=>e.pending)&&O(!0)},[T,Be,Fe]),(0,V.useEffect)(()=>{!Fe||C===`chat`||Ve.some(e=>e.pending)&&ee(!0)},[Ve,Fe,C]);let He=(0,V.useMemo)(()=>Re.filter(e=>e.kind===`message`||e.kind===`proposal`&&ce.includes(e.proposal.previewId)),[Re,ce]),Ue=He[He.length-1],We=Ue?.kind===`message`?Ue.message.text.length:0;(0,V.useEffect)(()=>{if(!T||!be.current)return;let e=window.requestAnimationFrame(()=>{be.current&&(be.current.scrollTop=be.current.scrollHeight)});return()=>window.cancelAnimationFrame(e)},[He.length,T,We]);let Ge=(0,V.useMemo)(()=>{if(h?.kind===`settings`)return null;if(h?.kind===`attention`)return{kind:`attention`,item:Gd(h.item,i.attentionHistory??i.userTodos)};if(h?.kind===`goal`){let e=Me.find(e=>e.goalId===h.item.goalId);return e?{item:e,kind:`goal`}:h}if(h?.kind!==`run`)return h;let e=Re.find(e=>e.kind===`run`&&e.run.runId===h.item.runId);return e?{item:e.run,kind:`run`}:h},[Re,h,Me,i.attentionHistory,i.userTodos]);(0,V.useEffect)(()=>{if(a){me({}),ge([]);return}let e=!1;return Promise.all([Lg(),Jg()]).then(([t,n])=>{e||(me(Object.fromEntries(t.map(e=>[e.goal_id,e.repository]))),ge(n))}).catch(()=>{}),()=>{e=!0}},[a]),(0,V.useEffect)(()=>{if(!ue)return;function e(e){e.key===`Escape`&&z(!1)}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ue]),(0,V.useEffect)(()=>{if(B||!Re.length)return;if(!_e.current){_e.current=!0;try{ve.current=Date.parse(window.localStorage.getItem(`loopx-pw-last-visit`)??``),window.localStorage.setItem(`loopx-pw-last-visit`,new Date().toISOString())}catch{ve.current=NaN}}let e=ve.current,t=Re.filter(e=>e.kind===`run`).map(e=>e.run),n=t=>{let n=Date.parse(t??``);return!Number.isNaN(e)&&!Number.isNaN(n)&&n>e},r={attention:Ne,done:t.filter(e=>e.status===`completed`&&n(e.latestActivity)).length,failed:t.filter(e=>(e.status===`failed`||e.status===`interrupted`)&&n(e.latestActivity)).length};Te(e=>e?.attention===r.attention&&e.done===r.done&&e.failed===r.failed?e:r)},[Re,Ne,B]),(0,V.useEffect)(()=>{if(a){S({});return}let e=!1;return Nh(B?{goalId:B}:{contextKind:`manager`}).then(t=>{if(e)return;let n=Object.fromEntries(t.filter(e=>[`preview_ready`,`gated`,`deferred`,`applying`].includes(e.status)||e.action_kind===`operation.execute`&&e.status===`applied`).map(e=>{let t=Nx(e,u);return[t.previewId,t]}));S(e=>({...e,...n}))}).catch(()=>{}),()=>{e=!0}},[a,B,u]);async function Ke(e,n={}){if(a)throw Error(u(`source.readOnlyWriteError`));let r;try{r=t.onPreviewAction?await t.onPreviewAction(e):Nx(await jh(e),u)}catch(t){if(!(t instanceof Eh)||t.payload.error_code!==`action_preview_gate`)throw t;let n=t.payload.gate&&typeof t.payload.gate==`object`?t.payload.gate:{},i=(Array.isArray(n.candidates)?n.candidates:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.workspace_ref==`string`&&typeof t.label==`string`?[{label:t.label,workspaceRef:t.workspace_ref}]:[]}),a=String(n.kind??`workspace_selection_required`),o=a===`agent_binding_required`||a===`agent_identity_selection_required`;r={actionKind:e.actionKind,fields:i.map(e=>({key:`workspace_ref:${e.workspaceRef}`,label:e.label,value:e.workspaceRef})),gate:{kind:a,nextAction:typeof n.next_action==`string`?n.next_action:void 0,summary:String(n.summary??u(`proposal.workspaceGate.defaultSummary`))},impact:u(o?`proposal.workspaceGate.agentImpact`:`proposal.workspaceGate.selectionImpact`),previewId:`workspace-choice-${Date.now().toString(36)}`,sourceRequest:e,status:`gated`,title:u(o?`proposal.workspaceGate.agentTitle`:`proposal.workspaceGate.selectionTitle`),workspaceCandidates:i}}return le(e=>e.includes(r.previewId)?e:[...e,r.previewId]),S(e=>({...e,[r.previewId]:r})),n.select!==!1&&g({item:r,kind:`proposal`}),r}function qe(){tt(null),ke(`manager:${Ee}`,u(`composer.createGoalTemplate`)),window.requestAnimationFrame(()=>ye.current?.focus())}async function Je(e,n){z(!1);let r={delete:`Deleted from the owner workspace`,resume:`Resumed from the owner workspace`,stop:`Stopped from the owner workspace`},i={delete:u(`proposal.summary.lifecycleDelete`,{title:e.title}),resume:u(`proposal.summary.lifecycleResume`,{title:e.title}),stop:u(`proposal.summary.lifecycleStop`,{title:e.title})},a=null,o=!1;try{if(n===`stop`){if(Se.current.has(e.goalId))return;Se.current.add(e.goalId),ie(new Set(Se.current)),g(null),a={goalId:e.goalId,next:`stopped`,optimisticApplied:!0,previous:e.activationState},I(u(`feedback.applying`,{title:i.stop})),t.onGoalActivationStateChange?.(e.goalId,`stopped`)}if(t.onExecuteGoalLifecycle){if(n===`delete`)throw Error(`The selected status source does not authorize Goal deletion.`);let a=await t.onExecuteGoalLifecycle({goalId:e.goalId,operation:n,reason:r[n]});if(!a.projectionVerified)throw Error(`Goal lifecycle projection did not verify.`);o=!0,t.onGoalActivationStateChange?.(e.goalId,a.activationState),I(u(`feedback.completed`,{title:i[n]})),n===`stop`&&tt(null),await(t.onReconcileStatus??t.onRefresh)?.();return}let s=await Ke({actionKind:`goal.lifecycle`,context:{kind:`goal_directory`,goal_id:e.goalId},idempotencyKey:`workspace-goal-${n}-${e.goalId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:n,reason:r[n]},summary:i[n]},{select:n!==`stop`});if(s.goalId!==e.goalId||s.lifecycleOperation!==n)throw g(null),Error(u(`actionReview.targetChanged`));n===`stop`&&(s.reviewPlan?.interaction===`direct`?(o=!0,await Qe(s,{lifecycleProjection:a??void 0,presentation:`feedback`})):(a&&t.onGoalActivationStateChange?.(a.goalId,a.previous),I(s.gate?u(`feedback.gateRequired`,{summary:s.gate.summary}):u(`feedback.notCompleted`,{status:s.status})),g({item:s,kind:`proposal`})))}catch(e){a&&!o&&t.onGoalActivationStateChange?.(a.goalId,a.previous),I(u(`feedback.executionFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{n===`stop`&&(Se.current.delete(e.goalId),ie(new Set(Se.current)))}}function Ye(e,t){Ae(u(t?e===`heartbeat`?`composer.heartbeatTemplate`:`composer.monitorTemplate`:e===`heartbeat`?`composer.heartbeatTemplateWithoutGoal`:`composer.monitorTemplateWithoutGoal`)),g(null),window.requestAnimationFrame(()=>ye.current?.focus())}async function Xe(e,n,r=``){let i=await t.onRequestScheduleConfig?.(e,n);if(i){le(e=>e.includes(i.previewId)?e:[...e,i.previewId]),S(e=>({...e,[i.previewId]:i})),g({item:i,kind:`proposal`});return}if(!n){Ae(u(e===`heartbeat`?`composer.heartbeatGoalQuestion`:`composer.monitorGoalQuestion`));return}let a=Date.now().toString(36);await Ke({actionKind:e===`heartbeat`?`heartbeat.bind`:`monitor.create`,context:{kind:`schedule`,goal_id:n},idempotencyKey:`workspace-${e}-${n}-${a}`,normalizedParameters:e===`heartbeat`?{agent_id:Ee,cadence:Rx(r),goal_id:n,stop_condition:Vx(r),timezone:`Asia/Shanghai`}:{agent_id:Ee,cadence:Rx(r),goal_id:n,stop_condition:Vx(r),target:Bx(r,u),target_key:`goal-${n}`,timezone:`Asia/Shanghai`},summary:e===`heartbeat`?u(`proposal.summary.heartbeat`):u(`proposal.summary.monitor`,{target:Bx(r,u)})})}async function Ze(e){if(!Ce.current.has(e.todoId)){Ce.current.add(e.todoId),ae(new Set(Ce.current)),I(u(`feedback.preparingPreview`,{title:e.text}));try{await Ke({actionKind:`todo.update`,context:{goal_id:e.goalId,kind:`todo`,todo_id:e.todoId},idempotencyKey:`workspace-todo-${e.todoId}-complete-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,operation:`complete`,todo_id:e.todoId},summary:u(`tasks.markComplete`,{name:e.text})}),I(null)}catch(e){I(u(`feedback.previewFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{Ce.current.delete(e.todoId),ae(new Set(Ce.current))}}}async function Qe(e,n={}){if(e.reviewPlan&&!e.reviewPlan.canApply)return;let r=n.presentation!==`feedback`,a=e.actionKind===`goal.lifecycle`&&e.goalId&&(e.lifecycleOperation===`stop`||e.lifecycleOperation===`resume`)?{goalId:e.goalId,next:e.lifecycleOperation===`stop`?`stopped`:`active`,optimisticApplied:!1,previous:i.goals.find(t=>t.goalId===e.goalId)?.activationState??(e.lifecycleOperation===`stop`?`active`:`stopped`)}:null,o=n.lifecycleProjection??a;I(u(`feedback.applying`,{title:e.title}));let s={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`pending`,reason:`apply_pending`,canApply:!1}:void 0,status:`applying`};S(t=>({...t,[e.previewId]:s})),r&&g({item:s,kind:`proposal`}),o&&!o.optimisticApplied&&t.onGoalActivationStateChange?.(o.goalId,o.next);try{if(t.onApplyProposal){await t.onApplyProposal(e);let n={...e,status:`applied`};if(S(t=>({...t,[e.previewId]:n})),r&&g({item:n,kind:`proposal`}),I(u(`feedback.completed`,{title:e.title})),e.actionKind===`goal.lifecycle`){(e.lifecycleOperation===`stop`||e.lifecycleOperation===`delete`)&&tt(null),e.lifecycleOperation===`delete`&&e.goalId&&t.onGoalDeleted?.(e.goalId);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>void 0)}return}let n=await Ph(e.previewId);if(n.proposal.proposal_id!==e.previewId||n.proposal.action_kind!==e.actionKind||e.actionKind===`goal.lifecycle`&&(n.proposal.normalized_parameters.goal_id!==e.goalId||Mx(n.proposal)!==e.lifecycleOperation))throw new Eh(u(`actionReview.targetChanged`),{error_code:`action_response_mismatch`});let i=Nx(n.proposal,u);if(S(t=>({...t,[e.previewId]:i})),r&&g({item:i,kind:`proposal`}),i.reviewPlan?.interaction!==`completed`){o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),g({item:i,kind:`proposal`}),I(n.proposal.status===`stale`?u(`feedback.stale`):u(`actionReview.${i.reviewPlan.reason}`));return}if(I(u(`feedback.completed`,{title:i.title})),i.actionKind===`todo.create`&&await t.onRefresh?.(),i.actionKind===`goal.lifecycle`&&(i.lifecycleOperation===`stop`||i.lifecycleOperation===`delete`)&&tt(null),i.actionKind===`goal.lifecycle`&&i.lifecycleOperation===`delete`&&i.goalId&&t.onGoalDeleted?.(i.goalId),i.actionKind===`goal.lifecycle`){let e=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>e?.()).catch(()=>void 0)}}catch(n){if(o&&t.onGoalActivationStateChange?.(o.goalId,o.previous),n instanceof Eh&&n.payload.error_code===`protected_action`){let r=n.payload.gate,i=r&&typeof r==`object`?r:{},a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:`gated`,reason:`authority_gate`,canApply:!1}:void 0,gate:{kind:String(i.kind??`protected_action`),nextAction:typeof i.next_action==`string`?i.next_action:void 0,summary:String(i.summary??n.message)},status:`gated`};S(t=>({...t,[e.previewId]:a})),g({item:a,kind:`proposal`}),I(u(`feedback.gateRequired`,{summary:a.gate.summary})),e.actionKind===`goal.create`&&e.goalId&&(t.onRefresh?.(),tt(e.goalId));return}let r=n instanceof Eh&&_y(n.payload),i=n instanceof Eh&&n.payload.error_code===`action_response_mismatch`,a={...e,reviewPlan:e.reviewPlan?{...e.reviewPlan,interaction:r?`refresh`:`repair`,reason:i?`readback_unverified`:r?`stale_proposal`:`apply_failed`,canApply:!1}:void 0,errorMessage:n instanceof Error?n.message:String(n),status:r?`stale`:`error`};S(t=>({...t,[e.previewId]:a})),g({item:a,kind:`proposal`}),I(u(`feedback.executionFailed`,{error:a.errorMessage}))}}let $e={...t,onOpenRunSession:async e=>{e.goalId!==B&&tt(e.goalId),w(`chat`),await t.onOpenRunSession?.(e),b(e),g(null)},onOpenGoal:e=>{tt(e);let n=t.onReconcileStatus??t.onRefresh;Promise.resolve().then(()=>n?.()).catch(()=>{I(u(`feedback.goalRefreshFailed`))})},onOpenGoalView:e=>{w(e),e===`chat`&&b(null),g(null)},onOpenOutput:e=>{e.goalId!==B&&tt(e.goalId),w(`files`),t.onOpenOutput?.(e)},onApplyProposal:Qe,onCancelProposal:async e=>{g(null),S(t=>{let n={...t};return delete n[e.previewId],n});try{t.onCancelProposal?.(e),t.onCancelProposal||await Fh(e.previewId)}catch(t){S(t=>({...t,[e.previewId]:e})),I(u(`feedback.cancelFailed`,{error:t instanceof Error?t.message:String(t)}))}},onTransitionProposal:async(e,t)=>{let n=Nx(await Ih(e.previewId,t),u);le(e=>e.includes(n.previewId)?e:[...e,n.previewId]),S(r=>{let i={...r};return t===`regenerate`&&delete i[e.previewId],i[n.previewId]=n,i}),g({item:n,kind:`proposal`})},onSelectWorkspaceCandidate:async(e,t)=>{e.sourceRequest&&(S(t=>{let n={...t};return delete n[e.previewId],n}),await Ke({...e.sourceRequest,idempotencyKey:`${e.sourceRequest.idempotencyKey}-${t}`,normalizedParameters:{...e.sourceRequest.normalizedParameters,workspace_ref:t}}))},onPreviewAction:Ke,onRequestScheduleConfig:(e,t)=>Ye(e,t),onOpenNotificationSettings:e=>g({goalId:e,kind:`settings`,tab:`lark`}),onFetchNotificationTargets:()=>ag(),onSetupGoalChannel:e=>sg(e),onToggleGoalAutoNotify:e=>cg(e),onUpdateSchedule:async(e,t)=>{let n=Date.now().toString(36),r=e.scheduleKind===`heartbeat`;await Ke({actionKind:r?`heartbeat.bind`:`monitor.update`,context:{kind:`schedule`,goal_id:e.goalId},idempotencyKey:`workspace-monitor-${e.scheduleId}-${t}-${n}`,normalizedParameters:{agent_id:e.agentId??Ee,...!r&&t===`run_now`?{endpoint_id:Ee}:{},...t===`edit`?{cadence:`2h`,...r?{timezone:e.timezone??`Asia/Shanghai`}:{}}:{},goal_id:e.goalId,operation:t,...!r&&t===`run_now`&&e.sessionId?{session_id:e.sessionId}:{},...r?{}:{todo_id:e.scheduleId}},summary:t===`pause`?`暂停自动运行:${e.label}`:t===`resume`?`恢复自动运行:${e.label}`:t===`run_now`?`立即运行:${e.label}`:t===`stop`?`停止自动运行:${e.label}`:`编辑自动运行生命周期:${e.label}`})}},et=a?{onOpenGoal:$e.onOpenGoal,onOpenGoalView:$e.onOpenGoalView,onOpenOutput:$e.onOpenOutput}:$e;function tt(e){f(e),E(!1),O(!1),ee(!1),b(null),g(null),w(`tasks`),z(!1),t.onSelectGoal?.(e)}function nt(e){m(e),t.onSelectAgent?.(e)}function rt(e){fe(e),yx(e)}async function it(n){let r=n?[]:N,i=(n??Oe).trim()||(r.length?u(`composer.imageAnalysisPrompt`):``);if(!(!i||j)){n||(Ae(``),P([])),ne(null),M(!0);try{if(r.length){B?C!==`chat`&&ee(!0):O(!0);let e=await t.onSendMessage?.(i,Ee,B,r);e&&await Ke(e);return}let n=Yy(i,{agents:e.map(e=>({agentId:e.agentId,label:e.label})),goalId:B,todos:(Fe?.agentTodos??[]).map(e=>({text:e.text,todoId:e.todoId}))});if(n.route===`clarify`){Ae(i);let e=u(`composer.clarifySingleAction`);n.missingFields.includes(`resume_when`)&&(e=u(`composer.clarifyDefer`)),I(e);return}if(n.actionKind===`goal.create`){let e=Lx(i,u),t=Px(e.title);await Ke({actionKind:`goal.create`,context:{kind:`manager`,goal_id:null,natural_language:i},idempotencyKey:`workspace-goal-intent-${t}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:Ee,completion_criteria:e.completionCriteria,execution_boundary:e.executionBoundary,goal_id:t,heartbeat:{cadence:Rx(i),enabled:n.normalizedParameters.heartbeat_enabled===!0,timezone:`Asia/Shanghai`},initial_todos:e.initialTodos,objective:e.objective,permission:e.permission,stop_condition:Vx(i),title:e.title,workspace_ref:`current`},summary:u(`proposal.summary.goalCreate`,{title:e.title})});return}if(B&&n.actionKind===`heartbeat.bind`){await Xe(`heartbeat`,B,i);return}if(B&&n.actionKind===`monitor.create`){let e=zx(i,u);if(e){Ae(i),I(e);return}await Xe(`monitor`,B,i);return}let a=Hx(i,e);if(B&&a&&n.actionKind===`agent.bind`){await Ke({actionKind:`agent.bind`,context:{kind:`goal`,goal_id:B,natural_language:i},idempotencyKey:`workspace-agent-bind-${B}-${a.agentId}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:a.agentId,goal_id:B},summary:`将 ${a.label} 绑定到 ${Fe?.title??B}`});return}if(B&&n.actionKind===`todo.create`){if(n.normalizedParameters.start_execution===!0){await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:B,natural_language:i},idempotencyKey:`workspace-task-start-${B}-${Date.now().toString(36)}`,normalizedParameters:{endpoint_id:a?.agentId??Ee,goal_id:B,start_execution:!0,text:i},summary:`交给 Agent 执行:${i.slice(0,120)}`});return}let e=a?.agentId??(/(交给|分配给|让).{0,24}(agent|codex|claude|kiro|kimi)/iu.test(i)?Ee:null);await Ke({actionKind:`todo.create`,context:{kind:`goal`,goal_id:B,natural_language:i},idempotencyKey:`workspace-todo-create-${B}-${Date.now().toString(36)}`,normalizedParameters:{...e?{endpoint_id:e}:{},goal_id:B,text:Ux(i)},summary:`创建 Todo:${Ux(i)}`});return}let o=Fe?.agentTodos.find(e=>i.includes(e.todoId)||i.includes(e.text)),s=typeof n.normalizedParameters.operation==`string`?n.normalizedParameters.operation:null;if(B&&o&&n.actionKind===`todo.update`&&s){await Ke({actionKind:`todo.update`,context:{kind:`todo`,goal_id:B,todo_id:o.todoId,natural_language:i},idempotencyKey:`workspace-todo-update-${o.todoId}-${s}-${Date.now().toString(36)}`,normalizedParameters:{agent_id:Ee,...s===`reassign`&&a?{endpoint_id:a.agentId}:{},...s===`block`?{note:i}:{},...s===`defer`&&typeof n.normalizedParameters.resume_when==`string`?{resume_when:n.normalizedParameters.resume_when}:{},goal_id:B,operation:s,todo_id:o.todoId},summary:`更新 Todo:${o.text}`});return}B?C!==`chat`&&ee(!0):O(!0);let c=await t.onSendMessage?.(i,Ee,B);c&&await Ke(c)}catch(e){n||(Ae(i),P(r));let t=e instanceof Error?e.message:u(`feedback.sendGenericError`);I(u(`feedback.sendFailed`,{error:t}))}finally{M(!1)}}}let at=e.find(e=>e.agentId===Ee)?.label??Ee,ot=!Fe&&Oe.startsWith(u(`composer.createGoalDraftLead`)),st=Re.filter(e=>e.kind===`run`&&!!e.run.sessionId&&!!e.run.canInterrupt&&(e.run.status===`running`||e.run.status===`queued`)).length;async function ct(e){if(!e?.length)return;let t=Kx-N.length,n=Array.from(e).slice(0,Math.max(0,t)),r=n.find(e=>!Wx.has(e.type)),i=n.find(e=>e.size>Gx);if(t<=0){ne(u(`composer.imageCountError`,{count:Kx}));return}if(r){ne(u(`composer.imageTypeError`));return}if(i){ne(u(`composer.imageSizeError`,{size:Gx/1024/1024}));return}try{let t=await Promise.all(n.map(e=>qx(e,u)));P(e=>[...e,...t].slice(0,Kx)),ne(e.length>n.length?u(`composer.imageCountError`,{count:Kx}):null)}catch(e){ne(e instanceof Error?e.message:u(`composer.imageReadGenericError`))}finally{xe.current&&(xe.current.value=``)}}function lt(e){let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).flatMap(e=>{let t=e.getAsFile();return t?[t]:[]});t.length&&(e.preventDefault(),ct(t))}async function ut(){let e=await Jg();ge(e)}async function dt(){await Promise.all([ut(),t.onRefresh?.()])}async function ft(){if(!(!t.onRefresh||oe===`loading`)){se(`loading`);try{await t.onRefresh(),se(`done`)}catch{se(`error`)}window.setTimeout(()=>se(`idle`),1800)}}return Ie?(0,H.jsx)(hx,{callbacks:et,focusGoalConnection:!!(h?.kind===`settings`&&h.goalId),goalNotifications:i.goalNotifications??[],goals:Me,initialGoalId:h?.kind===`settings`?h.goalId??B:B,initialTab:h?.kind===`settings`?h.tab??`lark`:`lark`,onChanged:()=>void dt(),onClose:()=>g(null),onThemeChange:rt,theme:de}):(0,H.jsx)(bx,{drawer:Ge?(0,H.jsx)(ib,{agents:e,attentionHistory:i.attentionHistory??i.userTodos,onSelectAttention:e=>g({kind:`attention`,item:e}),callbacks:et,goalNotifications:i.goalNotifications??[],goals:Me,inspectorExpanded:_,larkConnections:a?[]:he,onClose:()=>{Ge.kind===`proposal`&&[`applied`,`rejected`].includes(Ge.item.status)&&(Ge.item.actionKind!==`heartbeat.bind`||Ge.item.status!==`applied`)&&S(e=>{let t={...e};return delete t[Ge.item.previewId],t}),v(!1),g(null)},onToggleInspectorSize:()=>v(e=>!e),readOnly:a,runs:Re.flatMap(e=>e.kind===`run`?[e.run]:[]),selection:Ge}):null,drawerMode:Ge?.kind===`todo`?_?`inspector-full`:`inspector`:`panel`,drawerOpen:Ge!==null,mobileSidebarOpen:ue,onCloseMobileSidebar:()=>z(!1),theme:de,main:(0,H.jsxs)(`div`,{className:`personal-channel`,children:[(0,H.jsx)(Oy,{agents:e,managerChatOpen:T,managerRuntime:r,mobileNavigationOpen:ue,onOpenGoalCapabilities:Fe?()=>g({goalId:Fe.goalId,kind:`settings`,tab:`capabilities`}):void 0,onOpenGoalDetail:Fe&&!Fe.loadState?()=>g({item:Fe,kind:`goal`}):void 0,onRefresh:t.onRefresh?()=>void ft():void 0,onOpenNavigation:()=>z(!0),onOpenManagerChat:()=>{O(!1),E(!0)},onSelectGoalTab:e=>{w(e),e===`chat`&&(b(null),ee(!1))},onSelectAgent:nt,onReturnManagerHome:()=>{E(!1),O(!1),window.requestAnimationFrame(()=>be.current?.scrollTo({behavior:`smooth`,top:0}))},selectedAgentId:Ee,refreshState:oe,readOnlySourceLabel:a?c?.activeSource.label:void 0,selectedGoal:Fe,selectedGoalTab:C}),(0,H.jsxs)(`div`,{className:`personal-channel-scroll`,ref:be,children:[!Fe&&!T&&we&&we.done+we.failed+we.attention>0?(0,H.jsxs)(`section`,{className:`personal-digest-card`,"aria-label":u(`digest.away`),children:[(0,H.jsx)(`strong`,{children:u(`digest.away`)}),(0,H.jsxs)(`div`,{className:`personal-digest-stats`,children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`b`,{children:we.done}),u(`digest.completed`)]}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`b`,{children:we.failed}),u(`digest.failed`)]}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`b`,{children:we.attention}),u(`digest.needsYou`)]})]})]}):null,!Fe&&!T?(0,H.jsxs)(`section`,{className:`personal-manager-greeting`,children:[(0,H.jsx)(`span`,{children:(0,H.jsx)(Qp,{size:20})}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:u(`home.greeting`)}),(0,H.jsx)(`p`,{children:i.goals.some(e=>e.activationState===`active`&&e.loadState)?u(`startup.partial`):(0,H.jsxs)(H.Fragment,{children:[u(`home.waitingCount`,{count:Ne}),` `,u(`home.blockingSummary`,{count:Pe})]})})]})]}):null,Fe?.loadState?(0,H.jsx)(`section`,{className:`personal-manager-greeting`,role:`status`,"data-testid":`goal-status-loading`,children:(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:u(Fe.loadState===`error`?`startup.goalError`:`startup.goalLoading`)}),(0,H.jsx)(`p`,{children:u(Fe.loadError?`startup.error.${Fe.loadError}`:`startup.independent`)}),Fe.loadState===`error`?(0,H.jsx)(`button`,{className:`min-h-11 rounded-md border px-3 py-2 text-sm`,type:`button`,onClick:()=>void t.onRefresh?.(),children:u(`startup.retry`)}):null]})}):Fe&&C===`tasks`?(0,H.jsx)(Ab,{historyEnabled:!a,goal:Fe,items:Re,onDraftTaskFromMessage:a?void 0:e=>{Ae(`创建一个 Task:${xx(e)}`),I(u(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>ye.current?.focus())},onOpenChat:()=>w(`chat`),onQuickComplete:a?void 0:Ze,onSelect:g,quickCompletingTodoIds:R,selectedTodoId:Ge?.kind===`todo`?Ge.item.todoId:null,userTodos:i.userTodos}):Fe&&C===`files`?(0,H.jsx)(Tx,{items:Re.filter(e=>e.kind===`output`),onSelect:g,reportState:i.periodicReports}):!Fe&&!T?(0,H.jsx)(wx,{goals:Me,onRetry:()=>void t.onRefresh?.(),onSelectGoal:tt,systemHealth:i.systemHealth}):Fe?(0,H.jsxs)(H.Fragment,{children:[Fe&&y?.goalId===Fe.goalId?(0,H.jsx)(Dx,{onClose:()=>b(null),onOpenDetails:()=>g({item:y,kind:`run`}),run:y}):null,(0,H.jsx)(Vy,{items:ze,onSelect:g,selectedGoal:Fe})]}):(0,H.jsx)(Vy,{items:He,onSelect:g,selectedGoal:null})]}),(0,H.jsx)(`div`,{className:`personal-composer-wrap`,children:a?(0,H.jsxs)(`div`,{className:`personal-read-only-notice`,children:[(0,H.jsx)(`strong`,{children:u(`source.readOnlyNoticeTitle`)}),(0,H.jsx)(`span`,{children:u(`source.readOnlyNoticeDescription`)})]}):(0,H.jsxs)(H.Fragment,{children:[!Fe&&!T&&D&&Be.length?(0,H.jsx)(Ex,{messages:Be,onClose:()=>O(!1),onOpenConversation:()=>{O(!1),E(!0)}}):null,Fe&&C!==`chat`&&k&&Ve.length?(0,H.jsx)(Ex,{agentLabel:at,messages:Ve,onClose:()=>ee(!1),onDraftTask:C===`tasks`?e=>{Ae(`创建一个 Task:${xx(e)}`),I(u(`feedback.taskDraftCreated`)),window.requestAnimationFrame(()=>ye.current?.focus())}:void 0,onOpenConversation:()=>{ee(!1),w(`chat`)},title:`${Fe.title} · ${at}`}):null,re?(0,H.jsxs)(`div`,{className:`personal-action-feedback`,role:`status`,children:[(0,H.jsx)(`span`,{children:re}),(0,H.jsx)(`button`,{"aria-label":u(`common.closeActionReceipt`),onClick:()=>I(null),type:`button`,children:(0,H.jsx)(eh,{size:14})})]}):null,(0,H.jsx)(`p`,{className:`personal-composer-hint`,children:Fe?st>0?u(`composer.goalRunningHint`,{agent:at,count:st}):u(`composer.goalMessageHint`,{agent:at}):u(`composer.managerMessageHint`)}),Fe?(0,H.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,H.jsxs)(`button`,{"aria-label":u(`composer.nextAction`),className:`is-draft`,onClick:()=>je(u(`composer.nextActionPrompt`)),title:u(`composer.prepareDraft`),type:`button`,children:[(0,H.jsx)(Dm,{size:13}),(0,H.jsx)(`span`,{children:u(`composer.nextAction`)}),(0,H.jsx)(`small`,{className:`personal-prompt-subtle`,children:u(`composer.draft`)})]}),(0,H.jsxs)(`button`,{className:`is-immediate`,disabled:j,onClick:()=>void it(u(`composer.agentProgressPrompt`)),title:u(`composer.immediate`),type:`button`,children:[(0,H.jsx)(Vm,{size:13}),(0,H.jsx)(`span`,{children:u(`composer.agentProgress`)}),(0,H.jsx)(`em`,{className:`personal-prompt-badge`,children:u(`composer.immediate`)})]}),(0,H.jsxs)(`button`,{"aria-label":u(`composer.monitor`),className:`is-draft`,onClick:()=>Ye(`monitor`,B),title:u(`composer.monitorHint`),type:`button`,children:[(0,H.jsx)(em,{size:13}),(0,H.jsx)(`span`,{children:u(`composer.monitor`)}),(0,H.jsx)(`small`,{className:`personal-prompt-subtle`,children:u(`composer.draft`)})]})]}):(0,H.jsxs)(`div`,{className:`personal-quick-prompts`,children:[(0,H.jsxs)(`button`,{"aria-label":u(`composer.globalTasks`),className:`is-draft`,onClick:()=>je(u(`composer.globalTasksPrompt`)),title:u(`composer.prepareDraft`),type:`button`,children:[(0,H.jsx)(Dm,{size:13}),(0,H.jsx)(`span`,{children:u(`composer.globalTasks`)}),(0,H.jsx)(`small`,{className:`personal-prompt-subtle`,children:u(`composer.draft`)})]}),(0,H.jsxs)(`button`,{className:`is-immediate`,disabled:j,onClick:()=>void it(u(`composer.globalProgressPrompt`)),title:u(`composer.immediate`),type:`button`,children:[(0,H.jsx)(Vm,{size:13}),(0,H.jsx)(`span`,{children:u(`composer.globalProgress`)}),(0,H.jsx)(`em`,{className:`personal-prompt-badge`,children:u(`composer.immediate`)})]}),(0,H.jsxs)(`button`,{"aria-label":u(`composer.createGoal`),className:`is-draft`,onClick:qe,title:u(`composer.createGoalHint`),type:`button`,children:[(0,H.jsx)(Fm,{size:13}),(0,H.jsx)(`span`,{children:u(`composer.createGoal`)}),(0,H.jsx)(`small`,{className:`personal-prompt-subtle`,children:u(`composer.draft`)})]})]}),ot?(0,H.jsxs)(`div`,{className:`personal-goal-draft-status`,role:`status`,children:[(0,H.jsx)(`strong`,{children:u(`composer.createGoalDraft`)}),(0,H.jsx)(`span`,{children:u(`composer.createGoalDraftDescription`)})]}):null,N.length?(0,H.jsx)(`div`,{className:`personal-composer-images`,"aria-label":u(`composer.imagesPending`),children:N.map(e=>(0,H.jsxs)(`figure`,{children:[(0,H.jsx)(`img`,{alt:e.name,src:e.dataUrl}),(0,H.jsx)(`button`,{"aria-label":u(`composer.sentImageAlt`,{name:e.name}),onClick:()=>P(t=>t.filter(t=>t.id!==e.id)),type:`button`,children:(0,H.jsx)(eh,{size:13})})]},e.id))}):null,F?(0,H.jsx)(`p`,{className:`personal-composer-error`,role:`alert`,children:F}):null,(0,H.jsxs)(`div`,{className:`personal-channel-composer`,onDragOver:e=>{[...e.dataTransfer.items].some(e=>e.kind===`file`&&e.type.startsWith(`image/`))&&e.preventDefault()},onDrop:e=>{let t=[...e.dataTransfer.files].filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),ct(t))},children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(Qp,{size:17}),e.find(e=>e.agentId===Ee)?.label??Ee]}),(0,H.jsx)(`button`,{"aria-label":u(`composer.addImage`),className:`personal-composer-attach`,disabled:j||N.length>=Kx,onClick:()=>xe.current?.click(),title:u(`composer.attachImageHint`),type:`button`,children:(0,H.jsx)(Mm,{size:17})}),(0,H.jsx)(`input`,{accept:`image/png,image/jpeg,image/webp,image/gif`,"aria-label":u(`composer.imagePicker`),className:`personal-composer-file-input`,disabled:j||N.length>=Kx,multiple:!0,onChange:e=>void ct(e.target.files),ref:xe,type:`file`}),(0,H.jsx)(`textarea`,{"aria-label":u(`composer.sendMessage`),onChange:e=>Ae(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),it())},onPaste:lt,placeholder:Fe?u(`composer.goalPlaceholder`,{goal:Fe.title}):u(`composer.managerPlaceholder`),ref:ye,rows:1,value:Oe}),(0,H.jsx)(`button`,{"aria-label":u(ot?`composer.createGoal`:`composer.send`),disabled:!Oe.trim()&&N.length===0||j,onClick:()=>void it(),title:u(ot?`composer.createGoalHint`:`composer.sendMessageHint`),type:`button`,children:(0,H.jsx)(Vm,{size:18})})]})]})})]}),sidebar:(0,H.jsx)(Eb,{attentionCount:Ne,goals:Me,goalArchiveLoadState:n,goalLifecycleOperations:t.onExecuteGoalLifecycle?[`stop`,`resume`]:void 0,lifecycleBusyGoalIds:L,onRequestGoalCreate:a?void 0:qe,onRequestGoalLifecycle:a&&!t.onExecuteGoalLifecycle?void 0:(e,t)=>void Je(e,t),onRetryGoalArchive:t.onRetryGoalArchive||t.onRefresh?()=>void(t.onRetryGoalArchive??t.onRefresh)?.():void 0,onOpenSettings:a?void 0:()=>g({kind:`settings`}),onSelectGoal:tt,selectedGoalId:B,statusSourceControl:c},c?.activeSource.statusUrl??`/status.json`)})}function Yx(e){return(e??``).replace(/\s+/gu,` `).trim()}function Xx(e,t=120){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``)}…`}function Zx(e,t,n){let r=Yx(e);return!r||r===`暂无`?n?t(n):``:/refresh-state|latest_run|latest run-derived/iu.test(r)?t(`projection.refreshState`):/first read-only adapter tick|read-only adapter/iu.test(r)?t(`projection.firstReadOnlyAdapterCheck`):/todo update recorded for/iu.test(r)?t(`projection.todoStatusUpdated`):/^(loopx|python3|npm|git|run)\s|\s--[a-z0-9-]+|\b[a-z]+_[a-z_]+\b/iu.test(r)?t(n??`projection.agentPreparingNextStep`):Xx(r)}function Qx(e,t){return t({advancing:`projection.agentAdvancingGoal`,idle:`projection.agentIdle`,needs_you:`projection.agentNeedsDecision`,stopped:`projection.agentStopped`,waiting_external:`projection.agentWaitingExternal`}[e])}function $x({eventCount:e,hasArtifact:t,hasLatestValidation:n},r){return{label:r(n?`projection.latestValidation`:`projection.latestRun`),metadata:e>0?r(`projection.events24h`,{count:e}):r(t?`projection.runEvidenceAvailable`:`projection.publicSafeProjection`)}}var eS=`/status.json`,tS=`loopx-status-source-catalog-v1`,nS={id:`local`,kind:`local`,label:`本机`,readOnly:!1,statusUrl:eS};function rS(e,t){let n=ah(e,t).source;if(!n||!n.isLoopback||n.isRelative)return{error:`SSH 隧道来源必须使用显式的 localhost、127.0.0.1 或 ::1 URL。`};let r=new URL(n.url,t);return[`http:`,`https:`].includes(r.protocol)?{url:r.toString()}:{error:`状态来源只支持 HTTP 或 HTTPS。`}}function iS(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return`ssh-${(t>>>0).toString(36)}`}function aS(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.kind!==`ssh_tunnel`||typeof n.label!=`string`||typeof n.statusUrl!=`string`)return null;let r=n.label.trim(),i=rS(n.statusUrl,t);if(!r||r.length>48||!(`url`in i))return null;let a=gb(n.hostAlias)?n.hostAlias.trim():void 0;return{...a?{hostAlias:a}:{},id:iS(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url}}function oS(){return{schemaVersion:1,sources:[nS]}}function sS(e,t){try{let n=e.getItem(tS);if(!n)return oS();let r=JSON.parse(n);if(r.schemaVersion!==1||!Array.isArray(r.sources))return oS();let i=new Set([nS.statusUrl]);return{schemaVersion:1,sources:[nS,...r.sources.flatMap(e=>{let n=aS(e,t);return!n||i.has(n.statusUrl)?[]:(i.add(n.statusUrl),[n])})]}}catch{return oS()}}function cS(e,t){e.setItem(tS,JSON.stringify({schemaVersion:1,sources:t.sources.filter(e=>e.kind===`ssh_tunnel`)}))}function lS(e,t){let n=new Set(t.filter(gb).map(e=>e.trim())),r=!1,i=e.sources.map(e=>e.kind!==`ssh_tunnel`||e.hostAlias||!n.has(e.label)?e:(r=!0,{...e,hostAlias:e.label}));return r?{...e,sources:i}:e}function uS(e,t,n){let r=t.label.trim();if(!r)return{error:`请填写来源名称。`};if(r.length>48)return{error:`来源名称不能超过 48 个字符。`};let i=rS(t.statusUrl,n);if(!(`url`in i))return i;if(e.sources.some(e=>e.statusUrl===i.url))return{error:`这个状态 URL 已经在来源目录中。`};if(t.hostAlias!==void 0&&!gb(t.hostAlias))return{error:`请选择有效的 SSH Host。`};let a=t.hostAlias?.trim(),o={...a?{hostAlias:a}:{},id:iS(i.url),kind:`ssh_tunnel`,label:r,readOnly:!0,statusUrl:i.url};return{catalog:{...e,sources:[...e.sources,o]},source:o}}function dS(e,t){return{...e,sources:e.sources.filter(e=>e.kind===`local`||e.id!==t)}}function fS(e,t,n){if(!t.trim()||ah(t,n).source?.isRelative)return nS;let r=t.trim();try{r=new URL(r,n).toString()}catch{return null}return e.sources.find(e=>e.statusUrl===r)??null}function pS(e,t,n){return fS(e,t,n)||(ah(t,n).source?.isRelative?nS:{id:`temporary`,kind:`ssh_tunnel`,label:`临时来源`,readOnly:!0,statusUrl:t.trim()})}function mS(e,t,n,r){return pS(e,t??n,r)}var hS={delete:`删除`,deploy:`部署`,merge:`合并`,payment:`付款`,release:`发布`};function gS(e,t,n){let r=t.replace(/\s+/gu,` `).trim().toLowerCase(),i=n.target.replace(/\s+/gu,` `).trim().toLowerCase();return!i||!r.includes(i)?null:{actionKind:`goal.update`,context:{goal_id:e,kind:`goal`,natural_language:t,semantic_proposal:{operation:n.operation,target:n.target}},idempotencyKey:`workspace-semantic-protected-${e}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e,status:`operator_gate_requested`},summary:`请求受保护操作:${hS[n.operation]} · ${n.target}`}}var _S=eS;async function vS(e){let t=await fetch(e,{cache:`no-store`,signal:AbortSignal.timeout(3e4)});if(!t.ok)throw Error(`HTTP ${t.status} while loading ${e}`);return Ep(await t.json())}function yS(e,t){if(t?.controller_readiness?.decision_advisor_ready||t?.controller_readiness?.write_controller_ready)return`controller_ready`;if(t?.controller_readiness)return`controller_gated`;if(t?.human_reward)return`reward_judged`;if(t?.operator_gate?.decision===`approve`)return`operator_approved`;if(t?.operator_gate)return`operator_gated`;let n=e||t?.classification||``;return n===`connected_without_run`?`connected`:n===`read_only_project_map`||t?.project_map?`mapped`:n===`state_refreshed`?`refreshed`:n&&n!==`no_status`?`adapter_inspected`:`registered`}function bS(e,t){let n=new Map(t.map(e=>[e.goal_id,e])),r=new Set,i=e.map(e=>{r.add(e.id);let t=n.get(e.id),i=e.latest_runs[0],a=t?.lifecycle_phase??e.lifecycle_phase??i?.lifecycle_phase??yS(t?.status??i?.classification??e.status,i),o=t?.lifecycle_flags?.length?t.lifecycle_flags:e.lifecycle_flags?.length?e.lifecycle_flags:i?.lifecycle_flags?.length?i.lifecycle_flags:[a];return{goal:e,queueItem:t,latestRun:i,status:t?.status??i?.classification??e.status??`no_status`,waitingOn:t?.waiting_on??`clear`,severity:t?.severity??`clear`,lifecyclePhase:a,lifecycleFlags:o}});for(let e of t)r.has(e.goal_id)||i.push({goal:{activation_state:e.activation_state,id:e.goal_id,status:e.status,display_name:e.goal_id,latest_runs:[],lifecycle_flags:[e.lifecycle_phase??`registered`],registry_member:!0,legacy_runtime_goal:!1,index_exists:!1,raw_index_records:0,unique_runs:0},queueItem:e,status:e.status,waitingOn:e.waiting_on,severity:e.severity,lifecyclePhase:e.lifecycle_phase??`registered`,lifecycleFlags:e.lifecycle_flags??[`registered`]});return i}function xS(e){return(e??``).replace(/\s+/g,` `).trim()}function SS(e,t=132){let n=xS(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function CS(e){let t=new Map;for(let n of e?.goals??[])t.set(n.goal_id,n);return t}function wS(e,t){return e===void 0||t===void 0?void 0:e+t}function TS(e,t){if(!e)return null;let n=t===`user`?e.queueItem?.project_asset?.user_todos:e.queueItem?.project_asset?.agent_todos;if(n?.items?.length)return{done_count:n.done??n.items.filter(e=>e.done).length,items:n.items,open_count:n.open??n.items.filter(e=>!e.done).length,total_count:n.total??n.items.length};let r=t===`user`?e.queueItem?.user_todos:e.queueItem?.agent_todos;return r?.items?.length?r:null}function ES(e){return e?.items.find(e=>!e.done)}function DS(e,t,n=`todos`){return e?.items?.length?{advancement_done_count:e.advancement_done_count??t?.advancement_done_count,done_count:e.done??e.items.filter(e=>e.done).length,items:e.items,open_count:e.open??e.items.filter(e=>!e.done).length,total_count:e.total??e.items.length}:t??null}function OS(e){return e?.queueItem?.project_asset?.quota?.state??e?.queueItem?.quota?.state??e?.goal.quota?.state??`waiting`}function kS(e,t,n){let r=[];for(let t of e){let e=TS(t,`agent`);for(let n of e?.items??[])r.push({goalId:t.goal.id,role:`agent`,todo:n})}let i=new Map;for(let e of r){let t=e.todo.claimed_by||`codex`,n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Map((n?.agents??[]).map(e=>[e.agent_id,e]));return Array.from(new Set([...i.keys(),...a.keys()])).map(e=>{let t=i.get(e)??[],n=a.get(e),r=Array.from(new Set([...t.map(e=>e.goalId),n?.current_todo?.goal_id,...n?.goal_ids??[]].filter(Boolean))),o=(t.filter(e=>!e.todo.done)[0]??t[0])?.goalId??n?.current_todo?.goal_id??r[0]??``,s=n?.last_activity_at??null;return{agentId:e,claimedTodos:t,currentTodo:n?.current_todo??null,evidenceRefs:[],goalIds:r,handoffNote:null,lastActivity:s,nextSafeAction:n?.next_action?.trim()||`Inspect status projection before taking work`,primaryGoalId:o,quotaHints:[],staleClaimHint:null,status:{label:`可用`,summary:`正常运行`,variant:`success`},workspaceRef:null}})}function AS(e){return e?.map(e=>({dataUrl:e.data_url,id:e.id,mimeType:e.mime_type,name:e.name,size:e.size}))}var jS=`loopx.personal-agent-selection.v1`;function MS(){if(typeof window>`u`)return{};try{let e=JSON.parse(window.localStorage.getItem(jS)??`{}`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`))}catch{return{}}}var NS={需修复:`danger`,等你:`warning`,等待条件:`info`,推进中:`success`,安静运行:`neutral`,已停止:`neutral`,已完成:`neutral`};function PS(e,t){return xS(t)||e.replace(/^loopx[-_]/i,`LoopX `).split(/[-_]+/).filter(Boolean).map((e,t)=>t===0?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:e).join(` `)}function FS(e){return e.split(/\r?\n/u).filter(e=>!/^\s*GOAL_(STATUS|PROGRESS)\s*:/u.test(e)).map(e=>/^\s*GOAL_EVIDENCE\s*:/u.test(e)?e.replace(/^\s*GOAL_EVIDENCE\s*:/u,`验证依据:`):/^\s*NEXT_ACTION\s*:/u.test(e)?e.replace(/^\s*NEXT_ACTION\s*:/u,`下一步:`):e).join(`
-`).trim()}function IS(e,t){return[`agent`,`assistant`].includes(e.trim().toLowerCase())&&t.trim().length>0}var LS=`已发现的项目 Agent`;function RS(e){switch(ly(e)){case`codex`:return`Codex`;case`claude`:return`Claude Code`;case`kiro`:return`Kiro CLI`;case`trae`:return`Trae CLI Agent`;case`coco`:return`Coco Agent`;default:return PS(e)}}function zS(e,t){switch(uy(e,t)){case`codex`:return`代码与项目执行`;case`claude`:return`复杂分析与长任务`;case`openai`:case`anthropic`:return`管家问答 · 无工具`;case`kiro`:return`终端编码 · 原生 /goal 循环`;case`trae`:return`前端与交互实现`;case`coco`:return`通用任务`;default:return LS}}function BS(e,t){let n=e.project_asset;return t===`user`?DS(n?.user_todos,e.user_todos,`project_asset.user_todos`):DS(n?.agent_todos,e.agent_todos,`project_asset.agent_todos`)}function VS(e){return SS(e.title??e.text,112)}function HS(e){let t=e.resume_condition?.resume_receipt;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.receipt_id;return typeof n==`string`&&n.trim()?n.trim():null}function US(e,t){return{resumeWhen:e.resume_when??null,resumeReady:e.resume_ready??null,resumeReceiptId:HS(e),claimedBy:e.claimed_by??null,done:e.status!==`deferred`&&e.done,evidence:e.evidence?SS(e.evidence,96):null,index:e.index,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,taskDomain:e.task_domain??null,text:VS(e),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.index}`}}function WS(e){let t=e.queueItem?.agent_todos,n=t?.items??e.queueItem?.project_asset?.agent_todos?.items??[],r=new Map(n.map(t=>[t.todo_id?.trim()||`${e.goal.id}:agent:${t.index}`,t]));for(let n of t?.deferred_items??[]){let t=n.todo_id?.trim()||`${e.goal.id}:agent:${n.index}`;r.has(t)||r.set(t,n)}return[...r.values()]}function GS(e){return WS(e).map(t=>US(t,e))}function KS(e,t,n){let r=new Map;for(let n of e.todo_index?.items??[]){if(n.goal_id!==t.goal.id||n.role!==`agent`)continue;let e=US(n,t);r.set(e.todoId,e)}for(let e of n)r.has(e.todoId)||r.set(e.todoId,e);let i=new Map;for(let e of r.values()){if(e.done||e.taskClass!==`advancement_task`)continue;let t=e.taskDomain?.trim();t&&i.set(t,(i.get(t)??0)+1)}return[...i].map(([e,t])=>({domain:e,matchingTodoCount:t}))}function qS(e,t){return{claimedBy:e.claimed_by??null,done:e.status===`done`||e.status===`completed`,index:-1,priority:e.priority??null,status:e.status??null,taskClass:e.task_class??null,text:SS(e.title,112),todoId:e.todo_id?.trim()||`${t.goal.id}:agent:${e.claimed_by??`unknown`}:current`}}function JS(e,t,n){let r=new Map(e.map(e=>[e.todoId,e]));for(let e of t){let t=e.currentTodo;if(!t||t.goal_id!==n.goal.id)continue;let i=qS(t,n);r.has(i.todoId)||r.set(i.todoId,i)}return[...r.values()]}function YS(e){let t=e.queueItem?.project_asset?.agent_todos,n=e.queueItem?.agent_todos,r=WS(e),i=t?.advancement_done_count??n?.advancement_done_count??t?.done??n?.done_count??null,a=r.filter(e=>e.done&&e.status!==`deferred`).length,o=Math.max(i??0,a),s=new Set(r.map(e=>e.todo_id?.trim()).filter(e=>!!e)),c=(t?.recent_completed_advancement_items??[]).filter(e=>!e.todo_id?.trim()||!s.has(e.todo_id.trim())).map(t=>US(t,e)),l=r.find(e=>!e.done);return{doneTodoCount:o,nextTodoText:xS(t?.next??``)||(l?xS(l.title??``)||xS(l.text??``):``)||null,recentCompleted:c}}function XS(e,t){let n=xS(e);return n?/\b(state_file|registry_goal|authority_sources|source_registry)\b|\b[a-z_]+\s+\d+\/\d+/i.test(n)?t(`projection.goalVerified`):Zx(n,t,`projection.validationRecorded`):``}function ZS(e,t=4){if(e.length<=t)return e;let n=e.findIndex(e=>!e.done);if(n<0)return e.slice(-t);let r=Math.max(0,Math.min(n-2,e.length-t));return e.slice(r,r+t)}function QS(e,t,n){let r=t.queueItem?.project_asset?.latest_validation,i=t.latestRun,a=e.event_ledger_summary?.goals.find(e=>e.goal_id===t.goal.id);if(!r&&!i&&!a)return null;let o=[XS(r?.summary,n),Zx(i?.health_check,n),Zx(i?.recommended_action,n)].find(e=>e!==``&&e!==`暂无`)??n(`projection.runRecorded`),s=$x({eventCount:a?.events_24h??0,hasArtifact:!!(i?.json_exists||i?.markdown_exists),hasLatestValidation:!!r},n);return{generatedAt:r?.generated_at??i?.generated_at??a?.latest_event_at??``,label:s.label,metadata:s.metadata,runId:i?`${t.goal.id}:${i.generated_at}`:null,safePreview:[o,s.metadata].filter(Boolean).join(`
-`),summary:o,todoId:t.queueItem?.project_asset?.agent_todos?.items.find(e=>!e.done)?.todo_id??null}}function $S(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(done|complete|completed|finished|terminal|closed|success)([_\s-]|$)/i.test(e??``))}function eC(e,t){return e.global_registry?.findings?.find(e=>e.severity===`high`&&(e.goal_id===t.goal.id||e.goal_ids.includes(t.goal.id)))}function tC(e){return[e.status,e.goal.status,e.latestRun?.classification,e.lifecyclePhase].filter(Boolean).some(e=>/(^|[_\s-])(failure|failed|error|broken|unhealthy|blocked[_\s-]?health|health[_\s-]?blocked)([_\s-]|$)/i.test(e??``))}function nC(e,t){let n=t.queueItem?.stale_latest_run_warning;return t.severity===`high`||!!eC(e,t)||!!(n?.requires_refresh_state||n?.severity===`high`)||tC(t)}function rC(e,t){let n=eC(e,t);return t.queueItem?.stale_latest_run_warning?.recommended_action??t.queueItem?.stale_latest_run_warning?.reason??n?.recommended_action??n?.message??t.queueItem?.recommended_action??t.latestRun?.recommended_action??null}function iC(e){let t=e.latestRun?.operator_gate,n=t?.decision?.trim().toLowerCase()??``,r=new Set([`approve`,`approved`,`reject`,`rejected`,`defer`,`deferred`,`cancel`,`cancelled`]),i=[e.queueItem?.recommended_action,e.latestRun?.recommended_action].filter(Boolean).join(` `),a=/(?:等待|需要)(?:用户|你|owner).{0,24}(?:批准|确认|授权|补充|选择|决定)|(?:批准|确认|授权).{0,16}(?:后|才能|方可)/i.test(i);return!!(t&&!r.has(n))||e.lifecyclePhase===`operator_gated`&&!r.has(n)||a}function aC(e,t){let n=e.latestRun?.operator_gate;return Zx(n?.operator_question??n?.reason_summary??n?.follow_up??e.queueItem?.recommended_action??e.latestRun?.recommended_action,t,`projection.confirmAgentDecision`)}function oC(e,t){if(t.goal.activation_state===`stopped`)return`已停止`;let n=TS(t,`user`),r=TS(t,`agent`),i=!!ES(n),a=!!ES(r);return[`user_or_controller`,`controller`].includes(t.waitingOn)||i||iC(t)?`等你`:nC(e,t)?`需修复`:t.waitingOn===`external_evidence`?`等待条件`:OS(t)===`eligible`||a?`推进中`:$S(t)?`已完成`:`安静运行`}function sC(e,t,n,r){if(n===`已停止`)return Qx(`stopped`,r);if(n===`需修复`)return Zx(rC(e,t),r,`projection.statusRefreshNeeded`);if(n===`等你`)return Qx(`needs_you`,r);if(n===`推进中`){let e=[(TS(t,`agent`)?.items??[]).filter(e=>!e.done).flatMap(e=>[e.title,e.text]).map(e=>xS(e)).find(e=>e!==``&&e!==`暂无`),t.queueItem?.recommended_action,t.latestRun?.recommended_action].map(e=>xS(e)).find(e=>e!==``&&e!==`暂无`);return e?Zx(e,r,`projection.agentAdvancingGoal`):Qx(`advancing`,r)}return Qx(n===`等待条件`?`waiting_external`:`idle`,r)}function cC(e,t){return t.some(t=>e.includes(t))}function lC(e,t,n){if(t.goals.some(e=>e.activationState===`active`&&e.loadState))return{text:`Goal 状态尚未全部加载,暂不能给出完整统计。可先打开已加载的 Goal,失败项可重试。`,lines:[]};if(cC(n,[`Agent`,`agent`,`推进`,`在做`])){let e=t.goals.filter(e=>![`安静运行`,`已完成`,`已停止`].includes(e.state)),n=(e.length>0?e:t.goals).slice(0,3);return n.length===0?{text:`当前状态里还没有 Goal 可供汇总。`,lines:[]}:{text:e.length>0?`Agent 当前关注这些 Goal:`:`当前 Goal 都比较安静:`,lines:n.map(e=>`${e.title} · ${e.state} · ${e.agentSentence}`)}}if(cC(n,[`现在`,`下一步`,`我该`,`该做什么`,`优先处理`])){let e=t.userTodos[0];if(e)return{text:e.blocking?`先处理「${PS(e.goalId)}」:${e.text}`:`当前最先处理「${PS(e.goalId)}」:${e.text}`,lines:[]};let n=t.goals.find(e=>e.state===`需修复`);if(n)return{text:`没有待办,但这个 Goal 需要先修复。`,lines:[`${n.title} · ${n.agentSentence}`]};let r=t.goals.find(e=>e.state===`推进中`);return r?{text:`目前不需要你介入,Agent 正在推进。`,lines:[`${r.title} · ${r.agentSentence}`]}:{text:`当前系统很安静,没有需要你立即处理的事项。`,lines:[]}}if(cC(n,[`等我`,`阻塞`,`需要我`,`全局待办`]))return t.userTodos.length===0?{text:`目前没有 Goal 在等你,开放用户待办为 0。`,lines:[]}:{text:`有 ${t.userTodos.length} 项开放用户待办,阻塞项优先:`,lines:t.userTodos.slice(0,3).map(e=>`${PS(e.goalId)} · ${e.blocking?`阻塞`:`待处理`} · ${e.text}`)};if(cC(n,[`状态`,`异常`,`修复`,`健康`])){let n=t.systemHealth?!t.systemHealth.ok:!e.ok||!e.contract?.ok||!e.global_registry?.ok||(e.global_registry?.summary?.high??0)>0,r=t.goals.filter(e=>e.state===`需修复`),i=r.slice(0,n?2:3).map(e=>`${e.title} · ${e.agentSentence}`);return n&&i.push(`全局状态、契约或注册表健康检查未通过,请进入管理页检查。`),i.length===0?{text:`当前没有发现 Goal 级或全局健康异常。`,lines:[]}:{text:r.length>0?`当前需要关注这些健康问题:`:`Goal 状态正常,但全局健康需要检查:`,lines:i}}return{text:`当前管家支持三类问题:下一步、等待你的事项、Agent 与健康状态。`,lines:[`问“我现在该做什么?”`,`问“哪些 Goal 在等我?”`,`问“Agent 在做什么?”或当前健康状态`]}}function uC(e,t,n,r=!1){let i=new Map(t.map(e=>[e.goal.id,e])),a=new Set(e.run_history.goals.filter(e=>e.activation_state===`stopped`).map(e=>e.id)),o=CS(e.usage_summary),s=kS(t,e.todo_index,e.agent_management_projection),c=e.attention_queue.items.flatMap((e,t)=>{if(a.has(e.goal_id))return[];let n=[`user_or_controller`,`controller`].includes(e.waiting_on);return(BS(e,`user`)?.items??[]).map((r,i)=>({projectedDone:r.done,details:Ud(r),actionKind:r.action_kind??null,blocking:n,goalId:e.goal_id,sourceOrder:t,taskClass:r.task_class??null,text:VS(r),todoId:r.todo_id?.trim()||`${e.goal_id}:user:${r.index}`,todoOrder:i,updatedAt:r.updated_at??null}))}),l=c.filter(e=>!e.projectedDone),u=new Set(l.map(e=>e.goalId)),d=t.flatMap((t,r)=>a.has(t.goal.id)||u.has(t.goal.id)||!iC(t)?[]:[{details:Ud({task_class:`user_gate`,status:`open`,note:t.latestRun?.operator_gate?.reason_summary}),actionKind:`gate.resolve`,blocking:!0,goalId:t.goal.id,sourceOrder:e.attention_queue.items.length+r,taskClass:`user_gate`,text:aC(t,n),todoId:`${t.goal.id}:operator-gate`,todoOrder:0,updatedAt:t.latestRun?.operator_gate?.recorded_at??t.latestRun?.generated_at??null}]),f=[...l,...d].sort((e,t)=>Number(t.blocking)-Number(e.blocking)||e.sourceOrder-t.sourceOrder||e.todoOrder-t.todoOrder),p=e.run_history.goals.flatMap(t=>{if(t.registry_member===!1)return[];let a=i.get(t.id);if(!a)return[];let c=oC(e,a),l=f.find(e=>e.goalId===t.id),u=l?.text??null,d=YS(a),p=t.coordination?.registered_agents??[],m=new Set(p),h=[...s.filter(e=>e.goalIds.includes(t.id)&&!/unassigned|unknown/i.test(e.agentId)&&(m.size===0||m.has(e.agentId))&&(e.currentTodo?.goal_id===t.id||e.claimedTodos.some(e=>e.goalId===t.id)))].sort((e,t)=>(t.lastActivity??``).localeCompare(e.lastActivity??``)),g=new Set(h.map(e=>e.agentId)),_=[...h.map(e=>({agentId:e.agentId,label:e.agentId,lastActivityAt:e.lastActivity,state:e.status.label})),...p.filter(e=>!g.has(e)).map(e=>({agentId:e,label:e,lastActivityAt:null,state:`registered`}))],v=h[0],y=JS(GS(a),h,a),b=[d.nextTodoText,a.queueItem?.recommended_action,a.latestRun?.recommended_action,sC(e,a,c,n)].map(e=>Zx(e,n)).find(e=>e!==``&&e!==`暂无`)??n(`projection.nextUpdatePending`);return[{activationState:t.activation_state,agentId:v?.agentId??p[0]??`codex`,agentLaneCount:_.length,agentLanes:_,agentLabel:v?.agentId,agentSentence:sC(e,a,c,n),agentTodos:[...y,...d.recentCompleted],doneTodoCount:d.doneTodoCount,acceptanceObservation:t.acceptance_observation,goalId:t.id,latestActivity:a.latestRun?.generated_at??``,needsYou:u,needsYouActionKind:l?.actionKind??null,needsYouBlocking:l?.blocking??!1,needsYouTaskClass:l?.taskClass??null,needsYouTodoId:l?.todoId??null,nextSentence:b,runEvidence:QS(e,a,n),state:c,...r?{subagentExecution:{allowedDomains:t.spawn_policy?.allowed_domains??[],domainCandidates:KS(e,a,y),enabled:t.spawn_policy?.mode===`multi_subagent`&&t.spawn_policy.spawn_allowed===!0&&t.spawn_policy.max_children>0,maxChildren:t.spawn_policy?.max_children??0,modelConfig:t.spawn_policy?.model_config}}:{},title:PS(t.id,t.display_name),usage:(()=>{let e=o.get(t.id);return e?{costUsd24h:e.cost_usd_24h,costUsd7d:e.cost_usd_7d,durationMs24h:e.duration_ms_24h,durationMs7d:e.duration_ms_7d,tokens24h:wS(e.input_tokens_24h,e.output_tokens_24h),tokens7d:wS(e.input_tokens_7d,e.output_tokens_7d)}:null})()}]}),m=[];if(e.ok||m.push(`状态载荷未标记为正常 (payload.ok === false)`),e.contract&&!e.contract.ok){let t=e.contract.summary,n=t?`${t.errors} 项错误 / ${t.warnings} 项警告`:e.contract.errors?.[0]||`请检查控制面契约`;m.push(`契约检查未通过: ${n}`)}if(e.global_registry){e.global_registry.ok||m.push(`注册表状态异常: ${e.global_registry.summary.high} 项高危`);for(let t of e.global_registry.findings||[])t.severity===`high`&&m.push(`[${t.kind}] ${t.message}`)}let h=e.decision_freshness_summary?.summary?.stale_count?`${e.decision_freshness_summary.summary.stale_count} 项决策状态已过期`:null,g=m.length===0&&!h,_={ok:g,summary:g?`所有控制面契约与注册表检查均正常`:`发现 ${m.length+ +!!h} 项系统健康关注点`,issues:m,freshnessWarning:h};return{blockingTodoCount:f.filter(e=>e.blocking).length,goalNotifications:(e.goal_channel_notification_projection?.goals??[]).map(e=>({goalId:e.goal_id,configured:e.configured,enabled:e.enabled,humanGateAutoNotifyEnabled:e.human_gate_auto_notify_enabled,lastNotifiedAt:e.last_notified_at??null,receiptCount:e.receipt_count,targetRef:e.target_ref??null})),goals:p,openUserTodoCount:f.length,systemHealth:_,attentionHistory:[...c,...d],userTodos:f,visibleUserTodos:f.slice(0,5),workers:(e.agent_management_projection?.agents??[]).map(e=>({agentId:e.agent_id,currentTodoGoalId:e.current_todo?.goal_id??null,currentTodoText:e.current_todo?.title?SS(e.current_todo.title,96):null,lastActivityAt:e.last_activity_at??null,state:e.state??null}))}}function dC({goalArchiveLoadState:e,isLoading:t,onGoalActivationStateChange:n,onGoalDeleted:r,onSelectGoal:i,onReconcileStatus:a,onRefresh:o,onRetryGoalArchive:s,payload:c,progress:l,rows:u,selectedGoalId:d,statusSourceControl:f,theme:p,toggleTheme:m}){let h=f.activeSource.readOnly,g=f.activeSource.kind===`ssh_tunnel`?f.activeSource.hostAlias:void 0,{t:_}=qi(),[v,y]=(0,V.useState)([]),[b,x]=(0,V.useState)(!1),[S,C]=(0,V.useState)(null),w=(0,V.useMemo)(()=>{let e=uC(c,u,_,b);if(!l)return e;let t=Object.values(l.snapshots).map(e=>uC(e,bS(e.run_history.goals,e.attention_queue.items),_,b)),n=new Map(t.flatMap(e=>e.goals).map(e=>[e.goalId,e])),r=e.goals.map(e=>n.get(e.goalId)??{...e,loadError:l.errors[e.goalId],loadState:l.errors[e.goalId]?`error`:`loading`,agentId:``,agentSentence:``,nextSentence:``,subagentExecution:void 0}),i=t.flatMap(e=>e.userTodos),a=r.some(e=>e.activationState===`active`&&e.loadState),o=[...new Set(t.flatMap(e=>e.systemHealth?.issues??[]))];return{...e,goals:r,userTodos:i,attentionHistory:t.flatMap(e=>e.attentionHistory??e.userTodos),visibleUserTodos:i.slice(0,5),openUserTodoCount:i.length,blockingTodoCount:i.filter(e=>e.blocking).length,workers:[...new Map(t.flatMap(e=>e.workers??[]).map(e=>[e.agentId,e])).values()],goalNotifications:t.flatMap(e=>e.goalNotifications??[]),systemHealth:a||t.length===0?void 0:{ok:t.every(e=>e.systemHealth?.ok),issues:o,summary:o.length?`发现 ${o.length} 项系统健康关注点`:`状态检查已完成`,freshnessWarning:t.map(e=>e.systemHealth?.freshnessWarning).filter(Boolean).join(`;`)||null}}},[c,u,l,b,_]),T=w.goals.find(e=>e.goalId===d)??null,E=l?.snapshots[d]??c,[D,O]=(0,V.useState)(null),[k,ee]=(0,V.useState)(null),[te,A]=(0,V.useState)(!1),j=w.goals.some(e=>e.activationState===`active`&&e.loadState===`loading`)?`loading`:w.goals.map(e=>`${e.goalId}:${e.agentId}`).join(`|`),M=T?.goalId??`manager`;w.goals.some(e=>e.activationState===`active`&&e.loadState)||(w.systemHealth?!w.systemHealth.ok:!c.ok)||w.openUserTodoCount>0&&`${w.openUserTodoCount}${w.blockingTodoCount}`;let N=v.length>0?v.map(e=>({agentId:e.agent_id,adapterKind:e.adapter_kind,available:e.available,capability:zS(e.agent_id,e.adapter_kind),interrupt:e.interrupt,label:e.display_name,location:e.location,resume:e.resume,source:e.source,statusLabel:e.available?`可用`:`需要配置`,streaming:e.streaming,toolCalls:e.tool_calls,trustScope:e.trust_scope})):[{agentId:`codex`,available:!0,capability:zS(`codex`),label:`Codex`,statusLabel:`正在检测`}],P=[...N,{agentId:`status-only`,available:!0,capability:`不调用模型`,adapterKind:`status_projection`,interrupt:!1,label:`仅查状态`,resume:!0,statusLabel:`只读`,streaming:!1,toolCalls:!1,trustScope:`read_only`}],F=N.find(e=>e.label===`Codex`&&e.available)?.agentId??N.find(e=>e.available)?.agentId??`status-only`,[ne,re]=(0,V.useState)(MS),I=dh(P,ne[M]??F,F),[L,ie]=(0,V.useState)(!1),[R,ae]=(0,V.useState)(!1),[oe,se]=(0,V.useState)(`chat`),[ce,le]=(0,V.useState)(``),[ue,z]=(0,V.useState)({}),[de,fe]=(0,V.useState)({}),[pe,me]=(0,V.useState)(null),[he,ge]=(0,V.useState)({}),[_e,ve]=(0,V.useState)([]),[ye,be]=(0,V.useState)(null),[xe,Se]=(0,V.useState)({}),Ce=(0,V.useRef)(1),we=(0,V.useRef)(1),Te=(0,V.useRef)(new Map),B=(0,V.useRef)(new Set),Ee=(0,V.useRef)(new Map),De=(0,V.useRef)(new Map),Oe=(0,V.useRef)(new Set),ke=(0,V.useRef)(new Set),Ae=(0,V.useRef)(null),je=(0,V.useRef)(null),Me=(0,V.useRef)(null),Ne=(0,V.useRef)(null);(0,V.useRef)(null);let Pe=ue[M]??[];de[M];let Fe=T?w.userTodos.filter(e=>e.goalId===T.goalId):w.userTodos,Ie=T?.agentTodos??[];ZS(Ie,T?.needsYou?3:4);let Le=Ie.filter(e=>e.done).length,Re=Ie.length>0?`${Le}/${Ie.length}`:`暂无计划`;T&&({...w},Fe.filter(e=>e.blocking).length,Fe.length),(0,V.useEffect)(()=>{let e=ih(f.activeSource.statusUrl,window.location.href),t=e.source?ch(E,e.source):null;if(!T||!t?.indexUrl||!t.detailUrl){O(null),ee(null),A(!1);return}let{detailUrl:n,indexUrl:r}=t,i=!1;return O(null),ee(null),A(!0),lh(r,T.goalId).then(async e=>{let t=e.items[0]?.detail_ref;return t?uh(n,t):null}).then(e=>{i||O(e)}).catch(e=>{i||ee(Dp(e))}).finally(()=>{i||A(!1)}),()=>{i=!0}},[E,T?.goalId,f.activeSource.statusUrl]);let ze=T?void 0:he[M]?.sessionId;(0,V.useEffect)(()=>{if(h||!ze)return;let e=!1,t,n=async()=>{try{let t=await Vh(ze);if(e)return;let n=t.messages.filter(e=>e.origin===`manager_followup`);z(e=>{let t=e[M]??[],r=new Set(t.map(e=>e.sourceMessageId)),i=n.filter(e=>!r.has(e.message_id)),a=new Map(n.map(e=>[e.message_id,e.return_delivery])),o=!1,s=t.map(e=>{let t=e.sourceMessageId?a.get(e.sourceMessageId):void 0;return JSON.stringify(t)===JSON.stringify(e.returnDelivery)?e:(o=!0,{...e,returnDelivery:t})});return!i.length&&!o?e:{...e,[M]:[...s,...i.map(e=>({id:Ce.current++,sourceMessageId:e.message_id,role:`assistant`,agentLabel:I.label,sourceLabel:`管家交接回执`,text:FS(e.text),lines:[],returnDelivery:e.return_delivery}))]}})}catch{}finally{e||(t=setTimeout(n,3e3))}};return n(),()=>{e=!0,t&&clearTimeout(t)}},[h,ze,M,I.label]);function Be(e,t){ge(n=>{if(t===null){let t={...n};return delete t[e],t}return{...n,[e]:t}})}(0,V.useEffect)(()=>{if(h){y([]),x(!1),C(null);return}let e=!1;return Rh().then(t=>{if(!e){y(t.adapters??[]);let e=t.manager?.runtime;C(e?{schema_version:`manager_runtime_session_readback_v0`,runtime_profile:e.runtime_profile,configuration_revision:e.configuration_revision,status:e.status,sandbox:e.sandbox,standing_grant:e.standing_grant,tool_classes:e.tool_classes}:null),x(t.goal_subagent_configuration===`preview_locked`)}}).catch(()=>{e||x(!1)}),()=>{e=!0}},[h]),(0,V.useEffect)(()=>{try{window.localStorage.setItem(jS,JSON.stringify(ne))}catch{}},[ne]),(0,V.useEffect)(()=>{if(h||!I.available)return;let e=M,t=`${e}:${I.agentId}`,n=T?`goal`:`manager`,r=T?`goal.${T.goalId}`:`manager`,i=!1,a=null,o=null;return(async()=>{try{let s=await Wh({agentId:I.agentId,channelId:r,goalId:T?.goalId});if(i||(z(t=>(t[e]?.length??0)>0?t:{...t,[e]:s.messages.map(e=>({sourceMessageId:e.message_id,agentLabel:e.role===`user`?void 0:I.label,attachments:AS(e.attachments),id:Ce.current++,lines:[],role:e.role===`user`?`user`:`assistant`,returnDelivery:e.return_delivery,sourceLabel:e.role===`user`?void 0:e.role===`error`?`本地会话记录`:`恢复的 ${I.label} 会话`,text:e.role===`user`?e.text:FS(e.text)}))}),I.agentId===`status-only`))return;let c=s.sessions[0];if(o=c?.session_id??null,c&&!c.resumable){B.current.add(t),Be(e,{agentId:I.agentId,resumable:!1,sessionId:c.session_id,status:`resume_failed`});return}let l=n===`manager`?``:T?.goalId??``;if(n===`goal`&&!l)return;let u=await Bh(l,I.agentId,`resume_latest`,n);if(i)return;n===`manager`&&u.session.manager_runtime&&C(u.session.manager_runtime),Te.current.set(t,u.session_id);let d=s.snapshots.find(e=>e.session.session_id===u.session_id),f=d?.session.active_turn_id??``;if(Be(e,{agentId:I.agentId,resumable:!0,sessionId:u.session_id,status:f?`running`:`ready`,turnId:f||void 0}),B.current.delete(t),!f)return;let p=`${u.session_id}:${f}`;if(ke.current.has(p))return;ke.current.add(p),Ee.current.set(e,f),Be(e,{agentId:I.agentId,resumable:!0,sessionId:u.session_id,status:`running`,turnId:f}),me(e),a=new AbortController,De.current.set(e,a);let m=``,h=Ve(e,{activity:[`正在恢复进行中的 Agent 回合`],agentLabel:I.label,lines:[],pending:!0,sourceLabel:`恢复的 ${I.label} 会话`,text:``});try{let t=await Zh(u.session_id,f,{signal:a.signal,onDelta:t=>{m+=t,He(e,h,{text:m})},onActivity:t=>{z(n=>({...n,[e]:(n[e]??[]).map(e=>e.id===h?{...e,activity:[...new Set([...e.activity??[],t])].slice(-6)}:e)}))}});if(i)return;He(e,h,{lines:t.response.gate?[t.response.gate.summary,t.response.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:t.response.message||m.trim()||`${I.label} 已完成分析。`});let n=w.goals.find(e=>e.goalId===d?.session.goal_id)??T??w.goals[0]??null;if(n&&t.response.proposals.length>0){let r=t.response.proposals.map(e=>({goalId:n.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[e]:[...t[e]??[],...r]}))}}catch(t){if(i)return;He(e,h,{activity:[],lines:[],pending:!1,reconnect:t instanceof Eh&&t.payload.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t instanceof Error?t.message:`无法恢复进行中的 Agent 回合。`})}finally{ke.current.delete(p),Ee.current.get(e)===f&&Ee.current.delete(e),Be(e,{agentId:I.agentId,resumable:!0,sessionId:u.session_id,status:`ready`}),De.current.get(e)===a&&De.current.delete(e),i||me(t=>t===e?null:t)}}catch(n){if(i)return;n instanceof Eh&&n.payload.error_code===`resume_failed`&&(B.current.add(t),o&&Be(e,{agentId:I.agentId,resumable:!1,sessionId:o,status:`resume_failed`}))}})(),()=>{i=!0,a?.abort()}},[M,w.goals[0]?.goalId,h,T?.goalId,I.agentId,I.available,I.label]),(0,V.useEffect)(()=>{if(h||T||w.goals.length===0||j===`loading`)return;let e=!1;return Promise.all(w.goals.filter(e=>!e.loadState).map(async e=>{let t=await Hh({agentId:e.agentId,channelId:`goal.${e.goalId}`,goalId:e.goalId});return{goalId:e.goalId,session:t.sessions[0]??null}})).then(t=>{e||ge(e=>{let n={...e};for(let e of t)e.session&&(n[e.goalId]={agentId:e.session.agent_id,resumable:e.session.resumable,sessionId:e.session.session_id,status:e.session.active_turn_id?`running`:e.session.status,turnId:e.session.active_turn_id??void 0});return n})}).catch(()=>{}),()=>{e=!0}},[h,j,T?.goalId]),(0,V.useEffect)(()=>{if(be(null),h){ve([]),Se({});return}if(!T){ve([]),Se({});return}let e=!1,t=0,n=0;ve([]),Se({});let r=async()=>{if(!e){if(document.hidden){t=window.setTimeout(()=>void r(),1e4);return}try{let t=await Hh({goalId:T.goalId});if(!e){let r=t.sessions.filter(e=>e.channel_id?.startsWith(`task.`));ve(r);let i=await Promise.allSettled(r.map(e=>Vh(e.session_id)));if(!e){let e=i.some(e=>e.status===`rejected`);n=e?n+1:0,be(e?`partial`:null),Se(Object.fromEntries(i.flatMap((e,t)=>e.status===`fulfilled`?[[r[t].session_id,e.value]]:[])))}}}catch{n+=1,e||be(`offline`)}e||(t=window.setTimeout(()=>void r(),Math.min(3e4,2e3*2**Math.min(n,4))))}};return r(),()=>{e=!0,window.clearTimeout(t)}},[h,T?.goalId]),(0,V.useEffect)(()=>{if(!L)return;let e=window.requestAnimationFrame(()=>{Ae.current?.querySelector(`[role="menuitem"]:not(:disabled)`)?.focus()});return()=>{window.cancelAnimationFrame(e),je.current?.focus()}},[L]),(0,V.useEffect)(()=>{if(!R)return;let e=window.requestAnimationFrame(()=>Me.current?.focus());return()=>{window.cancelAnimationFrame(e),Ne.current?.focus()}},[R]),(0,V.useEffect)(()=>{if(!L&&!R)return;let e=e=>{e.key===`Escape`&&(ie(!1),ae(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[L,R]);function Ve(e,t){let n=Ce.current++;return z(r=>({...r,[e]:[...r[e]??[],{...t,id:n,role:`assistant`}]})),n}function He(e,t,n){z(r=>({...r,[e]:(r[e]??[]).map(e=>e.id===t?{...e,...n}:e)}))}async function Ue(e,t){let n=e.trim();if(!n)return;let r=t&&`goalId`in t?t.goalId??`manager`:M,i=r===`manager`?null:w.goals.find(e=>e.goalId===r)??null,a=t?.agentId?dh(P,t.agentId,F):I,o=r===`manager`?w:i?{...w,blockingTodoCount:w.userTodos.filter(e=>e.goalId===i.goalId&&e.blocking).length,goals:[i],openUserTodoCount:w.userTodos.filter(e=>e.goalId===i.goalId).length,userTodos:w.userTodos.filter(e=>e.goalId===i.goalId),visibleUserTodos:w.userTodos.filter(e=>e.goalId===i.goalId)}:w,s=Ce.current++;if(z(e=>({...e,[r]:[...e[r]??[],{attachments:t?.attachments,id:s,lines:[],role:`user`,text:n}]})),le(``),me(r),a.agentId===`status-only`||!i&&r!==`manager`){let e=lC(E,o,n),t=a.agentId===`status-only`;Ve(r,{agentLabel:t?`仅查状态`:`LoopX 管家`,lines:e.lines.slice(0,3),sourceLabel:t?`LoopX 状态投影 · 仅查状态`:`LoopX 状态投影`,text:e.text}),zh({answer:[e.text,...e.lines.slice(0,3)].filter(Boolean).join(`
-`),contextKind:r===`manager`?`manager`:`goal`,goalId:r===`manager`?void 0:r,question:n}).catch(()=>{}),me(null);return}let c=`${r}:${a.agentId}`,l=null;try{let e=Te.current.get(c);if(!e){let t=B.current.has(c)?`new`:`resume_latest`,n=await Bh(r===`manager`?``:i.goalId,a.agentId,t,r===`manager`?`manager`:`goal`);r===`manager`&&n.session.manager_runtime&&C(n.session.manager_runtime),e=n.session_id,Te.current.set(c,e),Be(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),B.current.delete(c)}let o=``;l=Ve(r,{activity:[`正在连接 Agent`],agentLabel:a.label,lines:[],pending:!0,sourceLabel:r===`manager`?`${a.label} 管家 · 跨 Goal`:`${a.label} Agent · ${PS(i.goalId)}`,text:``});let s=(await Yh(e,n,{attachments:t?.attachments,signal:(()=>{let e=new AbortController;return De.current.set(r,e),e.signal})(),onDelta:e=>{o+=e,l!==null&&He(r,l,{text:o})},onActivity:e=>{l!==null&&z(t=>({...t,[r]:(t[r]??[]).map(t=>t.id===l?{...t,activity:[...new Set([...t.activity??[],e])].slice(-6)}:t)}))},onPhase:(t,n)=>{Ee.current.set(r,n),Be(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`running`,turnId:n})}})).response;if(He(r,l,{lines:s.gate?[s.gate.summary,s.gate.next_action].filter(Boolean).slice(0,2):[],pending:!1,text:FS(s.message||o.trim())||`${a.label} 已完成分析。`}),s.proposals.length>0&&!i&&He(r,l,{lines:[`请进入要修改的 Goal,预览并确认具体变更。`]}),s.proposals.length>0&&i){let e=s.proposals.map(e=>({goalId:i.goalId,id:we.current++,previewId:null,proposal:e,receiptLabel:null,state:`candidate`,statusMessage:null}));fe(t=>({...t,[r]:[...t[r]??[],...e]}))}if(r!==`manager`&&s.protected_action){let e=gS(r,n,s.protected_action);if(e)return e}}catch(e){if(Oe.current.delete(r)){let e={agentLabel:a.label,lines:[],pending:!1,sourceLabel:`${a.label} 会话`,text:`已中断。你可以在当前会话继续发送消息。`};l===null?Ve(r,e):He(r,l,e);return}let t=e instanceof Eh?e.payload:null;t&&fh(t)&&Te.current.delete(c),t?.error_code===`resume_failed`&&(Te.current.delete(c),B.current.add(c),Be(r,{agentId:a.agentId,resumable:!1,sessionId:he[r]?.sessionId??`resume-failed`,status:`resume_failed`}));let n=t?.gate,i=n&&typeof n==`object`?String(n.summary??``):``,o={agentLabel:a.label,lines:i?[i]:[],pending:!1,reconnect:t?.reconnectable===!0,sourceLabel:`LoopX Chat 本地后端`,text:t?.error_code===`resume_failed`?`原 ${a.label} 会话无法恢复。本地历史已经保留,请在运行详情里选择“重试恢复”或“开始新 Session”。`:e instanceof Error?e.message:`${a.label} 会话暂时不可用。`};l===null?Ve(r,o):He(r,l,o)}finally{Ee.current.delete(r),De.current.delete(r);let e=Te.current.get(c);e&&Be(r,{agentId:a.agentId,resumable:!0,sessionId:e,status:`ready`}),me(e=>e===r?null:e)}}async function We(e){let t=e?.goalId??M,n=he[t],r=e?.agentId??n?.agentId??I.agentId,i=`${t}:${r}`,a=e?.sessionId??n?.sessionId??Te.current.get(i),o=e?.turnId??n?.turnId??Ee.current.get(t);if(!(!a||!o))try{Oe.current.add(t),await Jh(a,o),De.current.get(t)?.abort()}catch(e){throw Oe.current.delete(t),e}finally{Ee.current.delete(t),Be(t,{agentId:r,resumable:!0,sessionId:a,status:`ready`}),De.current.delete(t),me(e=>e===t?null:e)}}async function Ge(e){let t=e.goalId,n=`${t}:${e.agentId}`,r=e.sessionId??he[t]?.sessionId??Te.current.get(n);if(r)try{let i=await $h(r);Te.current.set(n,r),B.current.delete(n),Be(t,{agentId:e.agentId,resumable:i.session.resumable,sessionId:r,status:i.session.status})}catch{Be(t,{agentId:e.agentId,resumable:!1,sessionId:r,status:`resume_failed`})}}function Ke(e){let t=`${e.goalId}:${e.agentId}`;Te.current.delete(t),B.current.add(t),Be(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:`new-session-pending`,status:`ready`})}async function qe(e){let t=`${e.goalId}:${e.agentId}`,n=e.sessionId??he[e.goalId]?.sessionId??Te.current.get(t);n&&n!==`new-session-pending`&&await Qh(n),Te.current.delete(t),B.current.add(t),Be(e.goalId,null)}function Je(e){P.some(t=>t.agentId===e&&t.available)&&(re(t=>({...t,[M]:e})),ie(!1))}function Ye(){i(``),se(`chat`)}function Xe(e){i(e),se(`chat`)}T&&NS[T.state],T&&(`${I.label}${T.state}`,Ie.length>0&&`${Re}`,Fe.length>0&&`${Fe.length}`),T?.state===`需修复`||!T&&!c.ok?(T&&RS(T.agentId),T?.nextSentence,T?.agentSentence):T?.state===`等你`?(T.needsYouBlocking,T.needsYouBlocking,T.needsYou??T.nextSentence,T.needsYou):(T&&RS(T.agentId),T?.nextSentence);let Ze=[...!T&&he.manager?.status===`resume_failed`?[{id:`run:manager:resume-failed`,kind:`run`,run:{agentId:he.manager.agentId,agentLabel:RS(he.manager.agentId),canInterrupt:!1,completedSteps:0,goalId:`manager`,goalTitle:`LoopX 管家`,latestActivity:`本地聊天记录已保留,点我查看恢复方式。`,resumable:!1,runId:`manager:resume-failed`,sessionId:he.manager.sessionId,sessionStatus:`resume_failed`,status:`failed`,title:`上次会话需要恢复`,totalSteps:1,outputs:[]}}]:[],...T?_e.map(e=>{let t=e.channel_id?.startsWith(`task.`)?e.channel_id.slice(5):void 0,n=T.agentTodos.find(e=>e.todoId===t),r=!!e.active_turn_id,i=xe[e.session_id],a=i?.messages.some(e=>IS(e.role,e.text))===!0;return{id:`run:task:${e.session_id}`,kind:`run`,run:{agentId:e.agent_id,agentLabel:RS(e.agent_id),canInterrupt:r,completedSteps:n?.done||a?1:0,goalId:T.goalId,goalTitle:T.title,latestActivity:r?`Agent 正在执行,可进入 Session 查看过程或发送纠偏。`:a?`Agent 已返回结果,点击查看结果与完整运行记录。`:`执行 Session 已保留,可继续纠偏或恢复。`,resumable:e.resumable,runId:e.session_id,sessionId:e.session_id,sessionMessages:i?.messages.map(e=>({createdAt:e.created_at,messageId:e.message_id,role:e.role===`user`?`user`:IS(e.role,e.text)?`assistant`:`error`,text:e.role===`user`?e.text:FS(e.text)})),sessionStatus:a?`completed`:e.status,status:n?.done||a?`completed`:r?`running`:e.status===`resume_failed`?`failed`:`waiting`,title:n?.text??`Agent 执行任务`,todoId:t,totalSteps:1,turnId:e.active_turn_id??void 0}}}):[],...T?[{id:`run:${T.goalId}`,kind:`run`,run:{agentId:he[T.goalId]?.agentId??T.agentId,agentLabel:RS(he[T.goalId]?.agentId??T.agentId),canInterrupt:!!he[T.goalId]?.turnId,completedSteps:T.agentTodos.filter(e=>e.done).length,goalId:T.goalId,goalTitle:T.title,latestActivity:T.agentSentence,resumable:he[T.goalId]?.resumable??!0,runId:`goal:${T.goalId}`,sessionId:he[T.goalId]?.sessionId,sessionStatus:he[T.goalId]?.status,status:he[T.goalId]?.turnId?`running`:T.state===`需修复`?`failed`:`waiting`,title:T.nextSentence,totalSteps:T.agentTodos.length||1,turnId:he[T.goalId]?.turnId,outputs:T.runEvidence?[{createdAt:T.runEvidence.generatedAt,kind:`evidence`,outputId:`${T.goalId}:latest-evidence`,title:T.runEvidence.label}]:[]}}]:[],...Pe.map(e=>({id:`message:${e.id}`,kind:`message`,message:{agentLabel:e.agentLabel,attachments:e.attachments,id:String(e.id),pending:e.pending,returnDelivery:e.returnDelivery,role:e.role,text:e.text||(e.pending?`Agent 正在处理…`:e.lines.join(`
-`))}})),...(T?[T]:w.goals).flatMap(e=>e.runEvidence?[{id:`output:${e.goalId}:${e.runEvidence.generatedAt||`latest`}`,kind:`output`,output:{agentLabel:RS(e.agentId),createdAt:e.runEvidence.generatedAt,goalId:e.goalId,goalTitle:e.title,kind:`evidence`,outputId:`${e.goalId}:latest-evidence`,runId:e.runEvidence.runId??void 0,safePreview:e.runEvidence.safePreview,summary:e.runEvidence.summary,title:e.runEvidence.label,todoId:e.runEvidence.todoId??void 0}}]:[]),...T&&D?[{id:`output:${T.goalId}:report:${D.publication.publication_id}`,kind:`output`,output:{agentId:D.agent_id,agentLabel:RS(D.agent_id),createdAt:D.publication.delivered_at,goalId:T.goalId,goalTitle:T.title,kind:`report`,outputId:D.publication.publication_id,report:{addedCount:D.delta.added_count,changedCount:D.delta.changed_count,deliveredAt:D.publication.delivered_at,generationId:D.generation_id,items:D.delta.items.map(e=>({changeKind:e.change_kind,previousStatus:e.previous_status,sourceRef:e.source_ref,status:e.status,summary:e.summary,title:e.title})),periodEndAt:D.period_window.end_at,periodStartAt:D.period_window.start_at,predecessorPublicationId:D.publication.predecessor_publication_id,publicationId:D.publication.publication_id},safePreview:D.delta.items.map(e=>`${e.change_kind===`added`?`+`:`~`} ${e.title}\n${e.summary}`).join(`
-
-`),summary:D.summary,title:D.title}}]:[]],Qe=f.connectionState===`connected`,$e=new Map(w.goals.map(e=>[e.goalId,e.title])),et=e=>Wd(e,f.activeSource.statusUrl,Qe&&!l?.errors[e.goalId],$e.get(e.goalId)),tt={...vy(w),userTodos:w.userTodos.map(et),attentionHistory:(w.attentionHistory??w.userTodos).map(et),periodicReports:{error:k,loading:te},timeline:Ze};return(0,H.jsxs)(`div`,{className:p===`dark`?`dark`:``,"data-testid":`personal-goal-home`,children:[ye?(0,H.jsx)(`p`,{role:`status`,className:`m-0 bg-amber-50 px-4 py-2 text-sm text-amber-900`,children:_(ye===`partial`?`runs.discoveryPartial`:`runs.discoveryOffline`)}):null,(0,H.jsx)(Jx,{agents:P.map(e=>({adapterKind:e.adapterKind,agentId:e.agentId,available:e.available,capability:e.capability,interrupt:e.interrupt,label:e.label,location:e.location,resume:e.resume,source:e.source,streaming:e.streaming,toolCalls:e.toolCalls,trustScope:e.trustScope,workspaceCompatibility:e.available?`当前 Goal 写入前验证`:`不可用,需先修复 Endpoint`})),callbacks:{onApplyAttention:e=>Xe(e.goalId),onCorrectRun:async(e,t)=>{if(!e.sessionId)throw Error(`这个 Run 还没有可纠偏的执行 Session。`);let n=await Ph((await jh({actionKind:`run.correct`,context:{kind:`run`,goal_id:e.goalId,todo_id:e.todoId},idempotencyKey:`workspace-run-correct-${e.sessionId}-${Date.now().toString(36)}`,normalizedParameters:{goal_id:e.goalId,message:t,session_id:e.sessionId},summary:`纠偏执行任务:${e.title}`})).proposal_id),r=typeof n.turn?.turn_id==`string`?n.turn.turn_id:void 0;if(Be(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:r?`running`:`ready`,turnId:r}),r){Ee.current.set(e.goalId,r);let t=new AbortController;De.current.set(e.goalId,t);let n=``,i=Ve(e.goalId,{activity:[`正在把纠偏送入原执行 Session`],agentLabel:e.agentLabel,lines:[],pending:!0,sourceLabel:`${e.agentLabel} · 执行 Session`,text:``});try{let a=await Zh(e.sessionId,r,{signal:t.signal,onDelta:t=>{n+=t,He(e.goalId,i,{text:n})}});He(e.goalId,i,{activity:[],pending:!1,text:FS(a.response.message||n.trim())||`${e.agentLabel} 已完成纠偏。`})}catch(t){let n=Oe.current.delete(e.goalId);He(e.goalId,i,{activity:[],pending:!1,text:n?`已中断。你可以在当前会话继续发送消息。`:t instanceof Error?t.message:`纠偏回合失败。`})}finally{Ee.current.delete(e.goalId),De.current.delete(e.goalId),Be(e.goalId,{agentId:e.agentId,resumable:!0,sessionId:e.sessionId,status:`ready`})}}},onCloseRunSession:qe,onInterruptRun:async e=>We(e),onOpenGoal:Xe,onOpenRunSession:async e=>{if(!e.sessionId)return;let t=e.sessionId,n=await Vh(t);Se(e=>({...e,[t]:n})),Xe(e.goalId),z(t=>({...t,[e.goalId]:n.messages.map(t=>({agentLabel:t.role===`user`?void 0:e.agentLabel,attachments:AS(t.attachments),id:Ce.current++,lines:[],role:t.role===`user`?`user`:`assistant`,sourceLabel:t.role===`user`?void 0:`${e.agentLabel} · 执行 Session`,text:t.role===`user`?t.text:FS(t.text)}))})),Be(e.goalId,{agentId:e.agentId,resumable:n.session.resumable,sessionId:t,status:n.session.active_turn_id?`running`:n.session.status,turnId:n.session.active_turn_id??void 0})},onOpenOutput:e=>Xe(e.goalId),...b?{onPreviewGoalSubagentConfiguration:async e=>{let t=await ng(e);return{changed:t.changed,configuration:{allowedDomains:t.after.orchestration.allowed_domains,enabled:t.feature_summary.multi_subagent===`enabled`,maxChildren:t.after.orchestration.max_children,modelConfig:t.after.orchestration.model_config},previewId:t.preview_id}},onApplyGoalSubagentConfiguration:async({previewId:e,...t})=>{let n=await rg(t,e);return{allowedDomains:n.after.orchestration.allowed_domains,enabled:n.feature_summary.multi_subagent===`enabled`,maxChildren:n.after.orchestration.max_children,modelConfig:n.after.orchestration.model_config}}}:{},...g?{onExecuteGoalLifecycle:async({goalId:e,operation:t,reason:n})=>{let r=await Cb(g,e,t,n);return{activationState:r.activation_state,projectionVerified:r.projection_verified}}}:{},onGoalActivationStateChange:n,onGoalDeleted:r,onReconcileStatus:a,onRetryGoalArchive:s,onExportOutput:async e=>{let t=[`# ${e.title}`,``,e.summary??``,``,e.safePreview??`此产出没有可用的公开安全预览。`,``,`Goal: ${e.goalId}`,`Todo: ${e.todoId??`unlinked`}`,`Run: ${e.runId??`unlinked`}`].join(`
-`),n=URL.createObjectURL(new Blob([t],{type:`text/markdown;charset=utf-8`})),r=document.createElement(`a`);r.href=n,r.download=`${e.outputId.replace(/[^a-z0-9._-]+/gi,`-`)}.md`,r.click(),URL.revokeObjectURL(n)},onRefresh:o,onRetryResumeRun:Ge,onSelectAgent:Je,onSelectGoal:e=>e?Xe(e):Ye(),onSendMessage:async(e,t,n,r)=>Ue(e,{agentId:t,goalId:n,attachments:r}),onStartNewRunSession:Ke},goalArchiveLoadState:e,managerRuntime:S,model:tt,readOnly:h,selectedAgentId:I.agentId,selectedGoalId:T?.goalId??null,statusSourceControl:f})]})}function fC({error:e,isLoading:t,onRetry:n,requestedUrl:r,theme:i,toggleTheme:a}){let o=!!(e&&/failed to fetch|networkerror|load failed/i.test(e)&&r.includes(`status.json`));return(0,H.jsx)(`div`,{className:i===`dark`?`dark`:``,children:(0,H.jsxs)(`main`,{className:`min-h-screen bg-[#f6f7f9] text-slate-950 dark:bg-[#09090b] dark:text-zinc-50`,children:[(0,H.jsxs)(`header`,{className:`flex min-h-16 flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-zinc-800 dark:bg-zinc-950 sm:px-6`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h1`,{className:`text-xl font-semibold`,children:`LoopX Workspace`}),(0,H.jsx)(`p`,{className:`mt-1 break-all text-sm text-slate-500 dark:text-zinc-400`,children:`Personal Workspace`})]}),(0,H.jsx)(iy,{"aria-label":`切换主题`,onClick:a,size:`icon`,variant:`secondary`,children:i===`dark`?(0,H.jsx)(Ym,{className:`h-4 w-4`}):(0,H.jsx)(Am,{className:`h-4 w-4`})})]}),(0,H.jsxs)(`div`,{className:`grid min-h-[calc(100vh-80px)] sm:grid-cols-[240px_1fr]`,children:[(0,H.jsxs)(`aside`,{className:`hidden border-r border-slate-200 p-6 dark:border-zinc-800 sm:block`,"aria-label":`Workspace`,children:[(0,H.jsx)(`strong`,{children:`LoopX`}),(0,H.jsx)(`p`,{className:`mt-6 text-sm`,children:`Workspace`}),(0,H.jsx)(`p`,{className:`mt-8 text-xs text-slate-500`,children:`Goals`}),[1,2,3].map(e=>(0,H.jsx)(`div`,{className:`mt-4 h-8 rounded bg-slate-100 dark:bg-zinc-900`},e))]}),(0,H.jsx)(`div`,{className:`p-4 sm:p-8`,children:(0,H.jsx)(ay,{"data-testid":`initial-status-state`,children:(0,H.jsx)(oy,{className:`flex min-h-64 items-center justify-center p-6`,children:(0,H.jsxs)(`div`,{className:`max-w-xl text-center`,children:[e?(0,H.jsx)(am,{className:`mx-auto h-6 w-6 text-rose-600 dark:text-rose-300`}):(0,H.jsx)(Lm,{className:`mx-auto h-6 w-6 animate-spin text-slate-500 dark:text-zinc-400`}),(0,H.jsx)(`p`,{className:`mt-3 text-sm font-medium`,children:e?`无法加载实时状态`:`正在加载实时状态`}),e?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{className:`mt-2 break-words text-sm leading-6 text-slate-500 dark:text-zinc-400`,children:o?`本地状态服务暂时未连接。升级或启动期间可能短暂断开,请重试;仍失败时重新打开 LoopX App,或运行 loopx doctor。`:e}),o?(0,H.jsx)(`p`,{className:`mt-2 text-xs leading-5 text-slate-400 dark:text-zinc-500`,children:`重新加载不会执行任务,也不会改变 Goal 配置。`}):null,(0,H.jsx)(`div`,{className:`mt-4 flex flex-wrap justify-center gap-2`,children:(0,H.jsxs)(iy,{disabled:t,onClick:n,children:[(0,H.jsx)(Lm,{className:`h-4 w-4`}),`重试`]})})]}):(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-500 dark:text-zinc-400`,role:`status`,children:`正在连接 Workspace,Goal 列表将先出现,详细状态会逐个补齐。 / Connecting to your Workspace. Goals load independently.`})]})})})})]})]})})}function pC(){let e=uw.useSearch(),t=uw.useNavigate(),[n,r]=(0,V.useState)(`light`),[i,a]=(0,V.useState)(null),o=(0,V.useRef)(null),s=(0,V.useRef)(e.goalId);s.current=e.goalId;let[c,l]=(0,V.useState)(Op),[u,d]=(0,V.useState)({kind:`example`,label:`bundled example`}),[f,p]=(0,V.useState)(()=>sS(window.localStorage,window.location.href)),m=(0,V.useRef)(f);m.current=f;let[h,g]=(0,V.useState)(e.statusUrl),[_,v]=(0,V.useState)(null),[y,b]=(0,V.useState)(!1),[x,S]=(0,V.useState)({error:null,phase:`idle`}),[C,w]=(0,V.useState)(e.statusUrl.trim()||null),[T,E]=(0,V.useState)(!1),D=(0,V.useRef)(null),O=(0,V.useRef)(Zg(e.statusUrl.trim()||null)),k=!T&&u.kind===`example`?e.statusUrl.trim():``,ee=C??k,te=u.kind===`url`?u.label:_S,A=!!(_&&C),j=mS(f,C,te,window.location.href),M=u.kind===`example`&&!T,N=c.attention_queue,P=c.run_history,F=(0,V.useMemo)(()=>bS(P.goals,N.items),[P.goals,N.items]);function ne(e,t,n=0){S({error:null,phase:`loading`}),vS(oh(e,`stopped`,window.location.href)).then(r=>{if(!t_(O.current,t))return;let i=r.goal_projection?.registry_revision??null,a=t.registryRevision!==null&&t.registryRevision!==void 0&&i!==null&&t.registryRevision!==i;if(l(e=>w_(e,r)),a&&n<1){L(e,{background:!0,resyncAttempt:n+1});return}S(a?{error:`Goal 状态在加载历史时发生变化,请重试。`,phase:`error`}:{error:null,phase:`ready`})}).catch(e=>{t_(O.current,t)&&S({error:Dp(e),phase:`error`})})}function re(){let e=u.kind===`url`?u.label:h||_S,t=$g(O.current,e,{background:!0});if(i){L(e);return}t&&ne(e,t)}async function I(e,n,r){if(r.background)return l(e=>w_(e,n)),!0;let i={kind:`url`,label:e};return O.current.loadedUrl=e,l(n),d(i),g(e),await t({search:t=>({...t,statusUrl:e})}),e_(O.current,r)?(O.current.requestedUrl=null,w(null),!0):!1}async function L(e,t={}){let n=e.trim(),r=t.background===!0;if(!n){r||v(`状态地址不能为空`);return}let c=$g(O.current,n,{background:r,selectionRevision:t.selectionRevision});if(!c)return;o.current?.abort();let d=new AbortController;o.current=d,r||(D.current=null,E(!1),w(n),b(!0),v(null),S({error:null,phase:`idle`}));try{let e=await jp(n,window.location.href).catch(()=>null);if(!t_(O.current,c))return;if(e){let o=t.retryOnly&&u.kind===`url`&&u.label===n&&i?.directory.registry_revision===e.registry_revision?i.snapshots:{};a({directory:e,snapshots:o,errors:{}});let f={...e,goals:e.goals.filter(e=>!o[e.id])},p=!1,m=Mp(e);if(r)l(m);else if(!await I(n,m,c))return;if(S({error:null,phase:`loading`}),await Pp(n,window.location.href,f,(e,t,n)=>{n===`revision`&&(p=!0),a(r=>r&&{...r,snapshots:t?{...r.snapshots,[e]:t}:r.snapshots,errors:n?{...r.errors,[e]:n}:r.errors})},()=>t_(O.current,c),()=>s.current,d.signal),p&&(t.resyncAttempt??0)<1&&t_(O.current,c)){await L(n,{resyncAttempt:1});return}t_(O.current,c)&&S({error:null,phase:`ready`});return}let o=await vS(oh(n,`active`,window.location.href));if(!t_(O.current,c)||(a(null),c.registryRevision=o.goal_projection?.registry_revision??null,!await I(n,o,c)))return;if(o.goal_projection?.scope!==`active`||o.goal_projection.complete){S({error:null,phase:`ready`});return}ne(n,c,t.resyncAttempt??0)}catch(e){if(!e_(O.current,c))return;r||v(Dp(e))}finally{!r&&e_(O.current,c)&&b(!1)}}function ie(e,t={}){o.current?.abort();let n=Qg(O.current,e.statusUrl);D.current=null,E(!1),w(e.statusUrl),b(!0),v(null),(async()=>{if(t.ensureTunnel&&e.kind===`ssh_tunnel`){let t=new URL(e.statusUrl,window.location.href).port;if(t)try{await Sb(e.label,t)}catch{}}O.current.selectionRevision===n&&await L(e.statusUrl,{selectionRevision:n})})()}function R(e){m.current=e,p(e);try{cS(window.localStorage,e)}catch{}}let ae={activeSource:j,connectionState:y?`loading`:A?`error`:`connected`,errorMessage:A?`未切换到 ${C??`所选来源`}:${_}`:null,onAdd:e=>{let t=uS(f,e,window.location.href);return`error`in t?{error:t.error}:(R(t.catalog),ie(t.source,{ensureTunnel:e.ensureTunnel}),{})},onConfiguredHostsLoaded:e=>{let t=m.current,n=lS(t,e);n!==t&&R(n)},onRemove:e=>{R(dS(f,e)),j.id===e&&ie(nS)},onSelect:e=>{let t=f.sources.find(t=>t.id===e);t&&ie(t,{ensureTunnel:t.kind===`ssh_tunnel`})},sources:j.id===`temporary`?[...f.sources,j]:f.sources};(0,V.useEffect)(()=>{let t=e.statusUrl.trim();if(t){if(D.current===t||C&&C!==t)return;(u.kind!==`url`||u.label!==t)&&L(t);return}D.current=null,!T&&(C||u.kind===`example`&&L(_S))},[T,C,e.statusUrl,u.kind,u.label]),(0,V.useEffect)(()=>{if(e.statusUrl&&u.kind===`example`)return;let n=new Set(F.map(e=>e.goal.id));if(F.length===0){e.goalId&&t({search:e=>({...e,goalId:``})});return}e.goalId&&!n.has(e.goalId)&&x.phase!==`loading`&&t({search:e=>({...e,goalId:``})})},[x.phase,F,t,e.goalId,e.statusUrl,u.kind]),(0,V.useEffect)(()=>{if(!i||y||!e.goalId||u.kind!==`url`)return;let t=i.directory.goals.find(t=>t.id===e.goalId);t?.activation_state===`stopped`&&!i.snapshots[t.id]&&!i.errors[t.id]&&L(u.label,{retryOnly:!0})},[e.goalId,y,i,u]);function oe(e){t({search:t=>({...t,goalId:e})})}return M?(0,H.jsx)(fC,{error:_,isLoading:y,onRetry:()=>void L(ee||_S),requestedUrl:ee||_S,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)}):(0,H.jsx)(dC,{goalArchiveLoadState:x,isLoading:y,onGoalActivationStateChange:(e,t)=>{O.current.projectionRevision+=1,l(n=>wp(n,e,t)),a(n=>n&&{...n,snapshots:Object.fromEntries(Object.entries(n.snapshots).map(([n,r])=>[n,wp(r,e,t)]))})},onGoalDeleted:e=>{O.current.projectionRevision+=1,l(t=>Tp(t,e)),a(t=>t&&{...t,snapshots:Object.fromEntries(Object.entries(t.snapshots).filter(([t])=>t!==e))})},onSelectGoal:oe,onReconcileStatus:()=>L(u.kind===`url`?u.label:h||_S,{background:!0}),onRetryGoalArchive:re,onRefresh:()=>L(u.kind===`url`?u.label:h||_S,{retryOnly:!!(i&&Object.keys(i.errors).length)}),payload:c,progress:i,rows:F,selectedGoalId:e.goalId,statusSourceControl:ae,theme:n,toggleTheme:()=>r(n===`dark`?`light`:`dark`)})}var mC=k_(`inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs font-medium`,{variants:{variant:{neutral:`border-slate-200 bg-white text-slate-700 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-300`,success:`border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-200`,warning:`border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200`,info:`border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200`,danger:`border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-900 dark:bg-rose-950 dark:text-rose-200`}},defaultVariants:{variant:`neutral`}});function hC({className:e,variant:t,...n}){return(0,H.jsx)(`span`,{className:ny(mC({variant:t}),e),...n})}var gC=[{label:`status payload`,source:`apps/presentation/dashboard/src/data/status.ts`,detail:`status_contract, attention_queue, local_dashboard_api, run_history`},{label:`channel projection`,source:`apps/presentation/dashboard/src/data/goal-channel-frontstage.ts`,detail:`decision_frame, todos, gates, leases, artifacts, truth_contract`},{label:`public showcase catalog`,source:`docs/showcases/showcase-catalog.json`,detail:`case metadata, visual hints, evidence boundaries, story beats`},{label:`route smoke`,source:`apps/presentation/dashboard/smoke/frontstage-route-smoke.ts`,detail:`static route contract, source guards, component expectations`}],_C=[{axis:`schema`,current:`goal_channel_projection_v0`,proposed:`new optional projection field`,gate:`parser default plus route smoke assertion`},{axis:`truth`,current:`event ledger and active state remain source of truth`,proposed:`derived UI state only`,gate:`truth_contract must stay read-only`},{axis:`privacy`,current:`compact source refs and warnings`,proposed:`public-safe fixture field`,gate:`loopx check and browser fake-private fixture`},{axis:`interaction`,current:`render, filter, select, inspect`,proposed:`no browser write by default`,gate:`write affordance requires explicit loopback capability`}],vC=[{title:`Fixture sources`,body:`Use examples/status.example.json, browser-smoke fixtures, and docs/showcases/showcase-catalog.json.`},{title:`Required proof`,body:`Every projection addition needs parser coverage, route smoke assertions, and one browser or bundle check when UI output changes.`},{title:`Never include`,body:`Raw task text, trajectories, transcripts, local paths, private registry state, credentials, or internal document links.`}],yC=[`npm --prefix apps/presentation/dashboard run smoke:frontstage-route`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-browser`,`npm --prefix apps/presentation/dashboard run smoke:frontstage-share-bundle`,`npm --prefix apps/presentation/dashboard run build`,`loopx check --scan-path apps/presentation/dashboard --scan-path docs/status-data-contract.md`],bC=[{name:`Projection lane`,badges:[`read-only`,`schema v0`],body:`Summarizes one compact projection lane without mutating the underlying LoopX state.`},{name:`Capability badge`,badges:[`loopback`,`dry-run`],body:`Shows an advertised local capability only after the status feed declares it.`},{name:`Boundary warning`,badges:[`public-safe`,`omitted`],body:`Names omitted private material and points contributors back to compact source references.`}];function xC({children:e,icon:t,title:n}){return(0,H.jsxs)(`section`,{className:`rounded-lg border border-slate-200 bg-white shadow-sm`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3`,children:(0,H.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold text-slate-950`,children:[(0,H.jsx)(t,{className:`h-4 w-4 text-slate-500`}),n]})}),e]})}function SC(){return(0,H.jsx)(xC,{icon:$p,title:`Status Contract Explorer`,children:(0,H.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-2`,"data-testid":`developer-contract-explorer`,children:gC.map(e=>(0,H.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,H.jsx)(hC,{variant:`info`,children:e.label}),(0,H.jsx)(hC,{variant:`neutral`,children:`public contract`})]}),(0,H.jsx)(`div`,{className:`mt-2 break-words font-mono text-xs text-slate-700`,children:e.source}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.detail})]},e.label))})})}function CC(){return(0,H.jsx)(xC,{icon:ym,title:`Projection Diffing`,children:(0,H.jsx)(`div`,{className:`overflow-x-auto`,"data-testid":`developer-projection-diffing`,children:(0,H.jsxs)(`table`,{className:`min-w-full border-separate border-spacing-0 text-left text-sm`,children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{className:`bg-slate-50 text-xs uppercase tracking-normal text-slate-500`,children:[(0,H.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Axis`}),(0,H.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Current`}),(0,H.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Proposed`}),(0,H.jsx)(`th`,{className:`border-b border-slate-200 px-4 py-3 font-semibold`,children:`Gate`})]})}),(0,H.jsx)(`tbody`,{children:_C.map(e=>(0,H.jsxs)(`tr`,{className:`align-top`,children:[(0,H.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 font-semibold text-slate-950`,children:e.axis}),(0,H.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.current}),(0,H.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.proposed}),(0,H.jsx)(`td`,{className:`border-b border-slate-100 px-4 py-3 text-slate-600`,children:e.gate})]},e.axis))})]})})})}function wC(){return(0,H.jsx)(xC,{icon:hm,title:`Fixture Generation`,children:(0,H.jsx)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-fixture-generation`,children:vC.map(e=>(0,H.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-3`,children:[(0,H.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:e.title}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.title))})})}function TC(){return(0,H.jsx)(xC,{icon:sm,title:`Smoke Checklist`,children:(0,H.jsx)(`div`,{className:`space-y-2 p-4`,"data-testid":`developer-smoke-checklist`,children:yC.map(e=>(0,H.jsxs)(`div`,{className:`flex items-start gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,H.jsx)(Xp,{className:`mt-0.5 h-4 w-4 shrink-0 text-emerald-600`}),(0,H.jsx)(`code`,{className:`break-all text-xs font-semibold leading-5 text-slate-700`,children:e})]},e))})})}function EC(){return(0,H.jsx)(xC,{icon:cm,title:`Component Examples`,children:(0,H.jsx)(`div`,{className:`grid gap-3 p-4 lg:grid-cols-3`,"data-testid":`developer-component-examples`,children:bC.map(e=>(0,H.jsxs)(`article`,{className:`rounded-md border border-slate-200 bg-slate-50 p-3`,children:[(0,H.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.badges.map(e=>(0,H.jsx)(hC,{variant:e===`read-only`||e===`public-safe`?`success`:`neutral`,children:e},e))}),(0,H.jsx)(`h3`,{className:`mt-3 text-sm font-semibold leading-6 text-slate-950`,children:e.name}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:e.body})]},e.name))})})}function DC(){return(0,H.jsx)(`main`,{className:`min-h-screen bg-[#f7f7f4] px-4 py-4 text-slate-950 sm:px-5`,"data-testid":`frontstage-developer-cockpit`,children:(0,H.jsxs)(`div`,{className:`mx-auto grid max-w-[1500px] gap-4 xl:grid-cols-[260px_minmax(0,1fr)]`,children:[(0,H.jsxs)(`aside`,{className:`rounded-lg border border-slate-200 bg-white p-4 shadow-sm xl:sticky xl:top-4 xl:self-start`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`div`,{className:`flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-slate-950 text-white`,children:(0,H.jsx)(Xm,{className:`h-4 w-4`})}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`div`,{className:`text-sm font-semibold`,children:`Developer Cockpit`}),(0,H.jsx)(`div`,{className:`text-xs text-slate-500`,children:`Projection extension`})]})]}),(0,H.jsxs)(`div`,{className:`mt-4 grid gap-2`,children:[(0,H.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/`,children:[(0,H.jsx)(Sm,{className:`h-4 w-4`}),`LoopX home`]}),(0,H.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-medium`,href:`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`,children:[(0,H.jsx)(pm,{className:`h-4 w-4`}),`Public cases`]}),(0,H.jsxs)(`a`,{className:`flex items-center gap-2 rounded-md bg-slate-950 px-3 py-2 text-sm font-medium text-white`,href:`/chat/developers/projections/`,children:[(0,H.jsx)(cm,{className:`h-4 w-4`}),`Developer cockpit`]})]}),(0,H.jsxs)(`div`,{className:`mt-5 space-y-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs leading-5 text-emerald-950`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,H.jsx)(hC,{variant:`success`,children:`read-only`}),(0,H.jsx)(hC,{variant:`neutral`,children:`public fixtures`})]}),(0,H.jsx)(`p`,{children:`This route uses static public contracts only; live status feeds, registry files, and browser write APIs stay outside the cockpit.`})]})]}),(0,H.jsxs)(`section`,{className:`space-y-4`,children:[(0,H.jsx)(`div`,{className:`rounded-lg border border-slate-200 bg-white px-5 py-5 shadow-sm`,children:(0,H.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-4`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,H.jsx)(hC,{variant:`info`,children:`developers/projections`}),(0,H.jsx)(hC,{variant:`success`,children:`public-safe`}),(0,H.jsx)(hC,{variant:`neutral`,children:`no browser writes`})]}),(0,H.jsx)(`h1`,{className:`mt-3 text-3xl font-semibold tracking-normal text-slate-950`,children:`LoopX Projection Developer Cockpit`}),(0,H.jsx)(`p`,{className:`mt-2 max-w-3xl text-sm leading-6 text-slate-600`,children:`A read-only contributor workbench for adding dashboard/frontstage projections without reverse-engineering the large operator page.`})]}),(0,H.jsxs)(`div`,{className:`grid min-w-[260px] gap-2 text-sm`,children:[(0,H.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,H.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Source of truth`}),(0,H.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`status contract + compact fixtures`})]}),(0,H.jsxs)(`div`,{className:`rounded-md border border-slate-200 bg-slate-50 px-3 py-2`,children:[(0,H.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-normal text-slate-500`,children:`Boundary`}),(0,H.jsx)(`div`,{className:`mt-1 font-semibold text-slate-950`,children:`read-only extension surface`})]})]})]})}),(0,H.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[(0,H.jsx)(SC,{}),(0,H.jsx)(CC,{})]}),(0,H.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]`,children:[(0,H.jsx)(wC,{}),(0,H.jsx)(TC,{})]}),(0,H.jsx)(EC,{}),(0,H.jsx)(xC,{icon:Gm,title:`Extension Boundary`,children:(0,H.jsxs)(`div`,{className:`grid gap-3 p-4 md:grid-cols-3`,"data-testid":`developer-extension-boundary`,children:[(0,H.jsxs)(`div`,{className:`rounded-md border border-emerald-200 bg-emerald-50 px-3 py-3`,children:[(0,H.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Allowed`}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Versioned parser defaults, public fixtures, read-only route panels, and focused smoke assertions.`})]}),(0,H.jsxs)(`div`,{className:`rounded-md border border-amber-200 bg-amber-50 px-3 py-3`,children:[(0,H.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Review`}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`New dashboard dependencies, status contract fields, loopback capability display, and browser-visible workflows.`})]}),(0,H.jsxs)(`div`,{className:`rounded-md border border-rose-200 bg-rose-50 px-3 py-3`,children:[(0,H.jsx)(`div`,{className:`text-sm font-semibold text-slate-950`,children:`Stop`}),(0,H.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-slate-600`,children:`Credentials, private registry material, raw logs, transcripts, production actions, or default browser write authority.`})]})]})})]})]})})}var OC=Y({value:K().finite(),total:K().finite().positive().optional(),unit:G().optional(),higher_is_better:q()}).passthrough(),kC=hd(G(),K().finite()).default({}),AC=Y({outcome_status:G().optional(),failure_class:G(),causal_summary:G(),expectedness:G(),implication:G(),next_probe:G(),confidence:G(),evidence_refs:J(G()).optional()}).passthrough(),jC=Y({arm_id:G(),selected_run_id:G().nullable(),score_countable:q(),metrics:hd(G(),OC),effort:kC,insight:AC.nullable().optional()}),MC=Y({run_id:G(),case_id:G(),arm_id:G(),arm_role:G(),status:G(),protocol_id:G(),runner_revision:G().optional(),observed_at:G(),metrics:hd(G(),OC),countability:Y({integrity_qualified:q(),official_result_present:q(),score_countable:q()}).passthrough(),treatment_fidelity:G(),effort:kC,redacted_insight:AC.nullable().optional(),upload_provenance:Y({producer_id:G(),producer_version:G(),observed_at:G(),source_revision:G()}).passthrough()}).passthrough(),NC=Y({case_denominator:K().int().nonnegative(),value_sum:K().finite(),value_mean:K().finite().nullable(),value_median:K().finite().nullable(),value_min:K().finite().nullable(),value_max:K().finite().nullable(),case_macro_rate:K().finite().optional(),suite_micro_rate:K().finite().optional(),suite_micro_numerator:K().finite().optional(),suite_micro_denominator:K().finite().positive().optional()}).passthrough(),PC=Y({arm_id:G(),arm_role:G(),factor_assignments:hd(G(),G()),protocol_counts:hd(G(),K().int().nonnegative()).default({}),runner_revision_counts:hd(G(),K().int().nonnegative()).default({}),orchestrator_runtime_counts:hd(G(),K().int().nonnegative()).default({}),intended_case_count:K().int().positive(),run_count:K().int().nonnegative(),terminal_run_count:K().int().nonnegative(),selected_score_countable_case_count:K().int().nonnegative(),coverage_rate:K().finite().min(0).max(1),metrics:hd(G(),NC),binary_outcomes:hd(G(),Y({success_count:K().int().nonnegative(),case_denominator:K().int().nonnegative(),success_rate:K().finite().min(0).max(1).nullable()})),effort:hd(G(),Y({denominator:K().int().nonnegative(),mean:K().finite().nullable(),median:K().finite().nullable()})),failure_class_counts:hd(G(),K().int().nonnegative())}).passthrough(),FC=Y({baseline_value:K().finite(),candidate_value:K().finite(),delta:K().finite(),direction:_d([`improved`,`flat`,`regressed`]).optional()}).passthrough(),IC=Y({comparison_id:G(),comparison_anchor_run_id:G(),candidate_run_id:G(),candidate_arm_id:G(),primary_metric:G(),matched_pair_countable:X(!0),metric_deltas:hd(G(),FC)}).passthrough(),LC=Y({ok:X(!0),schema_version:X(`benchmark_study_dashboard_v0`),benchmark_id:G(),study_id:G(),status:_d([`complete`,`provisional`]),design:Y({protocol_id:G(),comparison_protocol_id:G(),baseline_arm_id:G(),case_set:Y({case_set_id:G(),case_ids:J(G())}),metric_catalog:J(Y({metric_name:G(),role:_d([`primary`,`guardrail`,`supporting`]),unit:G().optional(),higher_is_better:q(),binary:q()})),labels:hd(G(),G())}).passthrough(),campaign:Y({intended_case_count:K().int().positive(),intended_arm_count:K().int().positive(),intended_cell_denominator:K().int().positive(),selected_score_countable_cell_count:K().int().nonnegative(),selected_score_countable_coverage_rate:K().finite().min(0).max(1),complete_declared_design_case_count:K().int().nonnegative(),ambiguous_score_countable_cell_count:K().int().nonnegative(),in_flight_run_count:K().int().nonnegative(),matched_pair_countable_count:K().int().nonnegative(),factorial_contrast_count:K().int().nonnegative(),factorial_contrast_countable_count:K().int().nonnegative(),runtime_observation_count:K().int().nonnegative(),runtime_classification_counts:hd(G(),K().int().nonnegative())}),arms:J(PC),contrasts:hd(G(),Y({matched_pair_denominator:K().int().nonnegative(),primary_metric_directions:Y({improved:K().int().nonnegative(),flat:K().int().nonnegative(),regressed:K().int().nonnegative()}),binary_metric_transitions:hd(G(),Y({"0_to_1":K().int().nonnegative(),"1_to_0":K().int().nonnegative(),same:K().int().nonnegative()}))})),cases:J(Y({case_id:G(),complete_declared_design:q(),arms:J(jC),eligible_comparisons:J(IC),largest_eligible_primary_contrast:IC.nullable()})),runs:J(MC),authority:Y({score_source:G(),matched_comparison_source:G(),factorial_comparison_source:G().nullable(),manifest_changes_scores:X(!1),dashboard_is_execution_authority:X(!1)}),public_boundary:Y({raw_task_recorded:X(!1),raw_trajectory_recorded:X(!1),hidden_evaluation_recorded:X(!1),raw_verifier_output_recorded:X(!1),credentials_recorded:X(!1),local_paths_recorded:X(!1)}),write_performed:X(!1),network_access_performed:X(!1)});function RC(e){return LC.parse(e)}function zC(e,t){let n=new URL(t),r=new URL(e||`/benchmark-study.example.json`,n);if(!new Set([`http:`,`https:`]).has(r.protocol))throw Error(`Benchmark dashboard source must use HTTP or HTTPS`);if(r.origin!==n.origin)throw Error(`Benchmark dashboard source must use same-origin local readback`);return r.toString()}var BC=[{id:`campaign`,label:`Campaign`},{id:`arms`,label:`Arms`},{id:`cases`,label:`Cases`},{id:`runs`,label:`Runs`}];function VC(e){return e==null?`—`:`${(e*100).toFixed(e>=.995?0:1)}%`}function HC(e){return e==null?`—`:new Intl.NumberFormat(`en`,{maximumFractionDigits:2,notation:`compact`}).format(e)}function UC(e){if(e==null)return`—`;let t=e/6e4;return t>=120?`${(t/60).toFixed(1)} h`:`${HC(t)} min`}function WC(e){let t=Object.entries(e);return t.length?t.map(([e,t])=>`${e} (${t})`).join(`, `):`—`}function GC(e){if(!e)return`—`;let t=e.total==null?HC(e.value):`${HC(e.value)}/${HC(e.total)}`;return e.unit?`${t} ${e.unit}`:t}function KC(e,t){let n=e.metrics[t];return!n||n.case_denominator===0?`—`:n.suite_micro_rate==null?`${HC(n.value_mean)} mean`:`${VC(n.suite_micro_rate)} · ${HC(n.suite_micro_numerator)}/${HC(n.suite_micro_denominator)}`}function qC(e,t){let n=e.largest_eligible_primary_contrast,r=n?.metric_deltas[t];if(!n||!r)return null;let i=r.delta>0?`+`:``;return{direction:r.direction,text:`${n.candidate_arm_id}: ${i}${HC(r.delta)}`}}function JC({children:e,tone:t=`neutral`}){return(0,H.jsx)(`span`,{className:`benchmark-state benchmark-state-${t}`,children:e})}function YC({packet:e,primaryMetric:t}){return(0,H.jsxs)(`div`,{className:`benchmark-view-stack`,children:[(0,H.jsxs)(`section`,{"aria-labelledby":`arm-summary-title`,children:[(0,H.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`benchmark-kicker`,children:`ARM SUMMARY`}),(0,H.jsx)(`h2`,{id:`arm-summary-title`,children:`Comparable outcomes, denominator first`})]}),(0,H.jsx)(`p`,{children:`Only one score-countable run per declared case × arm cell is selected.`})]}),(0,H.jsx)(`div`,{className:`benchmark-arm-grid`,children:e.arms.map(e=>{let n=Object.values(e.binary_outcomes)[0];return(0,H.jsxs)(`article`,{className:`benchmark-arm-card`,children:[(0,H.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`benchmark-mono`,children:e.arm_role}),(0,H.jsx)(`h3`,{children:e.arm_id})]}),(0,H.jsx)(JC,{tone:e.coverage_rate===1?`success`:`warning`,children:e.coverage_rate===1?`Complete`:`Provisional`})]}),(0,H.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`dt`,{children:[`Primary · `,t]}),(0,H.jsx)(`dd`,{children:KC(e,t)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Score-countable coverage`}),(0,H.jsxs)(`dd`,{children:[e.selected_score_countable_case_count,`/`,e.intended_case_count]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Binary success`}),(0,H.jsx)(`dd`,{children:n?`${n.success_count}/${n.case_denominator}`:`Not declared`})]})]})]},e.arm_id)})})]}),(0,H.jsxs)(`section`,{"aria-labelledby":`contrast-title`,children:[(0,H.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`benchmark-kicker`,children:`MATCHED CONTRASTS`}),(0,H.jsx)(`h2`,{id:`contrast-title`,children:`Direction counts on eligible pairs`})]}),(0,H.jsx)(`p`,{children:`Raw run volume is never used as a comparison denominator.`})]}),(0,H.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,H.jsxs)(`table`,{children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{children:`Candidate arm`}),(0,H.jsx)(`th`,{children:`Matched denominator`}),(0,H.jsx)(`th`,{children:`Improved`}),(0,H.jsx)(`th`,{children:`Flat`}),(0,H.jsx)(`th`,{children:`Regressed`}),(0,H.jsx)(`th`,{children:`Binary transitions`})]})}),(0,H.jsxs)(`tbody`,{children:[Object.entries(e.contrasts).map(([e,t])=>(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`td`,{children:(0,H.jsx)(`strong`,{children:e})}),(0,H.jsx)(`td`,{children:t.matched_pair_denominator}),(0,H.jsx)(`td`,{className:`benchmark-positive`,children:t.primary_metric_directions.improved}),(0,H.jsx)(`td`,{children:t.primary_metric_directions.flat}),(0,H.jsx)(`td`,{className:`benchmark-negative`,children:t.primary_metric_directions.regressed}),(0,H.jsx)(`td`,{children:Object.entries(t.binary_metric_transitions).map(([e,t])=>`${e}: 0→1 ${t[`0_to_1`]}, 1→0 ${t[`1_to_0`]}, same ${t.same}`).join(` · `)||`—`})]},e)),Object.keys(e.contrasts).length===0&&(0,H.jsx)(`tr`,{children:(0,H.jsx)(`td`,{colSpan:6,children:`No matched comparisons are countable yet.`})})]})]})})]}),(0,H.jsxs)(`section`,{"aria-labelledby":`runtime-health-title`,children:[(0,H.jsxs)(`div`,{className:`benchmark-section-heading`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`benchmark-kicker`,children:`RUNTIME HEALTH`}),(0,H.jsx)(`h2`,{id:`runtime-health-title`,children:`Qualified observations, without execution authority`})]}),(0,H.jsxs)(`p`,{children:[e.campaign.runtime_observation_count,` public-safe runtime observations.`]})]}),(0,H.jsxs)(`div`,{className:`benchmark-runtime-list`,children:[Object.entries(e.campaign.runtime_classification_counts).map(([e,t])=>(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{children:e}),(0,H.jsx)(`strong`,{children:t})]},e)),e.campaign.runtime_observation_count===0&&(0,H.jsx)(`p`,{className:`benchmark-muted`,children:`No runtime observations uploaded.`})]})]})]})}function XC({packet:e}){return(0,H.jsx)(`div`,{className:`benchmark-detail-grid`,children:e.arms.map(t=>(0,H.jsxs)(`article`,{className:`benchmark-detail-card`,children:[(0,H.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`benchmark-mono`,children:t.arm_role}),(0,H.jsx)(`h2`,{children:t.arm_id})]}),(0,H.jsxs)(JC,{tone:t.coverage_rate===1?`success`:`warning`,children:[t.selected_score_countable_case_count,`/`,t.intended_case_count,` countable`]})]}),(0,H.jsx)(`div`,{className:`benchmark-factor-row`,children:Object.entries(t.factor_assignments).map(([e,t])=>(0,H.jsxs)(`span`,{children:[e,`: `,(0,H.jsx)(`strong`,{children:t})]},e))}),(0,H.jsxs)(`dl`,{className:`benchmark-stat-list`,children:[e.design.metric_catalog.map(e=>(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`dt`,{children:[e.role,` · `,e.metric_name]}),(0,H.jsx)(`dd`,{children:KC(t,e.metric_name)})]},e.metric_name)),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Runs terminal / observed`}),(0,H.jsxs)(`dd`,{children:[t.terminal_run_count,`/`,t.run_count]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Median duration`}),(0,H.jsx)(`dd`,{children:UC(t.effort.duration_ms?.median)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Protocols`}),(0,H.jsx)(`dd`,{children:WC(t.protocol_counts)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Runner revisions`}),(0,H.jsx)(`dd`,{children:WC(t.runner_revision_counts)})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Orchestrator runtimes`}),(0,H.jsxs)(`dd`,{children:[Object.keys(t.orchestrator_runtime_counts).length||0,` distinct`]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Failure classes`}),(0,H.jsx)(`dd`,{children:WC(t.failure_class_counts)})]})]})]},t.arm_id))})}function ZC({packet:e,primaryMetric:t,onOpenRun:n}){return(0,H.jsx)(`div`,{className:`benchmark-table-shell benchmark-wide-table`,children:(0,H.jsxs)(`table`,{children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{children:`Case`}),(0,H.jsx)(`th`,{children:`Design status`}),(0,H.jsx)(`th`,{children:`Largest eligible delta`}),e.arms.map(e=>(0,H.jsx)(`th`,{children:e.arm_id},e.arm_id))]})}),(0,H.jsx)(`tbody`,{children:e.cases.map(r=>{let i=qC(r,t);return(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`td`,{children:(0,H.jsx)(`strong`,{children:r.case_id})}),(0,H.jsx)(`td`,{children:(0,H.jsx)(JC,{tone:r.complete_declared_design?`success`:`warning`,children:r.complete_declared_design?`Complete`:`Provisional`})}),(0,H.jsx)(`td`,{className:i?.direction===`improved`?`benchmark-positive`:i?.direction===`regressed`?`benchmark-negative`:void 0,children:i?.text??`—`}),r.arms.map(r=>(0,H.jsx)(`td`,{children:r.selected_run_id&&r.score_countable?(0,H.jsxs)(`button`,{className:`benchmark-cell-link`,onClick:()=>n(r.selected_run_id),type:`button`,children:[(0,H.jsxs)(`span`,{children:[t,`: `,GC(r.metrics[t])]}),e.design.metric_catalog.filter(e=>e.metric_name!==t).map(e=>(0,H.jsxs)(`small`,{className:`benchmark-cell-metric`,children:[e.metric_name,`: `,GC(r.metrics[e.metric_name])]},e.metric_name)),(0,H.jsxs)(`small`,{children:[`Countable · `,UC(r.effort.duration_ms),` `,(0,H.jsx)(qp,{"aria-hidden":`true`,size:12})]}),r.insight&&(0,H.jsxs)(`small`,{children:[r.insight.failure_class,` · `,r.insight.confidence]})]}):(0,H.jsx)(`span`,{className:`benchmark-muted`,children:`Not countable`})},r.arm_id))]},r.case_id)})})]})})}function QC({run:e,packet:t}){return(0,H.jsxs)(`aside`,{"aria-label":`Run detail for ${e.run_id}`,className:`benchmark-run-detail`,children:[(0,H.jsxs)(`div`,{className:`benchmark-card-heading`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{className:`benchmark-mono`,children:`RUN DETAIL`}),(0,H.jsx)(`h2`,{children:e.run_id})]}),(0,H.jsx)(JC,{tone:e.countability.score_countable?`success`:`warning`,children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]}),(0,H.jsxs)(`dl`,{className:`benchmark-stat-list benchmark-run-facts`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Case / arm`}),(0,H.jsxs)(`dd`,{children:[e.case_id,` · `,e.arm_id]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Lifecycle`}),(0,H.jsxs)(`dd`,{children:[e.status,` · `,e.observed_at]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Protocol`}),(0,H.jsx)(`dd`,{children:e.protocol_id})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Qualification`}),(0,H.jsxs)(`dd`,{children:[`Integrity `,e.countability.integrity_qualified?`qualified`:`not qualified`,` · result `,e.countability.official_result_present?`present`:`missing`]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Treatment fidelity`}),(0,H.jsx)(`dd`,{children:e.treatment_fidelity})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Effort`}),(0,H.jsxs)(`dd`,{children:[UC(e.effort.duration_ms),` · `,HC(e.effort.agent_steps),` steps · `,HC(e.effort.token_count),` tokens`]})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Runner revision`}),(0,H.jsx)(`dd`,{children:e.runner_revision??`—`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Upload provenance`}),(0,H.jsxs)(`dd`,{children:[e.upload_provenance.producer_id,` · `,e.upload_provenance.source_revision]})]})]}),(0,H.jsx)(`div`,{className:`benchmark-run-metrics`,children:t.design.metric_catalog.map(t=>(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`span`,{children:t.metric_name}),(0,H.jsx)(`strong`,{children:GC(e.metrics[t.metric_name])})]},t.metric_name))}),e.redacted_insight&&(0,H.jsxs)(`div`,{className:`benchmark-insight`,children:[(0,H.jsxs)(`span`,{className:`benchmark-mono`,children:[`REDACTED CASE INSIGHT · `,e.redacted_insight.confidence]}),(0,H.jsx)(`p`,{children:e.redacted_insight.causal_summary}),(0,H.jsxs)(`small`,{children:[`Implication: `,e.redacted_insight.implication]}),(0,H.jsx)(`br`,{}),(0,H.jsxs)(`small`,{children:[`Next probe: `,e.redacted_insight.next_probe]}),!!e.redacted_insight.evidence_refs?.length&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`br`,{}),(0,H.jsxs)(`small`,{children:[`Evidence: `,e.redacted_insight.evidence_refs.join(`, `)]})]})]})]})}function $C({packet:e,selectedRunId:t,onSelectRun:n}){let r=e.runs.find(e=>e.run_id===t)??e.runs[0];return(0,H.jsxs)(`div`,{className:`benchmark-runs-layout`,children:[(0,H.jsx)(`div`,{className:`benchmark-table-shell`,children:(0,H.jsxs)(`table`,{children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{children:`Run`}),(0,H.jsx)(`th`,{children:`Case`}),(0,H.jsx)(`th`,{children:`Arm`}),(0,H.jsx)(`th`,{children:`Status`}),(0,H.jsx)(`th`,{children:`Countability`})]})}),(0,H.jsx)(`tbody`,{children:e.runs.map(e=>(0,H.jsxs)(`tr`,{"aria-selected":e.run_id===r?.run_id,children:[(0,H.jsx)(`td`,{children:(0,H.jsx)(`button`,{className:`benchmark-run-link`,onClick:()=>n(e.run_id),type:`button`,children:e.run_id})}),(0,H.jsx)(`td`,{children:e.case_id}),(0,H.jsx)(`td`,{children:e.arm_id}),(0,H.jsx)(`td`,{children:e.status}),(0,H.jsx)(`td`,{children:e.countability.score_countable?`Score-countable`:`Diagnostic only`})]},e.run_id))})]})}),r&&(0,H.jsx)(QC,{packet:e,run:r})]})}function ew(){let e=hw.useSearch(),t=hw.useNavigate(),[n,r]=(0,V.useState)(null),[i,a]=(0,V.useState)(null),[o,s]=(0,V.useState)(0),c=(0,V.useMemo)(()=>{let t=e.dashboardUrl||`/chat/benchmark-study.example.json`;try{return{url:zC(t,window.location.href),error:null}}catch(e){return{url:``,error:e instanceof Error?e.message:`Invalid dashboard source`}}},[e.dashboardUrl]);if((0,V.useEffect)(()=>{let e=!0;return r(null),a(null),c.error?(a(c.error),()=>{e=!1}):(fetch(c.url,{cache:`no-store`}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status} while loading the dashboard packet`);return RC(await e.json())}).then(t=>{e&&r(t)}).catch(t=>{e&&a(t instanceof Error?t.message:`Unable to load dashboard packet`)}),()=>{e=!1})},[o,c]),(0,V.useEffect)(()=>{n&&(document.title=`${n.design.labels.title??n.study_id} · LoopX Benchmark`)},[n]),i)return(0,H.jsxs)(`main`,{className:`benchmark-page benchmark-loading`,children:[(0,H.jsx)(am,{"aria-hidden":`true`}),(0,H.jsx)(`h1`,{children:`Dashboard packet unavailable`}),(0,H.jsx)(`p`,{children:i}),(0,H.jsxs)(`button`,{onClick:()=>s(e=>e+1),type:`button`,children:[(0,H.jsx)(Lm,{"aria-hidden":`true`,size:16}),` Retry readback`]})]});if(!n)return(0,H.jsxs)(`main`,{"aria-busy":`true`,className:`benchmark-page benchmark-loading`,children:[(0,H.jsx)(Wp,{"aria-hidden":`true`}),(0,H.jsx)(`h1`,{children:`Reading benchmark study`}),(0,H.jsx)(`p`,{children:`Validating the public-safe dashboard packet…`})]});let l=n.design.metric_catalog.find(e=>e.role===`primary`)?.metric_name??`primary`,u=(n,r=e.runId)=>t({search:e=>({...e,view:n,runId:r})}),d=new URL(c.url).pathname;return(0,H.jsxs)(`main`,{className:`benchmark-page`,children:[(0,H.jsxs)(`header`,{className:`benchmark-hero`,children:[(0,H.jsxs)(`div`,{className:`benchmark-hero-topline`,children:[(0,H.jsx)(`a`,{className:`benchmark-wordmark`,href:`/chat/`,children:`LoopX`}),(0,H.jsxs)(`div`,{className:`benchmark-readonly`,children:[(0,H.jsx)(Gm,{"aria-hidden":`true`,size:15}),` Derived read-only projection`]})]}),(0,H.jsxs)(`div`,{className:`benchmark-hero-grid`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`p`,{className:`benchmark-kicker`,children:[`BENCHMARK STUDY / `,n.benchmark_id]}),(0,H.jsxs)(`div`,{className:`benchmark-title-row`,children:[(0,H.jsx)(`h1`,{children:n.design.labels.title??n.study_id}),(0,H.jsx)(JC,{tone:n.status===`complete`?`success`:`warning`,children:n.status})]}),(0,H.jsx)(`p`,{className:`benchmark-lead`,children:`One declared study, explicit denominators, and the same countability rules from campaign summary to exact run.`})]}),(0,H.jsxs)(`dl`,{className:`benchmark-identity`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Study`}),(0,H.jsx)(`dd`,{children:n.study_id})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Protocol`}),(0,H.jsx)(`dd`,{children:n.design.protocol_id})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`Case set`}),(0,H.jsx)(`dd`,{children:n.design.case_set.case_set_id})]})]})]}),(0,H.jsxs)(`div`,{className:`benchmark-kpi-grid`,children:[(0,H.jsxs)(`article`,{children:[(0,H.jsx)(um,{"aria-hidden":`true`}),(0,H.jsx)(`span`,{children:`Score-countable cells`}),(0,H.jsxs)(`strong`,{children:[n.campaign.selected_score_countable_cell_count,(0,H.jsxs)(`small`,{children:[` / `,n.campaign.intended_cell_denominator]})]}),(0,H.jsxs)(`p`,{children:[VC(n.campaign.selected_score_countable_coverage_rate),` declared coverage`]})]}),(0,H.jsxs)(`article`,{children:[(0,H.jsx)(om,{"aria-hidden":`true`}),(0,H.jsx)(`span`,{children:`Complete designs`}),(0,H.jsxs)(`strong`,{children:[n.campaign.complete_declared_design_case_count,(0,H.jsxs)(`small`,{children:[` / `,n.campaign.intended_case_count]})]}),(0,H.jsx)(`p`,{children:`Cases with every declared arm`})]}),(0,H.jsxs)(`article`,{children:[(0,H.jsx)(qp,{"aria-hidden":`true`}),(0,H.jsx)(`span`,{children:`Matched comparisons`}),(0,H.jsx)(`strong`,{children:n.campaign.matched_pair_countable_count}),(0,H.jsx)(`p`,{children:`Eligible pairs only`})]}),(0,H.jsxs)(`article`,{children:[(0,H.jsx)(Wp,{"aria-hidden":`true`}),(0,H.jsx)(`span`,{children:`In flight`}),(0,H.jsx)(`strong`,{children:n.campaign.in_flight_run_count}),(0,H.jsx)(`p`,{children:n.status===`provisional`?`Coverage remains provisional`:`Declared coverage complete`})]})]})]}),(0,H.jsxs)(`nav`,{"aria-label":`Benchmark dashboard views`,className:`benchmark-tabs`,children:[BC.map(t=>(0,H.jsx)(`button`,{"aria-current":e.view===t.id?`page`:void 0,onClick:()=>u(t.id),type:`button`,children:t.label},t.id)),(0,H.jsxs)(`button`,{className:`benchmark-refresh`,onClick:()=>s(e=>e+1),type:`button`,children:[(0,H.jsx)(Lm,{"aria-hidden":`true`,size:14}),` Refresh local readback`]})]}),(0,H.jsxs)(`div`,{className:`benchmark-content`,children:[e.view===`campaign`&&(0,H.jsx)(YC,{packet:n,primaryMetric:l}),e.view===`arms`&&(0,H.jsx)(XC,{packet:n}),e.view===`cases`&&(0,H.jsx)(ZC,{onOpenRun:e=>u(`runs`,e),packet:n,primaryMetric:l}),e.view===`runs`&&(0,H.jsx)($C,{onSelectRun:e=>u(`runs`,e),packet:n,selectedRunId:e.runId})]}),(0,H.jsxs)(`footer`,{className:`benchmark-footer`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(Gm,{"aria-hidden":`true`,size:16}),(0,H.jsxs)(`span`,{children:[`Scores: `,n.authority.score_source]}),(0,H.jsx)(`span`,{children:`Dashboard cannot launch, grade, or mutate runs.`})]}),(0,H.jsxs)(`code`,{title:d,children:[`local`,d]})]})]})}var tw=Y({goalId:G().optional().default(``),statusUrl:G().optional().default(``)}),nw=Y({goalId:G().optional().default(``),mode:_d([`showcase`,`developer`,`ops`]).optional().default(`showcase`),statusUrl:G().optional().default(``),todoLane:_d([`all`,`user`,`agent`]).optional().default(`all`),todoQuery:G().optional().default(``)}),rw=nw.omit({mode:!0}),iw=Y({dashboardUrl:G().optional().default(``),view:_d([`campaign`,`arms`,`cases`,`runs`]).optional().default(`campaign`),runId:G().optional().default(``)});function aw(){let e=`https://huangruiteng.github.io/loopx/docs/showcases/index.en.html`;return(0,V.useEffect)(()=>{window.location.replace(e)},[]),(0,H.jsx)(`a`,{href:e,children:`Open LoopX cases / 浏览案例`})}function ow({goalId:e,statusUrl:t}){let n=t?ih(t,window.location.href):null;return n?.error?(0,H.jsx)(`main`,{role:`alert`,children:n.error}):(0,H.jsx)(ri,{replace:!0,to:`/`,search:{goalId:e,statusUrl:t}})}function sw(){let e=dw.useSearch();return e.mode===`ops`?(0,H.jsx)(ow,{...e}):e.mode===`developer`?(0,H.jsx)(ri,{replace:!0,to:`/developers/projections`}):(0,H.jsx)(aw,{})}function cw(){return(0,H.jsx)(ow,{...fw.useSearch()})}var lw=Si({component:()=>(0,H.jsx)(ji,{}),errorComponent:()=>(0,H.jsxs)(`main`,{role:`alert`,className:`p-8`,children:[(0,H.jsx)(`h1`,{children:`页面暂时无法显示 / Page unavailable`}),(0,H.jsx)(`p`,{children:`请重新加载页面;这不会执行任务。 / Reloading does not execute tasks.`}),(0,H.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:`重新加载 / Reload`})]})}),uw=bi({getParentRoute:()=>lw,path:`/`,validateSearch:e=>tw.parse(e),component:pC}),dw=bi({getParentRoute:()=>lw,path:`/frontstage`,validateSearch:e=>nw.parse(e),component:sw}),fw=bi({getParentRoute:()=>lw,path:`/deprecated/frontstage/ops`,validateSearch:e=>rw.parse(e),component:cw}),pw=bi({getParentRoute:()=>lw,path:`/frontstage/developer`,component:()=>(0,H.jsx)(ri,{replace:!0,to:`/developers/projections`})}),mw=bi({getParentRoute:()=>lw,path:`/developers/projections`,component:DC}),hw=bi({getParentRoute:()=>lw,path:`/benchmarks/study`,validateSearch:e=>iw.parse(e),component:ew}),gw=lw.addChildren([uw,dw,fw,pw,mw,hw]);function _w(e){return!e||e===`/`||e===`./`?`/`:(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}var vw=Ii({routeTree:gw,basepath:_w(`/chat/`),trailingSlash:`preserve`}),yw=document.getElementById(`root`);if(!yw)throw Error(`Root element not found`);var bw=new Oe({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,staleTime:1e4}}});(0,Bi.createRoot)(yw).render((0,H.jsx)(Me,{client:bw,children:(0,H.jsx)(Ki,{children:(0,H.jsx)(zi,{router:vw})})}));
\ No newline at end of file
diff --git a/loopx/web/chat/index.html b/loopx/web/chat/index.html
index b9dec8b70b..14608220f5 100644
--- a/loopx/web/chat/index.html
+++ b/loopx/web/chat/index.html
@@ -18,8 +18,8 @@
content="LoopX 个人 Agent 工作区:在同一个频道里查看、纠偏并推进 Goal。"
/>
LoopX 个人 Agent 工作区
-
-
+
+
diff --git a/scripts/dsh_turn_host_adapter.py b/scripts/dsh_turn_host_adapter.py
index f4f0566db9..2922163cde 100755
--- a/scripts/dsh_turn_host_adapter.py
+++ b/scripts/dsh_turn_host_adapter.py
@@ -23,6 +23,7 @@
COMPLETED_PHASES,
DEFAULT_MODEL,
DEFAULT_PROVIDER,
+ DEFAULT_REASONING_EFFORT,
DEFAULT_SESSION_ROOT_NAME,
LOOPX_TURN_HOST_REQUEST_SCHEMA,
LOOPX_TURN_RESULT_SCHEMA,
diff --git a/tests/dsh_goal_mode_fake_runner.py b/tests/dsh_goal_mode_fake_runner.py
index e8fb944f01..1361e6177e 100644
--- a/tests/dsh_goal_mode_fake_runner.py
+++ b/tests/dsh_goal_mode_fake_runner.py
@@ -9,6 +9,8 @@
import json
+from loopx.control_plane.turn_driver.execution_profile import REASONING_EFFORTS
+
def run_dsh_turn(
*,
@@ -18,6 +20,7 @@ def run_dsh_turn(
session_root: str,
provider: str,
model: str,
+ reasoning_effort: str,
max_tokens: int | None,
cordis: str | None,
runtime_bin: str | None,
@@ -25,6 +28,12 @@ def run_dsh_turn(
) -> str:
assert prompt, "the adapter must deliver the bounded task body"
assert session_id, "the adapter must key the dsh session"
+ # The resolved managed execution profile is part of the runner contract, so
+ # a regression that drops it fails here instead of reaching a real endpoint.
+ assert provider and model, "the adapter must hand over the resolved profile"
+ assert reasoning_effort in REASONING_EFFORTS, (
+ "the adapter must hand over a supported reasoning effort"
+ )
return json.dumps(
{
"result_kind": "validated_progress",
diff --git a/tests/test_chat_dsh_adapter.py b/tests/test_chat_dsh_adapter.py
new file mode 100644
index 0000000000..cfead4074a
--- /dev/null
+++ b/tests/test_chat_dsh_adapter.py
@@ -0,0 +1,177 @@
+"""The steward's managed-host transport runs one bounded, read-only segment."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from loopx.chat import CHAT_REVIEW_CLOSE_TAG, CHAT_REVIEW_OPEN_TAG
+from loopx.chat_agent import CodexChatAgentError
+from loopx.chat_dsh import (
+ HISTORY_LIMIT,
+ MANAGED_HOST_CHAT_FAILED,
+ MANAGED_HOST_CHAT_TIMEOUT,
+ STEWARD_SEGMENT_ENV,
+ DshChatAdapter,
+)
+
+
+class _Runner:
+ """Records the segment input and returns a scripted outcome."""
+
+ def __init__(self, outcome: Any) -> None:
+ self.outcome = outcome
+ self.calls: list[dict[str, Any]] = []
+
+ def __call__(self, **kwargs: Any) -> Any:
+ self.calls.append(kwargs)
+ return self.outcome
+
+
+def _envelope(message: str) -> str:
+ payload = {
+ "message": message,
+ "proposals": [],
+ "protected_action": None,
+ "context_handoff": None,
+ "gate": None,
+ }
+ return (
+ "visible answer\n"
+ + CHAT_REVIEW_OPEN_TAG
+ + json.dumps(payload)
+ + CHAT_REVIEW_CLOSE_TAG
+ )
+
+
+def _adapter(runner: _Runner, tmp_path: Path) -> DshChatAdapter:
+ return DshChatAdapter(
+ objective="You are the LoopX manager.",
+ work_dir=tmp_path,
+ provider="deepseek-official",
+ model="deepseek-v4-flash",
+ reasoning_effort="high",
+ runner=runner,
+ )
+
+
+def test_a_segment_carries_the_resolved_profile_and_a_read_only_boundary(
+ tmp_path: Path,
+) -> None:
+ runner = _Runner({"final_response": _envelope("answer"), "finish_reason": "stop"})
+ events: list[tuple[str, dict[str, Any]]] = []
+
+ response = _adapter(runner, tmp_path).start_turn(
+ "status please", lambda kind, payload: events.append((kind, payload))
+ )
+
+ call = runner.calls[0]
+ assert call["provider"] == "deepseek-official"
+ assert call["model"] == "deepseek-v4-flash"
+ assert call["reasoning_effort"] == "high"
+ # The channel pins its own segments read-only; dsh enforces it.
+ assert call["env"] == STEWARD_SEGMENT_ENV
+ assert call["session_root"] == tmp_path / ".local" / ".dsh-sessions"
+ assert response["message"] == "answer"
+ assert [kind for kind, _payload in events] == [
+ "turn.started",
+ "agent.phase",
+ "answer.delta",
+ "answer.final",
+ ]
+
+
+def test_the_segment_input_keeps_the_channel_objective_and_turn_contract(
+ tmp_path: Path,
+) -> None:
+ runner = _Runner({"final_response": _envelope("answer")})
+
+ _adapter(runner, tmp_path).start_turn("status please", lambda *_args: None)
+
+ prompt = runner.calls[0]["prompt"]
+ assert prompt.startswith("You are the LoopX manager.")
+ assert "Operator user message:\nstatus please" in prompt
+ assert CHAT_REVIEW_OPEN_TAG in prompt
+
+
+def test_an_empty_final_message_fails_closed(tmp_path: Path) -> None:
+ runner = _Runner({"final_response": "", "finish_reason": "error"})
+
+ with pytest.raises(CodexChatAgentError) as raised:
+ _adapter(runner, tmp_path).start_turn("status please", lambda *_args: None)
+
+ assert raised.value.error_code == MANAGED_HOST_CHAT_FAILED
+
+
+def test_an_unreadable_segment_result_fails_closed(tmp_path: Path) -> None:
+ runner = _Runner(["not", "a", "mapping"])
+
+ with pytest.raises(CodexChatAgentError) as raised:
+ _adapter(runner, tmp_path).start_turn("status please", lambda *_args: None)
+
+ assert raised.value.error_code == MANAGED_HOST_CHAT_FAILED
+
+
+def test_a_raising_runner_surfaces_one_typed_failure(tmp_path: Path) -> None:
+ def failing(**_kwargs: Any) -> Any:
+ raise RuntimeError("provider detail that must not become the error code")
+
+ adapter = DshChatAdapter(
+ objective="objective",
+ work_dir=tmp_path,
+ provider="deepseek-official",
+ model="deepseek-v4-flash",
+ reasoning_effort="high",
+ runner=failing,
+ )
+
+ with pytest.raises(CodexChatAgentError) as raised:
+ adapter.start_turn("status please", lambda *_args: None)
+
+ assert raised.value.error_code == MANAGED_HOST_CHAT_FAILED
+ assert "provider detail" not in raised.value.error_code
+
+
+def test_a_segment_that_never_returns_times_out(tmp_path: Path) -> None:
+ import threading
+
+ release = threading.Event()
+ try:
+ adapter = DshChatAdapter(
+ objective="objective",
+ work_dir=tmp_path,
+ provider="deepseek-official",
+ model="deepseek-v4-flash",
+ reasoning_effort="high",
+ timeout_sec=0.05,
+ runner=lambda **_kwargs: release.wait(5),
+ )
+
+ with pytest.raises(CodexChatAgentError) as raised:
+ adapter.start_turn("status please", lambda *_args: None)
+ finally:
+ release.set()
+
+ assert raised.value.error_code == MANAGED_HOST_CHAT_TIMEOUT
+
+
+def test_visible_history_is_bounded_and_reaches_the_next_segment(
+ tmp_path: Path,
+) -> None:
+ runner = _Runner({"final_response": _envelope("first answer")})
+ adapter = _adapter(runner, tmp_path)
+ adapter.start_turn("first question", lambda *_args: None)
+ runner.outcome = {"final_response": _envelope("second answer")}
+
+ adapter.start_turn("second question", lambda *_args: None)
+
+ assert adapter.history == [
+ {"role": "user", "content": "first question"},
+ {"role": "assistant", "content": "first answer"},
+ {"role": "user", "content": "second question"},
+ {"role": "assistant", "content": "second answer"},
+ ]
+ assert len(adapter.history) <= HISTORY_LIMIT
diff --git a/tests/test_dsh_goal_mode.py b/tests/test_dsh_goal_mode.py
index 98e52d0a24..ef39b7825f 100644
--- a/tests/test_dsh_goal_mode.py
+++ b/tests/test_dsh_goal_mode.py
@@ -544,6 +544,7 @@ def test_build_sdk_config_targets_the_current_sdk_surface(tmp_path: Path) -> Non
config = turn_host_adapter.build_sdk_config(
provider="deepseek-official",
model="deepseek-v4-flash",
+ reasoning_effort="high",
workspace=tmp_path,
dsh_home=dsh_home,
max_tokens=1024,
@@ -554,6 +555,7 @@ def test_build_sdk_config_targets_the_current_sdk_surface(tmp_path: Path) -> Non
assert set(config) <= {
"provider",
"model",
+ "reasoning_effort",
"cwd",
"dsh_home",
"max_tokens",
@@ -561,6 +563,7 @@ def test_build_sdk_config_targets_the_current_sdk_surface(tmp_path: Path) -> Non
"dsh_bin",
"request_timeout_seconds",
}
+ assert config["reasoning_effort"] == "high"
assert config["dsh_home"] == str(dsh_home)
assert config["dsh_bin"] == "/opt/dsh/bin/dsh"
assert config["patches"] == (str(cordis.expanduser().resolve()),)
@@ -568,6 +571,84 @@ def test_build_sdk_config_targets_the_current_sdk_surface(tmp_path: Path) -> Non
assert legacy_field not in config
+def test_build_sdk_config_omits_an_unset_reasoning_effort(tmp_path: Path) -> None:
+ # A caller that explicitly passes no effort must not have one invented for
+ # it: the SDK distinguishes "provider default" from a named effort.
+ config = turn_host_adapter.build_sdk_config(
+ provider="deepseek-official",
+ model="deepseek-v4-flash",
+ reasoning_effort=None,
+ workspace=tmp_path,
+ dsh_home=tmp_path / "dsh-home",
+ max_tokens=None,
+ cordis=None,
+ runtime_bin=None,
+ request_timeout_seconds=None,
+ )
+ assert "reasoning_effort" not in config
+
+
+def test_build_sdk_config_carries_a_caller_pinned_runtime_environment(
+ tmp_path: Path,
+) -> None:
+ # A Chat channel pins its own segments read-only through the runtime
+ # environment; the adapter forwards it instead of reinterpreting it.
+ config = turn_host_adapter.build_sdk_config(
+ provider="deepseek-official",
+ model="deepseek-v4-flash",
+ reasoning_effort="high",
+ workspace=tmp_path,
+ dsh_home=tmp_path / "dsh-home",
+ max_tokens=None,
+ cordis=None,
+ runtime_bin=None,
+ request_timeout_seconds=None,
+ env={"DSH_PERMISSION_MODE": "read-only"},
+ )
+ assert config["env"] == {"DSH_PERMISSION_MODE": "read-only"}
+
+ unpinned = turn_host_adapter.build_sdk_config(
+ provider="deepseek-official",
+ model="deepseek-v4-flash",
+ reasoning_effort="high",
+ workspace=tmp_path,
+ dsh_home=tmp_path / "dsh-home",
+ max_tokens=None,
+ cordis=None,
+ runtime_bin=None,
+ request_timeout_seconds=None,
+ )
+ assert "env" not in unpinned
+
+
+def test_host_config_resolves_the_shared_managed_profile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("LOOPX_TURN_MODEL", raising=False)
+ monkeypatch.delenv("DSH_MODEL", raising=False)
+ profile = turn_host_adapter.DshHostConfig(workspace=tmp_path).resolved_profile()
+ assert (
+ profile["provider"],
+ profile["model"],
+ profile["reasoning_effort"],
+ ) == (
+ turn_host_adapter.DEFAULT_PROVIDER,
+ turn_host_adapter.DEFAULT_MODEL,
+ turn_host_adapter.DEFAULT_REASONING_EFFORT,
+ )
+ assert profile["model_source"] == "product_default"
+
+ monkeypatch.setenv("LOOPX_TURN_MODEL", "fixture-model")
+ overridden = turn_host_adapter.DshHostConfig(
+ workspace=tmp_path, model="argument-model"
+ ).resolved_profile()
+ assert overridden["model"] == "argument-model"
+ assert overridden["model_source"] == "explicit_argument"
+ # An explicit field wins alone: the others still follow the environment.
+ assert overridden["reasoning_effort"] == turn_host_adapter.DEFAULT_REASONING_EFFORT
+
+
def test_dsh_home_resolution_prefers_config_then_environment(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -577,11 +658,11 @@ def test_dsh_home_resolution_prefers_config_then_environment(
environment = tmp_path / "environment-home"
monkeypatch.setenv("DSH_HOME", str(environment))
- assert turn_host_adapter._resolve_dsh_home(workspace, configured) == configured
- assert turn_host_adapter._resolve_dsh_home(workspace, None) == environment
+ assert turn_host_adapter.resolve_dsh_home(workspace, configured) == configured
+ assert turn_host_adapter.resolve_dsh_home(workspace, None) == environment
monkeypatch.delenv("DSH_HOME")
- assert turn_host_adapter._resolve_dsh_home(workspace, None) == (
+ assert turn_host_adapter.resolve_dsh_home(workspace, None) == (
workspace / ".local" / ".dsh-sessions"
)
diff --git a/tests/test_manager_channel_binding.py b/tests/test_manager_channel_binding.py
index b6ff43ebdd..7c585c7332 100644
--- a/tests/test_manager_channel_binding.py
+++ b/tests/test_manager_channel_binding.py
@@ -1,4 +1,4 @@
-"""The steward channel selects its executor explicitly; a credential only authenticates."""
+"""The steward channel resolves one disclosed default for its executor and model."""
from __future__ import annotations
@@ -6,16 +6,18 @@
import pytest
-from loopx.chat_agent import (
- MANAGED_HOST_CHAT_TRANSPORT_UNSUPPORTED,
- CodexChatAgentError,
-)
+from loopx.chat_agent import CodexChatAgentError
from loopx.capabilities.manager_runtime import manager_runtime_capability_projection
from loopx.chat_manager import (
+ MANAGER_ENDPOINT_DEFAULT_MANAGED,
+ MANAGER_ENDPOINT_DEFAULT_REASON_CREDENTIAL_ABSENT,
+ MANAGER_ENDPOINT_DEFAULT_REASON_CREDENTIAL_CONFIGURED,
MANAGER_ENDPOINT_SOURCE_EXPLICIT_CONFIG,
MANAGER_ENDPOINT_SOURCE_PRODUCT_DEFAULT,
+ MANAGER_MODEL_SOURCE_MANAGED_PROFILE,
MANAGER_MODEL_SOURCE_ENV_OVERRIDE,
MANAGER_MODEL_SOURCE_VENDOR_DEFAULT,
+ manager_endpoint_default_reason,
manager_channel_binding,
manager_executor_endpoint_default,
manager_model_config,
@@ -24,9 +26,12 @@
)
from loopx.chat_runtime import ChatRuntimeController
from loopx.chat_store import ChatSessionStore
+from loopx.control_plane.turn_driver import host_binding
+
+def test_without_the_operator_credential_the_channel_stays_on_the_cli_endpoint():
+ """A machine with only a personal login must keep a reachable steward."""
-def test_the_shipped_steward_channel_defaults_to_the_cli_endpoint():
binding = manager_channel_binding({})
assert (
@@ -35,35 +40,68 @@ def test_the_shipped_steward_channel_defaults_to_the_cli_endpoint():
assert (
binding["executor_endpoint_source"] == MANAGER_ENDPOINT_SOURCE_PRODUCT_DEFAULT
)
+ assert (
+ binding["executor_endpoint_default_reason"]
+ == manager_endpoint_default_reason({})
+ == MANAGER_ENDPOINT_DEFAULT_REASON_CREDENTIAL_ABSENT
+ )
assert binding["executor_kind"] == "individual"
assert binding["credential_env_var"] == ""
assert binding["operator_credential_configured"] is False
+ assert binding["execution_profile"] is None
assert binding["available"] is None
assert binding["unavailable_reason"] is None
assert binding["model"] == "gpt-6-astra"
assert binding["model_source"] == MANAGER_MODEL_SOURCE_VENDOR_DEFAULT
-def test_a_configured_credential_never_re_points_the_steward_channel():
- """Discovering a provider key must not change the executor or the model."""
+def test_the_shipped_default_follows_the_operator_credential_it_reports():
+ """One reported local fact decides the default, and the readback names it."""
without = manager_channel_binding({})
with_credential = manager_channel_binding({"DEEPSEEK_API_KEY": "fixture"})
- assert with_credential["executor_endpoint"] == without["executor_endpoint"]
+ assert without["executor_endpoint"] == "codex"
+ assert (
+ with_credential["executor_endpoint"]
+ == MANAGER_ENDPOINT_DEFAULT_MANAGED
+ == manager_executor_endpoint_default({"DEEPSEEK_API_KEY": "fixture"})
+ )
assert (
with_credential["executor_endpoint_source"]
== without["executor_endpoint_source"]
== MANAGER_ENDPOINT_SOURCE_PRODUCT_DEFAULT
)
- assert with_credential["model"] == without["model"] == "gpt-6-astra"
- assert with_credential["model_source"] == MANAGER_MODEL_SOURCE_VENDOR_DEFAULT
- # The credential stays a reported fact, not a selection signal.
+ assert (
+ with_credential["executor_endpoint_default_reason"]
+ == MANAGER_ENDPOINT_DEFAULT_REASON_CREDENTIAL_CONFIGURED
+ )
+ # The model follows the executor: the managed host runs the same execution
+ # profile a governed Turn runs, so the channel and its workers agree.
+ assert with_credential["model"] == "deepseek-v4-flash"
+ assert with_credential["model_source"] == MANAGER_MODEL_SOURCE_MANAGED_PROFILE
+ # One line, the same shape the governed Turn readback publishes, so the
+ # channel and its workers cannot report two different managed profiles.
+ assert with_credential["execution_profile"] == "deepseek-v4-flash@high"
assert with_credential["operator_credential_configured"] is True
- assert with_credential["credential_env_var"] == ""
+ assert with_credential["credential_env_var"] == "DEEPSEEK_API_KEY"
assert "fixture" not in json.dumps(with_credential)
+def test_an_explicit_endpoint_selection_reports_no_default_reason():
+ binding = manager_channel_binding(
+ {"LOOPX_MANAGER_ENDPOINT": "codex", "DEEPSEEK_API_KEY": "fixture"}
+ )
+
+ # The operator overruled the conditional default, so the projection must not
+ # claim a shipped-default reason for the endpoint it resolved.
+ assert binding["executor_endpoint"] == "codex"
+ assert binding["executor_endpoint_source"] == MANAGER_ENDPOINT_SOURCE_EXPLICIT_CONFIG
+ assert binding["executor_endpoint_default_reason"] == ""
+ assert binding["model"] == "gpt-6-astra"
+ assert binding["execution_profile"] is None
+
+
def test_an_explicit_endpoint_selection_wins_over_the_shipped_default():
endpoint, source = selected_manager_executor_endpoint(
{"LOOPX_MANAGER_ENDPOINT": "fixture-endpoint"}
@@ -76,15 +114,20 @@ def test_an_explicit_endpoint_selection_wins_over_the_shipped_default():
assert manager_executor_endpoint_default({"LOOPX_MANAGER_ENDPOINT": " "}) == "codex"
-def test_selecting_the_managed_host_reports_the_missing_chat_transport():
- """The managed host is a bounded Turn host, so the channel fails closed."""
+def test_selecting_the_managed_host_quotes_the_turn_executor_verdict():
+ """The channel cannot advertise an executor the Turn driver would refuse."""
binding = manager_channel_binding({"LOOPX_MANAGER_ENDPOINT": "dsh"})
assert binding["executor_endpoint"] == "dsh"
assert binding["executor_kind"] == "managed"
assert binding["available"] is False
- assert binding["unavailable_reason"] == MANAGED_HOST_CHAT_TRANSPORT_UNSUPPORTED
+ # The blocking fact is the credential or a missing runtime, and either way
+ # the channel fails closed instead of running on an unauthenticated host.
+ assert binding["unavailable_reason"] in {
+ "operator_credential_unconfigured",
+ "dsh_runtime_unavailable",
+ }
# An operator-billed endpoint names the credential it authenticates with.
assert binding["credential_env_var"] == ""
assert (
@@ -117,11 +160,15 @@ def test_explicit_model_override_wins_with_and_without_credential():
"model": "gpt-6-astra",
"reasoning_effort": "low",
}
+ # The managed effort is the same field the governed Turn surface resolves.
+ assert manager_model_config(
+ {"DEEPSEEK_API_KEY": "fixture", "LOOPX_TURN_REASONING_EFFORT": "max"}
+ ) == {"model": "deepseek-v4-flash", "reasoning_effort": "max"}
def test_manager_model_config_reads_the_process_environment(monkeypatch):
monkeypatch.delenv("LOOPX_MANAGER_MODEL", raising=False)
- monkeypatch.setenv("DEEPSEEK_API_KEY", "fixture")
+ monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
assert manager_model_config()["model"] == "gpt-6-astra"
@@ -147,7 +194,19 @@ def open_session(self, **kwargs):
assert calls[-1]["agent_id"] == "claude-code"
-def test_managed_host_without_a_chat_transport_raises_a_typed_gate(tmp_path):
+def _managed_endpoint_failure(tmp_path, monkeypatch, *, runtime_installed):
+ """Open the managed endpoint with its availability probe pinned.
+
+ Which typed reason appears must follow the fact under test, not whether the
+ machine running the suite happens to have the dsh runtime installed, so the
+ probe is pinned here instead of being read from the environment.
+ """
+
+ monkeypatch.setattr(
+ host_binding,
+ "dsh_runtime_importable",
+ lambda *args, **kwargs: runtime_installed,
+ )
runtime = ChatRuntimeController(
store=ChatSessionStore(tmp_path / "store"), codex_bin="fixture-codex"
)
@@ -162,10 +221,36 @@ def test_managed_host_without_a_chat_transport_raises_a_typed_gate(tmp_path):
)
finally:
runtime.close()
+ return raised.value
+
+
+def test_a_managed_host_without_a_credential_raises_the_credential_gate(
+ tmp_path, monkeypatch
+):
+ # The runtime is present and no operator credential is: the fact that blocks
+ # this launch is the credential, so the typed gate must name it.
+ monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
+
+ error = _managed_endpoint_failure(tmp_path, monkeypatch, runtime_installed=True)
+
+ assert error.error_code == "agent_endpoint_unavailable"
+ assert error.gate["kind"] == "host_tool_gate"
+ assert "DEEPSEEK_API_KEY" in error.gate["next_action"]
+
+
+def test_a_managed_host_without_its_runtime_names_the_install_step(
+ tmp_path, monkeypatch
+):
+ # The credential is configured and the runtime is missing, so the launch is
+ # blocked by the runtime instead; the gate must name that repair, not the
+ # credential the operator already set.
+ monkeypatch.setenv("DEEPSEEK_API_KEY", "fixture")
+
+ error = _managed_endpoint_failure(tmp_path, monkeypatch, runtime_installed=False)
- assert raised.value.error_code == MANAGED_HOST_CHAT_TRANSPORT_UNSUPPORTED
- assert raised.value.gate["kind"] == "host_tool_gate"
- assert "loopx turn" in raised.value.gate["next_action"]
+ assert error.error_code == "agent_endpoint_unavailable"
+ assert error.gate["kind"] == "host_tool_gate"
+ assert "pip install" in error.gate["next_action"]
def test_unknown_endpoint_keeps_the_untyped_lookup_error(tmp_path):
diff --git a/tests/test_turn_managed_executor_binding.py b/tests/test_turn_managed_executor_binding.py
index fddd1b9e99..48cc9c33ec 100644
--- a/tests/test_turn_managed_executor_binding.py
+++ b/tests/test_turn_managed_executor_binding.py
@@ -15,6 +15,14 @@
managed_executor_binding,
resolve_default_turn_host,
)
+from loopx.control_plane.turn_driver.execution_profile import (
+ INVALID_REASONING_EFFORT,
+ MANAGED_MODEL_DEFAULT,
+ MANAGED_PROVIDER_DEFAULT,
+ MANAGED_REASONING_EFFORT_DEFAULT,
+ managed_execution_profile,
+ managed_execution_profile_line,
+)
_NO_RUNTIME = lambda _module: False # noqa: E731 - tiny probe fixture
_RUNTIME = lambda _module: True # noqa: E731 - tiny probe fixture
@@ -36,6 +44,11 @@ def test_managed_executor_reports_the_operator_credential_and_endpoint():
"executor_kind": EXECUTOR_KIND_MANAGED,
"credential_env": "DEEPSEEK_API_KEY",
"endpoint_env": "DEEPSEEK_BASE_URL",
+ # The agent-facing payload names what would run, not the shipped
+ # constants it agrees with.
+ "execution_profile": (
+ f"{MANAGED_MODEL_DEFAULT}@{MANAGED_REASONING_EFFORT_DEFAULT}"
+ ),
"operator_credential_bound": True,
"available": True,
"unavailable_reason": None,
@@ -176,3 +189,93 @@ def test_endpoint_without_credential_is_reported_but_does_not_switch_host():
assert resolve_default_turn_host(environ) == MANAGED_TURN_HOST
assert binding["endpoint_env"] is None
+
+
+def test_managed_binding_projects_the_execution_profile_and_its_source():
+ binding = managed_executor_binding(
+ "dsh",
+ environ={
+ "DEEPSEEK_API_KEY": "sk-operator",
+ "LOOPX_TURN_MODEL": "fixture-model",
+ "LOOPX_TURN_REASONING_EFFORT": "max",
+ },
+ module_probe=_RUNTIME,
+ )
+
+ # An owner-set value appears as itself, so it is never read as the shipped
+ # default; the shipped provider is not restated.
+ assert binding["execution_profile"] == "fixture-model@max"
+ # An explicit argument outranks the environment and says so.
+ overridden = managed_executor_binding(
+ "dsh",
+ environ={"DEEPSEEK_API_KEY": "sk-operator", "LOOPX_TURN_MODEL": "fixture-model"},
+ module_probe=_RUNTIME,
+ model="cli-model",
+ )["execution_profile"]
+ assert overridden == "cli-model@high"
+
+
+def test_a_deviating_provider_is_named_in_the_profile_line():
+ # Dropping the provider unconditionally would let the line claim a profile
+ # this Turn would not use, so a non-shipped provider is spelled out.
+ binding = managed_executor_binding(
+ "dsh",
+ environ={
+ "DEEPSEEK_API_KEY": "sk-operator",
+ "LOOPX_TURN_PROVIDER": "fixture-provider",
+ },
+ module_probe=_RUNTIME,
+ )
+
+ assert binding["execution_profile"] == "fixture-provider/deepseek-v4-flash@high"
+
+
+def test_non_managed_hosts_carry_no_execution_profile():
+ for host in ("codex-cli", "generic-cli"):
+ binding = managed_executor_binding(
+ host, environ={"DEEPSEEK_API_KEY": "sk-operator"}, module_probe=_RUNTIME
+ )
+
+ assert binding["execution_profile"] is None, binding
+
+
+def test_an_unsupported_effort_fails_closed_before_launch():
+ # The endpoint rejects an effort outside its vocabulary, so the readback
+ # refuses instead of letting a bounded Turn spend itself on that request.
+ binding = managed_executor_binding(
+ "dsh",
+ environ={
+ "DEEPSEEK_API_KEY": "sk-operator",
+ "LOOPX_TURN_REASONING_EFFORT": "turbo",
+ },
+ module_probe=_RUNTIME,
+ )
+
+ # The refused effort is visible next to the typed verdict, so a reader does
+ # not have to re-derive which configured value the endpoint rejected.
+ assert binding["execution_profile"] == "deepseek-v4-flash@turbo"
+ assert binding["available"] is False
+ assert binding["unavailable_reason"] == INVALID_REASONING_EFFORT
+
+
+def test_a_missing_launch_fact_still_outranks_the_profile_verdict():
+ binding = managed_executor_binding(
+ "dsh",
+ environ={"LOOPX_TURN_REASONING_EFFORT": "turbo"},
+ module_probe=_RUNTIME,
+ )
+
+ # One typed reason per readback: the missing credential is the fact that
+ # decides whether this executor launches at all.
+ assert binding["unavailable_reason"] == OPERATOR_CREDENTIAL_UNCONFIGURED
+ assert binding["execution_profile"] == "deepseek-v4-flash@turbo"
+
+
+def test_the_agent_facing_profile_line_stays_one_bounded_line():
+ shipped = managed_execution_profile_line(managed_execution_profile({}))
+
+ assert shipped == f"{MANAGED_MODEL_DEFAULT}@{MANAGED_REASONING_EFFORT_DEFAULT}"
+ assert MANAGED_PROVIDER_DEFAULT not in shipped
+ # The budget this line has to fit is per planned Turn, so it must stay far
+ # below the object form's ~360 characters.
+ assert len(shipped) < 64