@rivet-dev/agentos 0.2.16-rc.1 → 0.2.16-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/assets/inspector-tabs-app/assets/__vite-browser-external-2447137e-BIHI7g3E.js +1 -0
  2. package/assets/inspector-tabs-app/assets/filesystem-C-x0K5sy.js +1 -0
  3. package/assets/inspector-tabs-app/assets/hooks-DU8a-cwM.js +1 -0
  4. package/assets/inspector-tabs-app/assets/index-7G_DbdZ6.js +110 -0
  5. package/assets/inspector-tabs-app/assets/index-DG_s1YoH.css +1 -0
  6. package/assets/inspector-tabs-app/assets/scroll-area-kPbv4IGy.js +1 -0
  7. package/assets/inspector-tabs-app/assets/system-D98yBhMj.js +2 -0
  8. package/assets/inspector-tabs-app/assets/terminal-Bv9GKv4q.js +13 -0
  9. package/assets/inspector-tabs-app/assets/transcript-kMbm_tF8.js +1 -0
  10. package/assets/inspector-tabs-app/assets/{useSuspenseQuery-BXmNSEVQ.js → useSuspenseQuery-ChN8rnBd.js} +1 -1
  11. package/assets/inspector-tabs-app/assets/vm-boot-gate-rpuO0b5W.js +1 -0
  12. package/assets/inspector-tabs-app/assets/vm-status-badges-09qyfN_A.js +5 -0
  13. package/assets/inspector-tabs-app/index.html +2 -2
  14. package/dist/index.d.ts +45 -2
  15. package/dist/index.js +340 -18
  16. package/dist/index.js.map +1 -1
  17. package/package.json +12 -6
  18. package/assets/inspector-tabs-app/assets/filesystem-Ce_1E-AG.js +0 -1
  19. package/assets/inspector-tabs-app/assets/index-AMqbzdhN.js +0 -126
  20. package/assets/inspector-tabs-app/assets/index-tcfmhW06.css +0 -1
  21. package/assets/inspector-tabs-app/assets/system-AIh54aFR.js +0 -2
  22. package/assets/inspector-tabs-app/assets/transcript-D07sAUKE.js +0 -1
  23. package/assets/inspector-tabs-app/assets/vm-boot-gate-CzDOFOZU.js +0 -1
  24. package/assets/inspector-tabs-app/assets/vm-status-badges-CnUikLsX.js +0 -5
@@ -0,0 +1 @@
1
+ import{a as f,u as te,r as l,l as ne,b as Y,c as re,m as oe,j as e,I as F,S as ae,P as ie,A as le,d as K,e as P,C as ce,f as de,g as H,h as U,i as W,k as ue,n as pe}from"./index-7G_DbdZ6.js";import{u as xe}from"./useSuspenseQuery-ChN8rnBd.js";import{S as G}from"./scroll-area-kPbv4IGy.js";import{V as me}from"./vm-status-badges-09qyfN_A.js";function fe({event:n}){var r,u;switch(n.kind){case"user":return e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[80%] whitespace-pre-wrap rounded-2xl rounded-br-md bg-muted px-3.5 py-2 text-sm",children:n.text||"—"})});case"assistant":return e.jsx("div",{className:"flex",children:e.jsx("div",{className:"max-w-[85%] whitespace-pre-wrap text-sm leading-relaxed",children:n.text||"—"})});case"thinking":return e.jsx("div",{className:"flex",children:e.jsx("div",{className:"max-w-[85%] whitespace-pre-wrap text-xs italic leading-relaxed text-muted-foreground/70",children:n.text||"—"})});case"tool":{const a=n.input!==void 0||n.output!==void 0||!!((r=n.locations)!=null&&r.length),o=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono",children:n.tool}),n.status?e.jsx("span",{className:"rounded-full border px-1.5 py-px text-[10px]",children:n.status}):null]});return a?e.jsxs("details",{className:"group rounded-lg border border-foreground/10 bg-muted/20 text-xs text-muted-foreground",children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-2 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden",children:[e.jsx(W,{className:"size-3 shrink-0 transition-transform group-open:rotate-90"}),o]}),e.jsxs("div",{className:"flex flex-col gap-2 border-t border-foreground/10 px-2.5 py-2",children:[n.input!==void 0?e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[10px] text-muted-foreground/70",children:"Input"}),e.jsx("pre",{className:"max-h-40 overflow-y-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 font-mono text-[11px] leading-relaxed",children:JSON.stringify(n.input,null,2)})]}):null,n.output!==void 0?e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[10px] text-muted-foreground/70",children:"Output"}),e.jsx("pre",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 font-mono text-[11px] leading-relaxed",children:n.output})]}):null,(u=n.locations)!=null&&u.length?e.jsx("div",{className:"font-mono text-[11px] text-muted-foreground/70",children:n.locations.join(" ")}):null]})]}):e.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:o})}case"plan":return e.jsxs("div",{className:"rounded-lg border border-foreground/10 bg-muted/20 px-2.5 py-2 text-xs text-muted-foreground",children:[e.jsx("div",{className:"mb-1 text-[10px] text-muted-foreground/70",children:"Plan"}),e.jsx("ul",{className:"flex flex-col gap-1",children:n.entries.map((a,o)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(P,{color:a.status==="completed"?"green":a.status==="in_progress"?"amber":"muted",className:"mt-1"}),e.jsx("span",{className:H("min-w-0 flex-1",a.status==="completed"&&"text-muted-foreground/60 line-through"),children:a.content})]},`${o}-${a.content.slice(0,24)}`))})]});case"notice":return e.jsx("div",{className:"text-center text-[11px] text-muted-foreground/60",children:n.text});case"permission":return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-2.5 py-1.5 text-xs text-amber-500/90",children:[e.jsx(P,{color:"amber",className:"size-1.5"}),n.text]});case"error":return e.jsx("div",{className:"whitespace-pre-wrap text-sm text-destructive",children:n.text});default:return e.jsxs("details",{className:"group text-xs text-muted-foreground/70",children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-1.5 [&::-webkit-details-marker]:hidden",children:[e.jsx(W,{className:"size-3 shrink-0 transition-transform group-open:rotate-90"}),e.jsx("span",{className:"font-mono",children:n.label})]}),e.jsx("pre",{className:"mt-1.5 max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 font-mono text-[11px] leading-relaxed",children:JSON.stringify(n.json,null,2)})]})}}function he({count:n}){const r=l.useRef(null),u=l.useRef(!0);return l.useEffect(()=>{const a=r.current,o=a==null?void 0:a.closest("[data-radix-scroll-area-viewport]");if(!a||!o)return;const c=new IntersectionObserver(([x])=>{u.current=x.isIntersecting},{root:o,rootMargin:"0px 0px 96px 0px"});return c.observe(a),()=>c.disconnect()},[]),l.useEffect(()=>{var a;u.current&&((a=r.current)==null||a.scrollIntoView({block:"end"}))},[n]),e.jsx("div",{ref:r,className:"h-px"})}function ge(n){const r=[],u=new Map;let a=null;for(const o of n){const c=r[r.length-1];if((o.kind==="user"||o.kind==="assistant"||o.kind==="thinking")&&(c==null?void 0:c.kind)===o.kind){r[r.length-1]={...c,text:c.text+o.text};continue}if(o.kind==="tool"&&o.toolCallId){const x=u.get(o.toolCallId);if(x!==void 0){const p=r[x];r[x]={...p,tool:o.tool!==o.toolCallId?o.tool:p.tool,status:o.status??p.status,input:o.input??p.input,output:o.output??p.output,locations:o.locations??p.locations};continue}u.set(o.toolCallId,r.length)}if(o.kind==="plan"){if(a!==null){r[a]={...r[a],entries:o.entries};continue}a=r.length}r.push(o)}return r}function ye(){return e.jsx("div",{className:"flex items-center gap-1 px-1 py-0.5","aria-label":"Turn in progress",children:[0,1,2].map(n=>e.jsx("span",{className:"size-1.5 animate-pulse rounded-full bg-muted-foreground/50",style:{animationDelay:`${n*200}ms`}},n))})}const D="agentos-inspector:composer-agent-type",L="agentos-inspector:composer-env",J=n=>`agentos-inspector:transcript:${n}`,X=JSON.stringify({ANTHROPIC_API_KEY:"",OPENCODE_CONFIG_CONTENT:JSON.stringify({model:"anthropic/claude-haiku-4-5-20251001"})},null,2);function ve(){const n=(localStorage.getItem(D)??"opencode").trim()||"opencode",r=localStorage.getItem(L)??X;let u;try{u=JSON.parse(r)}catch(a){throw new Error(`Session env is not valid JSON: ${a.message}`)}return{agentType:n,env:u}}function Ne({actorId:n,sessionId:r,sessionStatus:u,onSessionCreated:a,onErrorEvent:o,onBusyChange:c}){const[x,p]=l.useState(""),[g,R]=l.useState(!1),S=i=>{R(i),c==null||c(i)},[v,N]=l.useState(!1),[j,k]=l.useState(!1),[C,O]=l.useState(()=>localStorage.getItem(D)??"opencode"),[b,A]=l.useState(()=>localStorage.getItem(L)??X),E=l.useRef(null),T=(Y({...f.softwareQueryOptions(n),enabled:j}).data??[]).filter(i=>i.name.endsWith("· agent")).map(i=>{var d;return((d=i.name.split(" · ")[0])==null?void 0:d.split("/").pop())??""}).filter(Boolean),w=async()=>{const i=x.trim();if(!(!i||g)){S(!0),p("");try{let d=r;if(!d){let h;try{h=JSON.parse(b)}catch(_){throw new Error(`Session env is not valid JSON: ${_.message}`)}d=await f.createSession(C.trim()||"opencode",{env:h}),a(d)}E.current=d,await f.sendPrompt(d,i)}catch(d){let h=ue(d)?` — ${d.hint}`:"";r&&u!=="running"&&(h=" — this session is idle (not live in the current VM boot). Send without a selection to start a fresh session, or resume it from a client."),o(`${d instanceof Error?d.message:String(d)}${h}`)}finally{E.current=null,S(!1)}}},I=async()=>{const i=E.current??r;if(i)try{await pe(i)||(N(!0),o("Stop is not supported by this runtime (no cancelPrompt action)."))}catch(d){o(d instanceof Error?d.message:String(d))}};return e.jsx("div",{className:"shrink-0",children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl px-3 pb-3",children:[j&&!r?e.jsxs("div",{className:"mb-2 flex flex-col gap-2 rounded-xl border bg-muted/30 p-3 text-xs",children:[e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 text-muted-foreground",children:"Agent type"}),e.jsx("input",{value:C,onChange:i=>{O(i.target.value),localStorage.setItem(D,i.target.value)},list:"agentos-composer-agent-types",className:"flex-1 rounded border bg-background px-2 py-1 font-mono"}),e.jsx("datalist",{id:"agentos-composer-agent-types",children:T.map(i=>e.jsx("option",{value:i},i))})]}),e.jsxs("label",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 pt-1 text-muted-foreground",children:"Session env"}),e.jsx("textarea",{value:b,onChange:i=>{A(i.target.value),localStorage.setItem(L,i.target.value)},rows:4,spellCheck:!1,className:"flex-1 resize-y rounded border bg-background px-2 py-1 font-mono"})]}),e.jsx("div",{className:"text-muted-foreground/70",children:"Used when sending without a session: creates one with these options. Values stay in this browser."})]}):null,e.jsxs("div",{className:"rounded-2xl border bg-muted/40 transition-colors focus-within:border-ring/60",children:[e.jsx("textarea",{value:x,onChange:i=>p(i.target.value),onKeyDown:i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),w())},placeholder:r?"Prompt this session…":"Prompt a new session…",rows:2,className:"max-h-48 min-h-[3.25rem] w-full resize-none bg-transparent px-4 pt-3 text-sm placeholder:text-muted-foreground/50 focus:outline-none"}),e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 pb-2.5",children:[r?null:e.jsxs("button",{type:"button",onClick:()=>k(i=>!i),title:"New-session options (agent, env)",className:"inline-flex items-center gap-1 rounded px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[e.jsx("span",{"aria-hidden":"true",className:"text-sm leading-none",children:"+"}),"Options"]}),e.jsx("span",{className:"ml-auto"}),g?e.jsx("button",{type:"button",onClick:()=>void I(),disabled:v,title:v?"This runtime has no cancelPrompt action":"Stop the running turn",className:"inline-flex size-8 items-center justify-center rounded-md bg-foreground/90 text-background transition-opacity hover:opacity-80 disabled:opacity-40",children:e.jsx("span",{"aria-hidden":"true",className:"block size-2.5 rounded-[2px] bg-current"})}):e.jsx("button",{type:"button",onClick:()=>void w(),disabled:!x.trim(),title:"Send (⏎)",className:"inline-flex size-8 items-center justify-center rounded-md bg-primary text-primary-foreground transition-opacity hover:opacity-90 disabled:opacity-40",children:e.jsx("svg",{viewBox:"0 0 16 16",className:"size-4",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M8 13V3M4 7l4-4 4 4"})})})]})]})]})})}function Ce({actorId:n}){var V;const{data:r}=xe(f.sessionsQueryOptions(n)),u=te(),[a,o]=l.useState(()=>{try{const s=sessionStorage.getItem(J(n));if(!s)return;const t=JSON.parse(s);return t.selected===null||typeof t.selected=="string"?t.selected:void 0}catch{return}});l.useEffect(()=>{try{a===void 0?sessionStorage.removeItem(J(n)):sessionStorage.setItem(J(n),JSON.stringify({selected:a}))}catch(s){console.warn("agentos inspector: failed to persist transcript state",s)}},[n,a]);const c=a===void 0||typeof a=="string"&&!r.some(s=>s.sessionId===a)?((V=r[0])==null?void 0:V.sessionId)??null:a,x=l.useMemo(()=>ne(r),[r]),p=s=>x.has(s.sessionId),{data:g=[]}=Y(f.transcriptQueryOptions(n,c)),S=re().useEvent,[v,N]=l.useState([]),j=l.useRef(0),k=l.useRef(c);k.current=c,l.useEffect(()=>{N([])},[c]),S("sessionEvent",s=>{const t=s,y=k.current;if(!y||!(t!=null&&t.sessionId)||t.sessionId!==y)return;let m=oe(t);t.type==="permission_request"&&m.kind==="permission"&&(m={...m,text:`${m.text} (answer in the banner above)`});const q=j.current++;N(B=>{if(t.durability==="durable"){const se=t.type==="agent_message_chunk"||t.type==="agent_thought_chunk";return[...B.filter($=>$.seq!==m.seq&&!(se&&$.kind===m.kind&&!Number.isInteger($.seq)&&$.seq<m.seq)),{...m,liveKey:q}]}return[...B,{...m,liveKey:q}]})}),S("agentExit",s=>{const t=s,y=k.current;if(!y||(t==null?void 0:t.sessionId)!==y)return;const m=j.current++;N(q=>[...q,{kind:"error",seq:-1-m,liveKey:m,text:`Agent crashed (exit ${t.exitCode??"?"}) — restart: ${t.restart}${t.restartCount?` (attempt ${t.restartCount})`:""}`}])});const C=s=>{const t=j.current++;N(y=>[...y,{kind:"error",seq:-1-t,liveKey:t,text:s}])},O=s=>{o(s),u.invalidateQueries({queryKey:f.sessionsQueryOptions(n).queryKey})},[b,A]=l.useState(!1),[E,z]=l.useState(!1),[T,w]=l.useState(""),I=T.trim().toLowerCase(),i=I?r.filter(s=>s.sessionId.toLowerCase().includes(I)||s.agent.toLowerCase().includes(I)):r,[d,h]=l.useState(null),_=async()=>{if(!b){A(!0),h(null);try{const{agentType:s,env:t}=ve();O(await f.createSession(s,{env:t}))}catch(s){h(s)}finally{A(!1)}}},[M,Z]=l.useState(!1),ee=async s=>{try{await f.closeSession(s)}catch(t){C(t instanceof Error?t.message:String(t))}o(void 0),u.invalidateQueries({queryKey:f.sessionsQueryOptions(n).queryKey})},Q=l.useMemo(()=>{const s=new Set(g.map(t=>t.seq));return ge([...g.map(t=>({...t,key:`b-${t.seq}`})),...v.filter(t=>!s.has(t.seq)).map(t=>({...t,key:`l-${t.liveKey}`}))])},[g,v]);return e.jsxs("div",{className:"flex h-full min-h-0",children:[e.jsxs("div",{className:"flex h-full w-64 shrink-0 flex-col border-r",children:[e.jsxs("div",{className:"flex items-center px-3 pb-1 pt-2.5",children:[e.jsxs("span",{className:"text-[11px] font-medium text-muted-foreground",children:["Sessions",x.size>0?` · ${x.size} live`:""]}),e.jsx("span",{className:"ml-auto"}),e.jsx(F,{title:"Search sessions by id",onClick:()=>z(s=>(s&&w(""),!s)),className:"mr-1",children:e.jsx(ae,{className:"size-3.5"})}),e.jsx(F,{title:b?"Creating session…":"New session",onClick:()=>void _(),disabled:b,children:e.jsx(ie,{className:"size-3.5"})})]}),E?e.jsx("div",{className:"px-3 pb-1.5",children:e.jsx("input",{value:T,onChange:s=>w(s.target.value),onKeyDown:s=>{s.key==="Escape"&&(w(""),z(!1))},spellCheck:!1,autoFocus:!0,"aria-label":"Search sessions",placeholder:"session id or agent",className:"w-full rounded border bg-background px-2 py-1 font-mono text-xs focus:outline-none"})}):null,d?e.jsx(le,{error:d,className:"border-b py-2"}):null,r.length===0?e.jsx(K,{children:"No sessions yet."}):e.jsx(G,{className:"min-h-0 flex-1",children:e.jsxs("div",{className:"p-1.5",children:[i.length===0?e.jsx("div",{className:"px-2 py-3 text-center text-xs text-muted-foreground",children:"No sessions match."}):null,i.map(s=>e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>o(s.sessionId),onKeyDown:t=>{(t.key==="Enter"||t.key===" ")&&o(s.sessionId)},className:H("group flex w-full cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-left",s.sessionId===c?"bg-muted":"hover:bg-muted/50"),children:[e.jsx(P,{color:p(s)?"green":"muted"}),e.jsxs("div",{className:"min-w-0 flex-1",title:p(s)?"Live in the current VM":"Idle — persisted, not loaded in the current VM",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsxs("span",{className:"truncate font-mono",children:["…",s.sessionId.slice(-12)]}),e.jsx(ce,{value:s.sessionId,className:"opacity-0 focus:opacity-100 group-hover:opacity-100"})]}),e.jsxs("div",{className:"truncate text-[10px] text-muted-foreground/60",children:[s.agent," · ",de(Date.parse(s.createdAt))]})]}),p(s)?e.jsx("button",{type:"button",onClick:t=>{t.stopPropagation(),ee(s.sessionId)},title:"End the live agent process; the transcript stays","aria-label":"Close session",className:"text-muted-foreground/40 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 group-hover:opacity-100",children:e.jsx("svg",{viewBox:"0 0 12 12",className:"size-2.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:e.jsx("path",{d:"M3 3l6 6M9 3l-6 6"})})}):null]},s.sessionId))]})})]}),e.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[e.jsx("div",{className:"absolute right-3 top-2 z-10",children:e.jsx(me,{actorId:n})}),c?e.jsx(e.Fragment,{children:Q.length===0&&!M?e.jsx(K,{children:e.jsxs("div",{className:"flex flex-col items-center gap-5",children:[e.jsx(U,{className:"w-44"}),e.jsx("span",{children:"No activity yet — send a prompt below."})]})}):e.jsx(G,{className:"min-h-0 flex-1",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-3 px-4 py-4",children:[Q.map(s=>e.jsx(fe,{event:s},s.key)),M?e.jsx(ye,{}):null,e.jsx(he,{count:g.length+v.length})]})})}):e.jsx(K,{children:e.jsxs("div",{className:"flex flex-col items-center gap-5",children:[e.jsx(U,{className:"w-44"}),e.jsx("span",{children:"No session selected — press + or send a prompt below to start one."})]})}),e.jsx(Ne,{actorId:n,sessionId:c,sessionStatus:c?(()=>{const s=r.find(t=>t.sessionId===c);return s&&p(s)?"running":"idle"})():void 0,onSessionCreated:O,onErrorEvent:C,onBusyChange:Z})]})]})}export{Ce as TranscriptTabConnected};
@@ -1 +1 @@
1
- import{Y as r,Q as u,N as s}from"./index-AMqbzdhN.js";function t(e,a){return r({...e,enabled:!0,suspense:!0,throwOnError:s,placeholderData:void 0},u)}export{t as u};
1
+ import{Y as r,Q as u,N as s}from"./index-7G_DbdZ6.js";function t(e,a){return r({...e,enabled:!0,suspense:!0,throwOnError:s,placeholderData:void 0},u)}export{t as u};
@@ -0,0 +1 @@
1
+ var K=e=>{throw TypeError(e)};var E=(e,t,s)=>t.has(e)||K("Cannot "+s);var r=(e,t,s)=>(E(e,t,"read from private field"),s?s.call(e):t.get(e)),y=(e,t,s)=>t.has(e)?K("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),f=(e,t,s,i)=>(E(e,t,"write to private field"),i?i.call(e,s):t.set(e,s),s),v=(e,t,s)=>(E(e,t,"access private method"),s);import{v as A,x as N,a0 as R,a1 as Q,w as k,u as U,r as x,J as q,a2 as L,b as V,a3 as B,j as m,d as D,h as F}from"./index-7G_DbdZ6.js";var n,l,o,h,u,C,M,P,G=(P=class extends A{constructor(t,s){super();y(this,u);y(this,n);y(this,l);y(this,o);y(this,h);f(this,n,t),this.setOptions(s),this.bindMethods(),v(this,u,C).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){var i;const s=this.options;this.options=r(this,n).defaultMutationOptions(t),N(this.options,s)||r(this,n).getMutationCache().notify({type:"observerOptionsUpdated",mutation:r(this,o),observer:this}),s!=null&&s.mutationKey&&this.options.mutationKey&&R(s.mutationKey)!==R(this.options.mutationKey)?this.reset():((i=r(this,o))==null?void 0:i.state.status)==="pending"&&r(this,o).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=r(this,o))==null||t.removeObserver(this)}onMutationUpdate(t){v(this,u,C).call(this),v(this,u,M).call(this,t)}getCurrentResult(){return r(this,l)}reset(){var t;(t=r(this,o))==null||t.removeObserver(this),f(this,o,void 0),v(this,u,C).call(this),v(this,u,M).call(this)}mutate(t,s){var i;return f(this,h,s),(i=r(this,o))==null||i.removeObserver(this),f(this,o,r(this,n).getMutationCache().build(r(this,n),this.options)),r(this,o).addObserver(this),r(this,o).execute(t)}},n=new WeakMap,l=new WeakMap,o=new WeakMap,h=new WeakMap,u=new WeakSet,C=function(){var s;const t=((s=r(this,o))==null?void 0:s.state)??Q();f(this,l,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},M=function(t){k.batch(()=>{var s,i,a,p,c,g,S,w;if(r(this,h)&&this.hasListeners()){const b=r(this,l).variables,O=r(this,l).context,j={client:r(this,n),meta:this.options.meta,mutationKey:this.options.mutationKey};if((t==null?void 0:t.type)==="success"){try{(i=(s=r(this,h)).onSuccess)==null||i.call(s,t.data,b,O,j)}catch(d){Promise.reject(d)}try{(p=(a=r(this,h)).onSettled)==null||p.call(a,t.data,null,b,O,j)}catch(d){Promise.reject(d)}}else if((t==null?void 0:t.type)==="error"){try{(g=(c=r(this,h)).onError)==null||g.call(c,t.error,b,O,j)}catch(d){Promise.reject(d)}try{(w=(S=r(this,h)).onSettled)==null||w.call(S,void 0,t.error,b,O,j)}catch(d){Promise.reject(d)}}}this.listeners.forEach(b=>{b(r(this,l))})})},P);function T(e,t){const s=U(),[i]=x.useState(()=>new G(s,e));x.useEffect(()=>{i.setOptions(e)},[i,e]);const a=x.useSyncExternalStore(x.useCallback(c=>i.subscribe(k.batchCalls(c)),[i]),()=>i.getCurrentResult(),()=>i.getCurrentResult()),p=x.useCallback((c,g)=>{i.mutate(c,g).catch(q)},[i]);if(a.error&&L(i.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:p,mutateAsync:a.mutate}}function W({actorId:e,note:t,actionLabel:s,children:i}){const a=V(B(e)),[p,c]=x.useState(!1);return a.data&&!a.data.booted&&!p?m.jsx(D,{children:m.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-2",children:[m.jsx(F,{className:"mb-3 w-44"}),m.jsx("span",{children:t}),m.jsx("button",{type:"button",onClick:()=>c(!0),className:"rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s})]})}):m.jsx(m.Fragment,{children:i})}export{W as V,T as u};
@@ -0,0 +1,5 @@
1
+ import{k as h,b,a3 as j,r as x,c as v,j as t,e as $,g as N,i as w,C as d,f as g}from"./index-7G_DbdZ6.js";function k(s){return h(s)&&s.layer==="contract"}function C(s,r){if((r==null?void 0:r.kind)==="shutdown"){const a=r.reason??"unknown";return a==="error"?{tone:"red",label:"VM shut down after an error"}:{tone:"muted",label:`VM shut down (${a})`}}return s?s.sidecar&&s.sidecar.state!=="ready"?{tone:"red",label:`sidecar ${s.sidecar.state}`}:!s.booted&&(r==null?void 0:r.kind)!=="booted"?{tone:"muted",label:"VM not booted"}:null:null}function S({actorId:s,align:r="right"}){const a=b(j(s)),[p,c]=x.useState(null),[u,f]=x.useState(!1),m=v().useEvent;if(m("vmBooted",()=>{c({kind:"booted"}),a.refetch()}),m("vmShutdown",e=>{c({kind:"shutdown",reason:e==null?void 0:e.reason}),a.refetch()}),a.error&&k(a.error))return null;const n=a.data,o=a.error?{tone:"muted",label:"health unavailable"}:C(n,p),i=((n==null?void 0:n.warnings.length)??0)+((n==null?void 0:n.agentExits.length)??0);return!o&&i===0?null:t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs",children:[o?t.jsxs("span",{className:N("inline-flex items-center gap-1.5 rounded border px-2 py-0.5 text-[11px]",o.tone==="red"?"border-destructive/40 text-destructive":"border-foreground/15 text-muted-foreground"),children:[t.jsx($,{color:o.tone==="red"?"red":"muted"}),o.label]}):null,i>0?t.jsxs("span",{className:"relative",children:[t.jsxs("button",{type:"button",onClick:()=>f(e=>!e),className:"inline-flex items-center gap-1 rounded border border-amber-500/40 px-2 py-0.5 text-[11px] text-amber-500 transition-colors hover:bg-amber-500/10",children:[i," warning",i===1?"":"s",t.jsx(w,{className:`size-2.5 transition-transform ${u?"rotate-90":""}`})]}),u&&n?t.jsxs("div",{className:`absolute top-full z-20 mt-1 max-h-64 w-80 overflow-y-auto rounded-md border bg-background p-2 text-[11px] leading-relaxed shadow-lg ${r==="right"?"right-0":"left-0"}`,children:[n.warnings.length>0?t.jsxs("div",{className:"mb-2",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1 font-medium text-muted-foreground",children:["Limit warnings",t.jsx(d,{value:n.warnings.map(e=>`${new Date(e.ts).toISOString()} ${e.limit} ${e.observed}/${e.capacity} · ${e.fillPercent}%`).join(`
2
+ `)})]}),n.warnings.map((e,l)=>t.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[t.jsxs("span",{children:[e.limit," ",e.observed,"/",e.capacity," · ",e.fillPercent,"%"]}),t.jsx("span",{className:"ml-auto text-muted-foreground",children:g(e.ts)})]},`w-${l}`))]}):null,n.agentExits.length>0?t.jsxs("div",{className:"mb-2",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1 font-medium text-muted-foreground",children:["Agent exits",t.jsx(d,{value:n.agentExits.map(e=>`${new Date(e.ts).toISOString()} ${e.agentType} session=${e.sessionId} exit=${e.exitCode??"?"} restart=${e.restart} (${e.restartCount})`).join(`
3
+ `)})]}),n.agentExits.map((e,l)=>t.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[t.jsxs("span",{children:[e.agentType," exit ",e.exitCode??"?"," · ",e.restart," (",e.restartCount,")"]}),t.jsx("span",{className:"ml-auto text-muted-foreground",children:g(e.ts)})]},`e-${l}`))]}):null,n.stderrTail.length>0?t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1 font-medium text-muted-foreground",children:["Adapter stderr (tail)",t.jsx(d,{value:n.stderrTail.map(e=>e.line).join(`
4
+ `)})]}),t.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-muted-foreground",children:n.stderrTail.map(e=>e.line).join(`
5
+ `)})]}):null]}):null]}):null]})}export{S as V};
@@ -4,8 +4,8 @@
4
4
  <meta charset="utf-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>agentOS inspector</title>
7
- <script type="module" crossorigin src="./assets/index-AMqbzdhN.js"></script>
8
- <link rel="stylesheet" crossorigin href="./assets/index-tcfmhW06.css">
7
+ <script type="module" crossorigin src="./assets/index-7G_DbdZ6.js"></script>
8
+ <link rel="stylesheet" crossorigin href="./assets/index-DG_s1YoH.css">
9
9
  </head>
10
10
  <body>
11
11
  <div id="root"></div>
package/dist/index.d.ts CHANGED
@@ -13,7 +13,11 @@ interface VmShutdownPayload {
13
13
  }
14
14
  type ProcessOutputPayload = ProcessOutput;
15
15
  type ProcessExitPayload = ProcessExit;
16
- type ShellDataPayload = ShellData;
16
+ /** `seq` orders this chunk against `ShellSnapshot.seq`; it is 0 when the shell
17
+ * has no server-side emulator and therefore no replay. */
18
+ type ShellDataPayload = ShellData & {
19
+ seq: number;
20
+ };
17
21
  type ShellExitPayload = ShellExit;
18
22
  type SerializableCronEvent = CronEvent;
19
23
  type ActorData = {
@@ -115,6 +119,41 @@ interface RuntimeHealth {
115
119
  agentExits: RuntimeAgentExit[];
116
120
  stderrTail: RuntimeStderrLine[];
117
121
  }
122
+ /**
123
+ * One live shell from the observe-only `listShells` action. A shell outlives
124
+ * the page that opened it and keeps the VM awake until closed, so enumeration
125
+ * is server-owned rather than tracked per client.
126
+ */
127
+ interface ShellInfo {
128
+ shellId: string;
129
+ /** Epoch ms when the shell was opened through this actor. */
130
+ openedAt: number;
131
+ }
132
+ /**
133
+ * How much of a shell's history a snapshot repaints.
134
+ *
135
+ * - `none` — sequence number only; the caller repaints nothing.
136
+ * - `screen` — the visible viewport, cursor, and terminal modes.
137
+ * - `scrollback` — the retained scrollback above the viewport, then `screen`.
138
+ */
139
+ type ShellReplayMode = "none" | "screen" | "scrollback";
140
+ /**
141
+ * Server-rendered repaint for a shell that is already running. `data` is an
142
+ * ANSI stream to write verbatim into a fresh terminal.
143
+ */
144
+ interface ShellSnapshot {
145
+ shellId: string;
146
+ mode: ShellReplayMode;
147
+ /**
148
+ * Sequence of the last `shellData` chunk folded into this snapshot.
149
+ * Broadcasts carry the same counter, so a client applies the snapshot and
150
+ * then only the chunks whose `seq` is greater — no gap, no double-render.
151
+ */
152
+ seq: number;
153
+ cols: number;
154
+ rows: number;
155
+ data: string;
156
+ }
118
157
  type SerializableCronAction = {
119
158
  type: "session";
120
159
  agentType: string;
@@ -200,6 +239,8 @@ declare function createAgentOsActions(options?: AgentOsOptions, hooks?: AgentOsE
200
239
  openShell: (c: AnyContext, options?: _rivet_dev_agentos_core.ShellOptions | undefined) => Promise<{
201
240
  shellId: string;
202
241
  }>;
242
+ listShells: (c: AnyContext) => Promise<ShellInfo[]>;
243
+ shellSnapshot: (c: AnyContext, shellId: string, mode?: ShellReplayMode) => Promise<ShellSnapshot | null>;
203
244
  writeShell: (c: AnyContext, shellId: string, data: string | Uint8Array<ArrayBufferLike>) => Promise<void>;
204
245
  resizeShell: (c: AnyContext, shellId: string, cols: number, rows: number) => Promise<void>;
205
246
  closeShell: (c: AnyContext, shellId: string) => Promise<void>;
@@ -320,6 +361,8 @@ declare function createAgentOsActions(options?: AgentOsOptions, hooks?: AgentOsE
320
361
  open: (c: AnyContext, options?: _rivet_dev_agentos_core.ShellOptions | undefined) => Promise<{
321
362
  shellId: string;
322
363
  }>;
364
+ list: (c: AnyContext) => Promise<ShellInfo[]>;
365
+ snapshot: (c: AnyContext, shellId: string, mode?: ShellReplayMode) => Promise<ShellSnapshot | null>;
323
366
  write: (c: AnyContext, shellId: string, data: string | Uint8Array<ArrayBufferLike>) => Promise<void>;
324
367
  resize: (c: AnyContext, shellId: string, cols: number, rows: number) => Promise<void>;
325
368
  wait: (c: AnyContext, shellId: string) => Promise<number>;
@@ -419,4 +462,4 @@ declare function createAgentOS<TState = undefined, TConnParams = undefined, TCon
419
462
  */
420
463
  declare const setup: typeof setup$1;
421
464
 
422
- export { type ActorData, type ActorLanguageSpawnOptions, type ActorSpawnOptions, type AgentOsActorConfigInput as AgentOSActorConfigInput, type AgentOsActorConfigInput as AgentOSConfigInput, type AgentOsActions, type AgentOsActorConfigInput, type AgentOsActorExtras, type AgentOsEventHooks, type AgentOsEvents, type ProcessExitPayload, type ProcessOutputPayload, type RuntimeAgentExit, type RuntimeHealth, type RuntimeLimitWarning, type RuntimeSidecarInfo, type RuntimeStderrLine, type SerializableCronAction, type SerializableCronEvent, type SerializableCronJobInfo, type SerializableCronJobOptions, type ShellDataPayload, type ShellExitPayload, type VmBootedPayload, type VmFetchOptions, type VmFetchResponse, type VmFetchStreamChunk, type VmFetchStreamHead, type VmShutdownPayload, createAgentOS as agentOS, createAgentOS, createAgentOsActions, setup };
465
+ export { type ActorData, type ActorLanguageSpawnOptions, type ActorSpawnOptions, type AgentOsActorConfigInput as AgentOSActorConfigInput, type AgentOsActorConfigInput as AgentOSConfigInput, type AgentOsActions, type AgentOsActorConfigInput, type AgentOsActorExtras, type AgentOsEventHooks, type AgentOsEvents, type ProcessExitPayload, type ProcessOutputPayload, type RuntimeAgentExit, type RuntimeHealth, type RuntimeLimitWarning, type RuntimeSidecarInfo, type RuntimeStderrLine, type SerializableCronAction, type SerializableCronEvent, type SerializableCronJobInfo, type SerializableCronJobOptions, type ShellDataPayload, type ShellExitPayload, type ShellInfo, type ShellReplayMode, type ShellSnapshot, type VmBootedPayload, type VmFetchOptions, type VmFetchResponse, type VmFetchStreamChunk, type VmFetchStreamHead, type VmShutdownPayload, createAgentOS as agentOS, createAgentOS, createAgentOsActions, setup };
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
- import "./chunk-V6TY7KAL.js";
1
+ import {
2
+ __publicField
3
+ } from "./chunk-V6TY7KAL.js";
2
4
 
3
5
  // src/index.ts
4
6
  import { setup as rivetkitSetup } from "rivetkit";
@@ -18,6 +20,275 @@ import {
18
20
  } from "rivetkit";
19
21
  import { db } from "rivetkit/db";
20
22
  import { migrations } from "rivetkit/unstable/migrations";
23
+
24
+ // src/shell-replay.ts
25
+ import { readFile } from "fs/promises";
26
+ import { createRequire } from "module";
27
+ var MAX_REPLAY_SHELLS = 32;
28
+ var MAX_SCROLLBACK_LINES = 1e3;
29
+ var MAX_COLS = 1e3;
30
+ var MAX_ROWS = 1e3;
31
+ var DEFAULT_COLS = 80;
32
+ var DEFAULT_ROWS = 24;
33
+ var ghosttyPromise;
34
+ async function loadGhostty() {
35
+ ghosttyPromise ?? (ghosttyPromise = (async () => {
36
+ const require2 = createRequire(import.meta.url);
37
+ const { Ghostty } = await import("ghostty-web");
38
+ const bytes = await readFile(
39
+ require2.resolve("ghostty-web/ghostty-vt.wasm")
40
+ );
41
+ const webAssembly = Reflect.get(globalThis, "WebAssembly");
42
+ if (!webAssembly) {
43
+ throw new Error("WebAssembly is unavailable in this runtime");
44
+ }
45
+ const { instance } = await webAssembly.instantiate(bytes, {
46
+ env: { log: () => {
47
+ } }
48
+ });
49
+ const GhosttyConstructor = Ghostty;
50
+ return new GhosttyConstructor(instance);
51
+ })());
52
+ return ghosttyPromise;
53
+ }
54
+ var CELL_BOLD = 1;
55
+ var CELL_ITALIC = 2;
56
+ var CELL_UNDERLINE = 4;
57
+ var CELL_STRIKETHROUGH = 8;
58
+ var CELL_INVERSE = 16;
59
+ var CELL_INVISIBLE = 32;
60
+ var CELL_BLINK = 64;
61
+ var CELL_FAINT = 128;
62
+ var RESTORED_DEC_MODES = [
63
+ 1,
64
+ // DECCKM — application cursor keys
65
+ 7,
66
+ // DECAWM — autowrap
67
+ 1e3,
68
+ // mouse: click tracking
69
+ 1002,
70
+ // mouse: button-event tracking
71
+ 1003,
72
+ // mouse: any-event tracking
73
+ 1004,
74
+ // focus in/out reporting
75
+ 1005,
76
+ // mouse: UTF-8 coordinates
77
+ 1006,
78
+ // mouse: SGR coordinates
79
+ 1015,
80
+ // mouse: urxvt coordinates
81
+ 2004
82
+ // bracketed paste
83
+ ];
84
+ var DEFAULT_STYLE = { fg: null, bg: null, flags: 0 };
85
+ function rgb(r, g, b) {
86
+ return r << 16 | g << 8 | b;
87
+ }
88
+ function styleOf(cell, defaultFg, defaultBg) {
89
+ const fg = rgb(cell.fg_r, cell.fg_g, cell.fg_b);
90
+ const bg = rgb(cell.bg_r, cell.bg_g, cell.bg_b);
91
+ return {
92
+ fg: fg === defaultFg ? null : fg,
93
+ bg: bg === defaultBg ? null : bg,
94
+ flags: cell.flags
95
+ };
96
+ }
97
+ function sameStyle(a, b) {
98
+ return a.fg === b.fg && a.bg === b.bg && a.flags === b.flags;
99
+ }
100
+ function sgr(style) {
101
+ const params = [0];
102
+ if (style.flags & CELL_BOLD) params.push(1);
103
+ if (style.flags & CELL_FAINT) params.push(2);
104
+ if (style.flags & CELL_ITALIC) params.push(3);
105
+ if (style.flags & CELL_UNDERLINE) params.push(4);
106
+ if (style.flags & CELL_BLINK) params.push(5);
107
+ if (style.flags & CELL_INVERSE) params.push(7);
108
+ if (style.flags & CELL_INVISIBLE) params.push(8);
109
+ if (style.flags & CELL_STRIKETHROUGH) params.push(9);
110
+ if (style.fg !== null) {
111
+ params.push(
112
+ 38,
113
+ 2,
114
+ style.fg >> 16 & 255,
115
+ style.fg >> 8 & 255,
116
+ style.fg & 255
117
+ );
118
+ }
119
+ if (style.bg !== null) {
120
+ params.push(
121
+ 48,
122
+ 2,
123
+ style.bg >> 16 & 255,
124
+ style.bg >> 8 & 255,
125
+ style.bg & 255
126
+ );
127
+ }
128
+ return `\x1B[${params.join(";")}m`;
129
+ }
130
+ function serializeRow(cells, cols, defaultFg, defaultBg, graphemeAt) {
131
+ let lastMeaningful = -1;
132
+ for (let x = 0; x < cols; x++) {
133
+ const cell = cells[x];
134
+ if (!cell) continue;
135
+ const blank = cell.codepoint === 0 || cell.codepoint === 32;
136
+ if (!blank || !sameStyle(styleOf(cell, defaultFg, defaultBg), DEFAULT_STYLE)) {
137
+ lastMeaningful = x;
138
+ }
139
+ }
140
+ if (lastMeaningful < 0) return "\x1B[0m\x1B[K";
141
+ let out = "";
142
+ let current = DEFAULT_STYLE;
143
+ out += sgr(current);
144
+ for (let x = 0; x <= lastMeaningful; x++) {
145
+ const cell = cells[x];
146
+ if (!cell) {
147
+ out += " ";
148
+ continue;
149
+ }
150
+ if (cell.width === 0) continue;
151
+ const style = styleOf(cell, defaultFg, defaultBg);
152
+ if (!sameStyle(style, current)) {
153
+ out += sgr(style);
154
+ current = style;
155
+ }
156
+ if (cell.grapheme_len > 0) {
157
+ out += graphemeAt(x);
158
+ } else if (cell.codepoint === 0) {
159
+ out += " ";
160
+ } else {
161
+ out += String.fromCodePoint(cell.codepoint);
162
+ }
163
+ }
164
+ return `${out}\x1B[0m\x1B[K`;
165
+ }
166
+ function clamp(value, fallback, max) {
167
+ if (!Number.isFinite(value) || value === void 0 || value <= 0)
168
+ return fallback;
169
+ return Math.min(Math.floor(value), max);
170
+ }
171
+ var ShellReplayStore = class {
172
+ constructor() {
173
+ __publicField(this, "entries", /* @__PURE__ */ new Map());
174
+ __publicField(this, "ghostty", null);
175
+ }
176
+ /** Instantiates the WASM module. Callers must await this before opening a
177
+ * shell so that `open` itself can be synchronous: a PTY starts producing
178
+ * output the moment it exists, and any await between opening it and
179
+ * subscribing is a window where output is lost to every consumer. */
180
+ async warm() {
181
+ this.ghostty ?? (this.ghostty = await loadGhostty());
182
+ }
183
+ open(shellId, cols, rows) {
184
+ if (this.entries.has(shellId)) return;
185
+ if (this.entries.size >= MAX_REPLAY_SHELLS) {
186
+ throw new Error(
187
+ `agent-os shell replay limit reached (${MAX_REPLAY_SHELLS} emulators); close a shell or raise MAX_REPLAY_SHELLS in shell-replay.ts`
188
+ );
189
+ }
190
+ if (!this.ghostty) {
191
+ throw new Error("agent-os shell replay used before warm() resolved");
192
+ }
193
+ const width = clamp(cols, DEFAULT_COLS, MAX_COLS);
194
+ const height = clamp(rows, DEFAULT_ROWS, MAX_ROWS);
195
+ const term = this.ghostty.createTerminal(width, height, {
196
+ scrollbackLimit: MAX_SCROLLBACK_LINES
197
+ });
198
+ term.write("\x1Bc");
199
+ this.entries.set(shellId, { term, cols: width, rows: height, seq: 0 });
200
+ }
201
+ /** Feeds one broadcast chunk and returns its sequence number. Clients use
202
+ * it to drop chunks a snapshot already contains. Returns 0 when this shell
203
+ * has no emulator, which clients read as "no replay available". */
204
+ feed(shellId, data) {
205
+ const entry = this.entries.get(shellId);
206
+ if (!entry) return 0;
207
+ entry.term.write(data);
208
+ return ++entry.seq;
209
+ }
210
+ resize(shellId, cols, rows) {
211
+ const entry = this.entries.get(shellId);
212
+ if (!entry) return;
213
+ entry.cols = clamp(cols, entry.cols, MAX_COLS);
214
+ entry.rows = clamp(rows, entry.rows, MAX_ROWS);
215
+ entry.term.resize(entry.cols, entry.rows);
216
+ }
217
+ close(shellId) {
218
+ const entry = this.entries.get(shellId);
219
+ if (!entry) return;
220
+ this.entries.delete(shellId);
221
+ entry.term.free();
222
+ }
223
+ has(shellId) {
224
+ return this.entries.has(shellId);
225
+ }
226
+ snapshot(shellId, mode) {
227
+ const entry = this.entries.get(shellId);
228
+ if (!entry) return null;
229
+ const { term, cols, rows, seq } = entry;
230
+ const base = { shellId, seq, cols, rows };
231
+ if (mode === "none") return { ...base, mode, data: "" };
232
+ term.update();
233
+ const colors = term.getColors();
234
+ const defaultFg = rgb(
235
+ colors.foreground.r,
236
+ colors.foreground.g,
237
+ colors.foreground.b
238
+ );
239
+ const defaultBg = rgb(
240
+ colors.background.r,
241
+ colors.background.g,
242
+ colors.background.b
243
+ );
244
+ const alternate = term.isAlternateScreen();
245
+ let out = "\x1Bc";
246
+ if (mode === "scrollback" && !alternate) {
247
+ const available = Math.min(
248
+ term.getScrollbackLength(),
249
+ MAX_SCROLLBACK_LINES
250
+ );
251
+ for (let i = available; i > 0; i--) {
252
+ const offset = i - 1;
253
+ const line = term.getScrollbackLine(offset);
254
+ if (!line) continue;
255
+ out += serializeRow(
256
+ line,
257
+ cols,
258
+ defaultFg,
259
+ defaultBg,
260
+ (col) => term.getScrollbackGraphemeString(offset, col)
261
+ );
262
+ out += "\r\n";
263
+ }
264
+ }
265
+ if (alternate) out += "\x1B[?1049h";
266
+ for (const decMode of RESTORED_DEC_MODES) {
267
+ out += term.getMode(decMode) ? `\x1B[?${decMode}h` : `\x1B[?${decMode}l`;
268
+ }
269
+ const viewport = term.getViewport();
270
+ out += "\x1B[H";
271
+ for (let y = 0; y < rows; y++) {
272
+ if (y > 0) out += "\r\n";
273
+ const row = viewport.slice(y * cols, (y + 1) * cols);
274
+ out += serializeRow(
275
+ row,
276
+ cols,
277
+ defaultFg,
278
+ defaultBg,
279
+ (col) => term.getGraphemeString(y, col)
280
+ );
281
+ }
282
+ const cursor = term.getCursor();
283
+ const cy = Math.min(Math.max(cursor.viewportY, 0), rows - 1) + 1;
284
+ const cx = Math.min(Math.max(cursor.viewportX, 0), cols - 1) + 1;
285
+ out += `\x1B[0m\x1B[${cy};${cx}H`;
286
+ out += cursor.visible ? "\x1B[?25h" : "\x1B[?25l";
287
+ return { ...base, mode, data: out };
288
+ }
289
+ };
290
+
291
+ // src/actor.ts
21
292
  var DEFAULT_ACTION_TIMEOUT_MS = 2147483647;
22
293
  var DEFAULT_SLEEP_GRACE_PERIOD_MS = 15 * 6e4;
23
294
  var DEFAULT_PREVIEW_TTL_SECONDS = 3600;
@@ -31,6 +302,7 @@ var ACTOR_SQLITE_INLINE_THRESHOLD = 64 * 1024;
31
302
  var ROOT_NAMESPACE = "agentos-root";
32
303
  var PREVIEW_PATH_PATTERN = /^\/fetch\/([a-f0-9]{48})(\/.*)?$/;
33
304
  var MAX_SQLITE_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
305
+ var MAX_OPEN_SHELLS = 32;
34
306
  var ACTOR_SQLITE_MIGRATIONS = [
35
307
  {
36
308
  version: 1,
@@ -91,6 +363,9 @@ function runtimeFor(c) {
91
363
  if (!runtime) {
92
364
  runtime = {
93
365
  vm: null,
366
+ bootedVm: null,
367
+ openShells: /* @__PURE__ */ new Map(),
368
+ shellReplay: new ShellReplayStore(),
94
369
  subscribedSessions: /* @__PURE__ */ new Map(),
95
370
  vmCleanupRan: false,
96
371
  fetchStreamHolds: /* @__PURE__ */ new Map()
@@ -243,6 +518,7 @@ async function ensureVm(c, options) {
243
518
  }
244
519
  }
245
520
  vm.onCronEvent((cronEvent) => c.broadcast("cronEvent", cronEvent));
521
+ runtime.bootedVm = vm;
246
522
  c.broadcast("vmBooted", {});
247
523
  c.log.info({
248
524
  msg: "agent-os vm booted",
@@ -254,6 +530,7 @@ async function ensureVm(c, options) {
254
530
  return await runtime.vm;
255
531
  } catch (error) {
256
532
  runtime.vm = null;
533
+ runtime.bootedVm = null;
257
534
  c.log.error({
258
535
  msg: "agent-os vm bootstrap failed",
259
536
  actorId: c.actorId,
@@ -268,6 +545,7 @@ async function disposeVm(c, reason) {
268
545
  const runtime = runtimes.get(c.actorId);
269
546
  if (!runtime) return;
270
547
  const vm = runtime.vm;
548
+ runtime.bootedVm = null;
271
549
  runtimes.delete(c.actorId);
272
550
  for (const unsubscribers of runtime.subscribedSessions.values()) {
273
551
  for (const unsubscribe of unsubscribers) unsubscribe();
@@ -813,14 +1091,30 @@ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubsc
813
1091
  },
814
1092
  openShell: async (c, ...args) => {
815
1093
  const vm = await ensureVm(c, options);
1094
+ const runtime = runtimeFor(c);
1095
+ if (runtime.openShells.size >= MAX_OPEN_SHELLS) {
1096
+ throw new Error(
1097
+ `agent-os shell limit reached (${MAX_OPEN_SHELLS} open); close a shell or raise MAX_OPEN_SHELLS`
1098
+ );
1099
+ }
1100
+ await runtime.shellReplay.warm();
816
1101
  const shell = vm.terminal.open(...args);
1102
+ runtime.openShells.set(shell.shellId, { openedAt: Date.now() });
1103
+ runtime.shellReplay.open(shell.shellId, args[0]?.cols, args[0]?.rows);
817
1104
  const unsubscribeData = vm.onShellData(
818
1105
  shell.shellId,
819
- (event2) => c.broadcast("shellData", event2)
1106
+ (event2) => c.broadcast("shellData", {
1107
+ ...event2,
1108
+ seq: runtime.shellReplay.feed(event2.shellId, event2.data)
1109
+ })
820
1110
  );
821
1111
  const unsubscribeStderr = vm.onShellStderr(
822
1112
  shell.shellId,
823
- (event2) => c.broadcast("shellStderr", event2)
1113
+ (event2) => (
1114
+ // A diagnostic tap carrying bytes `shellData` already delivered, so
1115
+ // it is never folded into replay and carries no sequence.
1116
+ c.broadcast("shellStderr", { ...event2, seq: 0 })
1117
+ )
824
1118
  );
825
1119
  const unsubscribeExit = vm.onShellExit(
826
1120
  shell.shellId,
@@ -828,6 +1122,8 @@ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubsc
828
1122
  );
829
1123
  void c.keepAwake(
830
1124
  vm.terminal.wait(shell.shellId).finally(() => {
1125
+ runtime.openShells.delete(shell.shellId);
1126
+ runtime.shellReplay.close(shell.shellId);
831
1127
  unsubscribeData();
832
1128
  unsubscribeStderr();
833
1129
  unsubscribeExit();
@@ -841,8 +1137,29 @@ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubsc
841
1137
  );
842
1138
  return shell;
843
1139
  },
1140
+ // Observe-only: enumerates shells this actor opened without booting a
1141
+ // sleeping VM (a sleeping VM has none). Clients must not track shell ids
1142
+ // themselves — a shell outlives the page that opened it and keeps the VM
1143
+ // awake, so it has to stay discoverable.
1144
+ listShells: async (c) => {
1145
+ const runtime = runtimes.get(c.actorId);
1146
+ if (!runtime?.bootedVm) return [];
1147
+ return [...runtime.openShells.entries()].map(([shellId, entry]) => ({ shellId, openedAt: entry.openedAt })).sort((a, b) => a.openedAt - b.openedAt);
1148
+ },
844
1149
  writeShell: async (c, ...args) => (await ensureVm(c, options)).terminal.write(...args),
845
- resizeShell: async (c, ...args) => (await ensureVm(c, options)).terminal.resize(...args),
1150
+ resizeShell: async (c, ...args) => {
1151
+ const result = (await ensureVm(c, options)).terminal.resize(...args);
1152
+ runtimeFor(c).shellReplay.resize(args[0], args[1], args[2]);
1153
+ return result;
1154
+ },
1155
+ // Observe-only, like `listShells`: repainting a shell must never boot a
1156
+ // VM, and a sleeping VM has no live shells to repaint. Returns `null`
1157
+ // for an unknown shell so a client falls back to no replay.
1158
+ shellSnapshot: async (c, shellId, mode = "screen") => {
1159
+ const runtime = runtimes.get(c.actorId);
1160
+ if (!runtime?.bootedVm) return null;
1161
+ return runtime.shellReplay.snapshot(shellId, mode);
1162
+ },
846
1163
  closeShell: async (c, ...args) => (await ensureVm(c, options)).terminal.close(...args),
847
1164
  waitShell: async (c, ...args) => (await ensureVm(c, options)).terminal.wait(...args),
848
1165
  httpRequest: async (c, ...args) => (await ensureVm(c, options)).network.httpRequest(...args),
@@ -927,20 +1244,15 @@ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubsc
927
1244
  let booted = false;
928
1245
  let sessions = null;
929
1246
  let sidecar = null;
930
- if (runtime?.vm) {
931
- const vm = await Promise.race([
932
- runtime.vm.catch(() => null),
933
- Promise.resolve(null)
934
- ]);
935
- if (vm) {
936
- booted = true;
937
- sessions = runtime.subscribedSessions.size;
938
- const description = vm.sidecar.describe();
939
- sidecar = {
940
- state: description.state,
941
- activeVmCount: description.activeVmCount
942
- };
943
- }
1247
+ const vm = runtime?.bootedVm;
1248
+ if (runtime && vm) {
1249
+ booted = true;
1250
+ sessions = runtime.subscribedSessions.size;
1251
+ const description = vm.sidecar.describe();
1252
+ sidecar = {
1253
+ state: description.state,
1254
+ activeVmCount: description.activeVmCount
1255
+ };
944
1256
  }
945
1257
  return {
946
1258
  booted,
@@ -1228,6 +1540,8 @@ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubsc
1228
1540
  },
1229
1541
  terminal: {
1230
1542
  open: flat.openShell,
1543
+ list: flat.listShells,
1544
+ snapshot: flat.shellSnapshot,
1231
1545
  write: flat.writeShell,
1232
1546
  resize: flat.resizeShell,
1233
1547
  wait: flat.waitShell,
@@ -1313,6 +1627,8 @@ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubsc
1313
1627
  writeProcessStdin: nested.process.writeStdin,
1314
1628
  closeProcessStdin: nested.process.closeStdin,
1315
1629
  openShell: nested.terminal.open,
1630
+ listShells: nested.terminal.list,
1631
+ shellSnapshot: nested.terminal.snapshot,
1316
1632
  writeShell: nested.terminal.write,
1317
1633
  resizeShell: nested.terminal.resize,
1318
1634
  closeShell: nested.terminal.close,
@@ -1434,6 +1750,12 @@ var AGENTOS_INSPECTOR_CONFIG = {
1434
1750
  source: INSPECTOR_TABS_ASSET_DIR,
1435
1751
  icon: "folder-tree"
1436
1752
  },
1753
+ {
1754
+ id: "terminal",
1755
+ label: "Terminal",
1756
+ source: INSPECTOR_TABS_ASSET_DIR,
1757
+ icon: "terminal"
1758
+ },
1437
1759
  {
1438
1760
  id: "system",
1439
1761
  label: "System",