eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
3 lines • 2.08 kB
JavaScript
import{EVE_STREAM_LEASE_ENDED_CONTROL}from"#protocol/message.js";import{normalizeMessageStreamEvent}from"#protocol/message-version.js";function isStreamDisconnectError(e){if(e instanceof DOMException)return e.name===`AbortError`;if(!(e instanceof Error))return!1;let t=`code`in e&&typeof e.code==`string`?e.code:void 0;return e.name===`AbortError`||e.message===`terminated`||t===`UND_ERR_SOCKET`||e instanceof TypeError&&/^(?:failed to fetch|fetch failed)$/i.test(e.message)||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*readNdjsonStream(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=!1,abort=()=>{n.cancel().catch(()=>{})};t.signal?.addEventListener(`abort`,abort,{once:!0});try{for(;;){t.signal?.throwIfAborted();let e=await readWithIdleTimeout(n,t?.idleTimeoutMs);if(t.signal?.throwIfAborted(),e.done){a=!0,i+=r.decode();break}e.value&&(i+=r.decode(e.value,{stream:!0}));let o=i.indexOf(`
`);for(;o!==-1;){let e=i.slice(0,o).trim();if(i=i.slice(o+1),e.length>0){let n=JSON.parse(e);t.controlVersion===`1`&&isLeaseEndedControl(n)?t.onLeaseEnded?.():yield parseMessageStreamEvent(n,t.streamVersion)}o=i.indexOf(`
`)}}let e=i.trim();if(e.length>0){let n=JSON.parse(e);t.controlVersion===`1`&&isLeaseEndedControl(n)?t.onLeaseEnded?.():yield parseMessageStreamEvent(n,t.streamVersion)}}finally{t.signal?.removeEventListener(`abort`,abort),a||n.cancel().catch(()=>{}),n.releaseLock()}}function isLeaseEndedControl(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.$eve===EVE_STREAM_LEASE_ENDED_CONTROL.$eve&&t.version===EVE_STREAM_LEASE_ENDED_CONTROL.version}function parseMessageStreamEvent(e,t){return normalizeMessageStreamEvent(t,e)}async function readWithIdleTimeout(e,t){let n;try{return t===void 0?await e.read():await Promise.race([e.read(),new Promise((e,r)=>{n=setTimeout(()=>r(new DOMException(`Session stream was idle.`,`AbortError`)),t)})])}catch(e){throw e instanceof TypeError?Error(`Session stream disconnected.`,{cause:e}):e}finally{n!==void 0&&clearTimeout(n)}}export{isStreamDisconnectError,readNdjsonStream};