@urun-sh/openai 0.2.52 → 0.2.54

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.
@@ -1,3 +1,4 @@
1
- import{c as C}from"../chunk-FSS2A7IU.js";import{a as A,c as D}from"../chunk-PS4BLX7J.js";import{createAssistantMessageEventStream as J}from"@earendil-works/pi-ai";async function F(t){let e=await D(t),n=e.filter(o=>o.function_name===t.fnName&&o.deployment_status==="active").map(o=>o.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var O="urun-serve",G="serve",H=131072,Y=16384,$=3,B=42e4,X=6e4,z=15e3;function Q(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||A,fnName:(t.URUN_FUNCTION??"").trim()||G}}function V(t){let e=(t.URUN_BASE_URL??"").trim(),n=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!n)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let o=(t.URUN_JWT??"").trim();if(o)return{baseUrl:e,orgId:n,auth:{lane:"jwt",jwt:o}};let i=(t.URUN_API_KEY??"").trim();if(!i)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let a=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:n,auth:{lane:"api-key",apiKey:i,gatewayUrl:a}}}function Z(t){return async(e,n,o)=>{let{baseUrl:i,orgId:a,auth:s}=V(e),{App:u,createClientToken:l}=await t(),r=(s.lane==="jwt"?u(n,{baseUrl:i,orgId:a,jwt:s.jwt}):u(n,{baseUrl:i,orgId:a,getAccessToken:async()=>(await l(s.apiKey,{baseUrl:s.gatewayUrl,expiresIn:300,allowedFunctions:[`${n}/${o}`]})).token}))[o];if(typeof r!="function")throw new Error(`urun pi extension: app "${n}" has no function "${o}"`);let d=r(),p=d.connect;return typeof p=="function"&&await p.call(d),d}}var ee=Z(async()=>{let{createRequire:t}=await import("module"),e=t(import.meta.url);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function te(t){try{Promise.resolve(t.close?.()).catch(()=>{})}catch{}}var x=class{constructor(e,n,o){this.open=e;this.env=n;this.fnName=o}open;env;fnName;pool=new Map;acquire(e){let n=this.pool.get(e);if(!n){let o=Promise.resolve(this.open(this.env,e,this.fnName)).then(i=>({session:i,responses:new C(i)}));n=o,this.pool.set(e,o),o.catch(()=>{this.pool.get(e)===o&&this.pool.delete(e)})}return n}evict(e){let n=this.pool.get(e);n&&(this.pool.delete(e),n.then(o=>te(o.session),()=>{}))}closeAll(){for(let e of[...this.pool.keys()])this.evict(e)}};function ne(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let n of t.messages){let o=n.role==="assistant"?"assistant":"user";e.push({role:o,content:re(n.content)})}return oe(e)}function oe(t){let e=[];for(let n of t){let o=e[e.length-1];o&&o.role===n.role?o.content=[o.content,n.content].filter(i=>i.length>0).join(`
1
+ import{c as B}from"../chunk-DYBS3NLC.js";import{a as D,c as H}from"../chunk-PS4BLX7J.js";import{createAssistantMessageEventStream as te}from"@earendil-works/pi-ai";import{mkdirSync as ne,openSync as oe,writeSync as re}from"fs";import se from"os";import{dirname as ie,join as ae}from"path";async function Y(t){let e=await H(t),n=e.filter(o=>o.function_name===t.fnName&&o.deployment_status==="active").map(o=>o.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var Q="urun-serve",le="serve",ce=131072,ue=16384,X=3,pe=42e4,de=6e4,fe=15e3;function ge(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||D,fnName:(t.URUN_FUNCTION??"").trim()||le}}function me(t){let e=(t.URUN_BASE_URL??"").trim(),n=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!n)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let o=(t.URUN_JWT??"").trim();if(o)return{baseUrl:e,orgId:n,auth:{lane:"jwt",jwt:o}};let i=(t.URUN_API_KEY??"").trim();if(!i)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let c=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:n,auth:{lane:"api-key",apiKey:i,gatewayUrl:c}}}function ye(t){let e=null;return n=>{e===null&&(ne(ie(t),{recursive:!0}),e=oe(t,"a"));let o=n.detail?` ${JSON.stringify(n.detail)}`:"";re(e,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${o}
2
+ `)}}function he(t=se.homedir()){return ae(t,".urun","logs","pi-extension.log")}function we(t){let e=ye(he());return async(n,o,i)=>{let{baseUrl:c,orgId:s,auth:d}=me(n),{App:w,createClientToken:a}=await t(),_=(d.lane==="jwt"?w(o,{baseUrl:c,orgId:s,jwt:d.jwt,diagnosticSink:e}):w(o,{baseUrl:c,orgId:s,diagnosticSink:e,getAccessToken:async()=>(await a(d.apiKey,{baseUrl:d.gatewayUrl,expiresIn:300,allowedFunctions:[`${o}/${i}`]})).token}))[i];if(typeof _!="function")throw new Error(`urun pi extension: app "${o}" has no function "${i}"`);let y=_(),b=y.connect;return typeof b=="function"&&await b.call(y),y}}var _e=we(async()=>{let{createRequire:t}=await import("module"),e=t(import.meta.url);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function xe(t){try{Promise.resolve(t.close?.()).catch(()=>{})}catch{}}var F=class{constructor(e,n,o){this.open=e;this.env=n;this.fnName=o}open;env;fnName;pool=new Map;acquire(e){let n=this.pool.get(e);if(!n){let o=Promise.resolve(this.open(this.env,e,this.fnName)).then(i=>({session:i,responses:new B(i)}));n=o,this.pool.set(e,o),o.catch(()=>{this.pool.get(e)===o&&this.pool.delete(e)})}return n}evict(e){let n=this.pool.get(e);n&&(this.pool.delete(e),n.then(o=>xe(o.session),()=>{}))}closeAll(){for(let e of[...this.pool.keys()])this.evict(e)}};function ve(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let n of t.messages){if(n.role==="toolResult"){e.push({type:"function_call_output",call_id:n.toolCallId,output:Te(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let i="",c=()=>{i&&(e.push({role:"assistant",content:i}),i="")};for(let s of n.content)if(s.type==="text")i+=String(s.text??"");else if(s.type==="toolCall")c(),e.push({type:"function_call",call_id:String(s.id??""),name:String(s.name??""),arguments:JSON.stringify(s.arguments??{})});else{if(s.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(s.type)}"`)}c();continue}let o=n.role==="assistant"?"assistant":"user";e.push({role:o,content:Re(n.content)})}return ke(e)}function ke(t){let e=[];for(let n of t){let o=e[e.length-1];o&&"role"in o&&"role"in n&&o.role===n.role?o.content=[o.content,n.content].filter(i=>i.length>0).join(`
2
3
 
3
- `):e.push({...n})}return e}function re(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e?String(e.text):"").join(""):""}function se(t){let e=t instanceof Error?t.message:String(t),n=t?.code;return/\b529\b/.test(e)||/overloaded/i.test(e)||n===529||n==="529"}function ie(t){return new Promise(e=>setTimeout(e,t))}function ae(t,e,n,o){return new Promise((i,a)=>{let s=!1,u=r=>{s||(s=!0,clearTimeout(l),o?.removeEventListener("abort",c),r())},l=setTimeout(()=>u(()=>a(n())),e),c=()=>u(()=>a(new Error("aborted")));if(o?.aborted){c();return}o?.addEventListener("abort",c,{once:!0}),Promise.resolve(t).then(r=>u(()=>i(r)),r=>u(()=>a(r)))})}async function*ce(t,e){let n=t[Symbol.asyncIterator](),o,i=new Promise((a,s)=>{o=()=>s(new Error("aborted")),e.addEventListener("abort",o,{once:!0})});try{for(;;){if(e.aborted)throw new Error("aborted");let a=await Promise.race([n.next(),i]);if(a.done)return;yield a.value}}finally{o&&e.removeEventListener("abort",o),n.return?.(void 0)}}function ue(t,e){let n=t?.sendMessage;if(typeof n=="function")try{n.call(t,{customType:"urun-status",content:e,display:!0},{triggerTurn:!1})}catch{}}function pe(t,e={},n){let o=e.connectDeadlineMs??B,i=e.stallTimeoutMs??X,a=e.phaseHeartbeatMs??z;return(s,u,l)=>{let c=J(),r={role:"assistant",content:[{type:"text",text:""}],api:s.api,provider:s.provider,model:s.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},d=r.content[0],p=new AbortController,m=l?.signal,P=!1,b=()=>{P=!0,p.abort()};m&&(m.aborted?b():m.addEventListener("abort",b,{once:!0}));let E=!1,y,I=()=>{y&&clearTimeout(y),y=setTimeout(()=>{E=!0,p.abort()},i)},_=()=>{y&&clearTimeout(y),y=void 0};return(async()=>{c.push({type:"start",partial:r}),c.push({type:"text_start",contentIndex:0,partial:r});let k=!1,v,S=()=>{v&&clearInterval(v),v=void 0},K=Date.now();v=setInterval(()=>{let f=Math.round((Date.now()-K)/1e3);ue(n,`uRun: still opening the "${s.id}" session\u2026 (${f}s \u2014 serve apps scale to zero, first turn can cold-start ~6min)`)},a);try{let{responses:f}=await ae(t.acquire(s.id),o,()=>new Error(`uRun session for "${s.id}" did not connect within ${Math.round(o/1e3)}s \u2014 likely cold-starting (scaled to zero) or queued behind capacity. Retry shortly.`),p.signal);S();let T=ne(u),N,U;for(let R=1;R<=$;R++)try{let h=await f.responses.create({model:s.id,input:T,stream:!0,max_output_tokens:s.maxTokens});I();for await(let W of ce(h,p.signal)){I();let g=W;if(g.type==="response.output_text.delta"){let w=typeof g.delta=="string"?g.delta:"";w&&(d.text+=w,c.push({type:"text_delta",contentIndex:0,delta:w,partial:r}))}else if(g.type==="response.completed"){N=g.response;break}else if(g.type==="error"){let w=g.error,L=new Error(`uRun serve error: ${w?.message??"unknown error"}`);throw L.code=w?.code??null,L}}U=void 0;break}catch(h){if(U=h,p.signal.aborted)throw h;if(R<$&&se(h)&&d.text.length===0){await ie(R*500);continue}throw h}if(U)throw U;_(),c.push({type:"text_end",contentIndex:0,content:d.text,partial:r});let M=N?.status==="incomplete"?"length":"stop";r.stopReason=M,c.push({type:"done",reason:M,message:r}),c.end(r)}catch(f){if(k=!0,_(),P||m?.aborted&&!E)r.stopReason="aborted",r.errorMessage="aborted by user",c.push({type:"error",reason:"aborted",error:r});else{let T=E?`uRun stream stalled \u2014 no output for ${Math.round(i/1e3)}s; the model may be hung. Retry, or Ctrl-C to abort.`:f instanceof Error?f.message:String(f);r.stopReason="error",r.errorMessage=T,c.push({type:"error",reason:"error",error:r})}c.end(r)}finally{_(),S(),m&&m.removeEventListener("abort",b),k&&t.evict(s.id)}})(),c}}function le(t){return{id:t,name:`uRun ${t}`,api:O,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:H,maxTokens:Y}}function de(t={}){return async e=>{let n=t.env??process.env,{apiKey:o,apiUrl:i,fnName:a}=Q(n),s=await F({apiUrl:i,apiKey:o,fnName:a,fetchImpl:t.fetchImpl}),u=new x(t.openSession??ee,n,a);e.on("session_shutdown",()=>u.closeAll());let l={name:"uRun",api:O,baseUrl:"urun://session",apiKey:"$URUN_API_KEY",models:s.map(le),streamSimple:pe(u,t.timing??{},e)};e.registerProvider("urun",l)}}var Ue=de();export{x as SessionPool,O as URUN_API,oe as coalesceSameRole,de as createUrunExtension,Ue as default,Z as makeSessionFactory,pe as makeStreamSimple,V as resolveSessionEnv,ne as toResponsesInput};
4
+ `):e.push({...n})}return e}function Re(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e?String(e.text):"").join(""):""}function Te(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e="";for(let n of t){let o=String(n.type??"");if(o!=="text")throw new Error(`urun pi extension: unsupported toolResult content part "${o}" \u2014 the serve lane carries text tool results only`);e+=String(n.text??"")}return e}function Ae(t){if(!(!Array.isArray(t)||t.length===0))return t.map(e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))}function z(t,e){if(!e.trim())return{};try{return JSON.parse(e)}catch{throw new Error(`uRun serve error: tool call "${t}" arguments are not valid JSON: ${e}`)}}function be(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ue(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let o of e)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let i of o.content)i.type==="reasoning_text"&&(n+=String(i.text??""));return n}var Ee=["<tool_call>","<function="];function Se(t,e){let n=Ee.find(o=>e.includes(o));if(n)return new Error(`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`)}function Ie(t){let e=t instanceof Error?t.message:String(t),n=t?.code;return/\b529\b/.test(e)||/overloaded/i.test(e)||n===529||n==="529"}function Pe(t){return new Promise(e=>setTimeout(e,t))}function Ce(t,e,n,o){return new Promise((i,c)=>{let s=!1,d=r=>{s||(s=!0,clearTimeout(w),o?.removeEventListener("abort",a),r())},w=setTimeout(()=>d(()=>c(n())),e),a=()=>d(()=>c(new Error("aborted")));if(o?.aborted){a();return}o?.addEventListener("abort",a,{once:!0}),Promise.resolve(t).then(r=>d(()=>i(r)),r=>d(()=>c(r)))})}async function*Ne(t,e){let n=t[Symbol.asyncIterator](),o,i=new Promise((c,s)=>{o=()=>s(new Error("aborted")),e.addEventListener("abort",o,{once:!0})});try{for(;;){if(e.aborted)throw new Error("aborted");let c=await Promise.race([n.next(),i]);if(c.done)return;yield c.value}}finally{o&&e.removeEventListener("abort",o),n.return?.(void 0)}}function Le(t,e){let n=t?.sendMessage;if(typeof n=="function")try{n.call(t,{customType:"urun-status",content:e,display:!0},{triggerTurn:!1})}catch{}}function Me(t,e={},n){let o=e.connectDeadlineMs??pe,i=e.stallTimeoutMs??de,c=e.phaseHeartbeatMs??fe;return(s,d,w)=>{let a=te(),r={role:"assistant",content:[],api:s.api,provider:s.provider,model:s.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},_=new AbortController,y=w?.signal,b=!1,S=()=>{b=!0,_.abort()};y&&(y.aborted?S():y.addEventListener("abort",S,{once:!0}));let N=!1,T,K=()=>{T&&clearTimeout(T),T=setTimeout(()=>{N=!0,_.abort()},i)},L=()=>{T&&clearTimeout(T),T=void 0},x=null,v=null,g=null,J="",I=!1,M=()=>{if(!v)return;let p=v;v=null,a.push({type:"thinking_end",contentIndex:r.content.indexOf(p),content:p.thinking,partial:r})},W=()=>{if(!x)return;let p=x;x=null,a.push({type:"text_end",contentIndex:r.content.indexOf(p),content:p.text,partial:r})},O=()=>{if(!g)return;let{call:p,args:m,contentIndex:k}=g;g=null,p.arguments=z(p.name,m),a.push({type:"toolcall_end",contentIndex:k,toolCall:p,partial:r})},V=p=>{let m={type:"toolCall",id:String(p.call_id??p.id??`call_${r.content.length}`),name:String(p.name??""),arguments:{}};r.content.push(m);let k=r.content.length-1;a.push({type:"toolcall_start",contentIndex:k,partial:r});let U=typeof p.arguments=="string"?p.arguments:"";U&&a.push({type:"toolcall_delta",contentIndex:k,delta:U,partial:r}),m.arguments=z(m.name,U),a.push({type:"toolcall_end",contentIndex:k,toolCall:m,partial:r})};return(async()=>{a.push({type:"start",partial:r});let p=!1,m,k=()=>{m&&clearInterval(m),m=void 0},U=Date.now();m=setInterval(()=>{let R=Math.round((Date.now()-U)/1e3);Le(n,`uRun: still opening the "${s.id}" session\u2026 (${R}s \u2014 serve apps scale to zero, first turn can cold-start ~6min)`)},c);try{let{responses:R}=await Ce(t.acquire(s.id),o,()=>new Error(`uRun session for "${s.id}" did not connect within ${Math.round(o/1e3)}s \u2014 likely cold-starting (scaled to zero) or queued behind capacity. Retry shortly.`),_.signal);k();let $=ve(d),P,C;for(let u=1;u<=X;u++)try{let h=await R.responses.create({model:s.id,input:$,stream:!0,tools:Ae(d.tools),max_output_tokens:s.maxTokens});K();for await(let E of Ne(h,_.signal)){K();let f=E;if(f.type==="response.output_text.delta"){let l=typeof f.delta=="string"?f.delta:"";l&&(I=!0,M(),O(),x||(x={type:"text",text:""},r.content.push(x),a.push({type:"text_start",contentIndex:r.content.length-1,partial:r})),x.text+=l,J+=l,a.push({type:"text_delta",contentIndex:r.content.indexOf(x),delta:l,partial:r}))}else if(f.type==="response.reasoning_text.delta"){let l=typeof f.delta=="string"?f.delta:"";l&&(I=!0,v||(v={type:"thinking",thinking:""},r.content.push(v),a.push({type:"thinking_start",contentIndex:r.content.length-1,partial:r})),v.thinking+=l,a.push({type:"thinking_delta",contentIndex:r.content.indexOf(v),delta:l,partial:r}))}else if(f.type==="response.function_call_arguments.delta"&&typeof f.tool_index=="number"){let l=f;if(I=!0,M(),W(),!g||g.toolIndex!==l.tool_index){O();let G={type:"toolCall",id:l.call_id??`call_${l.tool_index}`,name:l.name??"",arguments:{}};r.content.push(G),g={call:G,args:"",contentIndex:r.content.length-1,toolIndex:l.tool_index},a.push({type:"toolcall_start",contentIndex:g.contentIndex,partial:r})}l.call_id&&(g.call.id=l.call_id),l.name&&(g.call.name=l.name);let A=typeof l.delta=="string"?l.delta:"";A&&(g.args+=A,a.push({type:"toolcall_delta",contentIndex:g.contentIndex,delta:A,partial:r}))}else if(f.type==="response.completed"){P=f.response;break}else if(f.type==="error"){let l=f.error,A=new Error(`uRun serve error: ${l?.message??"unknown error"}`);throw A.code=l?.code??null,A}}C=void 0;break}catch(h){if(C=h,_.signal.aborted)throw h;if(u<X&&Ie(h)&&!I){await Pe(u*500);continue}throw h}if(C)throw C;if(L(),M(),W(),O(),!r.content.some(u=>u.type==="toolCall"))for(let u of be(P))V(u);if(!r.content.some(u=>u.type==="thinking")){let u=Ue(P);if(u){let h={type:"thinking",thinking:""};r.content.push(h);let E=r.content.length-1;a.push({type:"thinking_start",contentIndex:E,partial:r}),h.thinking=u,a.push({type:"thinking_delta",contentIndex:E,delta:u,partial:r}),a.push({type:"thinking_end",contentIndex:E,content:u,partial:r})}}let q=r.content.filter(u=>u.type==="toolCall").length;if((d.tools?.length??0)>0&&q===0){let u=Se(s.id,J);if(u)throw u}let j=q>0?"toolUse":P?.status==="incomplete"?"length":"stop";r.stopReason=j,a.push({type:"done",reason:j,message:r}),a.end(r)}catch(R){if(p=!0,L(),b||y?.aborted&&!N)r.stopReason="aborted",r.errorMessage="aborted by user",a.push({type:"error",reason:"aborted",error:r});else{let $=N?`uRun stream stalled \u2014 no output for ${Math.round(i/1e3)}s; the model may be hung. Retry, or Ctrl-C to abort.`:R instanceof Error?R.message:String(R);r.stopReason="error",r.errorMessage=$,a.push({type:"error",reason:"error",error:r})}a.end(r)}finally{L(),k(),y&&y.removeEventListener("abort",S),p&&t.evict(s.id)}})(),a}}function Oe(t){return{id:t,name:`uRun ${t}`,api:Q,reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:ce,maxTokens:ue}}function $e(t={}){return async e=>{let n=t.env??process.env,{apiKey:o,apiUrl:i,fnName:c}=ge(n),s=await Y({apiUrl:i,apiKey:o,fnName:c,fetchImpl:t.fetchImpl}),d=new F(t.openSession??_e,n,c);e.on("session_shutdown",()=>d.closeAll());let w={name:"uRun",api:Q,baseUrl:"urun://session",apiKey:"$URUN_API_KEY",models:s.map(Oe),streamSimple:Me(d,t.timing??{},e)};e.registerProvider("urun",w)}}var Ye=$e();export{F as SessionPool,Q as URUN_API,ke as coalesceSameRole,ye as createFileDiagnosticSink,$e as createUrunExtension,Ye as default,we as makeSessionFactory,Me as makeStreamSimple,he as piDiagnosticLogPath,me as resolveSessionEnv,ve as toResponsesInput};