import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{GET,POST,defineChannel}from"#public/definitions/channel.js";import{ContextContainer,contextStorage}from"#context/container.js";import{ContextKey}from"#context/key.js";import{Actions,Button,Card,CardText,Chat,Message,ThreadImpl}from"#compiled/chat/index.js";import{isNotImplemented}from"#public/channels/chat-sdk/notImplemented.js";const log=createLogger(`chat-sdk.channel`),ActiveWebhookKey=new ContextKey(`chat-sdk.active-webhook`);function chatSdkChannel(e){let t=new Chat(e),n=e.inputActionPrefix??`eve_input:`,s=e.streaming??!0,c=e.streamingEditIntervalMs??1e3,l={...defaultEvents(n),...e.events};return t.onAction(async r=>{let i=decodeInputAction(r.actionId,n,r.value);if(i){if(!r.thread)throw Error(`chatSdkChannel input actions require a thread on the Chat SDK action event.`);await bridgeSend(t,{inputResponses:[i]},{auth:e.resolveInputAuth?await e.resolveInputAuth(r):null,thread:r.thread})}}),{bot:t,channel:defineChannel({kindHint:`chat-sdk`,state:initialState(),metadata:metadataFromState,context(e){return{bot:t,state:e,streaming:s,streamingEditIntervalMs:c,thread:threadFromState(t,e)}},routes:adapterNames(e.adapters).flatMap(n=>{let a=routeForAdapter(n,e),handler=async(r,i)=>{let a=t.webhooks[n],s=new ContextContainer;return s.setVirtualContext(ActiveWebhookKey,{send:i.send}),contextStorage.run(s,()=>a(r,{...e.webhook,waitUntil(e){i.waitUntil(e)}}))};return[GET(a,handler),POST(a,handler)]}),async receive(e,{send:n}){let r=serializeReceiveTarget(t,e.target);return n(e.message,{auth:e.auth,continuationToken:r.id,state:{thread:r}})},events:l}),send(e,n){return bridgeSend(t,e,n)}}}function defaultEvents(e){return{async"turn.started"(e,t,n){t.state.pendingToolCallMessage=null,clearStream(t.state),await safeStartTyping(t.thread,`Working...`)},async"actions.requested"(e,t,n){let r=t.state.pendingToolCallMessage;if(t.state.pendingToolCallMessage=null,r){await safeStartTyping(t.thread,truncate(r));return}let i=e.actions.map(e=>e.kind===`tool-call`?e.toolName:e.kind);await safeStartTyping(t.thread,truncate(`Running ${i.join(`, `)}...`))},async"message.appended"(e,t,n){if(!t.thread||!e.messageSoFar||!canStream(t))return;let r=t.state.anchorMessageId;if(!r||t.state.streamStepIndex!==e.stepIndex){let n=await t.thread.post({markdown:e.messageSoFar});t.state.anchorMessageId=n.id,t.state.streamStepIndex=e.stepIndex,t.state.lastEditAtMs=Date.now();return}let i=t.state.lastEditAtMs??0;if(!(Date.now()-i<t.streamingEditIntervalMs))try{await editMessage(t.thread,r,e.messageSoFar),t.state.lastEditAtMs=Date.now()}catch(e){if(!isNotImplemented(e))throw e;t.state.editSupported=!1,clearStream(t.state)}},async"input.requested"(t,n,r){!n.thread||t.requests.length===0||await n.thread.post(renderInputRequests(t.requests,e))},async"message.completed"(e,t,n){if(e.finishReason===`tool-calls`){t.state.pendingToolCallMessage=e.message?firstNonEmptyLine(e.message)??null:null,e.message?await finalizeStreamedMessage(t,e.message,!1):clearStream(t.state);return}if(t.state.pendingToolCallMessage=null,!e.message){clearStream(t.state);return}await finalizeStreamedMessage(t,e.message,!0)},async"turn.failed"(e,t,n){await postFailure(t.thread,`I hit an error while handling your request`,e)},async"session.failed"(e,t){await postFailure(t.thread,`This session could not recover from an error`,e)}}}async function safeStartTyping(e,t){if(e)try{await e.startTyping(t)}catch(e){if(!isNotImplemented(e))throw e}}async function editMessage(e,t,n){await e.adapter.editMessage(e.id,t,{markdown:n})}async function finalizeStreamedMessage(e,t,n){let r=e.thread;if(!r){clearStream(e.state);return}let i=e.state.anchorMessageId;if(canStream(e)&&i)try{await editMessage(r,i,t)}catch(i){if(!isNotImplemented(i))throw i;e.state.editSupported=!1,n&&await r.post({markdown:t})}else n&&await r.post({markdown:t});clearStream(e.state)}function canStream(e){return e.streaming&&e.state.editSupported!==!1}function clearStream(e){e.anchorMessageId=null,e.lastEditAtMs=null,e.streamStepIndex=null}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}function truncate(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function renderInputRequests(e,t){return Card({children:e.flatMap(e=>renderInputRequest(e,t))})}function renderInputRequest(e,t){let n=[CardText(e.prompt)];return e.options&&e.options.length>0?(n.push(Actions(e.options.map(n=>Button({id:encodeInputAction(t,e.requestId,n.id),label:n.label,style:n.style,value:n.id})))),n):(n.push(CardText(`This request needs a freeform answer. Continue from the Eve session UI.`)),n)}async function postFailure(e,r,i){if(!e)return;let a=formatErrorHint(i),o=extractErrorId(i.details);await e.post([`${r}${a}.`,`Please try again, rephrase, or reach out if it keeps failing.`,...o?[`Error id: ${o}`]:[]].join(`

`))}async function bridgeSend(e,t,n){let r=contextStorage.getStore()?.get(ActiveWebhookKey);if(!r)throw Error(`chatSdkChannel().send can only run during a Chat SDK webhook handler for this bridge.`);let i=serializeThread(e,n.thread,n.adapterName),a={auth:n.auth??null,continuationToken:i.id,state:{thread:i}};return n.callback&&(a.callback=n.callback),n.mode&&(a.mode=n.mode),n.title&&(a.title=n.title),r.send(t,a)}function initialState(){return{thread:null}}function metadataFromState(e){return{adapterName:e.thread?.adapterName??null,channelId:e.thread?.channelId??null,isDM:e.thread?.isDM??null,threadId:e.thread?.id??null}}function threadFromState(e,t){if(!t.thread)return null;try{let n=t.thread;return new ThreadImpl({adapter:e.getAdapter(n.adapterName),channelId:n.channelId,channelVisibility:n.channelVisibility,currentMessage:n.currentMessage?Message.fromJSON(n.currentMessage):void 0,id:n.id,isDM:n.isDM,stateAdapter:e.getState()})}catch(e){return log.warn(`failed to rebuild Chat SDK thread from channel state`,{error:e}),null}}function serializeReceiveTarget(e,t){if(t.thread)return t.thread;if(!t.threadId)throw Error(`chatSdkChannel().receive requires target.thread or target.threadId.`);return serializeThread(e,t.threadId,t.adapterName)}function serializeThread(e,t,n){if(typeof t==`string`){let r=n??inferAdapterName(t),i=e.getAdapter(r);return{_type:`chat:Thread`,adapterName:r,channelId:i.channelIdFromThreadId(t),channelVisibility:i.getChannelVisibility?.(t),id:t,isDM:!1}}return isSerializedThread(t)?t:t.toJSON()}function isSerializedThread(e){return`_type`in e&&e._type===`chat:Thread`}function inferAdapterName(e){let t=e.indexOf(`:`);if(t<=0)throw Error(`chatSdkChannel string thread references require options.adapterName.`);return e.slice(0,t)}function adapterNames(e){return Object.keys(e)}function routeForAdapter(e,t){return t.routes?.[e]||`${(t.route??`/eve/v1`).replace(/\/$/u,``)}/${e}`}function encodeInputAction(e,t,n){return`${e}${encodeURIComponent(t)}:${encodeURIComponent(n)}`}function decodeInputAction(e,t,n){if(!e.startsWith(t))return null;let r=e.slice(t.length),i=r.indexOf(`:`);if(i<=0)return null;try{let e=decodeURIComponent(r.slice(0,i));return{optionId:n??decodeURIComponent(r.slice(i+1)),requestId:e}}catch{return null}}export{chatSdkChannel};