Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

52.6 KB
Raw Blame
import{A as e,N as t,d as n,j as r,k as i,m as a,n as o,p as s,r as c,t as l,u,y as d}from"./served-from-8DzM0VAM.js";import{F as f,g as p,h as m,k as h,l as g,t as _}from"./parse-sse-frame-DXl4zDFf.js";function v(e=globalThis.document){return e?.querySelector(`meta[name="cmem-work-owner"]`)?.getAttribute(`content`)?.trim()||null}function y(e){globalThis.window?.dispatchEvent(new Event(e))}function b(e){return e.pathname===`/api/work-view`||e.pathname.startsWith(`/api/work-view/`)||e.pathname===`/api/cloud-sync/renewal-status`}function x(e,t,n,r){return async(i,a)=>{let o=new URL(i instanceof Request?i.url:String(i),t);if(o.origin!==t.origin||!b(o))return n(i,a);let s=new Request(i instanceof Request?i:o,{...a,redirect:`error`});s.headers.set(`X-Work-Session`,e);let c=s.method===`POST`&&o.pathname.startsWith(`/api/work-view/`);c&&!s.headers.has(`Idempotency-Key`)&&s.headers.set(`Idempotency-Key`,crypto.randomUUID());let l;try{l=await n(c?s.clone():s)}catch(e){if(!c||s.signal.aborted||!(e instanceof TypeError))throw e;l=await n(s)}if(l.status===401&&r(),l.status===409||l.status===403){let e=await l.clone().json().catch(()=>null);(e?.code===`owner_changed`||e?.code===`not_entitled`)&&r()}return l}}var S=t(r(),1),C=Object.defineProperty,w=(e,t)=>C(e,`name`,{value:t,configurable:!0}),T=S.useInsertionEffect;function E(e){let t=S.useRef(e);return typeof T==`function`?T(()=>{t.current=e}):n(()=>{t.current=e}),S.useMemo(()=>((...e)=>t.current?.(...e)),[])}w(E,`useCallbackRef`);var D=i(),O=Object.defineProperty,k=(e,t)=>O(e,`name`,{value:t,configurable:!0}),A=`dismissableLayer.update`,ee=`dismissableLayer.pointerDownOutside`,te=`dismissableLayer.focusOutside`,j,M=S.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),N=S.forwardRef(k(function(e,t){let{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:c,onDismiss:l,...f}=e,p=S.useContext(M),[m,h]=S.useState(null),g=m?.ownerDocument??globalThis?.document,[,_]=S.useState({}),v=d(t,h),y=Array.from(p.layers),[b]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),x=b?y.indexOf(b):-1,C=m?y.indexOf(m):-1,w=p.layersWithOutsidePointerEventsDisabled.size>0,T=C>=x,O=S.useRef(!1),ee=I(e=>{a?.(e),c?.(e),e.defaultPrevented||l?.()},{ownerDocument:g,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:O,dismissableSurfaces:p.dismissableSurfaces,shouldHandlePointerDownOutside:S.useCallback(e=>{if(!(e instanceof Node))return!1;let t=[...p.branches].some(t=>t.contains(e));return T&&!t},[p.branches,T])}),te=L(e=>{if(r&&O.current)return;let t=e.target;[...p.branches].some(e=>e.contains(t))||(o?.(e),c?.(e),e.defaultPrevented||l?.())},g),N=m?C===y.length-1:!1,P=E(e=>{e.key===`Escape`&&(i?.(e),!e.defaultPrevented&&l&&(e.preventDefault(),l()))});return S.useEffect(()=>{if(N)return g.addEventListener(`keydown`,P,{capture:!0}),()=>g.removeEventListener(`keydown`,P,{capture:!0})},[g,N,P]),S.useEffect(()=>{if(m)return n&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(j=g.body.style.pointerEvents,g.body.style.pointerEvents=`none`),p.layersWithOutsidePointerEventsDisabled.add(m)),p.layers.add(m),R(),()=>{n&&(p.layersWithOutsidePointerEventsDisabled.delete(m),p.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=j))}},[m,g,n,p]),S.useEffect(()=>()=>{m&&(p.layers.delete(m),p.layersWithOutsidePointerEventsDisabled.delete(m),R())},[m,p]),S.useEffect(()=>{let e=k(()=>_({}),`handleUpdate`);return document.addEventListener(A,e),()=>document.removeEventListener(A,e)},[]),(0,D.jsx)(s.div,{...f,ref:v,style:{pointerEvents:w?T?`auto`:`none`:void 0,...e.style},onFocusCapture:u(e.onFocusCapture,te.onFocusCapture),onBlurCapture:u(e.onBlurCapture,te.onBlurCapture),onPointerDownCapture:u(e.onPointerDownCapture,ee.onPointerDownCapture)})},`DismissableLayer`));function P(){let e=S.useContext(M),[t,n]=S.useState(null);return S.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}k(P,`useDismissableLayerSurface`);var F=k(()=>!0,`IS_TRUE`);function I(e,t){let{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:o=F}=t,s=E(e),c=S.useRef(!1),l=S.useRef(!1),u=S.useRef(new Map),d=S.useRef(()=>{});return S.useEffect(()=>{function e(){l.current=!1,i.current=!1,u.current.clear()}k(e,`resetOutsideInteraction`);function t(){return Array.from(u.current.values()).some(Boolean)}k(t,`isOutsideInteractionIntercepted`);function f(e){if(!l.current)return;let t=e.target;t instanceof Node&&[...a].some(e=>e.contains(t))||u.current.set(e.type,!0),e.type===`click`&&window.setTimeout(()=>{l.current&&d.current()},0)}k(f,`handleInteractionCapture`);function p(e){l.current&&u.current.set(e.type,!1)}k(p,`handleInteractionBubble`);let m=k(a=>{if(a.target&&!c.current){let f=function(){n.removeEventListener(`click`,d.current);let r=t();e(),r||z(ee,s,p,{discrete:!0})};if(k(f,`handleAndDispatchPointerDownOutsideEvent`),!o(a.target)){n.removeEventListener(`click`,d.current),e(),c.current=!1;return}let p={originalEvent:a};l.current=!0,i.current=r&&a.button===0,u.current.clear(),!r||a.button!==0?f():(n.removeEventListener(`click`,d.current),d.current=f,n.addEventListener(`click`,d.current,{once:!0}))}else n.removeEventListener(`click`,d.current),e();c.current=!1},`handlePointerDown`),h=[`pointerup`,`mousedown`,`mouseup`,`touchstart`,`touchend`,`click`];for(let e of h)n.addEventListener(e,f,!0),n.addEventListener(e,p);let g=window.setTimeout(()=>{n.addEventListener(`pointerdown`,m)},0);return()=>{window.clearTimeout(g),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`click`,d.current);for(let e of h)n.removeEventListener(e,f,!0),n.removeEventListener(e,p)}},[n,s,r,i,a,o]),{onPointerDownCapture:k(()=>c.current=!0,`onPointerDownCapture`)}}k(I,`usePointerDownOutside`);function L(e,t=globalThis?.document){let n=E(e),r=S.useRef(!1);return S.useEffect(()=>{let e=k(e=>{e.target&&!r.current&&z(te,n,{originalEvent:e},{discrete:!1})},`handleFocus`);return t.addEventListener(`focusin`,e),()=>t.removeEventListener(`focusin`,e)},[t,n]),{onFocusCapture:k(()=>r.current=!0,`onFocusCapture`),onBlurCapture:k(()=>r.current=!1,`onBlurCapture`)}}k(L,`useFocusOutside`);function R(){let e=new CustomEvent(A);document.dispatchEvent(e)}k(R,`dispatchUpdate`);function z(e,t,n,{discrete:r}){let i=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?a(i,o):i.dispatchEvent(o)}k(z,`handleAndDispatchCustomEvent`);var B=Object.defineProperty,V=(e,t)=>B(e,`name`,{value:t,configurable:!0}),H=`focusScope.autoFocusOnMount`,U=`focusScope.autoFocusOnUnmount`,W={bubbles:!1,cancelable:!0},G=S.forwardRef(V(function(e,t){let{loop:n=!1,trapped:r=!1,branches:i,onMountAutoFocus:a,onUnmountAutoFocus:o,...c}=e,[l,u]=S.useState(null),f=E(a),p=E(o),m=S.useRef(null),h=d(t,u),g=S.useRef(i);S.useEffect(()=>{g.current=i});let _=S.useCallback(e=>e?l?.contains(e)?!0:!!g.current?.some(t=>t.contains(e)):!1,[l]),v=S.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;S.useEffect(()=>{if(r){let e=function(e){if(v.paused||!l)return;let t=e.target;_(t)?m.current=t:Z(m.current,{select:!0})},t=function(e){if(v.paused||!l)return;let t=e.relatedTarget;t!==null&&(_(t)||Z(m.current,{select:!0}))},n=function(e){if(document.activeElement===document.body)for(let t of e)t.removedNodes.length>0&&Z(l)};V(e,`handleFocusIn`),V(t,`handleFocusOut`),V(n,`handleMutations`),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t);let r=new MutationObserver(n);return l&&r.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t),r.disconnect()}}},[r,l,v.paused,_]),S.useEffect(()=>{if(l){se.add(v);let e=document.activeElement;if(!l.contains(e)){let t=new CustomEvent(H,W);l.addEventListener(H,f),l.dispatchEvent(t),t.defaultPrevented||(re(le(X(l)),{select:!0}),document.activeElement===e&&Z(l))}return()=>{l.removeEventListener(H,f);let t=l.ownerDocument,n=CustomEvent;setTimeout(()=>{let r=new n(U,W);l.addEventListener(U,p),l.dispatchEvent(r),r.defaultPrevented||Z(e??t.body,{select:!0}),l.removeEventListener(U,p),se.remove(v)},0)}}},[l,f,p,v]);let y=S.useCallback(e=>{if(!n&&!r||v.paused)return;let t=e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){let t=e.currentTarget,[r,a]=Y(t);r&&a?!e.shiftKey&&i===a?(e.preventDefault(),n&&Z(r,{select:!0})):e.shiftKey&&i===r&&(e.preventDefault(),n&&Z(a,{select:!0})):i===t&&e.preventDefault()}},[n,r,v.paused]);return(0,D.jsx)(s.div,{tabIndex:-1,...c,ref:h,onKeyDown:y})},`FocusScope`)),K=S.createContext(null);function ne({registry:e,children:t}){return e?(0,D.jsx)(K.Provider,{value:e,children:t}):t}V(ne,`FocusScopeBranchProvider`);function q(){let[e,t]=S.useState([]);return{nodes:e,registry:S.useMemo(()=>({add:V(e=>t(t=>t.includes(e)?t:[...t,e]),`add`),remove:V(e=>t(t=>t.filter(t=>t!==e)),`remove`)}),[])}}V(q,`useFocusScopeBranchRegistry`);function J(e){let t=S.useContext(K);S.useEffect(()=>{if(e&&t)return t.add(e),()=>t.remove(e)},[e,t])}V(J,`useFocusScopeBranch`);function re(e,{select:t=!1}={}){let n=document.activeElement;for(let r of e)if(Z(r,{select:t}),document.activeElement!==n)return}V(re,`focusFirst`);function Y(e){let t=X(e);return[ie(t,e),ie(t.reverse(),e)]}V(Y,`getTabbableEdges`);function X(e){let t=[],n=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:V(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}V(X,`getTabbableCandidates`);function ie(e,t){let n=typeof t.checkVisibility==`function`&&t.checkVisibility({checkVisibilityCSS:!0});for(let r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):ae(r,{upTo:t})))return r}V(ie,`findVisible`);function ae(e,{upTo:t}){if(getComputedStyle(e).visibility===`hidden`)return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display===`none`)return!0;e=e.parentElement}return!1}V(ae,`isHidden`);function oe(e){return e.tagName===`INPUT`&&typeof e.select==`function`}V(oe,`isSelectableInput`);function Z(e,{select:t=!1}={}){if(e&&e.focus){let n=(e.ownerDocument??document).activeElement;e.focus({preventScroll:!0}),e!==n&&oe(e)&&t&&e.select()}}V(Z,`focus`);var se=ce();function ce(){let e=[];return{add(t){let n=e[0];t!==n&&n?.pause(),e=Q(e,t),e.unshift(t)},remove(t){e=Q(e,t),e[0]?.resume()}}}V(ce,`createFocusScopesStack`);function Q(e,t){let n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}V(Q,`arrayRemove`);function le(e){return e.filter(e=>e.tagName!==`A`)}V(le,`removeLinks`);var ue=t(e(),1),de=Object.defineProperty,fe=S.forwardRef(((e,t)=>de(e,`name`,{value:t,configurable:!0}))(function(e,t){let{container:r,...i}=e,[a,o]=S.useState(!1);n(()=>o(!0),[]);let c=r||a&&globalThis?.document?.body;return c?ue.createPortal((0,D.jsx)(s.div,{...i,ref:t}),c):null},`Portal`)),pe=`[&:not(button)]:focus-visible:outline-1 [&:not(button)]:focus-visible:outline-solid [&:not(button)]:focus-visible:outline-ring [&:not(button)]:focus-visible:ring-3 [&:not(button)]:focus-visible:ring-ring/50`,me=`a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [role="menuitem"], [role="option"], [role="switch"], [role="checkbox"], [role="tab"]`,he=`a[href], area[href], button, input, select, textarea, iframe, summary, [tabindex], [contenteditable]:not([contenteditable="false"])`;function ge(e){return e.matches(me)}function _e(e){return e.matches(`:focus-visible`)}function ve(e,t){let n=S.useRef(``),r=S.useRef(!1);return{recordPointerDown(t){n.current=t.pointerType,r.current=e},toggleOnTap(e){n.current!==`touch`||ge(e.currentTarget)||(e.preventDefault(),t(!r.current))}}}function ye(e,t){typeof e==`function`?e(t):e&&(e.current=t)}function be(e,t,n,r){let{ref:i,tabIndex:a,onFocus:o,onPointerDown:s,onClick:c}=r,l=ve(e,t),u=S.useRef(null),[d,f]=S.useState(!1);S.useLayoutEffect(()=>{let e=u.current;e&&!e.matches(he)&&f(!0)},[]);let p=S.useCallback(e=>{u.current=e,ye(i,e)},[i]),m=a??(d?0:void 0);return{ref:p,...m===void 0?{}:{tabIndex:m},onFocus(e){o?.(e),!e.defaultPrevented&&!_e(e.currentTarget)&&n(e)},onPointerDown(e){s?.(e),l.recordPointerDown(e)},onClick(e){c?.(e),e.defaultPrevented||l.toggleOnTap(e)}}}var xe=new WeakMap;function Se(e,t){xe.set(e,t)}function Ce(e){let t=e instanceof HTMLElement&&e!==document.body?e:null,n=new Set;for(;t&&!n.has(t);){n.add(t);let e=t.closest(`[role="menu"]`),r=e?xe.get(e)?.current:null;if(!r)break;t=r}return t}var we=e=>e.closest(`[hidden], [inert]`)===null;function Te(e){let t=e=>[...document.querySelectorAll(e)].find(we)??null;return(e===null?null:t(`[data-request-opener="${CSS.escape(e)}"]`))??t(`[data-view-heading]`)}function Ee(e){let t=S.useRef(null),{onOpenAutoFocus:n,onCloseAutoFocus:r}=e;return{onOpenAutoFocus(e){t.current=Ce(document.activeElement),n?.(e)},onCloseAutoFocus(e){r?.(e);let n=t.current;if(t.current=null,e.defaultPrevented||!n)return;let i=n.isConnected&&we(n)?n:Te(null);i&&(e.preventDefault(),i.focus())}}}var De=[{tier:`everywhere`,label:`Everywhere`},{tier:`project`,label:`In a repo`},{tier:`situation`,label:`In a situation`}],Oe=(e,t)=>De.findIndex(({tier:t})=>t===e.tier)-De.findIndex(({tier:e})=>e===t.tier)||e.name.localeCompare(t.name),ke=[{id:`everywhere`,tier:`everywhere`,name:`Everywhere`},{id:`cmem-cloud`,tier:`project`,name:`Hosted app`},{id:`claude-mem`,tier:`project`,name:`claude-mem`},{id:`frustrated`,tier:`situation`,name:`When I’m frustrated`},{id:`designs`,tier:`situation`,name:`When reviewing designs`}],Ae=e=>e.status===`on`&&(e.setBy===`owner`||e.setBy===`approved`),je=e=>`rule-${e}`,Me=[{id:`autonomy`,scopeId:`everywhere`,setBy:`owner`,when:`my directive is clear`,then:`Execute it. Don’t follow up with a question.`,timesSeen:11,latestAt:`Oct 20`,latestDaysAgo:0,source:`you`,status:`on`,quotes:[{at:`CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`When the ask is clear, do it instead of asking me to confirm.`},{at:`CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`You can make routine approvals for me along the way.`}],records:[{kind:`Instructions`,label:`CLAUDE.md · Autonomy`,at:`Oct 9`},{kind:`Review`,label:`request-progress · 7 requests showed it`,at:`Oct 20`}]},{id:`no-draft-pr`,scopeId:`everywhere`,setBy:`owner`,when:`you open a pull request`,then:`Never open it as a draft.`,timesSeen:6,latestAt:`Oct 18`,latestDaysAgo:2,source:`you`,status:`on`,quotes:[{at:`CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`Open pull requests ready for review, not as drafts.`}],records:[{kind:`Instructions`,label:`CLAUDE.md · Pull requests`,at:`Oct 9`}]},{id:`no-plan-pr`,scopeId:`everywhere`,setBy:`owner`,when:`the work is a plan, research, spec or notes`,then:`Keep it in a gitignored folder. Never open a PR for it.`,timesSeen:4,latestAt:`Oct 19`,latestDaysAgo:1,source:`you`,status:`on`,quotes:[{at:`CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`Plans and notes stay out of pull requests.`}],records:[{kind:`Instructions`,label:`CLAUDE.md · Pull requests`,at:`Oct 9`}]},{id:`no-tmp`,scopeId:`everywhere`,setBy:`owner`,when:`you write scratch or temporary files`,then:`Keep them inside the project, in .scratch/. Never use /tmp.`,timesSeen:5,latestAt:`Oct 20`,latestDaysAgo:0,source:`you`,status:`on`,quotes:[{at:`CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`Keep scratch files inside the project so they can be reviewed.`}],records:[{kind:`Instructions`,label:`CLAUDE.md · File locations`,at:`Oct 9`}]},{id:`decide-not-counts`,scopeId:`everywhere`,setBy:`approved`,when:`you report results`,then:`Lead with what I need to decide, not raw counts.`,timesSeen:6,latestAt:`Oct 17`,latestDaysAgo:3,source:`request-progress`,status:`on`,quotes:[{at:`Oct 17, 7:36 am`,where:`prompt`,kind:`frustration`,quote:`i care less about how many tests pass than what changed`},{at:`Oct 14, 10:28 pm`,where:`prompt`,kind:`directive`,quote:`tell me what I need to know first`}],records:[{kind:`Review`,label:`request-progress · “Admin price page” review`,at:`Oct 17`},{kind:`Prompt`,label:`Claude Code · hosted app`,at:`Oct 17, 7:36 am`}]},{id:`done-ping`,scopeId:`everywhere`,setBy:`approved`,when:`a long background run finishes`,then:`Send me a done-ping.`,timesSeen:2,latestAt:`Oct 12`,latestDaysAgo:8,source:`owner-goals`,status:`off`,quotes:[{at:`Oct 12, 9:14 pm`,where:`prompt`,kind:`directive`,quote:`let me know when it finishes`}],records:[{kind:`Goals run`,label:`owner-goals · “How they want work done”`,at:`Oct 18`}]},{id:`real-data`,scopeId:`everywhere`,setBy:`learned`,when:`you show numbers`,then:`Use the real rollup data. Leave it empty rather than simulate or forecast.`,timesSeen:4,latestAt:`Oct 19`,latestDaysAgo:1,source:`request-progress`,status:`suggested`,quotes:[{at:`Oct 15, 10:51 pm`,where:`prompt`,kind:`frustration`,quote:`use the real rollup data we already have, not a simulated forecast`},{at:`Oct 19, 1:12 am`,where:`prompt`,kind:`directive`,quote:`pull the key number out of the data and explain it plainly`}],records:[{kind:`Review`,label:`request-progress · 4 requests showed it`,at:`Oct 20, 1:50 pm`},{kind:`Prompt`,label:`Claude Code · usage forecast`,at:`Oct 15, 10:51 pm`}]},{id:`model-cron`,scopeId:`cmem-cloud`,setBy:`owner`,when:`choosing the shared observer model`,then:`Let the scheduled check pick the cheapest suitable model. A manual choice lasts until the next check.`,timesSeen:3,latestAt:`Oct 11`,latestDaysAgo:9,source:`you`,status:`on`,quotes:[{at:`Oct 11 · CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`pick the lowest-priced suitable model on each scheduled check`}],records:[{kind:`Instructions`,label:`Project CLAUDE.md · Model policy`,at:`Oct 11`},{kind:`Prompt`,label:`Claude Code · model check`,at:`Oct 11`}]},{id:`model-0731`,scopeId:`cmem-cloud`,setBy:`owner`,when:`choosing the shared observer model`,then:`Pin one specific model release.`,timesSeen:2,latestAt:`Oct 9`,latestDaysAgo:11,source:`you`,status:`replaced`,replacedBy:{ruleId:`model-cron`,at:`Oct 11`},quotes:[{at:`Oct 9 · CLAUDE.md`,where:`CLAUDE.md`,kind:`correction`,quote:`use this one release for now instead of always following the latest`}],records:[{kind:`Instructions`,label:`Project CLAUDE.md · Pinned release`,at:`Oct 9`}]},{id:`model-latest`,scopeId:`cmem-cloud`,setBy:`owner`,when:`choosing the shared observer model`,then:`Always follow the latest model release.`,timesSeen:3,latestAt:`Oct 2`,latestDaysAgo:18,source:`you`,status:`replaced`,replacedBy:{ruleId:`model-0731`,at:`Oct 9`},quotes:[{at:`Oct 2 · CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`always follow the latest release automatically`}],records:[{kind:`Instructions`,label:`Project CLAUDE.md · Latest model`,at:`Oct 2`}]},{id:`top-up`,scopeId:`cmem-cloud`,setBy:`owner`,when:`the provider balance runs out`,then:`Top up credits instead of rerouting traffic.`,timesSeen:2,latestAt:`Oct 4`,latestDaysAgo:16,source:`you`,status:`on`,quotes:[{at:`Oct 4 · CLAUDE.md`,where:`CLAUDE.md`,kind:`correction`,quote:`An empty balance is fixed by topping up, not by changing the routing.`}],records:[{kind:`Instructions`,label:`Project CLAUDE.md · Provider rule`,at:`Oct 4`}]},{id:`pr-after-push`,scopeId:`cmem-cloud`,setBy:`owner`,when:`you push a finished change to a feature branch`,then:`Open a PR to main right away.`,timesSeen:3,latestAt:`Oct 16`,latestDaysAgo:4,source:`you`,status:`on`,quotes:[{at:`CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`Open the pull request as soon as the branch is pushed.`}],records:[{kind:`Instructions`,label:`Project CLAUDE.md`,at:`Oct 9`}]},{id:`money`,scopeId:`cmem-cloud`,setBy:`learned`,when:`you report on cloud sync`,then:`Say first whether sync is healthy for everyone.`,timesSeen:3,latestAt:`Oct 15`,latestDaysAgo:5,source:`owner-goals`,status:`suggested`,quotes:[{at:`Oct 15, 8:49 pm`,where:`prompt`,kind:`directive`,quote:`what i need to know is whether sync is healthy for everyone`}],records:[{kind:`Goals run`,label:`owner-goals · “Make cloud sync dependable”`,at:`Oct 20, 11:02 am`}]},{id:`mockups-first`,scopeId:`claude-mem`,setBy:`approved`,when:`you design a screen`,then:`Generate image mockups with the UI Redesign skill before writing code.`,timesSeen:5,latestAt:`Oct 19`,latestDaysAgo:1,source:`request-progress`,status:`on`,quotes:[{at:`Oct 19, 9:45 am`,where:`prompt`,kind:`correction`,quote:`make image mockups first, not HTML edits`},{at:`Oct 13, 3:29 pm`,where:`prompt`,kind:`directive`,quote:`still just generated mockups until i say code`}],records:[{kind:`Review`,label:`request-progress · “Top-layer mockups” review`,at:`Oct 19`}]},{id:`ui-kit`,scopeId:`claude-mem`,setBy:`owner`,when:`you build a live interactive UI`,then:`Build it in React on a real UI kit, never plain HTML.`,timesSeen:4,latestAt:`Oct 17`,latestDaysAgo:3,source:`you`,status:`on`,quotes:[{at:`Oct 17, 8:25 am`,where:`prompt`,kind:`directive`,quote:`i want it done with a ui kit`},{at:`Oct 17, 2:25 pm`,where:`prompt`,kind:`correction`,quote:`the react version we already agreed to`}],records:[{kind:`Prompt`,label:`Claude Code · work monitor`,at:`Oct 17, 8:23 am`}]},{id:`codex-design`,scopeId:`claude-mem`,setBy:`learned`,when:`a design pass is needed`,then:`Have Codex run it, with the UI Redesign skill actually loaded.`,timesSeen:2,latestAt:`Oct 20`,latestDaysAgo:0,source:`request-progress`,status:`suggested`,quotes:[{at:`Oct 19, 11:11 am`,where:`prompt`,kind:`correction`,quote:`i wanted Codex to run this design pass`},{at:`Oct 20, 11:08 am`,where:`prompt`,kind:`frustration`,quote:`doesn’t feel like it has the ‘ui redesign’ skill applied to it`}],records:[{kind:`Review`,label:`request-progress · “Goals redesign” review`,at:`Oct 20, 1:50 pm`}]},{id:`frustrated`,scopeId:`frustrated`,setBy:`owner`,when:`I’m frustrated or cursing`,then:`Stop. Write out what you think I want, ask “Is this it? Yes, no, or modify?”, and do nothing else until I answer.`,timesSeen:3,latestAt:`Oct 20`,latestDaysAgo:0,source:`you`,status:`on`,quotes:[{at:`CLAUDE.md`,where:`CLAUDE.md`,kind:`directive`,quote:`when I sound frustrated, pause and confirm what I want before going on`}],records:[{kind:`Instructions`,label:`CLAUDE.md · Frustration check`,at:`Oct 9`}]},{id:`keep-liked`,scopeId:`designs`,setBy:`approved`,when:`I say I like where a design is`,then:`Don’t redesign it. Push it to git and save it.`,timesSeen:2,latestAt:`Oct 16`,latestDaysAgo:4,source:`request-progress`,status:`on`,quotes:[{at:`Oct 16, 1:42 am`,where:`prompt`,kind:`praise`,quote:`i like where this is at so push this stuff to git and save it`}],records:[{kind:`Review`,label:`request-progress · “Work monitor cards” review`,at:`Oct 16`}]}],Ne={preferencesFound:14,newSuggestions:3,reviewsRead:23};function Pe(e){if(!e)return null;let{latestAt:t,latestDaysAgo:n,quotes:r,records:i,replacedBy:a,...o}=e;return JSON.stringify({...o,quotes:r.map(({at:e,...t})=>t),records:i.map(({at:e,...t})=>t),replacedBy:a?.ruleId??null})}function Fe(e,t){let n={};for(let r of e){let e=t[r.id];e&&e.version===Pe(r)&&(e.decision===`approved`&&Ae(r)&&(n[r.id]=`approved`),e.decision===`rejected`&&r.status===`dismissed`&&(n[r.id]=`rejected`))}return n}function Ie(e,t,n){return t!==null&&t===Pe(n.find(t=>t.id===e))}function Le(e,t,n,r){if(r)return e.rules.find(e=>e.id===r);let i=new Set(t.map(e=>e.id)),a=e.rules.filter(t=>{if(i.has(t.id)||t.setBy!==`owner`||t.when!==n.when||t.then!==n.then)return!1;let r=e.ruleScopes.find(e=>e.id===t.scopeId);return r?.tier===n.scopeTier&&(n.scopeTier===`everywhere`||r.name===n.scopeName)});return a.length===1?a[0]:void 0}var Re={realtime:`Mode: realtime with HTTP recovery.`,polling:`Mode: HTTP polling.`},ze=`Changes remaining: {count}.`,Be={notReported:`This worker has not reported synchronization freshness.`,stale:`The last confirmed cloud check is old; the live connection does not prove the replica is current.`,unconfirmed:`Cloud freshness has not been confirmed.`},Ve={unconfigured:`Cloud sync off`,unknown:`Cloud freshness unknown`,current:`Cloud data current`,"catching-up":`Cloud catching up`,paused:`Cloud sync paused`,offline:`Cloud sync unavailable`,partial:`Cloud sync incomplete`,stale:`Cloud freshness stale`},He=`Limited sync scope`;function Ue(e,t){let n=e.remaining;return[t(e.sentence),e.mode?t(Re[e.mode]):``,n===null?``:t(ze).replace(/\{count\}/g,()=>n)].filter(Boolean).join(` `)}function We(e,t){return e.detailParts?Ue(e.detailParts,t):e.detail}function Ge(e){let t=e;return!!t&&typeof t.configured==`boolean`&&[`unconfigured`,`unknown`,`current`,`catching-up`,`paused`,`offline`,`partial`,`stale`].includes(t.state)&&[`polling`,`realtime`,`disabled`].includes(t.mode)&&Number.isFinite(t.observedAt)&&typeof t.message==`string`&&(t.checkedAt===null||Number.isFinite(t.checkedAt))&&!!t.projection&&(t.projection.remaining===null||/^(0|[1-9]\d*)$/.test(t.projection.remaining))&&!!t.completeness&&Number.isSafeInteger(t.completeness.pushQuarantine)&&t.completeness.pushQuarantine>=0&&Number.isSafeInteger(t.completeness.pullQuarantine)&&t.completeness.pullQuarantine>=0&&[`eligible`,`local-history-excluded`,`unknown`].includes(t.completeness.scope)&&(t.download===null||typeof t.download==`object`&&(t.download.lastSuccessAt===null||Number.isFinite(t.download.lastSuccessAt)))}function Ke(e,t,n){if(!e){let e=Be.notReported;return{state:`unknown`,label:Ve.unknown,detail:e,detailParts:{sentence:e,mode:null,remaining:null},tone:`neutral`,isCurrent:!1}}if(!e.configured)return{state:`unconfigured`,label:Ve.unconfigured,detail:e.message,detailParts:{sentence:e.message,mode:null,remaining:null},tone:`neutral`,isCurrent:!1,pendingUpload:null};let r=e.upload?.pending,i=typeof r==`number`&&Number.isSafeInteger(r)&&r>=0?r:null,a=e.checkedAt,o=e.download?.lastSuccessAt??null,s=a===null||o===null||o>e.observedAt?null:a,c=s===null?null:e.observedAt-s,l=t===null?null:n-t,u=e.state;[`current`,`partial`,`catching-up`].includes(u)&&(c===null||l===null||c<0||l<0||!Number.isFinite(c+l)?u=`unknown`:c+l>6e4&&(u=`stale`));let d=u===`partial`&&e.completeness.scope===`local-history-excluded`&&e.completeness.pushQuarantine===0&&e.completeness.pullQuarantine===0,f={sentence:u===e.state?e.message:u===`stale`?Be.stale:Be.unconfirmed,mode:e.mode===`disabled`?null:e.mode,remaining:u===`catching-up`?e.projection.remaining:null},p=Ue(f,e=>e);return{state:u,label:d?He:Ve[u],detail:p,detailParts:f,tone:u===`current`?`positive`:d||u===`unknown`?`neutral`:`warning`,isCurrent:u===`current`,pendingUpload:i}}var qe=35e3,Je=125e3;function Ye(e,t){return t===null||!Number.isFinite(e)||!Number.isFinite(t)||e<0||t<0||t>e+1e3?null:Math.max(0,e-t)}function Xe(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return null;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function Ze({transportConnected:e=!1,reconnecting:t=!1,now:n,lastEventAt:r=null,sourceConnected:i=null,lastSuccessfulCheckAt:a=null,lastSuccessfulCheckReceivedAt:o=null,wallNow:s=null,staleAfterMs:c=qe,where:l=`local`,sync:u=null,syncReceivedAt:d=null,activityCheckedAt:f=null,activityAgeAtReceipt:p=null,activityReceivedAt:m=null}){let h=l===`cloud`,g=h?`cloud feed`:`local feed`,_=h?`Cloud feed`:`Local feed`,v=Number.isFinite(c)&&c>0?c:qe,y=Ye(n,r),b=Ye(n,o),x=Xe(a),S=x!==null&&s!==null&&Number.isFinite(s)&&b!==null&&Math.abs(s-Date.parse(x)-b)>6e4,C=`connecting`,w=`Connecting to ${g}`,T=h?`Waiting for updates synced from your computers.`:`Waiting for updates from this computer.`,E=`neutral`;e?y===null||y>v?r!==null&&(C=`stale`,w=`${_} stale`,E=`warning`,T=`${h?`Cloud`:`Local`} updates have stopped arriving. Showing the last received work.`):i===!1?(C=`unavailable`,w=`${h?`Cloud`:`Local`} source unavailable`,E=`warning`,T=`Connected, but saved work cannot be read right now. Showing the last received work.`):i===!0&&x!==null&&b!==null&&(b>v?(C=`stale`,w=`${_} stale`,E=`warning`,T=`Connected, but the saved work has not been refreshed. Showing the last received work.`):(C=`live`,w=`Live updates`,E=`positive`,T=h?`Connected to the cloud viewer. Incoming synchronization is reported separately.`:`Updates are arriving from this computer. Each card shows when its work was last updated.`)):t&&y!==null&&y>v?(C=`stale`,w=`${_} stale`,E=`warning`,T=`Reconnecting to ${h?`your cloud viewer`:`this computer`}. No fresh update has arrived; showing the last received work.`):t&&(C=`reconnecting`,w=`Reconnecting to ${g}`,E=`warning`,T=`Connection interrupted. Showing the last received work while the ${g} reconnects.`);let D=Ye(n,m),O=p===null||D===null?null:p+D;C===`live`&&f!==null&&(O===null||O<0||!Number.isFinite(O))?(C=`stale`,w=`Activity freshness unknown`,E=`warning`,T=`The feed is connected, but the age of its saved activity could not be confirmed.`):C===`live`&&O!==null&&O>Je&&(C=`stale`,w=`Saved activity stale`,E=`warning`,T=`The feed is connected, but its activity projection has not been refreshed. Showing the last received work.`);let k=`Last successful ${h?`cloud`:`local`} check: ${x??`not yet confirmed`}. `+(f?`Activity last inspected: ${f}. `:``)+(S?`Source and browser clocks differ; freshness uses received heartbeats. `:``)+`Connection status does not indicate an agent is running.`;return{state:C,label:w,detail:T,tone:E,isLive:C===`live`,eventAgeMs:y,sourceAgeMs:b,lastSuccessfulCheckAt:x,activityCheckedAt:Xe(f),clockSkew:S,staleAfterMs:v,tooltip:k,sync:Ke(u,d,n)}}function Qe(e){let t=e?.save;return t&&[`local`,`shared`].includes(t.scope??``)&&[`saved`,`queued`,`unchanged`].includes(t.state??``)?{scope:t.scope,state:t.state,...t.localMaterialization===`pending`?{localMaterialization:`pending`}:{}}:void 0}var $e=`This work changed while you were reading. Review the latest version before checking.`,et=`Checked locally.`,tt=`Check undone. The result is ready to review.`,nt=e=>{let t=e?.error;return typeof t==`string`&&t.trim()?t.trim():null};function rt(e,t){if(e===200){if(!t||typeof t!=`object`)throw Error(`The local review was saved, but the worker sent no work snapshot back. Reload to see it.`);let e=Qe(t);return{kind:`saved`,snapshot:t,...e?{save:e}:{}}}if(e===409){let e=t,n=e?.overview??e?.snapshot;return{kind:`conflict`,serverMessage:nt(t),...n?{snapshot:n}:{}}}if(e===503)return{kind:`unavailable`,serverMessage:nt(t)};throw Error(`The local review could not be saved (${e}): ${nt(t)??`the worker gave no reason`}`)}function it(e,t){return t===e?`refused`:`changed-while-reading`}var at=[`claude`,`codex`];function ot(e){return typeof e==`string`&&at.includes(e)}var st=[`running`,`replied`,`failed`],ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lt={claude:`claude --resume`,codex:`codex resume`};function ut(e,t){return!ot(e)||!ct.test(t)?null:`${lt[e]} ${t}`}function dt(e){return!!(e.loadConversationContinuation&&e.continueConversation&&e.stopConversationContinuation&&e.subscribeToConversationContinuations)}function ft(e){return ot(e.platform)&&ct.test(e.conversationSessionId)}function pt(e,t){return e===`live-updates-reconnected`||e.platform===t.platform&&e.conversationSessionId===t.conversationSessionId}var mt=e=>JSON.stringify([e.platform,e.conversationSessionId]);function ht(e){if(!e)return!1;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===2&&t.every(e=>typeof e==`string`&&e!==``)}catch{return!1}}function gt(e,t){let{conversationSessionId:n,title:r}=e,i=n.slice(0,8),a=t.some(e=>e.conversationSessionId!==n&&e.conversationSessionId.slice(0,8)===i);return{recordedTitle:r===null||r===g(n)?null:r,tool:e.tool,idChip:_t(n,a)}}var _t=(e,t)=>t?`…${Dt(e)}`:e.slice(0,8),vt={running:`Working…`,replied:`Replied`,failed:`Did not finish`,reading:`Reading the conversation…`,idle:`Write a reply, then send it.`,sending:`Sending your reply…`,"turn-running":`You can send again when this turn ends.`,"cannot-continue":`This conversation can’t be continued from here.`,"read-failure":null};function yt({conversationIsContinuable:e,read:t,readFailed:n,sending:r}){return e?t===null?n?`read-failure`:`reading`:t.target.canContinue?r?`sending`:t.exchanges.some(e=>e.state===`running`)?`turn-running`:`idle`:`cannot-continue`:`cannot-continue`}var bt={english:`It finished without a written reply.`,values:{}};function xt(e){return{english:e===1?`{count} tool call was not allowed in this turn. Open the conversation to approve it.`:`{count} tool calls were not allowed in this turn. Open the conversation to approve them.`,values:{count:e}}}function St(e,t,n,r=null){let i=t.some(e=>e.state===`running`);return{refusalText:e.canContinue?null:e.refusalText,folderGoneNotice:e.canContinue&&e.recordedFolderIsGone?{english:`Its folder is gone, so this turn will run in {folder}.`,values:{folder:e.runsInFolder}}:null,composerIsShown:e.canContinue,sendIsEnabled:e.canContinue&&!i&&n.trim()!==``,stopIsShown:i,exchanges:t.map(e=>Ct(e,r))}}function Ct(e,t){let n=e.state===`replied`&&e.replyText?.trim()?e.replyText:null,r=e.deniedToolCallCount??0,i=[];return e.state===`replied`&&n===null&&i.push(bt),r>0&&i.push(xt(r)),{exchangeId:e.exchangeId,startedAtEpochMs:e.startedAtEpochMs,stopWasSent:t!==null&&t.exchangeId===e.exchangeId&&t.startedAtEpochMs===e.startedAtEpochMs,ownerMessage:e.ownerMessage,state:e.state,stateWords:vt[e.state],replyText:n,failureText:e.state===`failed`&&e.failureText?e.failureText:null,notices:i}}var wt={read:`Could not read this conversation.`,send:`Your reply was not sent.`,stop:`Could not stop this turn.`,"open-in-app":`Could not open this conversation in its app.`};function Tt(e,t){return e===null?null:{sentence:wt.read,failureText:e,tryAgainLabel:`Try again`,tryingAgainLabel:`Trying again…`,isTryingAgain:t}}var Et=/.{8}$/,Dt=e=>e.match(Et)?.[0]??e;function Ot(e){let t={conversation:e};return{messageBox:{english:`Your reply to {conversation}`,values:t},sendButton:{english:`Send to {conversation}`,values:t},stopButton:{english:`Stop the turn in {conversation}`,values:t}}}function kt(e,t){return e?t.composerIsShown?`message-box`:`conversation-box`:null}function At(e,t,n){let r=ut(e.platform,e.conversationSessionId);if(!t.canContinue||r===null)return null;let i={conversation:e.conversationName},a=t.opensInAppNamed;return{openInApp:a===null||!n?null:{app:a,label:{english:`Open in {app}`,values:{app:a}},buttonName:{english:`Open in {app}: {conversation}`,values:{app:a,...i}}},copyResumeCommand:{command:r,buttonName:{english:`Copy resume command for {conversation}`,values:i},copiedButtonName:{english:`Copied the resume command for {conversation}`,values:i}},runsInFolderNotice:t.recordedFolderIsGone?null:{english:`Runs in {folder}`,values:{folder:t.runsInFolder}}}}function jt(e){let t=e.includes(`/`)||!e.includes(`\\`)?`/`:`\\`,n=e.length>1&&e.endsWith(t)?t:``,r=(n?e.slice(0,-1):e).split(t);if(r.length<3)return[e];let i=[e];for(let e=1;e<=r.length-2;e++)i.push([r[0],`…`,...r.slice(1+e)].join(t)+n);return i}function Mt(e,t){let n=t.values.folder,r=e.indexOf(`{folder}`);return typeof n!=`string`||r===-1?null:{wordsBefore:e.slice(0,r),folder:n,wordsAfter:e.slice(r+8)}}function Nt(e,t,n){return[{text:e,isShown:!n},{text:t,isShown:n}]}function Pt(e){return{details:e,copyItFromHere:{english:`Copy it from here:`,values:{}}}}var $=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ft=e=>st.includes(e),It=(e,t)=>e===void 0||typeof e===t;function Lt(e){return $(e)&&typeof e.exchangeId==`number`&&ot(e.platform)&&typeof e.conversationSessionId==`string`&&Ft(e.state)&&typeof e.ownerMessage==`string`&&typeof e.startedAtEpochMs==`number`&&typeof e.ranInFolder==`string`&&It(e.endedAtEpochMs,`number`)&&It(e.replyText,`string`)&&It(e.failureText,`string`)&&It(e.deniedToolCallCount,`number`)}function Rt(e){return $(e)?e.canContinue===!0?typeof e.recordedFolder==`string`&&typeof e.runsInFolder==`string`&&typeof e.recordedFolderIsGone==`boolean`&&(e.opensInAppNamed===null||typeof e.opensInAppNamed==`string`):e.canContinue===!1&&typeof e.refusalText==`string`&&(e.recordedFolder===null||typeof e.recordedFolder==`string`):!1}function zt(e){if(!$(e))return null;let{target:t,exchanges:n}=e;return!Rt(t)||!Array.isArray(n)||!n.every(Lt)?null:{target:t,exchanges:n}}function Bt(e){return $(e)&&Lt(e.exchange)?e.exchange:null}function Vt(e){return!$(e)||e.printedText!==null&&typeof e.printedText!=`string`?null:{printedText:e.printedText}}function Ht(e){let{exchangeId:t,platform:n,conversationSessionId:r,state:i}=e;return typeof t==`number`&&ot(n)&&typeof r==`string`&&Ft(i)?{exchangeId:t,platform:n,conversationSessionId:r,state:i}:null}function Ut(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let n of e){if(!$(n)||typeof n.message!=`string`)return null;let e=Array.isArray(n.path)?n.path.join(`.`):``;t.push(e?`${e}: ${n.message}`:n.message)}return t.join(`; `)}function Wt(e,t,n){if(e.status===413)return`Could not ${n}: it is too large for the worker to take.`;if($(t)){if(t.error===`ValidationError`){let e=Ut(t.issues);if(e)return`Could not ${n}: the worker could not read the request (${e}).`}else{let e=[t.message,t.error].find(e=>typeof e==`string`&&e.trim()!==``);if(e)return e}}return`Could not ${n}: the worker answered ${e.status}${e.statusText?` ${e.statusText}`:``}.`}function Gt(e,t){return`Could not ${e}: the worker could not be reached (${t instanceof Error?t.message:String(t)}).`}function Kt(e){return`The worker answered ${e}, but this page cannot read its answer.`}var qt=(e,t)=>e.conversationKey===t.conversationKey&&e.requestId===t.requestId&&(e.expectedSuggestionHash??null)===(t.expectedSuggestionHash??null);function Jt(e,t){return!e||!t||t.confidence===void 0||!qt(e,t)?e:{...e,confidence:t.confidence}}function Yt(e,t){let{suggestion:n,...r}=t,i=Jt(e.suggestion,t.suggestion);return{...r,...e,terminal:t.terminal,workstreams:t.workstreams,granular:t.granular,latestRecordConversation:t.latestRecordConversation,recordsAtLimit:t.recordsAtLimit,conversations:t.conversations,prompts:t.prompts,workProduct:t.workProduct,story:t.story,storyNarrative:t.storyNarrative,evidence:t.evidence,...i?{suggestion:i}:{},detailLoaded:!0}}function Xt(e){return JSON.stringify([e.id,e.detailRevision??e.contentFingerprint??``])}function Zt(e,t,n){let r=t?.request??n?.request;return!r||r.id!==e?null:t?.error===void 0?{request:r}:{request:r,newerVersionReadFailure:t.error}}function Qt(e,t){return{...Yt(e,t),contentFingerprint:t.contentFingerprint}}var $t=`/api/work-view/activity`;function en(e={}){let t=globalThis,n=e.document??t.document,r=e.page??t.window;if(e.enabled===!1||!n||!r)return()=>{};let i=e.fetchImpl??fetch,a=e.viewerId??crypto.randomUUID(),o=e.renewMs??2e4,s=e.timeoutMs??1e4,c=0,l=!1,u=!1,d=null,f=new Set,p=e=>{d?.abort();let t=new AbortController;d=t,f.add(t);let n=setTimeout(()=>t.abort(),s),r=++c;i($t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({viewerId:a,visible:e,sequence:r}),signal:t.signal,keepalive:!e}).catch(()=>{}).finally(()=>{clearTimeout(n),f.delete(t),d===t&&(d=null)})},m=()=>{if(l)return;let e=n.visibilityState===`visible`;(e||u)&&p(e),u=e},h=()=>{!l&&u&&(u=!1,p(!1))},g=setInterval(()=>{!l&&u&&n.visibilityState===`visible`&&!d&&p(!0)},o);return n.addEventListener(`visibilitychange`,m),r.addEventListener(`pageshow`,m),r.addEventListener(`pagehide`,h),m(),()=>{if(!l){l=!0,clearInterval(g),n.removeEventListener(`visibilitychange`,m),r.removeEventListener(`pageshow`,m),r.removeEventListener(`pagehide`,h);for(let e of f)e.abort();u&&(u=!1,p(!1))}}}var tn=()=>globalThis.window;function nn(e={}){let t=e.fetchImpl??((e,t)=>fetch(e,t)),n=e.eventSourceFactory??(e=>new EventSource(e)),r=e.bootstrapTimeoutMs??1e4,i=e.requestTimeoutMs??2e4,a=`/api/work-view`,s=/^[a-f0-9]{64}$/,u=e.sharedOwner??v(),d=u||c(e.hostname??l()??`localhost`)?`cloud`:`local`,g=d===`cloud`?e.visibility??o():void 0,b=()=>g?.visibilityState===`hidden`,x=e.pageUnload??tn(),S={transportConnected:!1,reconnecting:!1,lastEventAt:null,sourceConnected:null,lastSuccessfulCheckAt:null,lastSuccessfulCheckReceivedAt:null,sync:null,syncReceivedAt:null,activityCheckedAt:null,activityAgeAtReceipt:null,activityReceivedAt:null},C=null,w=null,T=null,E=null,D=!1,O=0,k=0,A=0,ee=0,te=-1/0,j=null,M=null,N=null,P=new Set,F=new Map,I=null,L=new WeakMap;function R(e){let t=L.get(e);return t===void 0&&(t=JSON.stringify([e.agents,e.devices,e.people,e.requests,e.requestReadErrors,e.unlinkedWorkCount,e.sourceHealth,e.focusAreas,e.otherAsks,e.currentPeriod,e.pastPeriods,e.goalsReadError,e.lastRuns,e.refresh,e.rules,e.ruleScopes,e.rulesLearning,e.rulesFile,e.rulesReadError,e.buildStory,e.sharedState]),L.set(e,t)),t}let z=()=>Ze({...S,now:performance.now(),wallNow:Date.now(),where:d}),B=e=>{let t={...e,sourceKind:d,connection:z()};return L.set(t,R(e)),t};function V(e,t){S.sourceConnected=typeof e?.connected==`boolean`?e.connected:null,e?.connected===!0&&typeof e.lastCheckedAt==`string`&&Number.isFinite(Date.parse(e.lastCheckedAt))&&(S.lastSuccessfulCheckAt=e.lastCheckedAt,S.lastSuccessfulCheckReceivedAt=performance.now());let n=e?.activityCheckedAt?Date.parse(e.activityCheckedAt):NaN,r=Date.parse(t??e?.lastCheckedAt??``);S.activityCheckedAt=Number.isFinite(n)?e.activityCheckedAt:null,S.activityAgeAtReceipt=Number.isFinite(n)&&Number.isFinite(r)&&r>=n?r-n:null,S.activityReceivedAt=S.activityAgeAtReceipt===null?null:performance.now()}function H(e,t){Ge(e)&&(t===void 0||t===k)&&(S.sync&&JSON.stringify(e)===JSON.stringify(S.sync)||(k++,S.sync=e,S.syncReceivedAt=performance.now()))}function U(e,t,n){return O++,C=e,T=null,w=m(e,Date.now()),(u||t||S.lastEventAt===null)&&V(e.source,e.generatedAt),H(e.sync,n),B(w)}function W(e,t,n){O++,C=null,E=e.revision,(u||t||S.lastEventAt===null)&&V(e.source,e.generatedAt),H(e.sync,n);let r=`overview:${R(e.model)}`;if(w&&r===T)return B(w);T=r,w=p(e),L.set(w,r);let i=new Map(w.requests.map(e=>[e.id,e.detailRevision??e.contentFingerprint??``]));for(let[e,t]of F)i.get(e)!==t.fingerprint&&F.delete(e);return B(w)}let G=e=>{let t=e;return!!t&&t.version===1&&typeof t.revision==`string`&&[`requests`,`requestReadErrors`,`agents`,`devices`,`people`,`focusAreas`,`otherAsks`,`pastPeriods`,`rules`,`ruleScopes`].every(e=>Array.isArray(t.model?.[e]))&&t.model.requests.every(e=>typeof e?.id==`string`&&e.detailLoaded===!1&&typeof e.contentFingerprint==`string`&&s.test(e.contentFingerprint))&&typeof t.model.sourceHealth?.connected==`boolean`&&typeof t.source?.connected==`boolean`},K=()=>new DOMException(`The request was cancelled.`,`AbortError`);async function ne(e,n){let r=new AbortController,a=()=>r.abort(n?.reason??K());n?.aborted?a():n?.addEventListener(`abort`,a,{once:!0}),P.add(r);let o=setTimeout(()=>r.abort(new DOMException(`The worker took too long to respond.`,`TimeoutError`)),i);try{let n=await t(e,{cache:`no-store`,signal:r.signal}),i=null;try{i=await n.json()}catch(e){if(r.signal.aborted)throw e}if(r.signal.aborted)throw r.signal.reason??K();return{response:n,body:i}}finally{clearTimeout(o),n?.removeEventListener(`abort`,a),P.delete(r)}}async function q(e,t){let n=O,r=k;te=performance.now();let i=await ne(D?a:`/api/work-view/overview`,e);if(t?.(),!D&&i.response.status===404&&(D=!0,i=await ne(a,e),t?.()),!i.response.ok)throw Error(`The worker answered ${i.response.status} ${i.response.statusText}`.trim());if(O!==n&&w)return B(w);if(G(i.body))return W(i.body,!1,r);if(J(i.body))return U(i.body,!1,r);throw Error(`The worker returned an unreadable work view.`)}let J=e=>{let t=e;return!!t&&Array.isArray(t.humanRequests)&&typeof t.source?.connected==`boolean`};function re(){return{"Content-Type":`application/json`,...u&&E?{"X-Work-Revision":E}:{}}}function Y(e,t,n){return G(e)?t?B(t):W(e,!1,n):J(e)?t?B(t):U(e,!1,n):null}async function X(e,n,r,i=!1){let a=O,o=k,s=A,c=await t(e,{method:`POST`,headers:re(),body:JSON.stringify(n)}),l=null;try{l=await c.json()}catch{}let u=w&&(O!==a||s!==A)?w:null;if(!c.ok){let e=l,t=e?.error,n=`${r} was not saved: ${typeof t==`string`?t:`the worker answered ${c.status}`}`,i=Y(e?.overview??e?.snapshot,u,o);throw i?(I=R(i),new f(n,i)):Error(n)}let d=Y(l,u,o);if(!d)throw Error(`${r} was saved, but the worker sent back something that is not a work snapshot. Reload to see it.`);I=R(d);let h=d;i&&u&&(G(l)?h=B(p(l)):J(l)&&(h=B(m(l,Date.now()))));let{savedRuleId:g}=l,_=Qe(l);return{model:h,savedRuleId:typeof g==`string`?g:null,..._?{save:_}:{}}}let ie=new Set,ae=new EventTarget,oe=()=>ae.dispatchEvent(new Event(`change`)),Z=e=>{for(let t of[...ie])try{t(e)}catch(e){console.error(`[work-view] A conversation-continuation listener threw. The other listeners are still told.`,e)}},se=!1;async function ce(e,n,r,i){let a;try{a=await t(e,n)}catch(e){throw Error(Gt(r,e))}let o=null;try{o=await a.json()}catch{}if(!a.ok)throw Error(Wt(a,o,r));let s=i(o);if(s===null)throw Error(Kt(a.status));return s}let Q=e=>({method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),le={sourceKind:d,...d===`local`?{loadConversationContinuation:(e,t)=>ce(`/api/work-view/conversations/continuation?${new URLSearchParams({platform:e,conversationSessionId:t})}`,{cache:`no-store`},`read this conversation`,zt),continueConversation:(e,t,n)=>ce(`/api/work-view/conversations/continue`,Q({platform:e,conversationSessionId:t,ownerMessage:n}),`send your message`,Bt),stopConversationContinuation:(e,t)=>ce(`/api/work-view/conversations/stop`,Q({platform:e,conversationSessionId:t}),`stop this turn`,Bt),subscribeToConversationContinuations(e){let t=t=>e(t);return ie.add(t),()=>{ie.delete(t)}},async openConversationInApp(e,n){let r={platform:e,conversationSessionId:n,openInAppClickId:crypto.randomUUID()},i=()=>{t(`/api/work-view/conversations/open-in-app/stop`,{...Q(r),keepalive:!0}).catch(e=>{console.error(`[work-view] Could not ask the worker to stop opening a conversation in its app as this page closed.`,e)})};x?.addEventListener(`pagehide`,i);try{return await ce(`/api/work-view/conversations/open-in-app`,Q(r),`open this conversation in its app`,Vt)}finally{x?.removeEventListener(`pagehide`,i)}}}:{},subscribeToReviewStackChanges(e){return ae.addEventListener(`change`,e),()=>ae.removeEventListener(`change`,e)},async loadWorkModel(){if(!M){let e=j,t=A,n=(async()=>{let n=null;if(e&&!u){let i;try{n=await Promise.race([e.promise,new Promise(e=>{i=setTimeout(()=>e(null),r)})])}finally{clearTimeout(i)}if(t!==A)throw K();j===e&&(j=null)}return n??=await q(),I=R(n),n})().finally(()=>{M===n&&(M=null)});M=n}return M},async loadRequestDetail(e,t,{signal:n}={}){let r=++ee,i=A,a=()=>{if(n?.aborted||r!==ee||i!==A)throw K()};a();let o=F.get(e),s=w?.requests.find(t=>t.id===e);if(o&&o.fingerprint===t&&(!w||(s?.detailRevision??s?.contentFingerprint)===o.fingerprint))return s?Yt(s,o.request):o.request;let c=`/api/work-view/requests/`+encodeURIComponent(e);if(u&&c.length>1024){let t=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));c=`/api/work-view/requests/by-hash/`+btoa(String.fromCharCode(...t)).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``)}let l=t;for(let t=0;t<2;t++){let t=O,r=k,i=new URLSearchParams;l&&i.set(`fingerprint`,l);let{response:o,body:s}=await ne(`${c}${i.size?`?${i}`:``}`,n);if(a(),o.status===409&&G(s?.overview)){let n=s.overview,i=w!==null&&O!==t,a=i&&w?B(w):W(n,!1,r);i||N?.(a);let o=a.requests.find(t=>t.id===e);if(!o)throw Error(`This request is no longer in your work.`);l=o.detailRevision??o.contentFingerprint;continue}if(o.status===404){let t=await q(n,a);a(),N?.(t);let r=t.requests.find(t=>t.id===e);if(r&&r.detailLoaded!==!1)return r;throw Error(`This request is no longer available. Refresh your work and try again.`)}if(!o.ok)throw Error(`Request detail could not be loaded (${o.status}). Try again.`);let u=s;if(u?.version!==1||u.request?.id!==e||u.request.detailLoaded===!1)throw Error(`The worker returned unreadable request detail.`);let d=u.request.detailRevision??u.request.contentFingerprint??``,f=w?.requests.find(t=>t.id===e);if(w&&!f)throw Error(`This request is no longer in your work.`);if(l&&d!==l||f&&(f.detailRevision??f.contentFingerprint)!==d)throw Error(`This request changed while its detail was loading. Try again.`);for(a(),F.delete(e),F.set(e,{fingerprint:d,request:u.request});F.size>8;)F.delete(F.keys().next().value);return f?Yt(f,u.request):u.request}throw Error(`This request changed while its detail was loading. Try again.`)},async setRequestChecked(e,n,r,i){if(!s.test(n))throw Error(`Can't check ${e}: its recorded version (content fingerprint) is missing`);let a=O,o=k,c=A,l=await t(`/api/work-view/review`,{method:`POST`,headers:re(),body:JSON.stringify({requestId:e,expectedFingerprint:n,checked:r,expectedReviewHash:i})}),u=null;try{u=await l.json()}catch{}let d=rt(l.status,u);if(d.kind===`unavailable`)return{outcome:`unavailable`,serverMessage:d.serverMessage};let f=w&&(O!==a||c!==A)?w:null;if(d.kind===`conflict`){let t=Y(d.snapshot,f,o)??await le.loadWorkModel(),r=t.requests.find(t=>t.id===e)?.contentFingerprint;return it(n,r)===`refused`?{outcome:`refused`,serverMessage:d.serverMessage,model:t}:{outcome:`changed-while-reading`,model:t,serverMessage:d.serverMessage}}let p=Y(d.snapshot,f,o);if(!p)throw Error(`The local review was saved, but the worker sent back something that is not a work snapshot. Reload to see it.`);return I=R(p),{outcome:`saved`,model:p,...d.save?{save:d.save}:{}}},async answerRequestSuggestion(e,t){let{model:n,save:r}=await X(`/api/work-view/suggestions`,{conversationKey:e.conversationKey,action:t,expectedSuggestionHash:e.expectedSuggestionHash},`The suggestion decision`);return{model:n,...r?{save:r}:{}}},async saveRuleChange({expectedRuleVersion:e,...t}){if(e!==void 0&&(!e||e!==Pe(w?.rules.find(e=>e.id===t.ruleId))))throw Error(`This rule changed while you were editing. Reopen it to review the latest version.`);return X(`/api/work-view/rules`,t,`The rule change`)},saveFocusChange:async e=>(await X(`/api/work-view/focus`,e,`The focus change`,!0)).model,loadRulesInClaudeCode:async()=>(await X(`/api/work-view/rules/load-in-claude-code`,{},`Loading your rules into Claude Code`)).model,async refreshWork(){let e=await t(`/api/work-view/refresh`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`});if(!e.ok){let t=null;try{let n=await e.json();typeof n.error==`string`&&(t=n.error)}catch{}throw new h(e.status,t)}return await e.json()},markAgentFinished:async e=>(await X(`/api/work-view/agents/mark-finished`,{agentGroupId:e},`Marking the agent finished`)).model,subscribeToLiveUpdates(r,i){let a=en({...e.activityOptions,enabled:d===`local`,fetchImpl:t}),o=++A,s;j={promise:new Promise(e=>{s=e}),resolve:e=>s(e)};let c=j,l=()=>i(z()),f=()=>{S.transportConnected=!0,S.reconnecting=!1,S.lastEventAt=performance.now()},p=e=>{let t=R(e);t!==I&&(I=t,r(e))};N=p;let h=null,v,x=()=>{if(o!==A)return;let e=new URLSearchParams({view:`overview`});u&&e.set(`session`,u);let t=n(`/api/work-view/events?${e}`);h=t;let r=()=>o===A&&h===t;if(h.onopen=()=>{if(!r())return;S.transportConnected=!0,S.reconnecting=!1,l();let e=se;se=!0,e&&(Z(`live-updates-reconnected`),oe())},u){let e=!1,t=!1,n=async()=>{if(t=!0,!e){e=!0;try{for(;t&&r();){t=!1;let e=await q(void 0,()=>{if(!r())throw K()});if(!r())return;f(),c.resolve(e),p(e),l()}}catch{}finally{e=!1}}};h.addEventListener(`work-view-changed`,()=>{r()&&(oe(),n())})}else h.addEventListener(`review-stack-changed`,()=>{r()&&oe()});h.addEventListener(`work-view`,e=>{!u&&r()&&_(`work-view`,e.data,e=>{if(!J(e))return;f(),D=!0;let t=U(e,!0);c.resolve(t),p(t),l()})}),h.addEventListener(`work-view-overview`,e=>{!u&&r()&&_(`work-view-overview`,e.data,e=>{if(!G(e))return;f();let t=W(e,!0);c.resolve(t),p(t),l()})}),h.addEventListener(`heartbeat`,e=>{r()&&_(`heartbeat`,e.data,e=>{let t=e;if(u){if(!t.at||!Number.isFinite(Date.parse(t.at)))return;f(),S.sourceConnected&&S.lastSuccessfulCheckAt&&(S.lastSuccessfulCheckAt=t.at,S.lastSuccessfulCheckReceivedAt=performance.now()),l()}else typeof t.source?.connected==`boolean`&&(f(),V(t.source,t.at),H(t.sync),l())})}),h.addEventListener(`sync_status`,e=>{!u&&r()&&_(`sync_status`,e.data,e=>{Ge(e.sync)&&(H(e.sync),l())})}),h.addEventListener(`conversation-continuation`,e=>{!u&&r()&&_(`conversation-continuation`,e.data,e=>{let t=Ht(e);t&&Z(t)},e=>Ht(e)!==null)}),u&&h.addEventListener(`session-ended`,()=>{r()&&y(`cmem:session-ended`)}),h.onerror=()=>{r()&&(u&&y(`cmem:session-check`),c.resolve(null),S.transportConnected=!1,S.reconnecting=!0,l(),t.readyState===2&&(v=setTimeout(x,1e3)))}};b()||x();let T=()=>{o===A&&(b()?(clearTimeout(v),h?.close(),h=null,S.transportConnected=!1,S.reconnecting=!0,l()):h||x())};g?.addEventListener(`visibilitychange`,T);let E=setInterval(l,1e3),O=setInterval(()=>{b()||(C?p(B(m(C,Date.now()))):w&&!z().isLive&&performance.now()-te>=12e4&&q().then(e=>{o===A&&p(e)}).catch(()=>{}))},6e4);return()=>{if(c.resolve(null),clearTimeout(v),g?.removeEventListener(`visibilitychange`,T),h?.close(),clearInterval(E),clearInterval(O),a(),o===A){A++,ee++,j===c&&(j=null),M=null,N=null;for(let e of P)e.abort(K())}}}};return le}var rn=nn();export{J as $,We as A,je as B,Pt as C,tt as D,et as E,De as F,Ce as G,pe as H,Me as I,be as J,we as K,Ne as L,Fe as M,Ie as N,Ze as O,Pe as P,ne as Q,ke as R,yt as S,$e as T,ye as U,Ae as V,Te as W,fe as X,Ee as Y,G as Z,Tt as _,Qt as a,v as at,ft as b,Nt as c,St as d,q as et,At as f,gt as g,mt as h,Zt as i,x as it,Le as j,Be as k,dt as l,_t as m,Yt as n,P as nt,vt as o,Ot as p,Se as q,Xt as r,E as rt,wt as s,rn as t,N as tt,pt as u,kt as v,Mt as w,ht as x,jt as y,Oe as z};