@seqyuan/annovibe 0.8.129 → 0.8.130
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +8 -8
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/agent/runtime/route.js +1 -1
- package/.next/server/app/api/internal/runtime/route.js +1 -1
- package/.next/server/app/api/projects/browse/route.js +1 -1
- package/.next/server/app/api/version/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +2 -2
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/index.segments/_full.segment.rsc +2 -2
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +1 -1
- package/.next/server/app/login.rsc +1 -1
- package/.next/server/app/login.segments/_full.segment.rsc +1 -1
- package/.next/server/app/login.segments/_head.segment.rsc +1 -1
- package/.next/server/app/login.segments/_index.segment.rsc +1 -1
- package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/login.segments/login.segment.rsc +1 -1
- package/.next/server/app/page.js +23 -23
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/smoke/page_client-reference-manifest.js +1 -1
- package/.next/server/app/smoke/session-stream/page_client-reference-manifest.js +1 -1
- package/.next/server/app/smoke/session-stream.html +1 -1
- package/.next/server/app/smoke/session-stream.rsc +2 -2
- package/.next/server/app/smoke/session-stream.segments/_full.segment.rsc +2 -2
- package/.next/server/app/smoke/session-stream.segments/_head.segment.rsc +1 -1
- package/.next/server/app/smoke/session-stream.segments/_index.segment.rsc +1 -1
- package/.next/server/app/smoke/session-stream.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/smoke/session-stream.segments/smoke/session-stream/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/smoke/session-stream.segments/smoke/session-stream.segment.rsc +1 -1
- package/.next/server/app/smoke/session-stream.segments/smoke.segment.rsc +1 -1
- package/.next/server/app/smoke.html +2 -2
- package/.next/server/app/smoke.rsc +2 -2
- package/.next/server/app/smoke.segments/_full.segment.rsc +2 -2
- package/.next/server/app/smoke.segments/_head.segment.rsc +1 -1
- package/.next/server/app/smoke.segments/_index.segment.rsc +1 -1
- package/.next/server/app/smoke.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/smoke.segments/smoke/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/smoke.segments/smoke.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +8 -8
- package/.next/server/chunks/4584.js +1 -1
- package/.next/server/chunks/9230.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/{4456-3e2863e213864ce5.js → 4456-91f92907e8ef1f89.js} +2 -2
- package/.next/static/chunks/{9544-fc173153bf9a575d.js → 9544-5e2696923ae4f6b5.js} +1 -1
- package/.next/static/chunks/app/page-252ec85583b84aaa.js +44 -0
- package/package.json +1 -1
- package/.next/static/chunks/app/page-587c43474c9791be.js +0 -44
- /package/.next/static/{4FZ3Kf2g-93anWbAj4gqr → pD4GKzugLztRoTHeAKj_C}/_buildManifest.js +0 -0
- /package/.next/static/{4FZ3Kf2g-93anWbAj4gqr → pD4GKzugLztRoTHeAKj_C}/_ssgManifest.js +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9544],{9544:(e,t,n)=>{n.d(t,{T:()=>z});var r=n(12115);function a(e){return e?.phase==="running_tools"?{kind:"running_tools",tools:(e.activeTools??[]).map(e=>({id:e.id,name:e.name}))}:e?.phase==="streaming"||e?.phase==="compacting"||e?.phase==="idle"?null:{kind:"waiting_model"}}function s(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:n}}function o(e){if("assistant"!==e.role)return null;let t=e.timestamp;return"number"!=typeof t?null:`assistant:${t}`}class l extends Error{constructor(e,t,n){super(e),this.status=t,this.code=n,this.name="AgentCommandError"}}async function i(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new l(r.error??`HTTP ${n.status}`,n.status,r.code);return r.data}var u=n(28999);async function c(e,t){if(!t.length)return[];let n=await fetch("/api/images/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,images:t.map(e=>({data:e.data,mimeType:e.mimeType,name:e.name}))})}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw Error(r.error??`Upload failed (HTTP ${n.status})`);return(r.uploaded??[]).map((e,n)=>({...e,previewUrl:t[n]?.previewUrl}))}async function d(e,t,n){let r,a=new TextDecoder,s="",o=e=>{if(e.startsWith("id: ")){r=e.slice(4);return}if(!e.startsWith("data: "))return;let n=e.slice(6);if("[DONE]"!==n)try{t(n,r)}catch{}finally{r=void 0}},l=new Promise(e=>{n?.aborted?e():n?.addEventListener("abort",()=>e(),{once:!0})});for(;;){let t=await Promise.race([e.read(),l.then(()=>({done:!0,value:void 0}))]);if(t.done)break;let n=(s+=a.decode(t.value,{stream:!0})).split("\n");for(let e of(s=n.pop()||"",n))o(e)}if(s.trim())for(let e of s.split("\n"))o(e)}var p=n(16865);let m="__annovibeStreamSessions__",f="__annovibeStreamListeners__",g="__annovibeStreamErrorCallbacks__";function h(){let e=globalThis;return e[m]||(e[m]=new Map),e[m]}function y(){let e=globalThis;return e[g]||(e[g]=new Map),e[g]}function w(e){return{sessionId:e,phase:"idle",startedAt:null,lastEventAt:null,lastHeartbeatAt:null,reconnectCount:0,lastSyncReason:null,accumulatedText:"",toolCalls:[],toolResults:[],statusText:null,streamingMessage:null,isStreaming:!1,error:null}}function v(e,t){let n;for(let r of(!(n=globalThis)[f]&&(n[f]=new Map),n[f]).get(e)??[])try{r(t)}catch{}}function b(e){e.textThrottleTimer&&(clearTimeout(e.textThrottleTimer),e.textThrottleTimer=null),e.textDirty&&(e.textDirty=!1,C(e))}function T(e,t=!1){let n=Date.now();if(e.snapshot.lastEventAt=n,!t){e.textDirty=!0,e.textThrottleTimer||(e.textThrottleTimer=setTimeout(()=>{e.textThrottleTimer=null,e.textDirty&&(e.textDirty=!1,C(e))},100));return}b(e),C(e)}function C(e,t){let n=Date.now(),r=function(e){let t=[];for(let n of e.toolCalls.values())t.push({type:"toolCall",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input??{}});let n=e.accumulatedText.trim();return n&&t.push({type:"text",text:n}),t}(e),a=(t??e.snapshot.phase)==="active";e.snapshot={...e.snapshot,phase:t??e.snapshot.phase,lastEventAt:n,accumulatedText:e.accumulatedText,toolCalls:[...e.toolCalls.values()],toolResults:[...e.toolResults.values()],statusText:a?function(e){if(e.activeToolId){let t=e.toolCalls.get(e.activeToolId);if(t){let e=Math.max(0,Math.floor((Date.now()-t.startedAt)/1e3));return`Running ${t.toolName||"tool"}… (${e}s)`}}return e.accumulatedText.trim()?"Generating response…":e.toolCalls.size>0?"Finishing tool results…":null}(e):e.snapshot.statusText,streamingMessage:a&&r.length>0?{role:"assistant",content:r}:null,isStreaming:a},v(e.snapshot.sessionId,{type:"snapshot-updated",snapshot:e.snapshot})}function k(e){I(e),e.idleCheckTimer=setInterval(()=>{if("connected"!==e.connectionState)return;let t=Math.max(e.snapshot.lastEventAt??0,e.snapshot.lastHeartbeatAt??0);if(Date.now()-t>=18e4){S(e),b(e);let t="Stream idle timeout — no activity for 180s.";e.snapshot={...e.snapshot,phase:"error",isStreaming:!1,streamingMessage:null,statusText:null,error:t},I(e),v(e.snapshot.sessionId,{type:"error",snapshot:e.snapshot});let n=y().get(e.snapshot.sessionId);if(n)try{n(e.snapshot.sessionId,t)}catch{}}},1e4)}function I(e){e.idleCheckTimer&&(clearInterval(e.idleCheckTimer),e.idleCheckTimer=null)}function S(e){e.toolProgressTimer&&(clearInterval(e.toolProgressTimer),e.toolProgressTimer=null)}function _(e){let t=h(),n=t.get(e);return n||(n={snapshot:w(e),accumulatedText:"",toolCalls:new Map,toolResults:new Map,toolProgressTimer:null,activeToolId:null,textThrottleTimer:null,textDirty:!1,connectionState:"idle",idleCheckTimer:null},t.set(e,n)),n}function x(e,t){let n=y();return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function E(e){let t=h(),n=t.get(e);n&&(S(n),I(n),b(n)),t.delete(e)}function M(e){let t=h().get(e);t&&(t.snapshot={...t.snapshot,reconnectCount:t.snapshot.reconnectCount+1,lastSyncReason:"sse-reconnect",lastEventAt:Date.now()},T(t,!0))}let A="__annovibeSessionMessageCache__";function R(){let e=globalThis;if(!e[A]){var t;let n={entries:new Map,cleanupTimer:null};e[A]=n,(t=n).cleanupTimer||(t.cleanupTimer=setInterval(()=>{let e=Date.now();for(let[n,r]of t.entries)e-r.loadedAt>72e5&&t.entries.delete(n)},6e4))}return e[A]}function $(e){let t=R(),n=t.entries.get(e);return n?Date.now()-n.loadedAt>72e5?(t.entries.delete(e),null):(n.loadedAt=Date.now(),{...n,messages:[...n.messages],entryIds:[...n.entryIds]}):null}function D(e,t,n,r,a){let s=R(),o=s.entries.get(e);if(!o)return;let l=new Set(o.entryIds),i=[],u=[];for(let e=0;e<t.length;e++){let r=n[e];r&&!l.has(r)&&(i.push(t[e]),u.push(r))}0!==i.length&&s.entries.set(e,{...o,messages:[...i,...o.messages],entryIds:[...u,...o.entryIds],hasMore:r,loadedMessagesCount:a,loadedAt:Date.now()})}function L(e){R().entries.delete(e)}var N=n(14755);function P(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function U(e,t){return new DOMException(e,t)}function j(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}-${Math.random().toString(36).slice(2,11)}`}function O(e,t){return e.trim()||0!==t?`text:${e}|images:${t}`:null}function F(e){return"string"==typeof e?O(e,0):Array.isArray(e)?O(e.filter(e=>!!e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n"),e.filter(e=>!!e&&"object"==typeof e&&"image"===e.type).length):null}function H(e){let t=new Map;for(let n of e){let e="user"!==n.role?null:F(n.content);e&&t.set(e,(t.get(e)??0)+1)}return t}function J(e,t,n){return e.sessionId===t&&(!e.leafId||n.includes(e.leafId))}function B(e,t){let n=e.timestamp,r=t.timestamp;if("number"!=typeof n||"number"!=typeof r||n!==r||e.role!==t.role)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function z(e){let{session:t,newSessionCwd:n,onAgentEnd:m,onSessionCreated:f,onSessionForked:g,modelsRefreshKey:y,onBranchDataChange:C}=e,A=null===t&&null!==n,[z,K]=(0,r.useState)(null),[W,q]=(0,r.useState)(!A),[G,V]=(0,r.useState)(null),[Y,Q]=(0,r.useState)(null),[X,Z]=(0,r.useState)([]),[ee,et]=(0,r.useState)([]),[en,er]=(0,r.useState)(0),[ea,es]=(0,r.useState)(!1),[eo,el]=(0,r.useState)(0),[ei,eu]=(0,r.useReducer)(P,{isStreaming:!1,streamingMessage:null}),[ec,ed]=(0,r.useState)(!1),[ep,em]=(0,r.useState)({}),[ef,eg]=(0,r.useState)([]),[eh,ey]=(0,r.useState)({}),[ew,ev]=(0,r.useState)({}),[eb,eT]=(0,r.useState)(null),[eC,ek]=(0,r.useState)("full"),[eI,eS]=(0,r.useState)([...N.SN]),[e_,ex]=(0,r.useState)("auto"),[eE,eM]=(0,r.useState)(null),[eA,eR]=(0,r.useState)(null),[e$,eD]=(0,r.useState)(null),[eL,eN]=(0,r.useState)(null),[eP,eU]=(0,r.useState)(null),[ej,eO]=(0,r.useState)(null),[eF,eH]=(0,r.useState)(!1),[eJ,eB]=(0,r.useState)(null),[ez,eK]=(0,r.useState)(null),[eW,eq]=(0,r.useState)(null),[eG,eV]=(0,r.useState)(null),eY=(0,r.useRef)(null),eQ=(0,r.useRef)(t?.id??null),eX=(0,r.useRef)(!1),eZ=(0,r.useRef)(null),e0=(0,r.useRef)(null),e1=(0,r.useRef)(null),e4=(0,r.useRef)(!1),e3=(0,r.useRef)(null),e5=(0,r.useRef)(!1),e2=(0,r.useRef)(null),e6=(0,r.useRef)(null),e8=(0,r.useRef)(new Map),e9=(0,r.useRef)(new Map),e7=(0,r.useRef)(new Map),te=(0,r.useRef)(new Map),tt=(0,r.useRef)(null),tn=(0,r.useRef)([]),tr=(0,r.useRef)(null),ta=(0,r.useRef)(0),ts=(0,r.useRef)(!1),to=(0,r.useRef)(0),tl=(0,r.useRef)(!1),ti=(0,r.useRef)(!1),tu=(0,r.useRef)(0),tc=(0,r.useRef)(null),td=(0,r.useRef)(null),tp=(0,r.useRef)(0),tm=(0,r.useRef)(!1);(0,r.useEffect)(()=>{tt.current=Y},[Y]),(0,r.useEffect)(()=>{tm.current=ei.isStreaming},[ei.isStreaming]),(0,r.useEffect)(()=>{te.current.clear()},[t?.id]);let tf=e.setNewSessionModel??eT,tg=e.setToolPreset??ek,th=e.setMemoryTools??eS,ty=eP??z?.context.model??ej??null,tw=A?eb:ty,tv=(0,r.useCallback)(()=>(0,N.tE)(eC,eI),[eI,eC]),tb=(0,r.useCallback)(e=>e?.length?e.map((e,t)=>{let n=`Attachment ${t+1}: ${e.fileName} (${e.mimeType||"application/octet-stream"}, ${e.size} bytes)`;if(e.extractedText){let t=e.truncated?"\n[The extracted text was truncated before sending.]":"";return`${n}
|
|
2
2
|
${t}
|
|
3
3
|
${e.extractedText}`.trim()}return`${n}
|
|
4
|
-
[Text extraction unavailable: ${e.extractionError??"unsupported file type"}]`}).join("\n\n---\n\n"):"",[]),tT=(0,r.useCallback)(async e=>{let t=await fetch(`/api/agent/${encodeURIComponent(e)}/prepare`,{method:"POST"});if(!t.ok)throw Error((await t.json().catch(()=>({}))).error??`Failed to prepare session (HTTP ${t.status})`)},[]),tC=(()=>{let e={input:0,output:0,cacheRead:0,cacheWrite:0},t=0;for(let n of X){if("assistant"!==n.role)continue;let r=n.usage;r&&(e.input+=r.input??0,e.output+=r.output??0,e.cacheRead+=r.cacheRead??0,e.cacheWrite+=r.cacheWrite??0,t+=r.cost?.total??0)}return e.input+e.output+e.cacheRead+e.cacheWrite>0?{tokens:e,cost:t}:null})(),tk=(0,r.useRef)(!1),tI=(0,r.useCallback)(async()=>{let e=eQ.current;if(!e||tk.current||tl.current)return;tk.current=!0,ts.current=!0;let t=0,n=$(e);t=n?n.loadedMessagesCount:50;try{for(;;)try{let n=await fetch(`/api/sessions/${encodeURIComponent(e)}?limit=100&offset=${t}`);if(!n.ok)break;let r=await n.json();if(eQ.current!==e)break;let a=r.context.messages,s=r.context.entryIds??[];if(0===a.length)break;Z(e=>[...a,...e]),et(e=>{let t=[...s,...e];return tn.current=t,t});let o=t+a.length;if(el(o),to.current=o,es(r.hasMore??!1),D(e,a,s,r.hasMore??!1,o),t=o,!r.hasMore)break;await new Promise(e=>setTimeout(e,800))}catch{break}}finally{tk.current=!1,tl.current=!0,ts.current=!1}},[]),tS=(0,r.useCallback)(async(e,t=!1,n=!1,r=!1)=>{var a;let s=null;try{if(t&&q(!0),!n&&!eX.current&&!r){let n=$(e);if(n)return er(n.totalMessages),es(n.hasMore),el(n.loadedMessagesCount),Z(n.messages),tn.current=n.entryIds,et(n.entryIds),tt.current=n.leafId,Q(n.leafId),to.current=n.loadedMessagesCount,t&&q(!1),n.hasMore&&!tl.current&&setTimeout(()=>{tI()},1500),null}let l=n?`/api/sessions/${encodeURIComponent(e)}?includeState`:`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=0`,i=td.current;if(i?.sid===e&&!t)return null;i?.controller.abort(U("Session load superseded","AbortError"));let u=new AbortController;s=u,td.current={sid:e,controller:u};let c=setTimeout(()=>{u.abort(U("Session load timed out after 30 seconds","TimeoutError"))},3e4),d=await fetch(l,{signal:u.signal}).finally(()=>clearTimeout(c));if(eQ.current&&eQ.current!==e)return null;if(404===d.status)return t&&(K(null),tt.current=null,Q(null),Z([]),V(null)),null;if(!d.ok)throw Error(`HTTP ${d.status}`);let p=await d.json();n?(er(p.totalMessages??p.context.messages.length),es(!1)):(er(p.totalMessages??p.context.messages.length),es(p.hasMore??!1)),el(p.context.messages.length),K(p),tt.current=p.leafId,Q(p.leafId);let m=p.context.messages,f=H(m),g=new Map,h=Date.now();for(let[t,n]of e8.current)if(n.sessionId===e){if(h-n.createdAt>12e4){e8.current.delete(t);continue}if(n.confirmKey){let e=f.get(n.confirmKey)??0,r=g.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(e8.current.delete(t),g.set(n.confirmKey,r+1))}}e9.current=f;let y=p.context.entryIds??[],w=[...e8.current.values()].filter(t=>J(t,e,y)).map(e=>e.message),v=w.length>0?[...m,...w]:m,b=function(e,t,n){if(0===t.size)return e;let r=!1,a=e.map(e=>{let a=o(e);if(!a)return e;let s=t.get(a);return s?n-s.observedAt>5e3||function(e,t){let n=e.timestamp,r=t.timestamp;if("number"!=typeof n||"number"!=typeof r||n!==r||e.role!==t.role)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}(s.message,e)?(t.delete(a),e):(r=!0,s.message):e});return r?a:e}(v,te.current,Date.now()),T=e7.current.get(e);if(T){for(let[e,t]of T)h-t>12e4&&T.delete(e);0===T.size&&e7.current.delete(e)}let C=T?.size?T:null,k=C?new Set(y):null,I=!!C&&!!k&&[...C.keys()].some(e=>!k.has(e));C&&k&&!I&&e7.current.delete(e);let S=b.length;return!n&&(to.current>S||I)?(er(p.totalMessages??p.context.messages.length),es(p.hasMore??!1)):(Z(e=>(function(e,t){if(e.length!==t.length)return t;let n=!1,r=t.map((t,r)=>B(e[r],t)?e[r]:(n=!0,t));return n?r:e})(e,b)),tn.current=y,et(y),n?to.current=S:to.current=Math.max(to.current,S),a={sessionId:e,leafId:p.leafId,messages:b,entryIds:y,totalMessages:p.totalMessages??p.context.messages.length,hasMore:!n&&(p.hasMore??!1),loadedMessagesCount:p.context.messages.length},R().entries.set(e,{...a,loadedAt:Date.now()})),eU(e=>{if(!e)return null;let t=p.context.model;return t?.provider===e.provider&&t.modelId===e.modelId?null:e}),V(null),!p.agentState?.state?.thinkingLevel&&p.context.thinkingLevel&&"off"!==p.context.thinkingLevel&&ex(p.context.thinkingLevel),p.agentState??null}catch(e){if(e instanceof DOMException&&("AbortError"===e.name||"TimeoutError"===e.name)||e instanceof Error&&/aborted without reason|AbortError|Session load (?:timed out|superseded)/i.test(e.message))return null;return V(String(e)),null}finally{s&&td.current?.controller===s&&(td.current=null),t&&q(!1)}},[tI]),t_=(0,r.useRef)(!1),tx=(0,r.useCallback)(async()=>{if(t_.current)return;t_.current=!0;let e=eQ.current;if(!e){t_.current=!1;return}try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=${eo}`);if(!t.ok)return;let n=await t.json(),r=n.context.messages,a=n.context.entryIds??[];Z(e=>[...r,...e]),et(e=>{let t=[...a,...e];return tn.current=t,t}),el(e=>e+r.length),es(n.hasMore??!1),D(e,r,a,n.hasMore??!1,eo+r.length)}catch{}finally{t_.current=!1}},[eo]),tE=(0,r.useCallback)(async e=>{let t=eQ.current;if(!t)return[];let n=tt.current,r=n?`?leafId=${encodeURIComponent(n)}`:"";try{let n=await fetch(`/api/sessions/${encodeURIComponent(t)}/shadowed${r}`);if(!n.ok)return[];let a=await n.json(),s=a.groups?.find(t=>t.compactionEntryId===e);return s?.messages??[]}catch{return[]}},[]),tM=(0,r.useCallback)(async(e,t)=>{try{let n=t?`/api/sessions/${encodeURIComponent(e)}/context?leafId=${encodeURIComponent(t)}`:`/api/sessions/${encodeURIComponent(e)}/context`,r=await fetch(n);if(!r.ok)throw Error(`HTTP ${r.status}`);let a=await r.json(),s=a.context.messages,o=a.context.entryIds??[],l=H(s),i=new Map,u=Date.now();for(let[t,n]of e8.current)if(n.sessionId===e){if(u-n.createdAt>12e4){e8.current.delete(t);continue}if(n.confirmKey){let e=l.get(n.confirmKey)??0,r=i.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(e8.current.delete(t),i.set(n.confirmKey,r+1))}}e9.current=l;let c=[...e8.current.values()].filter(t=>J(t,e,o)).map(e=>e.message);Z(c.length>0?[...s,...c]:s),tn.current=o,et(o)}catch(e){console.error("Failed to load context:",e)}},[]),tA=(0,r.useCallback)(async e=>{try{let t=await i(e,{type:"get_tools"});t&&(tg((0,N.ES)(t)),th((0,N.IB)(t)))}catch(e){console.error("Failed to load tools:",e)}},[th,tg]),tR=(0,r.useCallback)((e,t={})=>{eY.current?.close(),eY.current=null;let n=`/api/agent/${encodeURIComponent(e)}/events${t.replay?"?replay=1":""}`;return!function(e){let t=_(e);if("active"===t.snapshot.phase)return T(t,!0),k(t),t.snapshot;let n=Date.now();t.snapshot={...w(e),phase:"active",startedAt:n,lastEventAt:n,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},k(t),T(t,!0),t.snapshot}(e),new Promise((r,a)=>{let s=!1,o=!1,l=null,i=e=>{if(!s){if(s=!0,clearTimeout(u),e){l?.close(),eY.current===l&&(eY.current=null),a(e);return}r()}},u=setTimeout(()=>{t.requireConnected?i(Error("Timed out waiting for event stream connection")):i()},t.timeoutMs??3e4);eY.current=l=function(e){let{url:t,onEvent:n,onStateChange:r,onFatalError:a,maxReconnectAttempts:s=1/0,reconnectBaseMs:o=1e3,reconnectMaxMs:l=3e4,autoReconnect:i=!0}=e,u="idle",c=new AbortController,p=0,m=null,f=null,g=!1,h=(e,t)=>{t&&(f=t),n(e,t)},y=e=>{u!==e&&(u=e,r?.(e))},w=()=>{null!==m&&(clearTimeout(m),m=null)},v=()=>{if(g)return;if(!i)return void y("error");if(p>=s){y("error"),a?.(Error(`Max reconnect attempts (${s}) reached`));return}let e=Math.min(l,o*2**p);p+=1,y("connecting"),m=setTimeout(()=>{m=null,b()},e)},b=async()=>{if(!g){w(),c=new AbortController,y("connecting");try{let e=await fetch(t,{signal:c.signal,headers:{Accept:"text/event-stream","Cache-Control":"no-cache",...f?{"Last-Event-ID":f}:{}}});if(!e.ok)throw Error(`HTTP ${e.status}: ${e.statusText}`);let n=e.body;if(!n)throw Error("Response has no readable body");let r=n.getReader();if(y("connected"),p=0,await d(r,h,c.signal),c.signal.aborted)try{await r.cancel()}catch{}r.releaseLock(),y("closed"),!g&&i&&v()}catch(e){if(g||e instanceof DOMException&&"AbortError"===e.name)return void y("closed");y("error"),i&&v()}}};return{get state(){return u},connect:()=>{g=!1,p=0,w(),b()},close:()=>{g=!0,w(),c.abort(),y("closed")},get abortController(){return c}}}({url:n,onEvent:t=>{try{let n=JSON.parse(t);if("connected"===n.type&&i(),eQ.current!==e)return;eZ.current?.(n)}catch{}},onStateChange:t=>{!function(e,t){let n=h().get(e);if(!n)return;let r=n.connectionState;n.connectionState=t,"connected"===t&&"connected"!==r&&(n.snapshot={...n.snapshot,lastEventAt:Date.now(),lastHeartbeatAt:Date.now()},k(n)),"connected"!==t&&"connected"===r&&I(n)}(e,t),"connected"===t&&(o&&(M(e),e0.current?.(e,"sse_reconnected")),o=!0)},reconnectBaseMs:1e3,reconnectMaxMs:3e4}),l.connect()})},[]),t$=(0,r.useCallback)(async(e,t="manual")=>{if(!e||eQ.current!==e)return;let n=ta.current;try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}`),r=await t.json().catch(()=>({}));if(eQ.current!==e||ta.current!==n)return;r.running?(eX.current=!0,ed(!0),eq(a(r.state)),eY.current&&"closed"!==eY.current.state&&"error"!==eY.current.state||(M(e),tR(e,{replay:!0}))):(eX.current=!1,eY.current?.close(),eY.current=null,E(e),ed(!1),eq(null),eM(null),eu({type:"end"}),L(e),await tS(e,!1,!1,!0)),r.state?.contextUsage!==void 0&&eR(r.state.contextUsage??null),r.state?.systemPrompt!==void 0&&eD(r.state.systemPrompt??null),r.state?.isCompacting!==void 0&&eH(r.state.isCompacting),r.state?.thinkingLevel!==void 0&&ex(r.state.thinkingLevel??"auto")}catch{}},[tR,tS]);(0,r.useEffect)(()=>{e0.current=t$},[t$]),(0,r.useEffect)(()=>{eX.current=ec},[ec]),eZ.current=(0,r.useCallback)(e=>{let t=eQ.current;switch(t&&function(e,t){let n=_(e),r=Date.now();switch(t.type){case"agent_start":if("active"===n.snapshot.phase)return T(n,!0),n.snapshot;return S(n),n.accumulatedText="",n.toolCalls.clear(),n.toolResults.clear(),n.activeToolId=null,n.snapshot={...w(e),phase:"active",startedAt:r,lastEventAt:r,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},k(n),T(n,!0),n.snapshot;case"message_update":{let e=t.message;if(!e||"assistant"!==e.role)return n.snapshot;let a=e.content;for(let e of Array.isArray(a)?a:[])"object"==typeof e&&null!==e&&"type"in e&&("text"===e.type?n.accumulatedText=e.text??"":"toolCall"===e.type&&e.toolCallId&&!n.toolCalls.has(e.toolCallId)&&n.toolCalls.set(e.toolCallId,{...e,startedAt:r}));return T(n,!1),n.snapshot}case"tool_execution_start":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",s=t.input??{};if(!e)return n.snapshot;let o=n.toolCalls.get(e);return n.toolCalls.set(e,{type:"toolCall",toolCallId:e,toolName:a,input:o?.input??s,startedAt:o?.startedAt??r}),n.activeToolId=e,S(n),n.activeToolId&&(n.toolProgressTimer=setInterval(()=>T(n,!0),1e3)),T(n,!0),n.snapshot}case"tool_execution_end":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",s="string"==typeof t.result?t.result:JSON.stringify(t.result??"");if(e){let o=n.toolCalls.get(e);o&&n.toolCalls.set(e,{...o,endedAt:r}),n.toolResults.set(e,{role:"toolResult",toolCallId:e,toolName:a,content:[{type:"text",text:s}],isError:!!t.isError,timestamp:r}),n.activeToolId===e&&(n.activeToolId=null,S(n))}return T(n,!0),n.snapshot}case"message_end":return b(n),T(n,!0),n.snapshot;case"agent_end":{if(b(n),S(n),n.activeToolId=null,!0===t.willRetry)return n.accumulatedText="",n.toolCalls.clear(),n.toolResults.clear(),n.snapshot={...n.snapshot,phase:"active",lastEventAt:r,accumulatedText:"",toolCalls:[],toolResults:[],statusText:null,streamingMessage:null,isStreaming:!0,error:null},k(n),v(e,{type:"snapshot-updated",snapshot:n.snapshot}),n.snapshot;I(n);let a="string"==typeof t.error?t.error:null;return n.snapshot={...n.snapshot,phase:a?"error":"completed",isStreaming:!1,streamingMessage:null,statusText:null,error:a},v(e,a?{type:"error",snapshot:n.snapshot}:{type:"completed",snapshot:n.snapshot}),n.snapshot}case"heartbeat":return n.snapshot={...n.snapshot,lastHeartbeatAt:r},n.snapshot;default:return n.snapshot}}(t,e),"heartbeat"!==e.type&&(tp.current=Date.now()),e.type){case"prompt_admitted":case"agent_start":eV(null),eX.current=!0,ed(!0),eq({kind:"waiting_model"}),eu({type:"start"});break;case"agent_end":if(!0===e.willRetry){eX.current=!0,ed(!0),eq({kind:"waiting_model"});break}eX.current=!1,eY.current?.close(),eY.current=null,ed(!1),eq(null),eM(null),eu({type:"end"}),t&&(L(t),tS(t,!1,!1,!0),tc.current&&clearTimeout(tc.current),tc.current=setTimeout(()=>{eQ.current!==t||eX.current||(L(t),tS(t,!1,!1,!0))},500),fetch(`/api/agent/${encodeURIComponent(t)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eR(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eD(e.state.systemPrompt??null),e.state?.isCompacting!==void 0&&eH(e.state.isCompacting)}).catch(()=>{})),m?.();break;case"message_start":case"message_update":{let t=e.message;if(t?.role==="user")break;eX.current||(eX.current=!0,ed(!0),eq({kind:"waiting_model"})),t&&eu({type:"update",message:s(t)}),eq(null);break}case"message_end":{let n=e.message,r="string"==typeof e.__entryId?e.__entryId:null,a=eX.current;if(n&&"user"!==n.role){"assistant"===n.role&&"error"===n.stopReason&&n.errorMessage?.trim()&&eV(`Model response failed: ${n.errorMessage.trim()}`);let e=s(n),a=o(e);if(a&&te.current.set(a,{observedAt:Date.now(),message:e}),!(r&&tn.current.includes(r))){if(t&&r){let e=e7.current.get(t)??new Map;e.set(r,Date.now()),e7.current.set(t,e)}Z(t=>t.some(t=>B(t,e))?t:[...t,e]),r&&et(e=>{if(e.includes(r))return e;let t=[...e,r];return tn.current=t,t})}}a&&(eu({type:"reset"}),eq({kind:"waiting_model"}));break}case"replay_gap":t&&(L(t),tS(t,!1,!1,!0));break;case"prompt_done":if(!eX.current)break;t$(eQ.current??"","prompt_done");break;case"prompt_error":{let n="string"==typeof e.error&&e.error.trim()?e.error.trim():"The model request failed before producing a response.";if(eX.current=!1,ed(!1),eq(null),eM(null),eu({type:"end"}),eY.current?.close(),eY.current=null,t){for(let[e,n]of(E(t),e8.current))n.sessionId===t&&"prompt"===n.kind&&e8.current.delete(e);L(t),tS(t,!1,!1,!0)}eV(`Model request failed: ${n}`),m?.();break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,a="bash"===n&&"string"==typeof r?.command?r.command:void 0;eq(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n,args:a}),{kind:"running_tools",tools:r}});break}case"tool_execution_end":{let t=e.toolCallId;eq(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"auto_retry_start":eV(null),eX.current=!0,ed(!0),eq({kind:"waiting_model"}),eM({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eM(null),!1===e.success&&"string"==typeof e.finalError&&e.finalError.trim()?eV(`Model response failed after retries: ${e.finalError.trim()}`):!0===e.success&&eV(null);break;case"auto_compaction_start":case"compaction_start":eH(!0),eB(null);break;case"auto_compaction_end":case"compaction_end":eH(!1),e.errorMessage?eB(e.errorMessage):!e.aborted&&eQ.current&&tS(eQ.current)}},[tS,m,t$]);let tD=(0,r.useCallback)(async(e,r,a,s)=>{if(!e.trim()&&!r?.length&&!a?.length||ec)return;ta.current+=1;let o=tb(a),d=e.trim()?o?`${e}
|
|
4
|
+
[Text extraction unavailable: ${e.extractionError??"unsupported file type"}]`}).join("\n\n---\n\n"):"",[]),tT=(0,r.useCallback)(async e=>{let t=await fetch(`/api/agent/${encodeURIComponent(e)}/prepare`,{method:"POST"});if(!t.ok)throw Error((await t.json().catch(()=>({}))).error??`Failed to prepare session (HTTP ${t.status})`)},[]),tC=(()=>{let e={input:0,output:0,cacheRead:0,cacheWrite:0};for(let t of X){if("assistant"!==t.role)continue;let n=t.usage;n&&(e.input+=n.input??0,e.output+=n.output??0,e.cacheRead+=n.cacheRead??0,e.cacheWrite+=n.cacheWrite??0)}return e.input+e.output+e.cacheRead+e.cacheWrite>0?{tokens:e}:null})(),tk=(0,r.useRef)(!1),tI=(0,r.useCallback)(async()=>{let e=eQ.current;if(!e||tk.current||tl.current)return;tk.current=!0,ts.current=!0;let t=0,n=$(e);t=n?n.loadedMessagesCount:50;try{for(;;)try{let n=await fetch(`/api/sessions/${encodeURIComponent(e)}?limit=100&offset=${t}`);if(!n.ok)break;let r=await n.json();if(eQ.current!==e)break;let a=r.context.messages,s=r.context.entryIds??[];if(0===a.length)break;Z(e=>[...a,...e]),et(e=>{let t=[...s,...e];return tn.current=t,t});let o=t+a.length;if(el(o),to.current=o,es(r.hasMore??!1),D(e,a,s,r.hasMore??!1,o),t=o,!r.hasMore)break;await new Promise(e=>setTimeout(e,800))}catch{break}}finally{tk.current=!1,tl.current=!0,ts.current=!1}},[]),tS=(0,r.useCallback)(async(e,t=!1,n=!1,r=!1)=>{var a;let s=null;try{if(t&&q(!0),!n&&!eX.current&&!r){let n=$(e);if(n)return er(n.totalMessages),es(n.hasMore),el(n.loadedMessagesCount),Z(n.messages),tn.current=n.entryIds,et(n.entryIds),tt.current=n.leafId,Q(n.leafId),to.current=n.loadedMessagesCount,t&&q(!1),n.hasMore&&!tl.current&&setTimeout(()=>{tI()},1500),null}let l=n?`/api/sessions/${encodeURIComponent(e)}?includeState`:`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=0`,i=td.current;if(i?.sid===e&&!t)return null;i?.controller.abort(U("Session load superseded","AbortError"));let u=new AbortController;s=u,td.current={sid:e,controller:u};let c=setTimeout(()=>{u.abort(U("Session load timed out after 30 seconds","TimeoutError"))},3e4),d=await fetch(l,{signal:u.signal}).finally(()=>clearTimeout(c));if(eQ.current&&eQ.current!==e)return null;if(404===d.status)return t&&(K(null),tt.current=null,Q(null),Z([]),V(null)),null;if(!d.ok)throw Error(`HTTP ${d.status}`);let p=await d.json();n?(er(p.totalMessages??p.context.messages.length),es(!1)):(er(p.totalMessages??p.context.messages.length),es(p.hasMore??!1)),el(p.context.messages.length),K(p),tt.current=p.leafId,Q(p.leafId);let m=p.context.messages,f=H(m),g=new Map,h=Date.now();for(let[t,n]of e8.current)if(n.sessionId===e){if(h-n.createdAt>12e4){e8.current.delete(t);continue}if(n.confirmKey){let e=f.get(n.confirmKey)??0,r=g.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(e8.current.delete(t),g.set(n.confirmKey,r+1))}}e9.current=f;let y=p.context.entryIds??[],w=[...e8.current.values()].filter(t=>J(t,e,y)).map(e=>e.message),v=w.length>0?[...m,...w]:m,b=function(e,t,n){if(0===t.size)return e;let r=!1,a=e.map(e=>{let a=o(e);if(!a)return e;let s=t.get(a);return s?n-s.observedAt>5e3||function(e,t){let n=e.timestamp,r=t.timestamp;if("number"!=typeof n||"number"!=typeof r||n!==r||e.role!==t.role)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}(s.message,e)?(t.delete(a),e):(r=!0,s.message):e});return r?a:e}(v,te.current,Date.now()),T=e7.current.get(e);if(T){for(let[e,t]of T)h-t>12e4&&T.delete(e);0===T.size&&e7.current.delete(e)}let C=T?.size?T:null,k=C?new Set(y):null,I=!!C&&!!k&&[...C.keys()].some(e=>!k.has(e));C&&k&&!I&&e7.current.delete(e);let S=b.length;return!n&&(to.current>S||I)?(er(p.totalMessages??p.context.messages.length),es(p.hasMore??!1)):(Z(e=>(function(e,t){if(e.length!==t.length)return t;let n=!1,r=t.map((t,r)=>B(e[r],t)?e[r]:(n=!0,t));return n?r:e})(e,b)),tn.current=y,et(y),n?to.current=S:to.current=Math.max(to.current,S),a={sessionId:e,leafId:p.leafId,messages:b,entryIds:y,totalMessages:p.totalMessages??p.context.messages.length,hasMore:!n&&(p.hasMore??!1),loadedMessagesCount:p.context.messages.length},R().entries.set(e,{...a,loadedAt:Date.now()})),eU(e=>{if(!e)return null;let t=p.context.model;return t?.provider===e.provider&&t.modelId===e.modelId?null:e}),V(null),!p.agentState?.state?.thinkingLevel&&p.context.thinkingLevel&&"off"!==p.context.thinkingLevel&&ex(p.context.thinkingLevel),p.agentState??null}catch(e){if(e instanceof DOMException&&("AbortError"===e.name||"TimeoutError"===e.name)||e instanceof Error&&/aborted without reason|AbortError|Session load (?:timed out|superseded)/i.test(e.message))return null;return V(String(e)),null}finally{s&&td.current?.controller===s&&(td.current=null),t&&q(!1)}},[tI]),t_=(0,r.useRef)(!1),tx=(0,r.useCallback)(async()=>{if(t_.current)return;t_.current=!0;let e=eQ.current;if(!e){t_.current=!1;return}try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=${eo}`);if(!t.ok)return;let n=await t.json(),r=n.context.messages,a=n.context.entryIds??[];Z(e=>[...r,...e]),et(e=>{let t=[...a,...e];return tn.current=t,t}),el(e=>e+r.length),es(n.hasMore??!1),D(e,r,a,n.hasMore??!1,eo+r.length)}catch{}finally{t_.current=!1}},[eo]),tE=(0,r.useCallback)(async e=>{let t=eQ.current;if(!t)return[];let n=tt.current,r=n?`?leafId=${encodeURIComponent(n)}`:"";try{let n=await fetch(`/api/sessions/${encodeURIComponent(t)}/shadowed${r}`);if(!n.ok)return[];let a=await n.json(),s=a.groups?.find(t=>t.compactionEntryId===e);return s?.messages??[]}catch{return[]}},[]),tM=(0,r.useCallback)(async(e,t)=>{try{let n=t?`/api/sessions/${encodeURIComponent(e)}/context?leafId=${encodeURIComponent(t)}`:`/api/sessions/${encodeURIComponent(e)}/context`,r=await fetch(n);if(!r.ok)throw Error(`HTTP ${r.status}`);let a=await r.json(),s=a.context.messages,o=a.context.entryIds??[],l=H(s),i=new Map,u=Date.now();for(let[t,n]of e8.current)if(n.sessionId===e){if(u-n.createdAt>12e4){e8.current.delete(t);continue}if(n.confirmKey){let e=l.get(n.confirmKey)??0,r=i.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(e8.current.delete(t),i.set(n.confirmKey,r+1))}}e9.current=l;let c=[...e8.current.values()].filter(t=>J(t,e,o)).map(e=>e.message);Z(c.length>0?[...s,...c]:s),tn.current=o,et(o)}catch(e){console.error("Failed to load context:",e)}},[]),tA=(0,r.useCallback)(async e=>{try{let t=await i(e,{type:"get_tools"});t&&(tg((0,N.ES)(t)),th((0,N.IB)(t)))}catch(e){console.error("Failed to load tools:",e)}},[th,tg]),tR=(0,r.useCallback)((e,t={})=>{eY.current?.close(),eY.current=null;let n=`/api/agent/${encodeURIComponent(e)}/events${t.replay?"?replay=1":""}`;return!function(e){let t=_(e);if("active"===t.snapshot.phase)return T(t,!0),k(t),t.snapshot;let n=Date.now();t.snapshot={...w(e),phase:"active",startedAt:n,lastEventAt:n,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},k(t),T(t,!0),t.snapshot}(e),new Promise((r,a)=>{let s=!1,o=!1,l=null,i=e=>{if(!s){if(s=!0,clearTimeout(u),e){l?.close(),eY.current===l&&(eY.current=null),a(e);return}r()}},u=setTimeout(()=>{t.requireConnected?i(Error("Timed out waiting for event stream connection")):i()},t.timeoutMs??3e4);eY.current=l=function(e){let{url:t,onEvent:n,onStateChange:r,onFatalError:a,maxReconnectAttempts:s=1/0,reconnectBaseMs:o=1e3,reconnectMaxMs:l=3e4,autoReconnect:i=!0}=e,u="idle",c=new AbortController,p=0,m=null,f=null,g=!1,h=(e,t)=>{t&&(f=t),n(e,t)},y=e=>{u!==e&&(u=e,r?.(e))},w=()=>{null!==m&&(clearTimeout(m),m=null)},v=()=>{if(g)return;if(!i)return void y("error");if(p>=s){y("error"),a?.(Error(`Max reconnect attempts (${s}) reached`));return}let e=Math.min(l,o*2**p);p+=1,y("connecting"),m=setTimeout(()=>{m=null,b()},e)},b=async()=>{if(!g){w(),c=new AbortController,y("connecting");try{let e=await fetch(t,{signal:c.signal,headers:{Accept:"text/event-stream","Cache-Control":"no-cache",...f?{"Last-Event-ID":f}:{}}});if(!e.ok)throw Error(`HTTP ${e.status}: ${e.statusText}`);let n=e.body;if(!n)throw Error("Response has no readable body");let r=n.getReader();if(y("connected"),p=0,await d(r,h,c.signal),c.signal.aborted)try{await r.cancel()}catch{}r.releaseLock(),y("closed"),!g&&i&&v()}catch(e){if(g||e instanceof DOMException&&"AbortError"===e.name)return void y("closed");y("error"),i&&v()}}};return{get state(){return u},connect:()=>{g=!1,p=0,w(),b()},close:()=>{g=!0,w(),c.abort(),y("closed")},get abortController(){return c}}}({url:n,onEvent:t=>{try{let n=JSON.parse(t);if("connected"===n.type&&i(),eQ.current!==e)return;eZ.current?.(n)}catch{}},onStateChange:t=>{!function(e,t){let n=h().get(e);if(!n)return;let r=n.connectionState;n.connectionState=t,"connected"===t&&"connected"!==r&&(n.snapshot={...n.snapshot,lastEventAt:Date.now(),lastHeartbeatAt:Date.now()},k(n)),"connected"!==t&&"connected"===r&&I(n)}(e,t),"connected"===t&&(o&&(M(e),e0.current?.(e,"sse_reconnected")),o=!0)},reconnectBaseMs:1e3,reconnectMaxMs:3e4}),l.connect()})},[]),t$=(0,r.useCallback)(async(e,t="manual")=>{if(!e||eQ.current!==e)return;let n=ta.current;try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}`),r=await t.json().catch(()=>({}));if(eQ.current!==e||ta.current!==n)return;r.running?(eX.current=!0,ed(!0),eq(a(r.state)),eY.current&&"closed"!==eY.current.state&&"error"!==eY.current.state||(M(e),tR(e,{replay:!0}))):(eX.current=!1,eY.current?.close(),eY.current=null,E(e),ed(!1),eq(null),eM(null),eu({type:"end"}),L(e),await tS(e,!1,!1,!0)),r.state?.contextUsage!==void 0&&eR(r.state.contextUsage??null),r.state?.systemPrompt!==void 0&&eD(r.state.systemPrompt??null),r.state?.isCompacting!==void 0&&eH(r.state.isCompacting),r.state?.thinkingLevel!==void 0&&ex(r.state.thinkingLevel??"auto")}catch{}},[tR,tS]);(0,r.useEffect)(()=>{e0.current=t$},[t$]),(0,r.useEffect)(()=>{eX.current=ec},[ec]),eZ.current=(0,r.useCallback)(e=>{let t=eQ.current;switch(t&&function(e,t){let n=_(e),r=Date.now();switch(t.type){case"agent_start":if("active"===n.snapshot.phase)return T(n,!0),n.snapshot;return S(n),n.accumulatedText="",n.toolCalls.clear(),n.toolResults.clear(),n.activeToolId=null,n.snapshot={...w(e),phase:"active",startedAt:r,lastEventAt:r,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},k(n),T(n,!0),n.snapshot;case"message_update":{let e=t.message;if(!e||"assistant"!==e.role)return n.snapshot;let a=e.content;for(let e of Array.isArray(a)?a:[])"object"==typeof e&&null!==e&&"type"in e&&("text"===e.type?n.accumulatedText=e.text??"":"toolCall"===e.type&&e.toolCallId&&!n.toolCalls.has(e.toolCallId)&&n.toolCalls.set(e.toolCallId,{...e,startedAt:r}));return T(n,!1),n.snapshot}case"tool_execution_start":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",s=t.input??{};if(!e)return n.snapshot;let o=n.toolCalls.get(e);return n.toolCalls.set(e,{type:"toolCall",toolCallId:e,toolName:a,input:o?.input??s,startedAt:o?.startedAt??r}),n.activeToolId=e,S(n),n.activeToolId&&(n.toolProgressTimer=setInterval(()=>T(n,!0),1e3)),T(n,!0),n.snapshot}case"tool_execution_end":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",s="string"==typeof t.result?t.result:JSON.stringify(t.result??"");if(e){let o=n.toolCalls.get(e);o&&n.toolCalls.set(e,{...o,endedAt:r}),n.toolResults.set(e,{role:"toolResult",toolCallId:e,toolName:a,content:[{type:"text",text:s}],isError:!!t.isError,timestamp:r}),n.activeToolId===e&&(n.activeToolId=null,S(n))}return T(n,!0),n.snapshot}case"message_end":return b(n),T(n,!0),n.snapshot;case"agent_end":{if(b(n),S(n),n.activeToolId=null,!0===t.willRetry)return n.accumulatedText="",n.toolCalls.clear(),n.toolResults.clear(),n.snapshot={...n.snapshot,phase:"active",lastEventAt:r,accumulatedText:"",toolCalls:[],toolResults:[],statusText:null,streamingMessage:null,isStreaming:!0,error:null},k(n),v(e,{type:"snapshot-updated",snapshot:n.snapshot}),n.snapshot;I(n);let a="string"==typeof t.error?t.error:null;return n.snapshot={...n.snapshot,phase:a?"error":"completed",isStreaming:!1,streamingMessage:null,statusText:null,error:a},v(e,a?{type:"error",snapshot:n.snapshot}:{type:"completed",snapshot:n.snapshot}),n.snapshot}case"heartbeat":return n.snapshot={...n.snapshot,lastHeartbeatAt:r},n.snapshot;default:return n.snapshot}}(t,e),"heartbeat"!==e.type&&(tp.current=Date.now()),e.type){case"prompt_admitted":case"agent_start":eV(null),eX.current=!0,ed(!0),eq({kind:"waiting_model"}),eu({type:"start"});break;case"agent_end":if(!0===e.willRetry){eX.current=!0,ed(!0),eq({kind:"waiting_model"});break}eX.current=!1,eY.current?.close(),eY.current=null,ed(!1),eq(null),eM(null),eu({type:"end"}),t&&(L(t),tS(t,!1,!1,!0),tc.current&&clearTimeout(tc.current),tc.current=setTimeout(()=>{eQ.current!==t||eX.current||(L(t),tS(t,!1,!1,!0))},500),fetch(`/api/agent/${encodeURIComponent(t)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eR(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eD(e.state.systemPrompt??null),e.state?.isCompacting!==void 0&&eH(e.state.isCompacting)}).catch(()=>{})),m?.();break;case"message_start":case"message_update":{let t=e.message;if(t?.role==="user")break;eX.current||(eX.current=!0,ed(!0),eq({kind:"waiting_model"})),t&&eu({type:"update",message:s(t)}),eq(null);break}case"message_end":{let n=e.message,r="string"==typeof e.__entryId?e.__entryId:null,a=eX.current;if(n&&"user"!==n.role){"assistant"===n.role&&"error"===n.stopReason&&n.errorMessage?.trim()&&eV(`Model response failed: ${n.errorMessage.trim()}`);let e=s(n),a=o(e);if(a&&te.current.set(a,{observedAt:Date.now(),message:e}),!(r&&tn.current.includes(r))){if(t&&r){let e=e7.current.get(t)??new Map;e.set(r,Date.now()),e7.current.set(t,e)}Z(t=>t.some(t=>B(t,e))?t:[...t,e]),r&&et(e=>{if(e.includes(r))return e;let t=[...e,r];return tn.current=t,t})}}a&&(eu({type:"reset"}),eq({kind:"waiting_model"}));break}case"replay_gap":t&&(L(t),tS(t,!1,!1,!0));break;case"prompt_done":if(!eX.current)break;t$(eQ.current??"","prompt_done");break;case"prompt_error":{let n="string"==typeof e.error&&e.error.trim()?e.error.trim():"The model request failed before producing a response.";if(eX.current=!1,ed(!1),eq(null),eM(null),eu({type:"end"}),eY.current?.close(),eY.current=null,t){for(let[e,n]of(E(t),e8.current))n.sessionId===t&&"prompt"===n.kind&&e8.current.delete(e);L(t),tS(t,!1,!1,!0)}eV(`Model request failed: ${n}`),m?.();break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,a="bash"===n&&"string"==typeof r?.command?r.command:void 0;eq(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n,args:a}),{kind:"running_tools",tools:r}});break}case"tool_execution_end":{let t=e.toolCallId;eq(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"auto_retry_start":eV(null),eX.current=!0,ed(!0),eq({kind:"waiting_model"}),eM({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eM(null),!1===e.success&&"string"==typeof e.finalError&&e.finalError.trim()?eV(`Model response failed after retries: ${e.finalError.trim()}`):!0===e.success&&eV(null);break;case"auto_compaction_start":case"compaction_start":eH(!0),eB(null);break;case"auto_compaction_end":case"compaction_end":eH(!1),e.errorMessage?eB(e.errorMessage):!e.aborted&&eQ.current&&tS(eQ.current)}},[tS,m,t$]);let tD=(0,r.useCallback)(async(e,r,a,s)=>{if(!e.trim()&&!r?.length&&!a?.length||ec)return;ta.current+=1;let o=tb(a),d=e.trim()?o?`${e}
|
|
5
5
|
|
|
6
6
|
Attached document text:
|
|
7
7
|
|