eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 10 kB
JavaScript
import{parseCreatedSlackConnector,parseSlackConnectorDetails,pickSlackConnector}from"./slack-connect.js";import{CONNECT_LOOKUP_TIMEOUT_MS,attachSlackConnector,cleanupCreatedAttempt,fetchSlackWorkspace,findSlackConnector,listSlackConnectors}from"./slack-connect-lifecycle.js";import{createSlackConnector}from"./slack-connect-create.js";import{join}from"node:path";import{SLACK_CHANNEL_DEFAULT_ROUTE}from"#setup/scaffold/index.js";import{performance}from"node:perf_hooks";import{readProjectLink}from"#setup/project-resolution.js";import{captureVercel,runVercel,runVercelCaptureStdout}from"#setup/primitives/run-vercel.js";import{setTimeout}from"node:timers/promises";import{createPromptCommandOutput,withPhase}from"#setup/cli/index.js";import{updateSlackChannelConnectorUid}from"#setup/scaffold/update/update-slack-channel.js";const defaultDeps={captureVercel,runVercel,runVercelCaptureStdout},realDelay=(e,t)=>setTimeout(e,void 0,{signal:t}),monotonicNow=()=>performance.now();async function pollSlackWorkspace(e,t,n,r,i,a){let o=e.delay??realDelay,s=e.now??monotonicNow,c=s()+3e5;for(;;){a?.throwIfAborted();let l=c-s();if(l<=0)return{state:`timed-out`};let u=await fetchSlackWorkspace({deps:e,projectRoot:t,connectorId:n,orgId:r,onOutput:i,timeoutMs:Math.min(CONNECT_LOOKUP_TIMEOUT_MS,l),signal:a});if(a?.throwIfAborted(),u.state!==`pending`)return u;let d=c-s();if(d<=0)return{state:`timed-out`};await o(Math.min(3e3,d),a)}}function isAbortFromSignal(e,t){return t?.aborted===!0&&(e===t.reason||e instanceof Error&&e.name===`AbortError`)}function cleanupFailureResult(e){return{state:`cleanup-failed`,connectorUids:e.connectorUids}}async function runAttempt(e){let{log:t,deps:n,projectRoot:r,orgId:i,onOutput:a,signal:o,phase:s}=e,c,l;if(e.source.state===`existing`)c=e.source.ref;else{let u=await createSlackConnector({deps:n,projectRoot:r,orgId:i,slug:e.slug,onOutput:a,signal:o,phase:s,onCreated:e.onCreated,waitForWorkspace:async(e,t)=>{let o=await pollSlackWorkspace(n,r,e.id,i,a,t);return o.state===`connected`?o.workspace:void 0}});if(u.state===`failed`)return{state:`create-failed`};if(u.state===`unresolved`)return t.warning(`Vercel did not return an exact Slack connector UID for this request, so eve cannot attach or remove it safely.`),{state:`unresolved`};c=u.ref,u.via===`workspace`&&(l=u.workspace)}if(e.source.state===`existing`&&l===void 0){let e=await s(`Waiting for the Slack workspace connection...`,()=>pollSlackWorkspace(n,r,c.id,i,a,o));if(e.state===`timed-out`)return{state:`timed-out`,ref:c};if(e.state===`failed`)return{state:`failed`,ref:c,message:e.message};l=e.workspace}let u=await s(`Configuring Slack event delivery for this agent...`,()=>attachSlackConnector(n,r,c,a,o));return o?.throwIfAborted(),u.state===`attached`?l===void 0?{state:`attached`,ref:c}:{state:`attached`,ref:c,workspace:l}:{state:u.state,ref:c}}async function raceAttemptAgainstChoice(e){let t=new AbortController,n=e.outerSignal?AbortSignal.any([e.outerSignal,t.signal]):t.signal,r=e.run(n);try{let i=await Promise.race([r.then(e=>({via:`work`,outcome:e})),e.prompt.choice.then(e=>({via:`choice`,choice:e}))]);if(i.via===`work`)return i;t.abort();let a;try{a=await r}catch(e){if(!isAbortFromSignal(e,n))throw e}return{via:`choice`,choice:i.choice,settled:a}}catch(e){t.abort();try{await r}catch{}throw e}finally{e.prompt.close()}}async function inspectSlackbotConnectors(e,t,n,r,i=defaultDeps){let a=await(i.readProjectLink??readProjectLink)(t),o=await findSlackConnector(i,t,a?.projectId,`slack/${n}`,createPromptCommandOutput(e),r);if(o.state===`failed`)throw Error(o.message);return o}async function provisionSlackbot(e,t,n,r=defaultDeps,i={}){i.signal?.throwIfAborted();let a=createPromptCommandOutput(e),o={log:e,deps:r,projectRoot:t,onOutput:a},s=await(r.readProjectLink??readProjectLink)(t),c=s?.projectId,l=s?.orgId,u=`slack/${n}`,d=await withPhase(e,`Checking for an existing Slackbot...`,()=>findSlackConnector(r,t,c,u,a,i.signal));if(i.signal?.throwIfAborted(),d.state===`failed`)return e.warning(`Could not inspect existing Slack connectors, so eve did not create another one. ${d.message}`),{state:`connector-lookup-failed`};if(c===void 0&&d.connectorUids.size>0)return e.warning("Could not verify which Slack connectors belong to this Vercel project, so eve did not create another one. Restore `.vercel/project.json`, then try again."),{state:`connector-lookup-failed`};let finishOutcome=async(t,n,r)=>{let i=n.state===`new`;switch(t.state){case`create-failed`:if(i){let e=await r();if(e.state===`failed`)return cleanupFailureResult(e)}return{state:`create-failed`};case`unresolved`:if(i){let e=await r();if(e.state===`failed`)return cleanupFailureResult(e)}return{state:`create-failed`};case`detach-failed`:return e.warning(`Could not remove the connector's existing trigger destination. Run \`vercel connect detach ${t.ref.uid} --yes\`, then \`vercel connect attach ${t.ref.uid} --triggers --trigger-path ${SLACK_CHANNEL_DEFAULT_ROUTE} --yes\`.`),{state:`detach-failed`,connectorUid:t.ref.uid};case`attach-failed`:return e.warning(`Could not register this project as a trigger destination. Run \`vercel connect attach ${t.ref.uid} --triggers --trigger-path ${SLACK_CHANNEL_DEFAULT_ROUTE} --yes\` to enable event delivery.`),{state:`attach-failed`,connectorUid:t.ref.uid};case`attached`:return t.workspace===void 0?{state:`attached`,connectorUid:t.ref.uid}:{state:`attached`,connectorUid:t.ref.uid,chatUrl:t.workspace.workspaceUrl,workspaceName:t.workspace.workspaceName};case`failed`:return e.warning(`Could not verify the Slack workspace connection. ${t.message}`),{state:`installation-check-failed`,connectorUid:t.ref.uid};case`timed-out`:if(e.warning(`The Slackbot did not connect to a Slack workspace in time.`),i){let e=await r();if(e.state===`failed`)return cleanupFailureResult(e)}return{state:`not-installed`}}},cleanupNewAttempt=async(e,t)=>cleanupCreatedAttempt(o,{expectedUid:u,baselineConnectorUids:e.baselineConnectorUids,createdRef:t});function attemptInput(i,o){return{log:e,deps:r,projectRoot:t,orgId:l,slug:n,source:i,onOutput:a,onCreated:o}}async function runExistingConnector(t){let cleanupCurrentAttempt=async()=>({state:`clean`}),notInstalled=()=>(e.warning(`The existing Slack connector \`${t.ref.uid}\` is not connected to a Slack workspace. eve did not remove it because this run did not create it. If its original browser request is still open, complete it; otherwise run \`vercel connect remove ${t.ref.uid} --disconnect-all --yes\` before trying again.`),{state:`existing-not-installed`,connectorUid:t.ref.uid}),finishExistingOutcome=async e=>e.state===`timed-out`?notInstalled():finishOutcome(e,t,cleanupCurrentAttempt);if(i.awaitChoice!==void 0){let e=await raceAttemptAgainstChoice({prompt:i.awaitChoice({status:`Waiting for the existing Slack workspace connection...`,context:`Complete the original setup in the browser`,actions:[{value:`cancel`,label:`Stop waiting`}]}),outerSignal:i.signal,run:e=>runAttempt({...attemptInput(t,()=>{}),signal:e,phase:(e,t)=>t()})});return e.via===`work`?finishExistingOutcome(e.outcome):e.settled?.state===`attached`?finishExistingOutcome(e.settled):notInstalled()}return finishExistingOutcome(await runAttempt({...attemptInput(t,()=>{}),signal:i.signal,phase:(t,n)=>withPhase(e,t,n)}))}async function runUncontrolledAttempt(t){let n,cleanupCurrentAttempt=()=>cleanupNewAttempt(t,n),r=runAttempt({...attemptInput(t,e=>{n=e}),signal:i.signal,phase:(t,n)=>withPhase(e,t,n)});try{return await finishOutcome(await r,t,cleanupCurrentAttempt)}catch(e){throw i.signal?.aborted===!0&&await cleanupCurrentAttempt(),e}}async function runInteractiveAttempt(n,o){let s,cleanupCurrentAttempt=()=>cleanupNewAttempt(n,s),c=o({status:`Waiting for Slack setup to finish...`,context:`Complete setup in the browser, then wait while eve verifies the connection`,actions:[{value:`retry`,label:`Did your browser not open? Try again`},{value:`cancel`,label:`Cancel`}]}),l;try{l=await raceAttemptAgainstChoice({prompt:c,outerSignal:i.signal,run:t=>runAttempt({...attemptInput(n,e=>{s=e}),signal:t,phase:e.spinner===void 0?(e,t)=>t():(t,n)=>withPhase(e,t,n)})})}catch(e){throw await cleanupCurrentAttempt(),e}if(l.via===`work`)return{state:`finished`,result:await finishOutcome(l.outcome,n,cleanupCurrentAttempt)};if(l.settled?.state===`attached`)return{state:`finished`,result:await finishOutcome(l.settled,n,cleanupCurrentAttempt)};let u=await cleanupCurrentAttempt();if(u.state===`failed`)return{state:`finished`,result:cleanupFailureResult(u)};if(l.choice===`retry`){let n=await withPhase(e,`Checking existing Slack connectors...`,()=>listSlackConnectors(r,t,a,i.signal));return i.signal?.throwIfAborted(),n.state===`failed`?(e.warning(`Could not inspect existing Slack connectors, so eve did not create another one. ${n.message}`),{state:`finished`,result:{state:`connector-lookup-failed`}}):{state:`retry`,source:{state:`new`,baselineConnectorUids:new Set(n.connectors.map(e=>e.uid))}}}return{state:`finished`,result:{state:`cancelled`}}}if(d.state===`found`){let e=i.selectConnector===void 0?d.preferred??d.connectors[0]:await i.selectConnector(d.connectors,d.preferred);if(i.signal?.throwIfAborted(),e!==`create`)return runExistingConnector({state:`existing`,ref:e})}let f={state:`new`,baselineConnectorUids:d.connectorUids};if(i.awaitChoice===void 0)return runUncontrolledAttempt(f);for(;;){let e=await runInteractiveAttempt(f,i.awaitChoice);if(e.state===`finished`)return e.result;f=e.source}}async function reconcileSlackUid(e,t,n,r){if(n.state!==`attached`||n.connectorUid===r)return!0;let i=join(t,`agent/channels/slack.ts`),{patched:a}=await updateSlackChannelConnectorUid(i,n.connectorUid);return a?!0:(e.warning(`Could not patch agent/channels/slack.ts automatically. Update \`connectSlackCredentials("...")\` to \`"${n.connectorUid}"\` and run \`vercel deploy --prod\`.`),!1)}export{inspectSlackbotConnectors,parseCreatedSlackConnector,parseSlackConnectorDetails,pickSlackConnector,provisionSlackbot,reconcileSlackUid};