UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

1 lines 5.96 kB
import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#tools/schema.js";var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(e,t){let n=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0),{sessionId:r}=await readAcceptedMessage(n),i=new ClientSession(e,{sessionId:r,streamIndex:0});return{response:i.#r(n,t,0),session:i}}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#o({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e},!0)}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),i=t?await postSessionSend(this.#e,r,e):await postTurn(this.#e,r,e,!1),{sessionId:a,deliveryId:o}=await readAcceptedMessage(i,this.#t.sessionId);if(a!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(e.message!==void 0&&o===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#r(i,e,n,e.message===void 0?void 0:o)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}#r(e,t,n,r){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:()=>this.#i(n,t,r),sessionId:this.#t.sessionId})}async*#i(e,t,n){let r=0,i=n===void 0,a=!1,o=new Set;try{for await(let s of this.#o({headers:t.headers,keepAlive:shouldKeepActiveTurnAlive(t.streamReconnectPolicy),signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy})){if(r+=1,n!==void 0){let e=s.meta?.deliveryIds?.includes(n)===!0,t=s.type===`session.failed`||s.type===`session.completed`;if(!e&&t&&(!i||s.type===`session.completed`))throw Error(`The session ended before the accepted message reached its turn boundary.`);if(!i&&!e||!t&&s.meta?.deliveryIds!==void 0&&!e)continue;i=!0}if(s.type===`authorization.required`&&s.data.webhookUrl!==void 0?o.add(s.data.name):s.type===`authorization.completed`&&o.delete(s.data.name),a=isCurrentTurnBoundaryEvent(s)&&(s.type!==`session.waiting`||o.size===0),yield s,a)break}if(n!==void 0&&!a&&!t.signal?.aborted)throw Error(`The response stream ended before the accepted message reached its turn boundary.`)}finally{this.#t={sessionId:this.#t.sessionId,streamIndex:Math.max(this.#t.streamIndex,e+r)}}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;try{for await(let r of this.#o({follow:e?.follow,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,yield r}finally{t>=0&&(this.#t={sessionId:this.#t.sessionId,streamIndex:t+n})}}#o(e){return followStreamIterable({follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.headers),redirect:this.#e.redirect,sessionId:this.#t.sessionId,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy})}};async function postSessionSend(e,t,n){let r=250;for(let i=0;;i+=1){try{return await postTurn(e,t,n,!1)}catch(e){if(!isSessionNotActive(e)||i>=3)throw e}await sleep(r,n.signal),n.signal?.throwIfAborted(),r*=2}}function isSessionNotActive(e){return e instanceof ClientError&&e.status===409&&e.code===`session_not_active`}function shouldKeepActiveTurnAlive(e){return e&&`reconnect`in e?!1:e?.streamIdleReconnectPolicy?.maxAttempts===void 0}async function postTurn(e,t,n,r){let i=createMessageBody(n,r);if(i===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let a=await e.resolveHeaders(n.headers);a.set(`content-type`,`application/json`);let o=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(i),headers:a,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!o.ok){let e=await o.text();throw new ClientError(o.status,e,o.headers)}return o}async function readAcceptedMessage(e,t){let n=await e.json(),r=(typeof n.sessionId==`string`?n.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!r)throw Error(`Message route did not return a session id.`);return{sessionId:r,deliveryId:typeof n.deliveryId==`string`&&n.deliveryId.length>0?n.deliveryId:void 0}}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession};