@gram-ai/elements 1.6.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/elements.cjs +20 -14
- package/dist/elements.css +1 -1
- package/dist/elements.js +4566 -4540
- package/dist/server.cjs +1 -1
- package/dist/server.js +12 -11
- package/dist/types/index.d.ts +6 -0
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -51,4 +51,4 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
|
|
|
51
51
|
|
|
52
52
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
53
53
|
|
|
54
|
-
`)}})}},Es={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function jp({status:e,statusText:t,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new Is);if(s){const[l,i]=o.tee();o=l,s({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Dt(r,Es)})}function Dp({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function Up(e){return e.type.startsWith("data-")}function Ss(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const s=t[n];if(s===void 0)continue;const o=n in e?e[n]:void 0,l=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);l&&i?r[n]=Ss(o,s):r[n]=s}return r}function qp(e){const t=["ROOT"];let r=-1,n=null;function s(c,u,d){switch(c){case'"':{r=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=u,n=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{r=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{r=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=u,t.pop();break}}}function l(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),r=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{r=c,t.pop();break}default:{r=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const p=e.substring(n,c+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(u,c)):r=c;break}}}let i=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const d=e.substring(n,e.length);"true".startsWith(d)?i+="true".slice(d.length):"false".startsWith(d)?i+="false".slice(d.length):"null".startsWith(d)&&(i+="null".slice(d.length))}}return i}async function xs(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ae({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ae({text:qp(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function sr(e){return e.type.startsWith("data-")}function ir(e){return e.type==="text"}function lr(e){return e.type==="file"}function Xn(e){return e.type==="reasoning"}function $e(e){return e.type.startsWith("tool-")}function Hr(e){return e.type==="dynamic-tool"}function Qn(e){return $e(e)||Hr(e)}function Pt(e){return e.type.split("-").slice(1).join("-")}function Fp(e){return Hr(e)?e.toolName:Pt(e)}function Lp({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Vp({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:l}){return e.pipeThrough(new TransformStream({async transform(i,c){await n(async({state:u,write:d})=>{var p,h,f,m;function v(g){const S=u.message.parts.filter($e).find(I=>I.toolCallId===g);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function _(g){const S=u.message.parts.filter(I=>I.type==="dynamic-tool").find(I=>I.toolCallId===g);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function y(g){var E;const S=u.message.parts.find(P=>$e(P)&&P.toolCallId===g.toolCallId),I=g,x=S;S!=null?(S.state=g.state,x.input=I.input,x.output=I.output,x.errorText=I.errorText,x.rawInput=I.rawInput,x.preliminary=I.preliminary,x.providerExecuted=(E=I.providerExecuted)!=null?E:S.providerExecuted,I.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:`tool-${g.toolName}`,toolCallId:g.toolCallId,state:g.state,input:I.input,output:I.output,rawInput:I.rawInput,errorText:I.errorText,providerExecuted:I.providerExecuted,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}function w(g){var E,S;const I=u.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===g.toolCallId),x=g,P=I;I!=null?(I.state=g.state,P.toolName=g.toolName,P.input=x.input,P.output=x.output,P.errorText=x.errorText,P.rawInput=(E=x.rawInput)!=null?E:P.rawInput,P.preliminary=x.preliminary,P.providerExecuted=(S=x.providerExecuted)!=null?S:I.providerExecuted,x.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=x.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:g.toolName,toolCallId:g.toolCallId,state:g.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function b(g){if(g!=null){const E=u.message.metadata!=null?Ss(u.message.metadata,g):g;t!=null&&await gr({value:E,schema:t}),u.message.metadata=E}}switch(i.type){case"text-start":{const g={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=g,u.message.parts.push(g),d();break}case"text-delta":{const g=u.activeTextParts[i.id];g.text+=i.delta,g.providerMetadata=(p=i.providerMetadata)!=null?p:g.providerMetadata,d();break}case"text-end":{const g=u.activeTextParts[i.id];g.state="done",g.providerMetadata=(h=i.providerMetadata)!=null?h:g.providerMetadata,delete u.activeTextParts[i.id],d();break}case"reasoning-start":{const g={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=g,u.message.parts.push(g),d();break}case"reasoning-delta":{const g=u.activeReasoningParts[i.id];g.text+=i.delta,g.providerMetadata=(f=i.providerMetadata)!=null?f:g.providerMetadata,d();break}case"reasoning-end":{const g=u.activeReasoningParts[i.id];g.providerMetadata=(m=i.providerMetadata)!=null?m:g.providerMetadata,g.state="done",delete u.activeReasoningParts[i.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),d();break}case"tool-input-start":{const g=u.message.parts.filter($e);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:g.length,dynamic:i.dynamic},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),d();break}case"tool-input-delta":{const g=u.partialToolCalls[i.toolCallId];g.text+=i.inputTextDelta;const{value:E}=await xs(g.text);g.dynamic?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:E}):y({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:E}),d();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d();break}case"tool-output-available":{if(i.dynamic){const g=_(i.toolCallId);w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-available",input:g.input,output:i.output,preliminary:i.preliminary})}else{const g=v(i.toolCallId);y({toolCallId:i.toolCallId,toolName:Pt(g),state:"output-available",input:g.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}d();break}case"tool-output-error":{if(i.dynamic){const g=_(i.toolCallId);w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-error",input:g.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const g=v(i.toolCallId);y({toolCallId:i.toolCallId,toolName:Pt(g),state:"output-error",input:g.input,rawInput:g.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await b(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&d();break}case"finish":{await b(i.messageMetadata),i.messageMetadata!=null&&d();break}case"message-metadata":{await b(i.messageMetadata),i.messageMetadata!=null&&d();break}case"error":{s?.(new Error(i.errorText));break}default:if(Up(i)){r?.[i.type]!=null&&await gr({value:i.data,schema:r[i.type]});const g=i;if(g.transient){l?.(g);break}const E=g.id!=null?u.message.parts.find(S=>g.type===S.type&&g.id===S.id):void 0;E!=null?E.data=g.data:u.message.parts.push(g),l?.(g),d()}}c.enqueue(i)})}}))}function Hp({messageId:e,originalMessages:t=[],onFinish:r,onError:n,stream:s}){let o=t?.[t.length-1];o?.role!=="assistant"?o=void 0:e=o.id;let l=!1;const i=s.pipeThrough(new TransformStream({transform(h,f){if(h.type==="start"){const m=h;m.messageId==null&&e!=null&&(m.messageId=e)}h.type==="abort"&&(l=!0),f.enqueue(h)}}));if(r==null)return i;const c=Lp({lastMessage:o?structuredClone(o):void 0,messageId:e??""}),u=async h=>{await h({state:c,write:()=>{}})};let d=!1;const p=async()=>{if(d||!r)return;d=!0;const h=c.message.id===o?.id;await r({isAborted:l,isContinuation:h,responseMessage:c.message,messages:[...h?t.slice(0,-1):t,c.message]})};return Vp({stream:i,runUpdateMessageJob:u,onError:n}).pipeThrough(new TransformStream({transform(h,f){f.enqueue(h)},async cancel(){await p()},async flush(){await p()}}))}function Bp({response:e,status:t,statusText:r,headers:n,stream:s,consumeSseStream:o}){let l=s.pipeThrough(new Is);if(o){const[i,c]=l.tee();l=i,o({stream:c})}Ts({response:e,status:t,statusText:r,headers:Object.fromEntries(Dt(n,Es).entries()),stream:l.pipeThrough(new TextEncoderStream)})}function ft(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var l;n=!0;try{o&&await((l=r.cancel)==null?void 0:l.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:l}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:l}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},t}async function Zp({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function ea(){let e,t;return{promise:new Promise((n,s)=>{e=n,t=s}),resolve:e,reject:t}}function Kp(){let e=[],t=null,r=!1,n=ea();const s=()=>{r=!0,n.resolve(),e.forEach(l=>l.cancel()),e=[],t?.close()},o=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=ea(),await n.promise,o();try{const{value:l,done:i}=await e[0].read();i?(e.shift(),e.length>0?await o():r&&t?.close()):t?.enqueue(l)}catch(l){t?.error(l),e.shift(),s()}};return{stream:new ReadableStream({start(l){t=l},pull:o,async cancel(){for(const l of e)await l.cancel();e=[],r=!0}}),addStream:l=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(l.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:s}}var mt=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function Gp(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function Jp({tools:e,generatorStream:t,tracer:r,telemetry:n,system:s,messages:o,abortSignal:l,repairToolCall:i,experimental_context:c}){let u=null;const d=new ReadableStream({start(y){u=y}}),p=new Set,h=new Map;let f=!1,m;function v(){f&&p.size===0&&(m!=null&&u.enqueue(m),u.close())}const _=new TransformStream({async transform(y,w){const b=y.type;switch(b){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{w.enqueue(y);break}case"file":{w.enqueue({type:"file",file:new Pp({data:y.data,mediaType:y.mediaType})});break}case"finish":{m={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const g=await kp({toolCall:y,tools:e,repairToolCall:i,system:s,messages:o});if(w.enqueue(g),g.invalid){u.enqueue({type:"tool-error",toolCallId:g.toolCallId,toolName:g.toolName,input:g.input,error:mo(g.error),dynamic:!0});break}const E=e[g.toolName];if(h.set(g.toolCallId,g.input),E.onInputAvailable!=null&&await E.onInputAvailable({input:g.input,toolCallId:g.toolCallId,messages:o,abortSignal:l,experimental_context:c}),E.execute!=null&&g.providerExecuted!==!0){const S=Du();p.add(S),Ir({name:"ai.toolCall",attributes:Ne({telemetry:n,attributes:{...Tr({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":g.toolName,"ai.toolCall.id":g.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(g.input)}}}),tracer:r,fn:async I=>{let x;try{const P=Wc({execute:E.execute.bind(E),input:g.input,options:{toolCallId:g.toolCallId,messages:o,abortSignal:l,experimental_context:c}});for await(const F of P)u.enqueue({...g,type:"tool-result",output:F.output,...F.type==="preliminary"&&{preliminary:!0}}),F.type==="final"&&(x=F.output)}catch(P){_s(I,P),u.enqueue({...g,type:"tool-error",error:P}),p.delete(S),v();return}p.delete(S),v();try{I.setAttributes(Ne({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(x)}}}))}catch{}}})}}catch(g){u.enqueue({type:"error",error:g})}break}case"tool-result":{const g=y.toolName;y.isError?u.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:g,input:h.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):w.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:g,input:h.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const g=b;throw new Error(`Unhandled chunk type: ${g}`)}}},flush(){f=!0,v()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(_).pipeTo(new WritableStream({write(w){y.enqueue(w)},close(){}})),d.pipeTo(new WritableStream({write(w){y.enqueue(w)},close(){y.close()}}))])}})}var zp=lt({prefix:"aitxt",size:24});function Wp({model:e,tools:t,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:l,abortSignal:i,headers:c,stopWhen:u=ws(1),experimental_output:d,experimental_telemetry:p,prepareStep:h,providerOptions:f,experimental_activeTools:m,activeTools:v=m,experimental_repairToolCall:_,experimental_transform:y,experimental_download:w,includeRawChunks:b=!1,onChunk:g,onError:E=({error:M})=>{console.error(M)},onFinish:S,onAbort:I,onStepFinish:x,experimental_context:P,_internal:{now:F=Gp,generateId:K=zp,currentDate:de=()=>new Date}={},...q}){return new Xp({model:fs(e),telemetry:p,headers:c,settings:q,maxRetries:l,abortSignal:i,system:n,prompt:s,messages:o,tools:t,toolChoice:r,transforms:Jn(y),activeTools:v,repairToolCall:_,stopConditions:Jn(u),output:d,providerOptions:f,prepareStep:h,includeRawChunks:b,onChunk:g,onError:E,onFinish:S,onAbort:I,onStepFinish:x,now:F,currentDate:de,generateId:K,experimental_context:P,download:w})}function Yp(e){if(!e)return new TransformStream({transform(l,i){i.enqueue({part:l,partialOutput:void 0})}});let t,r="",n="",s="";function o({controller:l,partialOutput:i=void 0}){l.enqueue({part:{type:"text-delta",id:t,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(l,i){if(l.type==="finish-step"&&n.length>0&&o({controller:i}),l.type!=="text-delta"&&l.type!=="text-start"&&l.type!=="text-end"){i.enqueue({part:l,partialOutput:void 0});return}if(t==null)t=l.id;else if(l.id!==t){i.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-start"){i.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:l,partialOutput:void 0});return}r+=l.text,n+=l.text;const c=await e.parsePartial({text:r});if(c!=null){const u=JSON.stringify(c.partial);u!==s&&(o({controller:i,partialOutput:c.partial}),s=u)}}})}var Xp=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:s,abortSignal:o,system:l,prompt:i,messages:c,tools:u,toolChoice:d,transforms:p,activeTools:h,repairToolCall:f,stopConditions:m,output:v,providerOptions:_,prepareStep:y,includeRawChunks:w,now:b,currentDate:g,generateId:E,onChunk:S,onError:I,onFinish:x,onAbort:P,onStepFinish:F,experimental_context:K,download:de}){this._totalUsage=new mt,this._finishReason=new mt,this._steps=new mt,this.output=v,this.includeRawChunks=w,this.tools=u;let q,M=[];const pe=[];let fe,we,re={},O=[];const R=[];let Z,ae={},C={};const k=new TransformStream({async transform(V,H){var G,N,oe,qe;H.enqueue(V);const{part:T}=V;if((T.type==="text-delta"||T.type==="reasoning-delta"||T.type==="source"||T.type==="tool-call"||T.type==="tool-result"||T.type==="tool-input-start"||T.type==="tool-input-delta"||T.type==="raw")&&await S?.({chunk:T}),T.type==="error"&&await I({error:_p(T.error)}),T.type==="text-start"&&(ae[T.id]={type:"text",text:"",providerMetadata:T.providerMetadata},M.push(ae[T.id])),T.type==="text-delta"){const L=ae[T.id];if(L==null){H.enqueue({part:{type:"error",error:`text part ${T.id} not found`},partialOutput:void 0});return}L.text+=T.text,L.providerMetadata=(G=T.providerMetadata)!=null?G:L.providerMetadata}if(T.type==="text-end"){const L=ae[T.id];if(L==null){H.enqueue({part:{type:"error",error:`text part ${T.id} not found`},partialOutput:void 0});return}L.providerMetadata=(N=T.providerMetadata)!=null?N:L.providerMetadata,delete ae[T.id]}if(T.type==="reasoning-start"&&(C[T.id]={type:"reasoning",text:"",providerMetadata:T.providerMetadata},M.push(C[T.id])),T.type==="reasoning-delta"){const L=C[T.id];if(L==null){H.enqueue({part:{type:"error",error:`reasoning part ${T.id} not found`},partialOutput:void 0});return}L.text+=T.text,L.providerMetadata=(oe=T.providerMetadata)!=null?oe:L.providerMetadata}if(T.type==="reasoning-end"){const L=C[T.id];if(L==null){H.enqueue({part:{type:"error",error:`reasoning part ${T.id} not found`},partialOutput:void 0});return}L.providerMetadata=(qe=T.providerMetadata)!=null?qe:L.providerMetadata,delete C[T.id]}if(T.type==="file"&&M.push({type:"file",file:T.file}),T.type==="source"&&M.push(T),T.type==="tool-call"&&M.push(T),T.type==="tool-result"&&!T.preliminary&&M.push(T),T.type==="tool-error"&&M.push(T),T.type==="start-step"&&(re=T.request,O=T.warnings),T.type==="finish-step"){const L=Yn({content:M,tools:u}),Fe=new Op({content:M,finishReason:T.finishReason,usage:T.usage,warnings:O,request:re,response:{...T.response,messages:[...pe,...L]},providerMetadata:T.providerMetadata});await F?.(Fe),Pd(O),R.push(Fe),M=[],C={},ae={},pe.push(...L),q.resolve()}T.type==="finish"&&(we=T.totalUsage,fe=T.finishReason)},async flush(V){try{if(R.length===0){const oe=new $d({message:"No output generated. Check the stream for errors."});ne._finishReason.reject(oe),ne._totalUsage.reject(oe),ne._steps.reject(oe);return}const H=fe??"unknown",G=we??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};ne._finishReason.resolve(H),ne._totalUsage.resolve(G),ne._steps.resolve(R);const N=R[R.length-1];await x?.({finishReason:H,totalUsage:G,usage:N.usage,content:N.content,text:N.text,reasoningText:N.reasoningText,reasoning:N.reasoning,files:N.files,sources:N.sources,toolCalls:N.toolCalls,staticToolCalls:N.staticToolCalls,dynamicToolCalls:N.dynamicToolCalls,toolResults:N.toolResults,staticToolResults:N.staticToolResults,dynamicToolResults:N.dynamicToolResults,request:N.request,response:N.response,warnings:N.warnings,providerMetadata:N.providerMetadata,steps:R}),Z.setAttributes(Ne({telemetry:t,attributes:{"ai.response.finishReason":H,"ai.response.text":{output:()=>N.text},"ai.response.toolCalls":{output:()=>{var oe;return(oe=N.toolCalls)!=null&&oe.length?JSON.stringify(N.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(N.providerMetadata),"ai.usage.inputTokens":G.inputTokens,"ai.usage.outputTokens":G.outputTokens,"ai.usage.totalTokens":G.totalTokens,"ai.usage.reasoningTokens":G.reasoningTokens,"ai.usage.cachedInputTokens":G.cachedInputTokens}}))}catch(H){V.error(H)}finally{Z.end()}}}),$=Kp();this.addStream=$.addStream,this.closeStream=$.close;const z=$.stream.getReader();let Ut=new ReadableStream({async start(V){V.enqueue({type:"start"})},async pull(V){function H(){P?.({steps:R}),V.enqueue({type:"abort"}),V.close()}try{const{done:G,value:N}=await z.read();if(G){V.close();return}if(o?.aborted){H();return}V.enqueue(N)}catch(G){Re(G)&&o?.aborted?H():V.error(G)}},cancel(V){return $.stream.cancel(V)}});for(const V of p)Ut=Ut.pipeThrough(V({tools:u,stopStream(){$.terminate()}}));this.baseStream=Ut.pipeThrough(Yp(v)).pipeThrough(k);const{maxRetries:Rs,retry:As}=Ap({maxRetries:s,abortSignal:o}),qt=Ip(t),ye=sp(n),Br=bp({model:e,telemetry:t,headers:r,settings:{...ye,maxRetries:Rs}}),ne=this;Ir({name:"ai.streamText",attributes:Ne({telemetry:t,attributes:{...Tr({operationId:"ai.streamText",telemetry:t}),...Br,"ai.prompt":{input:()=>JSON.stringify({system:l,prompt:i,messages:c})}}}),tracer:qt,endWhenDone:!1,fn:async V=>{Z=V;async function H({currentStep:G,responseMessages:N,usage:oe}){var qe,T,L,Fe,Zr;const Kr=ne.includeRawChunks;q=new mt;const Gr=await yp({system:l,prompt:i,messages:c}),Le=[...Gr.messages,...N],me=await y?.({model:e,steps:R,stepNumber:R.length,messages:Le}),ke=fs((qe=me?.model)!=null?qe:e),Jr=await rp({prompt:{system:(T=me?.system)!=null?T:Gr.system,messages:(L=me?.messages)!=null?L:Le},supportedUrls:await ke.supportedUrls,download:de}),{toolChoice:Ft,tools:Lt}=lp({tools:u,toolChoice:(Fe=me?.toolChoice)!=null?Fe:d,activeTools:(Zr=me?.activeTools)!=null?Zr:h}),{result:{stream:Cs,response:zr,request:Wr},doStreamSpan:Oe,startTimestampMs:Yr}=await As(()=>Ir({name:"ai.streamText.doStream",attributes:Ne({telemetry:t,attributes:{...Tr({operationId:"ai.streamText.doStream",telemetry:t}),...Br,"ai.model.provider":ke.provider,"ai.model.id":ke.modelId,"ai.prompt.messages":{input:()=>Ep(Jr)},"ai.prompt.tools":{input:()=>Lt?.map(A=>JSON.stringify(A))},"ai.prompt.toolChoice":{input:()=>Ft!=null?JSON.stringify(Ft):void 0},"gen_ai.system":ke.provider,"gen_ai.request.model":ke.modelId,"gen_ai.request.frequency_penalty":ye.frequencyPenalty,"gen_ai.request.max_tokens":ye.maxOutputTokens,"gen_ai.request.presence_penalty":ye.presencePenalty,"gen_ai.request.stop_sequences":ye.stopSequences,"gen_ai.request.temperature":ye.temperature,"gen_ai.request.top_k":ye.topK,"gen_ai.request.top_p":ye.topP}}),tracer:qt,endWhenDone:!1,fn:async A=>({startTimestampMs:b(),doStreamSpan:A,result:await ke.doStream({...ye,tools:Lt,toolChoice:Ft,responseFormat:v?.responseFormat,prompt:Jr,providerOptions:_,abortSignal:o,headers:r,includeRawChunks:Kr})})})),Ps=Jp({tools:u,generatorStream:Cs,tracer:qt,telemetry:t,system:l,messages:Le,repairToolCall:f,abortSignal:o,experimental_context:K}),ks=Wr??{},ut=[],Vt=[];let Ht;const Bt={};let Me="unknown",se={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},Zt,Xr=!0,he={id:E(),timestamp:g(),modelId:e.modelId},Qr="";ne.addStream(Ps.pipeThrough(new TransformStream({async transform(A,J){var Ve,He,ct,_e;if(A.type==="stream-start"){Ht=A.warnings;return}if(Xr){const W=b()-Yr;Xr=!1,Oe.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":W}),Oe.setAttributes({"ai.response.msToFirstChunk":W}),J.enqueue({type:"start-step",request:ks,warnings:Ht??[]})}const en=A.type;switch(en){case"text-start":case"text-end":{J.enqueue(A);break}case"text-delta":{A.delta.length>0&&(J.enqueue({type:"text-delta",id:A.id,text:A.delta,providerMetadata:A.providerMetadata}),Qr+=A.delta);break}case"reasoning-start":case"reasoning-end":{J.enqueue(A);break}case"reasoning-delta":{J.enqueue({type:"reasoning-delta",id:A.id,text:A.delta,providerMetadata:A.providerMetadata});break}case"tool-call":{J.enqueue(A),ut.push(A);break}case"tool-result":{J.enqueue(A),A.preliminary||Vt.push(A);break}case"tool-error":{J.enqueue(A),Vt.push(A);break}case"response-metadata":{he={id:(Ve=A.id)!=null?Ve:he.id,timestamp:(He=A.timestamp)!=null?He:he.timestamp,modelId:(ct=A.modelId)!=null?ct:he.modelId};break}case"finish":{se=A.usage,Me=A.finishReason,Zt=A.providerMetadata;const W=b()-Yr;Oe.addEvent("ai.stream.finish"),Oe.setAttributes({"ai.response.msToFinish":W,"ai.response.avgOutputTokensPerSecond":1e3*((_e=se.outputTokens)!=null?_e:0)/W});break}case"file":{J.enqueue(A);break}case"source":{J.enqueue(A);break}case"tool-input-start":{Bt[A.id]=A.toolName;const W=u?.[A.toolName];W?.onInputStart!=null&&await W.onInputStart({toolCallId:A.id,messages:Le,abortSignal:o,experimental_context:K}),J.enqueue({...A,dynamic:W?.type==="dynamic"});break}case"tool-input-end":{delete Bt[A.id],J.enqueue(A);break}case"tool-input-delta":{const W=Bt[A.id],Kt=u?.[W];Kt?.onInputDelta!=null&&await Kt.onInputDelta({inputTextDelta:A.delta,toolCallId:A.id,messages:Le,abortSignal:o,experimental_context:K}),J.enqueue(A);break}case"error":{J.enqueue(A),Me="error";break}case"raw":{Kr&&J.enqueue(A);break}default:{const W=en;throw new Error(`Unknown chunk type: ${W}`)}}},async flush(A){const J=ut.length>0?JSON.stringify(ut):void 0;try{Oe.setAttributes(Ne({telemetry:t,attributes:{"ai.response.finishReason":Me,"ai.response.text":{output:()=>Qr},"ai.response.toolCalls":{output:()=>J},"ai.response.id":he.id,"ai.response.model":he.modelId,"ai.response.timestamp":he.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Zt),"ai.usage.inputTokens":se.inputTokens,"ai.usage.outputTokens":se.outputTokens,"ai.usage.totalTokens":se.totalTokens,"ai.usage.reasoningTokens":se.reasoningTokens,"ai.usage.cachedInputTokens":se.cachedInputTokens,"gen_ai.response.finish_reasons":[Me],"gen_ai.response.id":he.id,"gen_ai.response.model":he.modelId,"gen_ai.usage.input_tokens":se.inputTokens,"gen_ai.usage.output_tokens":se.outputTokens}}))}catch{}finally{Oe.end()}A.enqueue({type:"finish-step",finishReason:Me,usage:se,providerMetadata:Zt,response:{...he,headers:zr?.headers}});const Ve=Sp(oe,se);await q.promise;const He=ut.filter(_e=>_e.providerExecuted!==!0),ct=Vt.filter(_e=>_e.providerExecuted!==!0);if(He.length>0&&ct.length===He.length&&!await Mp({stopConditions:m,steps:R})){N.push(...Yn({content:R[R.length-1].content,tools:u}));try{await H({currentStep:G+1,responseMessages:N,usage:Ve})}catch(_e){A.enqueue({type:"error",error:_e}),ne.closeStream()}}else A.enqueue({type:"finish",finishReason:Me,totalUsage:Ve}),ne.closeStream()}})))}await H({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(V=>{ne.addStream(new ReadableStream({start(H){H.enqueue({type:"error",error:V}),H.close()}})),ne.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return ft(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ft(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Zp({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new Rd;return ft(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:l=!0,sendFinish:i=!0,onError:c=a.getErrorMessage}={}){const u=t!=null?Dp({originalMessages:e,responseMessageId:t}):void 0,d={},p=f=>{var m,v;const _=d[f];return((v=(m=this.tools)==null?void 0:m[_])==null?void 0:v.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(f,m)=>{const v=n?.({part:f}),_=f.type;switch(_){case"text-start":{m.enqueue({type:"text-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-delta":{m.enqueue({type:"text-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-end":{m.enqueue({type:"text-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-start":{m.enqueue({type:"reasoning-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-delta":{s&&m.enqueue({type:"reasoning-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-end":{m.enqueue({type:"reasoning-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"file":{m.enqueue({type:"file",mediaType:f.file.mediaType,url:`data:${f.file.mediaType};base64,${f.file.base64}`});break}case"source":{o&&f.sourceType==="url"&&m.enqueue({type:"source-url",sourceId:f.id,url:f.url,title:f.title,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}}),o&&f.sourceType==="document"&&m.enqueue({type:"source-document",sourceId:f.id,mediaType:f.mediaType,title:f.title,filename:f.filename,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"tool-input-start":{d[f.id]=f.toolName;const y=p(f.id);m.enqueue({type:"tool-input-start",toolCallId:f.id,toolName:f.toolName,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{m.enqueue({type:"tool-input-delta",toolCallId:f.id,inputTextDelta:f.delta});break}case"tool-call":{d[f.toolCallId]=f.toolName;const y=p(f.toolCallId);f.invalid?m.enqueue({type:"tool-input-error",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:c(f.error)}):m.enqueue({type:"tool-input-available",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=p(f.toolCallId);m.enqueue({type:"tool-output-available",toolCallId:f.toolCallId,output:f.output,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.preliminary!=null?{preliminary:f.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=p(f.toolCallId);m.enqueue({type:"tool-output-error",toolCallId:f.toolCallId,errorText:c(f.error),...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{m.enqueue({type:"error",errorText:c(f.error)});break}case"start-step":{m.enqueue({type:"start-step"});break}case"finish-step":{m.enqueue({type:"finish-step"});break}case"start":{l&&m.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&m.enqueue({type:"finish",...v!=null?{messageMetadata:v}:{}});break}case"abort":{m.enqueue(f);break}case"tool-input-end":break;case"raw":break;default:{const y=_;throw new Error(`Unknown chunk type: ${y}`)}}v!=null&&_!=="start"&&_!=="finish"&&m.enqueue({type:"message-metadata",messageMetadata:v})}}));return ft(Hp({stream:h,messageId:u??t?.(),originalMessages:e,onFinish:r,onError:c}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:l,sendFinish:i,sendStart:c,onError:u,...d}={}){Bp({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:l,sendFinish:i,sendStart:c,onError:u}),...d})}pipeTextStreamToResponse(e,t){$p({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:l,sendStart:i,onError:c,...u}={}){return jp({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:l,sendStart:i,onError:c}),...u})}toTextStreamResponse(e){return Np({textStream:this.textStream,...e})}};function Qp(e,t){const r=[];t?.ignoreIncompleteToolCalls&&(e=e.map(n=>({...n,parts:n.parts.filter(s=>!Qn(s)||s.state!=="input-streaming"&&s.state!=="input-available")})));for(const n of e)switch(n.role){case"system":{const s=n.parts.filter(l=>l.type==="text"),o=s.reduce((l,i)=>i.providerMetadata!=null?{...l,...i.providerMetadata}:l,{});r.push({role:"system",content:s.map(l=>l.text).join(""),...Object.keys(o).length>0?{providerOptions:o}:{}});break}case"user":{r.push({role:"user",content:n.parts.map(s=>{var o;if(ir(s))return{type:"text",text:s.text,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}};if(lr(s))return{type:"file",mediaType:s.mediaType,filename:s.filename,data:s.url,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}};if(sr(s))return(o=t?.convertDataPart)==null?void 0:o.call(t,s)}).filter(s=>s!=null)});break}case"assistant":{if(n.parts!=null){let s=function(){var l,i,c;if(o.length===0)return;const u=[];for(const p of o)if(ir(p))u.push({type:"text",text:p.text,...p.providerMetadata!=null?{providerOptions:p.providerMetadata}:{}});else if(lr(p))u.push({type:"file",mediaType:p.mediaType,filename:p.filename,data:p.url});else if(Xn(p))u.push({type:"reasoning",text:p.text,providerOptions:p.providerMetadata});else if(Hr(p)){const h=p.toolName;p.state!=="input-streaming"&&u.push({type:"tool-call",toolCallId:p.toolCallId,toolName:h,input:p.input,...p.callProviderMetadata!=null?{providerOptions:p.callProviderMetadata}:{}})}else if($e(p)){const h=Pt(p);p.state!=="input-streaming"&&(u.push({type:"tool-call",toolCallId:p.toolCallId,toolName:h,input:p.state==="output-error"?(l=p.input)!=null?l:p.rawInput:p.input,providerExecuted:p.providerExecuted,...p.callProviderMetadata!=null?{providerOptions:p.callProviderMetadata}:{}}),p.providerExecuted===!0&&(p.state==="output-available"||p.state==="output-error")&&u.push({type:"tool-result",toolCallId:p.toolCallId,toolName:h,output:ze({output:p.state==="output-error"?p.errorText:p.output,tool:(i=t?.tools)==null?void 0:i[h],errorMode:p.state==="output-error"?"json":"none"})}))}else if(sr(p)){const h=(c=t?.convertDataPart)==null?void 0:c.call(t,p);h!=null&&u.push(h)}else{const h=p;throw new Error(`Unsupported part: ${h}`)}r.push({role:"assistant",content:u});const d=o.filter(p=>$e(p)&&p.providerExecuted!==!0||p.type==="dynamic-tool");d.length>0&&r.push({role:"tool",content:d.map(p=>{var h;switch(p.state){case"output-error":case"output-available":{const f=Fp(p);return{type:"tool-result",toolCallId:p.toolCallId,toolName:f,output:ze({output:p.state==="output-error"?p.errorText:p.output,tool:(h=t?.tools)==null?void 0:h[f],errorMode:p.state==="output-error"?"text":"none"})}}default:return null}}).filter(p=>p!=null)}),o=[]},o=[];for(const l of n.parts)ir(l)||Xn(l)||lr(l)||Qn(l)||sr(l)?o.push(l):l.type==="step-start"&&s();s();break}break}default:{const s=n.role;throw new Hd({originalMessage:n,message:`Unsupported role: ${s}`})}}return r}lt({prefix:"aiobj",size:24});lt({prefix:"aiobj",size:24});var ef={};Sd(ef,{object:()=>rf,text:()=>tf});var tf=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),rf=({schema:e})=>{const t=jt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await xs(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await Ae({text:r});if(!s.success)throw new Kn({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Se({value:s.value,schema:t});if(!o.success)throw new Kn({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}};const nf="https://app.getgram.ai",af=()=>({chat:sf}),of=a.object({mcp:a.union([a.string()]),environment:a.record(a.string(),a.unknown()).optional(),projectSlug:a.string(),model:a._enum$1(a.MODELS)}),sf=async(e,t)=>{if(e.method==="POST")try{const r=[];for await(const p of e)r.push(p);const n=Buffer.concat(r).toString(),{messages:s,config:o}=JSON.parse(n),l=of.parse(o),c=await(await wl({transport:{type:"http",url:l.mcp,headers:{...lf(l.environment??{}),Authorization:`Bearer ${process.env.GRAM_API_KEY??""}`}}})).tools(),u=fo({baseURL:nf,apiKey:"must be set",headers:{"Gram-Project":l.projectSlug,"Gram-Key":process.env.GRAM_API_KEY??""}}),d=Wp({model:u.chat(l.model),messages:Qp(s),tools:c,stopWhen:ws(10)});t.setHeader("Content-Type","text/event-stream"),t.setHeader("Cache-Control","no-cache"),t.setHeader("Connection","keep-alive"),t.setHeader("Transfer-Encoding","chunked"),t.statusCode=200,d.pipeUIMessageStreamToResponse(t,{sendReasoning:!0,sendSources:!0})}catch(r){t.statusCode=500,t.end(JSON.stringify({error:r instanceof Error?r.message:"Unknown error"}))}},ta="MCP-";function lf(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[r,n])=>{const s=r.replace(/_/g,"-"),o=s.startsWith(ta)?s:`${ta}${s}`;return t[o]=n,t},{})}exports.createElementsServerHandlers=af;
|
|
54
|
+
`)}})}},Es={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function jp({status:e,statusText:t,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new Is);if(s){const[l,i]=o.tee();o=l,s({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Dt(r,Es)})}function Dp({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function Up(e){return e.type.startsWith("data-")}function Ss(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const s=t[n];if(s===void 0)continue;const o=n in e?e[n]:void 0,l=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);l&&i?r[n]=Ss(o,s):r[n]=s}return r}function qp(e){const t=["ROOT"];let r=-1,n=null;function s(c,u,d){switch(c){case'"':{r=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=u,n=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{r=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{r=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=u,t.pop();break}}}function l(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),r=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{r=c,t.pop();break}default:{r=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const p=e.substring(n,c+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(u,c)):r=c;break}}}let i=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const d=e.substring(n,e.length);"true".startsWith(d)?i+="true".slice(d.length):"false".startsWith(d)?i+="false".slice(d.length):"null".startsWith(d)&&(i+="null".slice(d.length))}}return i}async function xs(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ae({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ae({text:qp(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function sr(e){return e.type.startsWith("data-")}function ir(e){return e.type==="text"}function lr(e){return e.type==="file"}function Xn(e){return e.type==="reasoning"}function $e(e){return e.type.startsWith("tool-")}function Hr(e){return e.type==="dynamic-tool"}function Qn(e){return $e(e)||Hr(e)}function Pt(e){return e.type.split("-").slice(1).join("-")}function Fp(e){return Hr(e)?e.toolName:Pt(e)}function Lp({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Vp({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:l}){return e.pipeThrough(new TransformStream({async transform(i,c){await n(async({state:u,write:d})=>{var p,h,f,m;function v(g){const S=u.message.parts.filter($e).find(I=>I.toolCallId===g);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function _(g){const S=u.message.parts.filter(I=>I.type==="dynamic-tool").find(I=>I.toolCallId===g);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function y(g){var E;const S=u.message.parts.find(P=>$e(P)&&P.toolCallId===g.toolCallId),I=g,x=S;S!=null?(S.state=g.state,x.input=I.input,x.output=I.output,x.errorText=I.errorText,x.rawInput=I.rawInput,x.preliminary=I.preliminary,x.providerExecuted=(E=I.providerExecuted)!=null?E:S.providerExecuted,I.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:`tool-${g.toolName}`,toolCallId:g.toolCallId,state:g.state,input:I.input,output:I.output,rawInput:I.rawInput,errorText:I.errorText,providerExecuted:I.providerExecuted,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}function w(g){var E,S;const I=u.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===g.toolCallId),x=g,P=I;I!=null?(I.state=g.state,P.toolName=g.toolName,P.input=x.input,P.output=x.output,P.errorText=x.errorText,P.rawInput=(E=x.rawInput)!=null?E:P.rawInput,P.preliminary=x.preliminary,P.providerExecuted=(S=x.providerExecuted)!=null?S:I.providerExecuted,x.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=x.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:g.toolName,toolCallId:g.toolCallId,state:g.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function b(g){if(g!=null){const E=u.message.metadata!=null?Ss(u.message.metadata,g):g;t!=null&&await gr({value:E,schema:t}),u.message.metadata=E}}switch(i.type){case"text-start":{const g={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=g,u.message.parts.push(g),d();break}case"text-delta":{const g=u.activeTextParts[i.id];g.text+=i.delta,g.providerMetadata=(p=i.providerMetadata)!=null?p:g.providerMetadata,d();break}case"text-end":{const g=u.activeTextParts[i.id];g.state="done",g.providerMetadata=(h=i.providerMetadata)!=null?h:g.providerMetadata,delete u.activeTextParts[i.id],d();break}case"reasoning-start":{const g={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=g,u.message.parts.push(g),d();break}case"reasoning-delta":{const g=u.activeReasoningParts[i.id];g.text+=i.delta,g.providerMetadata=(f=i.providerMetadata)!=null?f:g.providerMetadata,d();break}case"reasoning-end":{const g=u.activeReasoningParts[i.id];g.providerMetadata=(m=i.providerMetadata)!=null?m:g.providerMetadata,g.state="done",delete u.activeReasoningParts[i.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),d();break}case"tool-input-start":{const g=u.message.parts.filter($e);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:g.length,dynamic:i.dynamic},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),d();break}case"tool-input-delta":{const g=u.partialToolCalls[i.toolCallId];g.text+=i.inputTextDelta;const{value:E}=await xs(g.text);g.dynamic?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:E}):y({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:E}),d();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d();break}case"tool-output-available":{if(i.dynamic){const g=_(i.toolCallId);w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-available",input:g.input,output:i.output,preliminary:i.preliminary})}else{const g=v(i.toolCallId);y({toolCallId:i.toolCallId,toolName:Pt(g),state:"output-available",input:g.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}d();break}case"tool-output-error":{if(i.dynamic){const g=_(i.toolCallId);w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-error",input:g.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const g=v(i.toolCallId);y({toolCallId:i.toolCallId,toolName:Pt(g),state:"output-error",input:g.input,rawInput:g.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await b(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&d();break}case"finish":{await b(i.messageMetadata),i.messageMetadata!=null&&d();break}case"message-metadata":{await b(i.messageMetadata),i.messageMetadata!=null&&d();break}case"error":{s?.(new Error(i.errorText));break}default:if(Up(i)){r?.[i.type]!=null&&await gr({value:i.data,schema:r[i.type]});const g=i;if(g.transient){l?.(g);break}const E=g.id!=null?u.message.parts.find(S=>g.type===S.type&&g.id===S.id):void 0;E!=null?E.data=g.data:u.message.parts.push(g),l?.(g),d()}}c.enqueue(i)})}}))}function Hp({messageId:e,originalMessages:t=[],onFinish:r,onError:n,stream:s}){let o=t?.[t.length-1];o?.role!=="assistant"?o=void 0:e=o.id;let l=!1;const i=s.pipeThrough(new TransformStream({transform(h,f){if(h.type==="start"){const m=h;m.messageId==null&&e!=null&&(m.messageId=e)}h.type==="abort"&&(l=!0),f.enqueue(h)}}));if(r==null)return i;const c=Lp({lastMessage:o?structuredClone(o):void 0,messageId:e??""}),u=async h=>{await h({state:c,write:()=>{}})};let d=!1;const p=async()=>{if(d||!r)return;d=!0;const h=c.message.id===o?.id;await r({isAborted:l,isContinuation:h,responseMessage:c.message,messages:[...h?t.slice(0,-1):t,c.message]})};return Vp({stream:i,runUpdateMessageJob:u,onError:n}).pipeThrough(new TransformStream({transform(h,f){f.enqueue(h)},async cancel(){await p()},async flush(){await p()}}))}function Bp({response:e,status:t,statusText:r,headers:n,stream:s,consumeSseStream:o}){let l=s.pipeThrough(new Is);if(o){const[i,c]=l.tee();l=i,o({stream:c})}Ts({response:e,status:t,statusText:r,headers:Object.fromEntries(Dt(n,Es).entries()),stream:l.pipeThrough(new TextEncoderStream)})}function ft(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var l;n=!0;try{o&&await((l=r.cancel)==null?void 0:l.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:l}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:l}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},t}async function Zp({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function ea(){let e,t;return{promise:new Promise((n,s)=>{e=n,t=s}),resolve:e,reject:t}}function Kp(){let e=[],t=null,r=!1,n=ea();const s=()=>{r=!0,n.resolve(),e.forEach(l=>l.cancel()),e=[],t?.close()},o=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=ea(),await n.promise,o();try{const{value:l,done:i}=await e[0].read();i?(e.shift(),e.length>0?await o():r&&t?.close()):t?.enqueue(l)}catch(l){t?.error(l),e.shift(),s()}};return{stream:new ReadableStream({start(l){t=l},pull:o,async cancel(){for(const l of e)await l.cancel();e=[],r=!0}}),addStream:l=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(l.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:s}}var mt=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function Gp(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function Jp({tools:e,generatorStream:t,tracer:r,telemetry:n,system:s,messages:o,abortSignal:l,repairToolCall:i,experimental_context:c}){let u=null;const d=new ReadableStream({start(y){u=y}}),p=new Set,h=new Map;let f=!1,m;function v(){f&&p.size===0&&(m!=null&&u.enqueue(m),u.close())}const _=new TransformStream({async transform(y,w){const b=y.type;switch(b){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{w.enqueue(y);break}case"file":{w.enqueue({type:"file",file:new Pp({data:y.data,mediaType:y.mediaType})});break}case"finish":{m={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const g=await kp({toolCall:y,tools:e,repairToolCall:i,system:s,messages:o});if(w.enqueue(g),g.invalid){u.enqueue({type:"tool-error",toolCallId:g.toolCallId,toolName:g.toolName,input:g.input,error:mo(g.error),dynamic:!0});break}const E=e[g.toolName];if(h.set(g.toolCallId,g.input),E.onInputAvailable!=null&&await E.onInputAvailable({input:g.input,toolCallId:g.toolCallId,messages:o,abortSignal:l,experimental_context:c}),E.execute!=null&&g.providerExecuted!==!0){const S=Du();p.add(S),Ir({name:"ai.toolCall",attributes:Ne({telemetry:n,attributes:{...Tr({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":g.toolName,"ai.toolCall.id":g.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(g.input)}}}),tracer:r,fn:async I=>{let x;try{const P=Wc({execute:E.execute.bind(E),input:g.input,options:{toolCallId:g.toolCallId,messages:o,abortSignal:l,experimental_context:c}});for await(const F of P)u.enqueue({...g,type:"tool-result",output:F.output,...F.type==="preliminary"&&{preliminary:!0}}),F.type==="final"&&(x=F.output)}catch(P){_s(I,P),u.enqueue({...g,type:"tool-error",error:P}),p.delete(S),v();return}p.delete(S),v();try{I.setAttributes(Ne({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(x)}}}))}catch{}}})}}catch(g){u.enqueue({type:"error",error:g})}break}case"tool-result":{const g=y.toolName;y.isError?u.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:g,input:h.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):w.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:g,input:h.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const g=b;throw new Error(`Unhandled chunk type: ${g}`)}}},flush(){f=!0,v()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(_).pipeTo(new WritableStream({write(w){y.enqueue(w)},close(){}})),d.pipeTo(new WritableStream({write(w){y.enqueue(w)},close(){y.close()}}))])}})}var zp=lt({prefix:"aitxt",size:24});function Wp({model:e,tools:t,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:l,abortSignal:i,headers:c,stopWhen:u=ws(1),experimental_output:d,experimental_telemetry:p,prepareStep:h,providerOptions:f,experimental_activeTools:m,activeTools:v=m,experimental_repairToolCall:_,experimental_transform:y,experimental_download:w,includeRawChunks:b=!1,onChunk:g,onError:E=({error:M})=>{console.error(M)},onFinish:S,onAbort:I,onStepFinish:x,experimental_context:P,_internal:{now:F=Gp,generateId:K=zp,currentDate:de=()=>new Date}={},...q}){return new Xp({model:fs(e),telemetry:p,headers:c,settings:q,maxRetries:l,abortSignal:i,system:n,prompt:s,messages:o,tools:t,toolChoice:r,transforms:Jn(y),activeTools:v,repairToolCall:_,stopConditions:Jn(u),output:d,providerOptions:f,prepareStep:h,includeRawChunks:b,onChunk:g,onError:E,onFinish:S,onAbort:I,onStepFinish:x,now:F,currentDate:de,generateId:K,experimental_context:P,download:w})}function Yp(e){if(!e)return new TransformStream({transform(l,i){i.enqueue({part:l,partialOutput:void 0})}});let t,r="",n="",s="";function o({controller:l,partialOutput:i=void 0}){l.enqueue({part:{type:"text-delta",id:t,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(l,i){if(l.type==="finish-step"&&n.length>0&&o({controller:i}),l.type!=="text-delta"&&l.type!=="text-start"&&l.type!=="text-end"){i.enqueue({part:l,partialOutput:void 0});return}if(t==null)t=l.id;else if(l.id!==t){i.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-start"){i.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:l,partialOutput:void 0});return}r+=l.text,n+=l.text;const c=await e.parsePartial({text:r});if(c!=null){const u=JSON.stringify(c.partial);u!==s&&(o({controller:i,partialOutput:c.partial}),s=u)}}})}var Xp=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:s,abortSignal:o,system:l,prompt:i,messages:c,tools:u,toolChoice:d,transforms:p,activeTools:h,repairToolCall:f,stopConditions:m,output:v,providerOptions:_,prepareStep:y,includeRawChunks:w,now:b,currentDate:g,generateId:E,onChunk:S,onError:I,onFinish:x,onAbort:P,onStepFinish:F,experimental_context:K,download:de}){this._totalUsage=new mt,this._finishReason=new mt,this._steps=new mt,this.output=v,this.includeRawChunks=w,this.tools=u;let q,M=[];const pe=[];let fe,we,re={},O=[];const R=[];let Z,ae={},C={};const k=new TransformStream({async transform(V,H){var G,N,oe,qe;H.enqueue(V);const{part:T}=V;if((T.type==="text-delta"||T.type==="reasoning-delta"||T.type==="source"||T.type==="tool-call"||T.type==="tool-result"||T.type==="tool-input-start"||T.type==="tool-input-delta"||T.type==="raw")&&await S?.({chunk:T}),T.type==="error"&&await I({error:_p(T.error)}),T.type==="text-start"&&(ae[T.id]={type:"text",text:"",providerMetadata:T.providerMetadata},M.push(ae[T.id])),T.type==="text-delta"){const L=ae[T.id];if(L==null){H.enqueue({part:{type:"error",error:`text part ${T.id} not found`},partialOutput:void 0});return}L.text+=T.text,L.providerMetadata=(G=T.providerMetadata)!=null?G:L.providerMetadata}if(T.type==="text-end"){const L=ae[T.id];if(L==null){H.enqueue({part:{type:"error",error:`text part ${T.id} not found`},partialOutput:void 0});return}L.providerMetadata=(N=T.providerMetadata)!=null?N:L.providerMetadata,delete ae[T.id]}if(T.type==="reasoning-start"&&(C[T.id]={type:"reasoning",text:"",providerMetadata:T.providerMetadata},M.push(C[T.id])),T.type==="reasoning-delta"){const L=C[T.id];if(L==null){H.enqueue({part:{type:"error",error:`reasoning part ${T.id} not found`},partialOutput:void 0});return}L.text+=T.text,L.providerMetadata=(oe=T.providerMetadata)!=null?oe:L.providerMetadata}if(T.type==="reasoning-end"){const L=C[T.id];if(L==null){H.enqueue({part:{type:"error",error:`reasoning part ${T.id} not found`},partialOutput:void 0});return}L.providerMetadata=(qe=T.providerMetadata)!=null?qe:L.providerMetadata,delete C[T.id]}if(T.type==="file"&&M.push({type:"file",file:T.file}),T.type==="source"&&M.push(T),T.type==="tool-call"&&M.push(T),T.type==="tool-result"&&!T.preliminary&&M.push(T),T.type==="tool-error"&&M.push(T),T.type==="start-step"&&(re=T.request,O=T.warnings),T.type==="finish-step"){const L=Yn({content:M,tools:u}),Fe=new Op({content:M,finishReason:T.finishReason,usage:T.usage,warnings:O,request:re,response:{...T.response,messages:[...pe,...L]},providerMetadata:T.providerMetadata});await F?.(Fe),Pd(O),R.push(Fe),M=[],C={},ae={},pe.push(...L),q.resolve()}T.type==="finish"&&(we=T.totalUsage,fe=T.finishReason)},async flush(V){try{if(R.length===0){const oe=new $d({message:"No output generated. Check the stream for errors."});ne._finishReason.reject(oe),ne._totalUsage.reject(oe),ne._steps.reject(oe);return}const H=fe??"unknown",G=we??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};ne._finishReason.resolve(H),ne._totalUsage.resolve(G),ne._steps.resolve(R);const N=R[R.length-1];await x?.({finishReason:H,totalUsage:G,usage:N.usage,content:N.content,text:N.text,reasoningText:N.reasoningText,reasoning:N.reasoning,files:N.files,sources:N.sources,toolCalls:N.toolCalls,staticToolCalls:N.staticToolCalls,dynamicToolCalls:N.dynamicToolCalls,toolResults:N.toolResults,staticToolResults:N.staticToolResults,dynamicToolResults:N.dynamicToolResults,request:N.request,response:N.response,warnings:N.warnings,providerMetadata:N.providerMetadata,steps:R}),Z.setAttributes(Ne({telemetry:t,attributes:{"ai.response.finishReason":H,"ai.response.text":{output:()=>N.text},"ai.response.toolCalls":{output:()=>{var oe;return(oe=N.toolCalls)!=null&&oe.length?JSON.stringify(N.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(N.providerMetadata),"ai.usage.inputTokens":G.inputTokens,"ai.usage.outputTokens":G.outputTokens,"ai.usage.totalTokens":G.totalTokens,"ai.usage.reasoningTokens":G.reasoningTokens,"ai.usage.cachedInputTokens":G.cachedInputTokens}}))}catch(H){V.error(H)}finally{Z.end()}}}),$=Kp();this.addStream=$.addStream,this.closeStream=$.close;const z=$.stream.getReader();let Ut=new ReadableStream({async start(V){V.enqueue({type:"start"})},async pull(V){function H(){P?.({steps:R}),V.enqueue({type:"abort"}),V.close()}try{const{done:G,value:N}=await z.read();if(G){V.close();return}if(o?.aborted){H();return}V.enqueue(N)}catch(G){Re(G)&&o?.aborted?H():V.error(G)}},cancel(V){return $.stream.cancel(V)}});for(const V of p)Ut=Ut.pipeThrough(V({tools:u,stopStream(){$.terminate()}}));this.baseStream=Ut.pipeThrough(Yp(v)).pipeThrough(k);const{maxRetries:Rs,retry:As}=Ap({maxRetries:s,abortSignal:o}),qt=Ip(t),ye=sp(n),Br=bp({model:e,telemetry:t,headers:r,settings:{...ye,maxRetries:Rs}}),ne=this;Ir({name:"ai.streamText",attributes:Ne({telemetry:t,attributes:{...Tr({operationId:"ai.streamText",telemetry:t}),...Br,"ai.prompt":{input:()=>JSON.stringify({system:l,prompt:i,messages:c})}}}),tracer:qt,endWhenDone:!1,fn:async V=>{Z=V;async function H({currentStep:G,responseMessages:N,usage:oe}){var qe,T,L,Fe,Zr;const Kr=ne.includeRawChunks;q=new mt;const Gr=await yp({system:l,prompt:i,messages:c}),Le=[...Gr.messages,...N],me=await y?.({model:e,steps:R,stepNumber:R.length,messages:Le}),ke=fs((qe=me?.model)!=null?qe:e),Jr=await rp({prompt:{system:(T=me?.system)!=null?T:Gr.system,messages:(L=me?.messages)!=null?L:Le},supportedUrls:await ke.supportedUrls,download:de}),{toolChoice:Ft,tools:Lt}=lp({tools:u,toolChoice:(Fe=me?.toolChoice)!=null?Fe:d,activeTools:(Zr=me?.activeTools)!=null?Zr:h}),{result:{stream:Cs,response:zr,request:Wr},doStreamSpan:Oe,startTimestampMs:Yr}=await As(()=>Ir({name:"ai.streamText.doStream",attributes:Ne({telemetry:t,attributes:{...Tr({operationId:"ai.streamText.doStream",telemetry:t}),...Br,"ai.model.provider":ke.provider,"ai.model.id":ke.modelId,"ai.prompt.messages":{input:()=>Ep(Jr)},"ai.prompt.tools":{input:()=>Lt?.map(A=>JSON.stringify(A))},"ai.prompt.toolChoice":{input:()=>Ft!=null?JSON.stringify(Ft):void 0},"gen_ai.system":ke.provider,"gen_ai.request.model":ke.modelId,"gen_ai.request.frequency_penalty":ye.frequencyPenalty,"gen_ai.request.max_tokens":ye.maxOutputTokens,"gen_ai.request.presence_penalty":ye.presencePenalty,"gen_ai.request.stop_sequences":ye.stopSequences,"gen_ai.request.temperature":ye.temperature,"gen_ai.request.top_k":ye.topK,"gen_ai.request.top_p":ye.topP}}),tracer:qt,endWhenDone:!1,fn:async A=>({startTimestampMs:b(),doStreamSpan:A,result:await ke.doStream({...ye,tools:Lt,toolChoice:Ft,responseFormat:v?.responseFormat,prompt:Jr,providerOptions:_,abortSignal:o,headers:r,includeRawChunks:Kr})})})),Ps=Jp({tools:u,generatorStream:Cs,tracer:qt,telemetry:t,system:l,messages:Le,repairToolCall:f,abortSignal:o,experimental_context:K}),ks=Wr??{},ut=[],Vt=[];let Ht;const Bt={};let Me="unknown",se={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},Zt,Xr=!0,he={id:E(),timestamp:g(),modelId:e.modelId},Qr="";ne.addStream(Ps.pipeThrough(new TransformStream({async transform(A,J){var Ve,He,ct,_e;if(A.type==="stream-start"){Ht=A.warnings;return}if(Xr){const W=b()-Yr;Xr=!1,Oe.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":W}),Oe.setAttributes({"ai.response.msToFirstChunk":W}),J.enqueue({type:"start-step",request:ks,warnings:Ht??[]})}const en=A.type;switch(en){case"text-start":case"text-end":{J.enqueue(A);break}case"text-delta":{A.delta.length>0&&(J.enqueue({type:"text-delta",id:A.id,text:A.delta,providerMetadata:A.providerMetadata}),Qr+=A.delta);break}case"reasoning-start":case"reasoning-end":{J.enqueue(A);break}case"reasoning-delta":{J.enqueue({type:"reasoning-delta",id:A.id,text:A.delta,providerMetadata:A.providerMetadata});break}case"tool-call":{J.enqueue(A),ut.push(A);break}case"tool-result":{J.enqueue(A),A.preliminary||Vt.push(A);break}case"tool-error":{J.enqueue(A),Vt.push(A);break}case"response-metadata":{he={id:(Ve=A.id)!=null?Ve:he.id,timestamp:(He=A.timestamp)!=null?He:he.timestamp,modelId:(ct=A.modelId)!=null?ct:he.modelId};break}case"finish":{se=A.usage,Me=A.finishReason,Zt=A.providerMetadata;const W=b()-Yr;Oe.addEvent("ai.stream.finish"),Oe.setAttributes({"ai.response.msToFinish":W,"ai.response.avgOutputTokensPerSecond":1e3*((_e=se.outputTokens)!=null?_e:0)/W});break}case"file":{J.enqueue(A);break}case"source":{J.enqueue(A);break}case"tool-input-start":{Bt[A.id]=A.toolName;const W=u?.[A.toolName];W?.onInputStart!=null&&await W.onInputStart({toolCallId:A.id,messages:Le,abortSignal:o,experimental_context:K}),J.enqueue({...A,dynamic:W?.type==="dynamic"});break}case"tool-input-end":{delete Bt[A.id],J.enqueue(A);break}case"tool-input-delta":{const W=Bt[A.id],Kt=u?.[W];Kt?.onInputDelta!=null&&await Kt.onInputDelta({inputTextDelta:A.delta,toolCallId:A.id,messages:Le,abortSignal:o,experimental_context:K}),J.enqueue(A);break}case"error":{J.enqueue(A),Me="error";break}case"raw":{Kr&&J.enqueue(A);break}default:{const W=en;throw new Error(`Unknown chunk type: ${W}`)}}},async flush(A){const J=ut.length>0?JSON.stringify(ut):void 0;try{Oe.setAttributes(Ne({telemetry:t,attributes:{"ai.response.finishReason":Me,"ai.response.text":{output:()=>Qr},"ai.response.toolCalls":{output:()=>J},"ai.response.id":he.id,"ai.response.model":he.modelId,"ai.response.timestamp":he.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Zt),"ai.usage.inputTokens":se.inputTokens,"ai.usage.outputTokens":se.outputTokens,"ai.usage.totalTokens":se.totalTokens,"ai.usage.reasoningTokens":se.reasoningTokens,"ai.usage.cachedInputTokens":se.cachedInputTokens,"gen_ai.response.finish_reasons":[Me],"gen_ai.response.id":he.id,"gen_ai.response.model":he.modelId,"gen_ai.usage.input_tokens":se.inputTokens,"gen_ai.usage.output_tokens":se.outputTokens}}))}catch{}finally{Oe.end()}A.enqueue({type:"finish-step",finishReason:Me,usage:se,providerMetadata:Zt,response:{...he,headers:zr?.headers}});const Ve=Sp(oe,se);await q.promise;const He=ut.filter(_e=>_e.providerExecuted!==!0),ct=Vt.filter(_e=>_e.providerExecuted!==!0);if(He.length>0&&ct.length===He.length&&!await Mp({stopConditions:m,steps:R})){N.push(...Yn({content:R[R.length-1].content,tools:u}));try{await H({currentStep:G+1,responseMessages:N,usage:Ve})}catch(_e){A.enqueue({type:"error",error:_e}),ne.closeStream()}}else A.enqueue({type:"finish",finishReason:Me,totalUsage:Ve}),ne.closeStream()}})))}await H({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(V=>{ne.addStream(new ReadableStream({start(H){H.enqueue({type:"error",error:V}),H.close()}})),ne.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return ft(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ft(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Zp({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new Rd;return ft(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:l=!0,sendFinish:i=!0,onError:c=a.getErrorMessage}={}){const u=t!=null?Dp({originalMessages:e,responseMessageId:t}):void 0,d={},p=f=>{var m,v;const _=d[f];return((v=(m=this.tools)==null?void 0:m[_])==null?void 0:v.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(f,m)=>{const v=n?.({part:f}),_=f.type;switch(_){case"text-start":{m.enqueue({type:"text-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-delta":{m.enqueue({type:"text-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-end":{m.enqueue({type:"text-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-start":{m.enqueue({type:"reasoning-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-delta":{s&&m.enqueue({type:"reasoning-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-end":{m.enqueue({type:"reasoning-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"file":{m.enqueue({type:"file",mediaType:f.file.mediaType,url:`data:${f.file.mediaType};base64,${f.file.base64}`});break}case"source":{o&&f.sourceType==="url"&&m.enqueue({type:"source-url",sourceId:f.id,url:f.url,title:f.title,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}}),o&&f.sourceType==="document"&&m.enqueue({type:"source-document",sourceId:f.id,mediaType:f.mediaType,title:f.title,filename:f.filename,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"tool-input-start":{d[f.id]=f.toolName;const y=p(f.id);m.enqueue({type:"tool-input-start",toolCallId:f.id,toolName:f.toolName,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{m.enqueue({type:"tool-input-delta",toolCallId:f.id,inputTextDelta:f.delta});break}case"tool-call":{d[f.toolCallId]=f.toolName;const y=p(f.toolCallId);f.invalid?m.enqueue({type:"tool-input-error",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:c(f.error)}):m.enqueue({type:"tool-input-available",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=p(f.toolCallId);m.enqueue({type:"tool-output-available",toolCallId:f.toolCallId,output:f.output,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.preliminary!=null?{preliminary:f.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=p(f.toolCallId);m.enqueue({type:"tool-output-error",toolCallId:f.toolCallId,errorText:c(f.error),...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{m.enqueue({type:"error",errorText:c(f.error)});break}case"start-step":{m.enqueue({type:"start-step"});break}case"finish-step":{m.enqueue({type:"finish-step"});break}case"start":{l&&m.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&m.enqueue({type:"finish",...v!=null?{messageMetadata:v}:{}});break}case"abort":{m.enqueue(f);break}case"tool-input-end":break;case"raw":break;default:{const y=_;throw new Error(`Unknown chunk type: ${y}`)}}v!=null&&_!=="start"&&_!=="finish"&&m.enqueue({type:"message-metadata",messageMetadata:v})}}));return ft(Hp({stream:h,messageId:u??t?.(),originalMessages:e,onFinish:r,onError:c}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:l,sendFinish:i,sendStart:c,onError:u,...d}={}){Bp({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:l,sendFinish:i,sendStart:c,onError:u}),...d})}pipeTextStreamToResponse(e,t){$p({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:l,sendStart:i,onError:c,...u}={}){return jp({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:l,sendStart:i,onError:c}),...u})}toTextStreamResponse(e){return Np({textStream:this.textStream,...e})}};function Qp(e,t){const r=[];t?.ignoreIncompleteToolCalls&&(e=e.map(n=>({...n,parts:n.parts.filter(s=>!Qn(s)||s.state!=="input-streaming"&&s.state!=="input-available")})));for(const n of e)switch(n.role){case"system":{const s=n.parts.filter(l=>l.type==="text"),o=s.reduce((l,i)=>i.providerMetadata!=null?{...l,...i.providerMetadata}:l,{});r.push({role:"system",content:s.map(l=>l.text).join(""),...Object.keys(o).length>0?{providerOptions:o}:{}});break}case"user":{r.push({role:"user",content:n.parts.map(s=>{var o;if(ir(s))return{type:"text",text:s.text,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}};if(lr(s))return{type:"file",mediaType:s.mediaType,filename:s.filename,data:s.url,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}};if(sr(s))return(o=t?.convertDataPart)==null?void 0:o.call(t,s)}).filter(s=>s!=null)});break}case"assistant":{if(n.parts!=null){let s=function(){var l,i,c;if(o.length===0)return;const u=[];for(const p of o)if(ir(p))u.push({type:"text",text:p.text,...p.providerMetadata!=null?{providerOptions:p.providerMetadata}:{}});else if(lr(p))u.push({type:"file",mediaType:p.mediaType,filename:p.filename,data:p.url});else if(Xn(p))u.push({type:"reasoning",text:p.text,providerOptions:p.providerMetadata});else if(Hr(p)){const h=p.toolName;p.state!=="input-streaming"&&u.push({type:"tool-call",toolCallId:p.toolCallId,toolName:h,input:p.input,...p.callProviderMetadata!=null?{providerOptions:p.callProviderMetadata}:{}})}else if($e(p)){const h=Pt(p);p.state!=="input-streaming"&&(u.push({type:"tool-call",toolCallId:p.toolCallId,toolName:h,input:p.state==="output-error"?(l=p.input)!=null?l:p.rawInput:p.input,providerExecuted:p.providerExecuted,...p.callProviderMetadata!=null?{providerOptions:p.callProviderMetadata}:{}}),p.providerExecuted===!0&&(p.state==="output-available"||p.state==="output-error")&&u.push({type:"tool-result",toolCallId:p.toolCallId,toolName:h,output:ze({output:p.state==="output-error"?p.errorText:p.output,tool:(i=t?.tools)==null?void 0:i[h],errorMode:p.state==="output-error"?"json":"none"})}))}else if(sr(p)){const h=(c=t?.convertDataPart)==null?void 0:c.call(t,p);h!=null&&u.push(h)}else{const h=p;throw new Error(`Unsupported part: ${h}`)}r.push({role:"assistant",content:u});const d=o.filter(p=>$e(p)&&p.providerExecuted!==!0||p.type==="dynamic-tool");d.length>0&&r.push({role:"tool",content:d.map(p=>{var h;switch(p.state){case"output-error":case"output-available":{const f=Fp(p);return{type:"tool-result",toolCallId:p.toolCallId,toolName:f,output:ze({output:p.state==="output-error"?p.errorText:p.output,tool:(h=t?.tools)==null?void 0:h[f],errorMode:p.state==="output-error"?"text":"none"})}}default:return null}}).filter(p=>p!=null)}),o=[]},o=[];for(const l of n.parts)ir(l)||Xn(l)||lr(l)||Qn(l)||sr(l)?o.push(l):l.type==="step-start"&&s();s();break}break}default:{const s=n.role;throw new Hd({originalMessage:n,message:`Unsupported role: ${s}`})}}return r}lt({prefix:"aiobj",size:24});lt({prefix:"aiobj",size:24});var ef={};Sd(ef,{object:()=>rf,text:()=>tf});var tf=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),rf=({schema:e})=>{const t=jt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await xs(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await Ae({text:r});if(!s.success)throw new Kn({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Se({value:s.value,schema:t});if(!o.success)throw new Kn({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}};const nf="https://app.getgram.ai",af=()=>({chat:sf}),of=a.object({mcp:a.union([a.string()]),environment:a.record(a.string(),a.unknown()).optional(),projectSlug:a.string(),model:a._enum$1(a.MODELS)}),sf=async(e,t)=>{if(e.method==="POST")try{const r=[];for await(const h of e)r.push(h);const n=Buffer.concat(r).toString(),{messages:s,config:o,system:l}=JSON.parse(n),i=of.parse(o),u=await(await wl({transport:{type:"http",url:i.mcp,headers:{...lf(i.environment??{}),Authorization:`Bearer ${process.env.GRAM_API_KEY??""}`}}})).tools(),d=fo({baseURL:nf,apiKey:"must be set",headers:{"Gram-Project":i.projectSlug,"Gram-Key":process.env.GRAM_API_KEY??""}}),p=Wp({system:l,model:d.chat(i.model),messages:Qp(s),tools:u,stopWhen:ws(10)});t.setHeader("Content-Type","text/event-stream"),t.setHeader("Cache-Control","no-cache"),t.setHeader("Connection","keep-alive"),t.setHeader("Transfer-Encoding","chunked"),t.statusCode=200,p.pipeUIMessageStreamToResponse(t,{sendReasoning:!0,sendSources:!0})}catch(r){t.statusCode=500,t.end(JSON.stringify({error:r instanceof Error?r.message:"Unknown error"}))}},ta="MCP-";function lf(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[r,n])=>{const s=r.replace(/_/g,"-"),o=s.startsWith(ta)?s:`${ta}${s}`;return t[o]=n,t},{})}exports.createElementsServerHandlers=af;
|
package/dist/server.js
CHANGED
|
@@ -10534,34 +10534,35 @@ const Bf = "https://app.getgram.ai", Wf = () => ({
|
|
|
10534
10534
|
if (e.method === "POST")
|
|
10535
10535
|
try {
|
|
10536
10536
|
const r = [];
|
|
10537
|
-
for await (const
|
|
10538
|
-
r.push(
|
|
10539
|
-
const a = Buffer.concat(r).toString(), { messages: o, config: n } = JSON.parse(a),
|
|
10537
|
+
for await (const m of e)
|
|
10538
|
+
r.push(m);
|
|
10539
|
+
const a = Buffer.concat(r).toString(), { messages: o, config: n, system: i } = JSON.parse(a), s = Hf.parse(n), l = await (await su({
|
|
10540
10540
|
transport: {
|
|
10541
10541
|
type: "http",
|
|
10542
|
-
url:
|
|
10542
|
+
url: s.mcp,
|
|
10543
10543
|
headers: {
|
|
10544
|
-
...Jf(
|
|
10544
|
+
...Jf(s.environment ?? {}),
|
|
10545
10545
|
// Always send the Gram-Key header last so that it isn't clobbered by the environment variables.
|
|
10546
10546
|
Authorization: `Bearer ${process.env.GRAM_API_KEY ?? ""}`
|
|
10547
10547
|
}
|
|
10548
10548
|
}
|
|
10549
|
-
})).tools(),
|
|
10549
|
+
})).tools(), d = Do({
|
|
10550
10550
|
baseURL: Bf,
|
|
10551
10551
|
// We do not use the apiKey field as the requests are proxied through the Gram API.
|
|
10552
10552
|
// Instead we use the Gram-Key header to authenticate the request.
|
|
10553
10553
|
apiKey: "must be set",
|
|
10554
10554
|
headers: {
|
|
10555
|
-
"Gram-Project":
|
|
10555
|
+
"Gram-Project": s.projectSlug,
|
|
10556
10556
|
"Gram-Key": process.env.GRAM_API_KEY ?? ""
|
|
10557
10557
|
}
|
|
10558
|
-
}),
|
|
10559
|
-
|
|
10558
|
+
}), p = Uf({
|
|
10559
|
+
system: i,
|
|
10560
|
+
model: d.chat(s.model),
|
|
10560
10561
|
messages: qf(o),
|
|
10561
|
-
tools:
|
|
10562
|
+
tools: l,
|
|
10562
10563
|
stopWhen: Gs(10)
|
|
10563
10564
|
});
|
|
10564
|
-
t.setHeader("Content-Type", "text/event-stream"), t.setHeader("Cache-Control", "no-cache"), t.setHeader("Connection", "keep-alive"), t.setHeader("Transfer-Encoding", "chunked"), t.statusCode = 200,
|
|
10565
|
+
t.setHeader("Content-Type", "text/event-stream"), t.setHeader("Cache-Control", "no-cache"), t.setHeader("Connection", "keep-alive"), t.setHeader("Transfer-Encoding", "chunked"), t.statusCode = 200, p.pipeUIMessageStreamToResponse(t, {
|
|
10565
10566
|
sendReasoning: !0,
|
|
10566
10567
|
sendSources: !0
|
|
10567
10568
|
});
|
package/dist/types/index.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ export interface ElementsProviderProps {
|
|
|
14
14
|
}
|
|
15
15
|
type ServerUrl = string;
|
|
16
16
|
export interface ElementsConfig {
|
|
17
|
+
/**
|
|
18
|
+
* The system prompt to use for the Elements library.
|
|
19
|
+
*/
|
|
20
|
+
systemPrompt?: string;
|
|
17
21
|
/**
|
|
18
22
|
* The project slug to use for the Elements library.
|
|
19
23
|
*/
|
|
@@ -205,6 +209,8 @@ export type ElementsContextType = {
|
|
|
205
209
|
model: Model;
|
|
206
210
|
isExpanded: boolean;
|
|
207
211
|
setIsExpanded: (isExpanded: boolean) => void;
|
|
212
|
+
isOpen: boolean;
|
|
213
|
+
setIsOpen: (isOpen: boolean) => void;
|
|
208
214
|
};
|
|
209
215
|
declare const ContentSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
210
216
|
type: z.ZodLiteral<"text">;
|
package/package.json
CHANGED