UNPKG

eve

Version:

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

1 lines 8.67 kB
import{randomUUID}from"node:crypto";import{realpath}from"node:fs/promises";import{PROTOCOL_VERSION,RequestError,methods}from"#compiled/@agentclientprotocol/sdk/index.js";import{Client,ClientError}from"#client/index.js";const ANSWER_FIELD=`answer`,ERROR_CODE_EVE=-32002;var EveAcpAdapter=class{#e;#t;#n;#r=!1;#i=new Map;constructor(e){this.#t=e.eveVersion,this.#n=e.workspaceRoot,this.#e=e.client??new Client({auth:e.auth,headers:e.headers,host:e.serverUrl,redirect:`manual`})}initialize(e){return this.#r=e.clientCapabilities?.elicitation?.form!==void 0,{protocolVersion:PROTOCOL_VERSION,agentCapabilities:{loadSession:!1,promptCapabilities:{},sessionCapabilities:{close:{}}},agentInfo:{name:`eve`,title:`eve`,version:this.#t},authMethods:[]}}async newSession(e){if(e.mcpServers.length>0)throw unsupported(`Client-provided MCP servers are not supported by eve ACP mode.`);if((e.additionalDirectories?.length??0)>0)throw unsupported(`Additional workspace directories are not supported by eve ACP mode.`);if(this.#n!==void 0){let t=await normalizedRealpath(e.cwd,`session/new.cwd`),n=await normalizedRealpath(this.#n,`the eve application root`);if(t!==n)throw RequestError.invalidParams({cwd:e.cwd,workspaceRoot:n},`ACP cwd must be the eve application root`)}let t=randomUUID();return this.#i.set(t,{tools:new Map}),{sessionId:t}}async prompt(e,t,n){let r=this.#s(e.sessionId);if(r.active!==void 0)throw new RequestError(-32001,`ACP session ${e.sessionId} already has an active prompt.`);let i=promptContent(e);r.tools.clear();let a=Promise.withResolvers(),o={cancelRequested:!1,protocolCancelled:!1,outboundController:new AbortController,settled:a.promise,resolveSettled:a.resolve};r.active=o;let onProtocolCancel=()=>{o.protocolCancelled=!0,this.#o(r).catch(()=>void 0)};n.aborted?onProtocolCancel():n.addEventListener(`abort`,onProtocolCancel,{once:!0});try{if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});let a={message:i};for(;;){let i;if(r.client===void 0){if(a.message===void 0)throw Error(`ACP session has not started.`);let e=await this.#e.sessions.create({...a,message:a.message});r.client=e.session,i=e.response}else i=a.inputResponses===void 0?await r.client.send(a.message):await r.client.respond(a.inputResponses);(o.cancelRequested||o.protocolCancelled)&&await this.#o(r);let s=[],c=!1,l,u;for await(let n of i){let i=`data`in n&&`turnId`in n.data?n.data.turnId:void 0;typeof i==`string`&&(o.turnId=i),n.type===`input.requested`&&s.push(...n.data.requests),n.type===`authorization.required`&&(u=unsupported(`Connection authorization cannot be completed through eve ACP mode.`)),n.type===`turn.cancelled`&&(c=!0),(n.type===`turn.failed`||n.type===`session.failed`)&&(l=n),await this.#c(e.sessionId,r,n,t)}if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(c||o.cancelRequested)return{stopReason:`cancelled`};if(l!==void 0)throw eveFailure(l);if(u!==void 0)throw u;if(s.length===0)return{stopReason:`end_turn`};let d;try{d=await Promise.all(s.map(i=>this.#l(e.sessionId,r,i,t,n)))}catch(t){if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested)return{stopReason:`cancelled`};throw t}if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested)return{stopReason:`cancelled`};a={inputResponses:d}}}catch(e){throw acpRequestError(e)}finally{n.removeEventListener(`abort`,onProtocolCancel),r.tools.clear(),o.resolveSettled(),r.active===o&&(r.active=void 0)}}async cancel(e){let t=this.#i.get(e);t!==void 0&&t.active!==void 0&&(t.active.cancelRequested=!0,await this.#o(t))}async closeSession(e){let t=this.#s(e);this.#i.delete(e),await this.#a(t)}async close(){let e=[...this.#i.values()];this.#i.clear(),await Promise.allSettled(e.map(e=>this.#a(e)))}async#a(e){let t;if(e.active!==void 0){let n=e.active;n.cancelRequested=!0;try{await this.#o(e)}catch(e){t=e}await n.settled}try{await e.client?.reset()}catch(e){throw t===void 0?e:AggregateError([t,e],`Could not cancel or reset the eve session`)}if(t!==void 0)throw t}async#o(e){e.active?.outboundController.abort(),e.client!==void 0&&await e.client.cancel(e.active?.turnId===void 0?void 0:{turnId:e.active.turnId})}#s(e){let t=this.#i.get(e);if(t===void 0)throw RequestError.invalidParams({sessionId:e},`Unknown or closed ACP session`);return t}async#c(e,t,n,r){switch(n.type){case`message.appended`:await notifyUpdate(r,e,{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:n.data.messageDelta},messageId:`${n.data.turnId}:message:${n.data.stepIndex}`});return;case`reasoning.appended`:await notifyUpdate(r,e,{sessionUpdate:`agent_thought_chunk`,content:{type:`text`,text:n.data.reasoningDelta},messageId:`${n.data.turnId}:thought:${n.data.stepIndex}`});return;case`actions.requested`:for(let i of n.data.actions){let n=toolCallForAction(i);t.tools.set(i.callId,n),await notifyUpdate(r,e,{sessionUpdate:`tool_call`,...n})}return;case`action.result`:{let t=n.data.result,i=n.data.status!==`completed`||t.isError?`failed`:`completed`;await notifyUpdate(r,e,{sessionUpdate:`tool_call_update`,toolCallId:t.callId,status:i,content:[{type:`content`,content:{type:`text`,text:stringifyOutput(t.output)}}],rawOutput:t.output});return}default:return}}async#l(e,t,n,r,i){let a=AbortSignal.any([i,t.active.outboundController.signal]);if(n.display===`confirmation`){let i=`${n.requestId}:approve`,o=`${n.requestId}:deny`,s=t.tools.get(n.action.callId)??toolCallForAction(n.action),c=await r.request(methods.client.session.requestPermission,{sessionId:e,toolCall:s,options:[{kind:`allow_once`,name:`Approve`,optionId:i},{kind:`reject_once`,name:`Deny`,optionId:o}]},{cancellationSignal:a});if(c.outcome.outcome===`cancelled`)return this.#u(t),{requestId:n.requestId};if(c.outcome.optionId===i)return{requestId:n.requestId,optionId:`approve`};if(c.outcome.optionId===o)return{requestId:n.requestId,optionId:`deny`};throw RequestError.invalidParams({optionId:c.outcome.optionId},`Unknown ACP permission option`)}if(!this.#r)throw unsupported(`The ACP client does not support form elicitation required by this eve question.`);let o=elicitationProperty(n),s=await r.request(methods.client.elicitation.create,{mode:`form`,sessionId:e,message:n.prompt,requestedSchema:{type:`object`,properties:{[ANSWER_FIELD]:o},required:[ANSWER_FIELD]}},{cancellationSignal:a});if(s.action!==`accept`)return this.#u(t),{requestId:n.requestId};let c=s.content?.[ANSWER_FIELD];if(typeof c!=`string`)throw RequestError.invalidParams(s.content,`ACP elicitation response must contain a string answer`);if(n.display===`select`){if(!n.options?.some(e=>e.id===c))throw RequestError.invalidParams({answer:c},`Unknown eve question option`);return{requestId:n.requestId,optionId:c}}return{requestId:n.requestId,text:c}}#u(e){let t=e.active;t.cancelRequested=!0,t.outboundController.abort()}};async function normalizedRealpath(e,t){try{return await realpath(e)}catch(n){throw RequestError.invalidParams({path:e},`Could not resolve ${t}: ${errorMessage(n)}`)}}function promptContent(e){let t=e.prompt.map(e=>{if(e.type!==`text`)throw unsupported(`ACP prompt content type ${JSON.stringify(e.type)} is not supported.`);return{type:`text`,text:e.text}});if(t.every(e=>e.text.length===0))throw RequestError.invalidParams(e.prompt,`ACP prompt must contain at least one non-empty text block`);return t}function toolCallForAction(e){let t=e.kind===`tool-call`||e.kind===`workflow-tool-call`?e.toolName:e.kind===`load-skill`?`Load skill`:e.name;return{toolCallId:e.callId,title:t,kind:`other`,status:`pending`,rawInput:e.input}}function elicitationProperty(e){if(e.display===`select`&&e.allowFreeform!==!0&&e.options?.length)return{type:`string`,title:e.prompt,oneOf:e.options.map(e=>({const:e.id,title:e.label,description:e.description}))};if(e.display===`text`&&e.allowFreeform!==!1)return{type:`string`,title:e.prompt,minLength:1};throw unsupported(`This eve question shape cannot be represented by ACP form elicitation.`)}async function notifyUpdate(e,t,n){await e.notify(methods.client.session.update,{sessionId:t,update:n})}function stringifyOutput(e){return typeof e==`string`?e:JSON.stringify(e,null,2)}function unsupported(e){return new RequestError(-32003,e)}function eveFailure(e){return new RequestError(ERROR_CODE_EVE,e.data.message,{code:e.data.code,details:e.data.details})}function acpRequestError(e){return e instanceof RequestError?e:e instanceof ClientError?new RequestError(ERROR_CODE_EVE,e.message,{httpStatus:e.status}):new RequestError(ERROR_CODE_EVE,errorMessage(e))}function errorMessage(e){return e instanceof Error?e.message:String(e)}export{EveAcpAdapter};