@urun-sh/openai 0.3.6 → 0.4.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/chunk-AIKXXK57.js +6 -0
- package/dist/{chunk-EZGLK3VT.js → chunk-HTPQYXGG.js} +1 -1
- package/dist/hosted/bin.cjs +1 -1
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +5 -5
- package/dist/hosted/index.d.cts +12 -3
- package/dist/hosted/index.d.ts +1 -0
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +50 -50
- package/dist/proxy/cli.cjs +2 -2
- package/dist/proxy/cli.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-FVEXRGKL.js +0 -6
package/dist/proxy/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var vn=Object.create;var nt=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var Rn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of xn(t))!Sn.call(e,r)&&r!==n&&nt(e,r,{get:()=>t[r],enumerable:!(o=kn(t,r))||o.enumerable});return e};var te=(e,t,n)=>(n=e!=null?vn(bn(e)):{},Rn(t||!e||!e.__esModule?nt(n,"default",{value:e,enumerable:!0}):n,e));var An=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,I=An();var et=require("child_process"),Y=require("fs"),wn=te(require("path"),1),_=te(require("process"),1);var ce=require("@urun-sh/core");async function ot(e){let n=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}function rt(e,t,n,o){let r=e.response??{},s={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(s.instructions=r.instructions),Array.isArray(r.modalities)&&(s.modalities=r.modalities),typeof r.temperature=="number"&&(s.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(s.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(s.tools=r.tools),s}function st(e,t,n){let o={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),o}function it(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{};return{type:"error",error:{type:"urun_error",code:t.code??null,message:n.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var En="llm-resp";async function*Ce(e,t){let n=`${En}:${t}`,o=`resp_${t}`;yield{type:"response.created",response:{id:o,status:"in_progress"}};let r=new Map;for await(let s of e.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,u=r.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),r.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...i.body}};return}else if(i.t==="error"){yield it(i);return}}}var On="llm",he=class{constructor(t){this.session=t;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc(On).set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){let o=st(t,n,this.consumerId);return this.write(o),Ce(this.session,n)}sendResponseCreate(t,n,o){let r=rt(t,n,o,this.consumerId);return this.write(r),Ce(this.session,o)}};var at=0;function In(){return at+=1,`req_${Date.now().toString(36)}_${at.toString(36)}`}var ye=class{transport;constructor(t){this.transport=new he(t)}responses={create:async t=>{let n=In(),o=this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*o})(),{requestId:n})}}};var Ue=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),o=Math.floor(n.byteLength/2),r=new Int16Array(o);for(let s=0;s<o;s++)r[s]=n.readInt16LE(s*2);this.source.onData(r)}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let o=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function lt(e,t,n=1e4){let o=new Ue(t,{sampleRate:24e3}),r=await o.startOutbound();await e.stream("rt-audio-in").attach(r);let s=await Tn(e,n);return await o.startInbound(s),o}function Tn(e,t){let n=e.stream("rt-audio-out");return n.track!=null?Promise.resolve(n.track):new Promise((o,r)=>{let s,i=setTimeout(()=>{s?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),a=c=>{c!=null&&(clearTimeout(i),s?.(),o(c))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var ut="rt-video-in",ct=256e3;function dt(e){let t=e.stream(ut),n=t.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${ut}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>ct)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${ct}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(t,o)}}}var Pn=24e3,ue=480,Cn=111;async function Un(){let e=await import("opusscript"),t=e.default??e;return new t(Pn,1,2048)}async function we(){let e=await import("werift"),t=await Un();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let c=new Int16Array(i.length+a.length);c.set(i,0),c.set(a,i.length);let u=0;for(;c.length-u>=ue;){let l=c.subarray(u,u+ue);u+=ue;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),g=t.encode(p,ue);r=r+1&65535,s=s+ue>>>0;let h=new e.RtpHeader({version:2,payloadType:Cn,sequenceNumber:r,timestamp:s,ssrc:o,marker:!1}),w=new e.RtpPacket(h,g);n.writeRtp(w)}i=c.slice(u)}}},createSink:n=>{let o={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=t.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let c=0;c<a.length;c++)a[c]=i.readInt16LE(c*2);o.onframe?.({samples:a})}),o}}}var _e=require("@urun-sh/core"),$e="rt-video-out";var $n="h264";function Ln(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function Nn(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let o=n;if(o===null||typeof o!="object"||o.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(o?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let r=o;Ln(r,"decodeVideoOutRecord");let s=e.subarray(2+t);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:r,au:s.slice()}}var pt="urun.videoOut.v2-ws";function ft(e){let t=e.stream($e);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${$e}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,o=new Set,r=new Set,s=c=>{for(let u of o)u(c)},i=!1,a=async()=>{for await(let c of t.messages()){if(!(c instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${$e}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=Nn(c)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(u)}for(let c of r)c()};return{codec:$n,onOutputFrame:c=>(n.add(c),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(c)),onLaneError:c=>(o.add(c),()=>o.delete(c)),onEnd:c=>(r.add(c),()=>r.delete(c))}}function Mn(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Dn(e){let t=e?.type;return t==="response.completed"||t==="error"}function mt(e){return async function(n){return(async function*(){for(let r=1;r<=2;r++){let{app:s,entry:i}=await e.sessionFor(n.model),a=!1,c=!1;try{let u=await e.createStream(i,n);for await(let l of u){if(Dn(l)&&(a=!0),Mn(l)){if(r>1)continue}else c=!0;yield l}}catch(u){if(r<2&&!c){await e.evict(s,i);continue}throw u}if(a)return;if(r<2&&!c){await e.evict(s,i);continue}return}})()}}var gt="https://api.urun.sh/v1";function Le(e){return e.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var L=class extends Error{},V=class extends Error{},Ne="urs1.";function jn(e,t){return Ne+Buffer.from(JSON.stringify([e,t]),"utf8").toString("base64url")}function Vn(e){if(!e.startsWith(Ne))return null;try{let t=JSON.parse(Buffer.from(e.slice(Ne.length),"base64url").toString("utf8"));if(Array.isArray(t)&&typeof t[0]=="string"&&typeof t[1]=="string")return{app:t[0],key:t[1]}}catch{}return null}async function ht(e){let t=e.fetchImpl??fetch,n=`${e.apiUrl.replace(/\/+$/,"")}/apps`,o=await t(n,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}var Bn=6e4,ve=class{constructor(t){this.opts=t}opts;pool=new Map;appsCache=null;seed(t,n){this.pool.set(t,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let t=this.opts.appsTtlMs??Bn;if(this.appsCache&&Date.now()-this.appsCache.at<t)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}servable(t){return t.filter(n=>n.function_name===this.opts.fnName&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let t=this.opts.defaultApp,n=new Set(t===null?[]:[t]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))n.add(r);for(let r of this.pool.keys())n.add(r);let o=[...n].filter(r=>r!==t).sort();return t===null?o:[t,...o]}async noDefaultApp(t){let n=await this.availableIds(),o=n.length>0?n.join(", "):"(none deployed)";throw new L(t===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed "${this.opts.fnName}" apps; available models: ${o}`:`model "${t}" does not name a deployed "${this.opts.fnName}" app in your org, and this endpoint has no default model to fall back to; available models: ${o}`)}async resolveApp(t){let n=(t??"").trim(),o=this.opts.defaultApp;if(!n||n==="urun")return o===null?this.noDefaultApp(n):o;let r=Le(n);if(r===o)return o;if(this.pool.has(r))return r;if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(r))return r;let a=i.filter(u=>u.startsWith(`${r}-`));if(a.length===1)return a[0];if(a.length>1)throw new L(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let c=s.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(c)throw new L(`model "${n}" maps to app "${c.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||r===Le(a.model_id)||r===Le(`${a.model_id}-${a.variant}`));if(i)throw new L(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(n):o}async sessionFor(t){let n=await this.resolveApp(t),o=this.pool.get(n);return o||(o=Promise.resolve(this.opts.openSession(n)),this.pool.set(n,o),o.catch(()=>this.pool.delete(n))),{app:n,entry:await o}}keyOf(t){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=n(t);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(t){let{app:n,entry:o}=await this.sessionFor(t);return{app:n,handle:jn(n,this.keyOf(o))}}async sessionForHandle(t){let n=Vn(t);if(!n)throw new V(`malformed session handle ${JSON.stringify(t)} \u2014 not issued by this proxy`);let{app:o,key:r}=n,s=this.pool.get(o),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new V(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==r)throw new V(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:i}}async evict(t,n){let o=this.pool.get(t);!o||await o.then(s=>s,()=>null)!==n||this.pool.get(t)!==o||(this.pool.delete(t),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(n=>({id:n,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let t=[...this.pool.values()];this.pool.clear();let n=[];if(await Promise.all(t.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){n.push(String(r instanceof Error?r.message:r))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Fn=3,Gn="llm",Hn=new Set(["ended","expired","error"]);function yt(e,t){let n=e.doc(Gn),o=typeof n.onConnectionState=="function",r=typeof e.onPhase=="function";if(!o&&!r)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=new Set,a=[],c=u=>{if(!s){s=u;for(let l of[...i])l(u);i.clear()}};return o&&a.push(n.onConnectionState(u=>{u.consecutiveFailures<Fn||c(new V(`the pooled session for app "${t}" is gone: its doc backhaul failed ${u.consecutiveFailures} consecutive times (last close ${u.lastCloseCode===null?"by provider liveness reap":`code ${u.lastCloseCode}`}${u.lastCloseReason?`, reason ${JSON.stringify(u.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),r&&a.push(e.onPhase(u=>{Hn.has(u.name)&&c(new V(`the pooled session for app "${t}" is gone: it reached terminal phase "${u.name}". The entry is evicted; retry to get a fresh session.`))})),{gone:()=>s,onGone(u){return s?(u(s),()=>{}):(i.add(u),()=>i.delete(u))},dispose(){i.clear();for(let u of a.splice(0))u()}}}async function*Me(e,t){let n=t.gone();if(n)throw n;let o=e[Symbol.asyncIterator](),r,s=new Promise((i,a)=>{r=t.onGone(c=>a(c))});s.catch(()=>{});try{for(;;){let i=await Promise.race([o.next(),s]);if(i.done)return;yield i.value}}finally{r?.(),o.return?.(void 0)}}function wt(e,t,n){let o=e[n];if(typeof o!="function")throw new Error(`app "${t}" has no function "${n}" (set URUN_FUNCTION)`);let r=o();if(typeof r.end!="function")throw new Error(`app "${t}" function "${n}" returned a session without end()`);return r}function qn(e,t){let{baseUrl:n,orgId:o,fnName:r,auth:s,subject:i}=e,a=p=>({session:p,responses:new ye(p),gone:yt(p,t)});if(s.lane==="jwt"){let p=(0,ce.App)(t,{baseUrl:n,orgId:o,jwt:s.jwt});return a(wt(p,t,r))}let{apiKey:c,gatewayUrl:u}=s,l=(0,ce.App)(t,{baseUrl:n,orgId:o,getAccessToken:async()=>(await(0,ce.createClientToken)(c,{baseUrl:u,expiresIn:300,allowedFunctions:[`${t}/${r}`],...i===void 0?{}:{subject:i}})).token});return a(wt(l,t,r))}function Jn(e){let t=e.session.id;if(typeof t!="string"||t.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return t}var Wn=new Set(["error","ended","expired"]);function _t(e){let{auth:t,catalog:n}=e,o=null,r=i=>{let a=qn(e,i);return a.gone.onGone(()=>{o?.evict(i,a)}),a},s=new ve({defaultApp:e.defaultApp,fnName:e.fnName,openSession:r,closeSession:async i=>{i.gone.dispose(),await i.session.end()},listApps:t.lane==="api-key"?()=>ht({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:n?()=>ot(n):null,sessionKey:Jn});return o=s,e.defaultApp!==null&&s.seed(e.defaultApp,r(e.defaultApp)),s}function vt(e,t=we){let n=new WeakMap,o=new WeakMap,r=new WeakMap;return{createResponse:mt({sessionFor:s=>e.sessionFor(s),evict:(s,i)=>e.evict(s,i),createStream:async(s,i)=>Me(await s.responses.responses.create(i),s.gone)}),listModels:()=>e.modelList(),openAudio:async s=>{let{entry:i}=await e.sessionFor(s),a=n.get(i);return a||(a=(async()=>lt(i.session,await t()))(),n.set(i,a),a.catch(()=>n.delete(i))),a},openVideo:async s=>{let{entry:i}=await e.sessionFor(s),a=o.get(i);return a||(a=dt(i.session),o.set(i,a)),a},openVideoOut:async s=>{let{entry:i}=await e.sessionFor(s),a=r.get(i);return a||(a=ft(i.session),r.set(i,a)),a},sessionHandle:async s=>(await e.handleFor(s)).handle,createResponseOn:async(s,i)=>{let{entry:a}=await e.sessionForHandle(s);return Me(await a.responses.responses.create(i),a.gone)},onSessionEnd:async(s,i)=>{let{entry:a}=await e.sessionForHandle(s),c=a.session;if(typeof c.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let u=!1;return c.onPhase(l=>{if(u||!Wn.has(l.name))return;u=!0;let p=c.endsAt??null;i({timeLeftMs:p?Math.max(0,p.getTime()-Date.now()):null,reason:l.name==="expired"?"session reached its maximum length":`session ${l.name}`})})}}}var qt=require("http");var jt=require("crypto"),Vt=require("ws");var xt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Yn=1007,bt=1008,W=1011,De=1008,d=class extends Error{constructor(n,o=Yn){super(n);this.closeCode=o}closeCode},E=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,ke=["setup","clientContent","realtimeInput","toolResponse"];function St(e){let t;try{t=JSON.parse(e)}catch{throw new d("client message is not valid JSON")}let n=E(t);if(!n)throw new d("client message must be a JSON object");let o=ke.filter(a=>n[a]!==void 0),r=Object.keys(n).filter(a=>!ke.includes(a));if(r.length>0)throw new d(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${ke.join(", ")}`);if(o.length!==1)throw new d(`client message must contain exactly one of ${ke.join(", ")} (got ${o.length})`);let s=o[0],i=E(n[s]);if(!i)throw new d(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Rt(e,t){if(typeof e=="string")return e;let n=E(e),o=n?n.parts:void 0;if(!Array.isArray(o))throw new d(`${t}: expected a Content with a parts array`);let r=[];for(let s of o){let i=E(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new d(`${t}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new d(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new d(`${t}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
|
|
2
|
+
"use strict";var vn=Object.create;var nt=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var Rn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of xn(t))!Sn.call(e,r)&&r!==n&&nt(e,r,{get:()=>t[r],enumerable:!(o=kn(t,r))||o.enumerable});return e};var te=(e,t,n)=>(n=e!=null?vn(bn(e)):{},Rn(t||!e||!e.__esModule?nt(n,"default",{value:e,enumerable:!0}):n,e));var An=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,I=An();var et=require("child_process"),Y=require("fs"),wn=te(require("path"),1),_=te(require("process"),1);var ce=require("@urun-sh/core");async function ot(e){let n=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}function rt(e,t,n,o){let r=e.response??{},s={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(s.instructions=r.instructions),Array.isArray(r.modalities)&&(s.modalities=r.modalities),typeof r.temperature=="number"&&(s.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(s.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(s.tools=r.tools),s}function st(e,t,n){let o={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),o}function it(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{};return{type:"error",error:{type:"urun_error",code:t.code??null,message:n.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var En="llm-resp";async function*Ce(e,t){let n=`${En}:${t}`,o=`resp_${t}`;yield{type:"response.created",response:{id:o,status:"in_progress"}};let r=new Map;for await(let s of e.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,u=r.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),r.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...i.body}};return}else if(i.t==="error"){yield it(i);return}}}var On="llm",he=class{constructor(t){this.session=t;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc(On).set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){let o=st(t,n,this.consumerId);return this.write(o),Ce(this.session,n)}sendResponseCreate(t,n,o){let r=rt(t,n,o,this.consumerId);return this.write(r),Ce(this.session,o)}};var at=0;function In(){return at+=1,`req_${Date.now().toString(36)}_${at.toString(36)}`}var ye=class{transport;constructor(t){this.transport=new he(t)}responses={create:async t=>{let n=In(),o=this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*o})(),{requestId:n})}}};var Ue=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),o=Math.floor(n.byteLength/2),r=new Int16Array(o);for(let s=0;s<o;s++)r[s]=n.readInt16LE(s*2);this.source.onData(r)}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let o=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function lt(e,t,n=1e4){let o=new Ue(t,{sampleRate:24e3}),r=await o.startOutbound();await e.stream("rt-audio-in").attach(r);let s=await Tn(e,n);return await o.startInbound(s),o}function Tn(e,t){let n=e.stream("rt-audio-out");return n.track!=null?Promise.resolve(n.track):new Promise((o,r)=>{let s,i=setTimeout(()=>{s?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),a=c=>{c!=null&&(clearTimeout(i),s?.(),o(c))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var ut="rt-video-in",ct=256e3;function dt(e){let t=e.stream(ut),n=t.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${ut}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>ct)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${ct}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(t,o)}}}var Pn=24e3,ue=480,Cn=111;async function Un(){let e=await import("opusscript"),t=e.default??e;return new t(Pn,1,2048)}async function we(){let e=await import("werift"),t=await Un();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let c=new Int16Array(i.length+a.length);c.set(i,0),c.set(a,i.length);let u=0;for(;c.length-u>=ue;){let l=c.subarray(u,u+ue);u+=ue;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),g=t.encode(p,ue);r=r+1&65535,s=s+ue>>>0;let h=new e.RtpHeader({version:2,payloadType:Cn,sequenceNumber:r,timestamp:s,ssrc:o,marker:!1}),w=new e.RtpPacket(h,g);n.writeRtp(w)}i=c.slice(u)}}},createSink:n=>{let o={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=t.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let c=0;c<a.length;c++)a[c]=i.readInt16LE(c*2);o.onframe?.({samples:a})}),o}}}var _e=require("@urun-sh/core"),$e="rt-video-out";var $n="h264";function Ln(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function Nn(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let o=n;if(o===null||typeof o!="object"||o.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(o?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let r=o;Ln(r,"decodeVideoOutRecord");let s=e.subarray(2+t);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:r,au:s.slice()}}var pt="urun.videoOut.v2-ws";function ft(e){let t=e.stream($e);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${$e}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,o=new Set,r=new Set,s=c=>{for(let u of o)u(c)},i=!1,a=async()=>{for await(let c of t.messages()){if(!(c instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${$e}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=Nn(c)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(u)}for(let c of r)c()};return{codec:$n,onOutputFrame:c=>(n.add(c),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(c)),onLaneError:c=>(o.add(c),()=>o.delete(c)),onEnd:c=>(r.add(c),()=>r.delete(c))}}function Mn(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Dn(e){let t=e?.type;return t==="response.completed"||t==="error"}function mt(e){return async function(n){return(async function*(){for(let r=1;r<=2;r++){let{app:s,entry:i}=await e.sessionFor(n.model),a=!1,c=!1;try{let u=await e.createStream(i,n);for await(let l of u){if(Dn(l)&&(a=!0),Mn(l)){if(r>1)continue}else c=!0;yield l}}catch(u){if(r<2&&!c){await e.evict(s,i);continue}throw u}if(a)return;if(r<2&&!c){await e.evict(s,i);continue}return}})()}}var gt="https://api.urun.sh/v1";function Le(e){return e.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var L=class extends Error{},V=class extends Error{},Ne="urs1.";function jn(e,t){return Ne+Buffer.from(JSON.stringify([e,t]),"utf8").toString("base64url")}function Vn(e){if(!e.startsWith(Ne))return null;try{let t=JSON.parse(Buffer.from(e.slice(Ne.length),"base64url").toString("utf8"));if(Array.isArray(t)&&typeof t[0]=="string"&&typeof t[1]=="string")return{app:t[0],key:t[1]}}catch{}return null}async function ht(e){let t=e.fetchImpl??fetch,n=`${e.apiUrl.replace(/\/+$/,"")}/apps`,o=await t(n,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}var Bn=6e4,ve=class{constructor(t){this.opts=t}opts;pool=new Map;appsCache=null;seed(t,n){this.pool.set(t,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let t=this.opts.appsTtlMs??Bn;if(this.appsCache&&Date.now()-this.appsCache.at<t)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}servable(t){return t.filter(n=>n.function_name===this.opts.fnName&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let t=this.opts.defaultApp,n=new Set(t===null?[]:[t]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))n.add(r);for(let r of this.pool.keys())n.add(r);let o=[...n].filter(r=>r!==t).sort();return t===null?o:[t,...o]}async noDefaultApp(t){let n=await this.availableIds(),o=n.length>0?n.join(", "):"(none deployed)";throw new L(t===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed "${this.opts.fnName}" apps; available models: ${o}`:`model "${t}" does not name a deployed "${this.opts.fnName}" app in your org, and this endpoint has no default model to fall back to; available models: ${o}`)}async resolveApp(t){let n=(t??"").trim(),o=this.opts.defaultApp;if(!n||n==="urun")return o===null?this.noDefaultApp(n):o;let r=Le(n);if(r===o)return o;if(this.pool.has(r))return r;if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(r))return r;let a=i.filter(u=>u.startsWith(`${r}-`));if(a.length===1)return a[0];if(a.length>1)throw new L(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let c=s.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(c)throw new L(`model "${n}" maps to app "${c.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||r===Le(a.model_id)||r===Le(`${a.model_id}-${a.variant}`));if(i)throw new L(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(n):o}async sessionFor(t){let n=await this.resolveApp(t),o=this.pool.get(n);return o||(o=Promise.resolve(this.opts.openSession(n)),this.pool.set(n,o),o.catch(()=>this.pool.delete(n))),{app:n,entry:await o}}keyOf(t){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=n(t);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(t){let{app:n,entry:o}=await this.sessionFor(t);return{app:n,handle:jn(n,this.keyOf(o))}}async sessionForHandle(t){let n=Vn(t);if(!n)throw new V(`malformed session handle ${JSON.stringify(t)} \u2014 not issued by this proxy`);let{app:o,key:r}=n,s=this.pool.get(o),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new V(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==r)throw new V(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:i}}async evict(t,n){let o=this.pool.get(t);!o||await o.then(s=>s,()=>null)!==n||this.pool.get(t)!==o||(this.pool.delete(t),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(n=>({id:n,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let t=[...this.pool.values()];this.pool.clear();let n=[];if(await Promise.all(t.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){n.push(String(r instanceof Error?r.message:r))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Fn=3,Gn="llm",Hn=new Set(["paused","error"]);function yt(e,t){let n=e.doc(Gn),o=typeof n.onConnectionState=="function",r=typeof e.onPhase=="function";if(!o&&!r)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=new Set,a=[],c=u=>{if(!s){s=u;for(let l of[...i])l(u);i.clear()}};return o&&a.push(n.onConnectionState(u=>{u.consecutiveFailures<Fn||c(new V(`the pooled session for app "${t}" is gone: its doc backhaul failed ${u.consecutiveFailures} consecutive times (last close ${u.lastCloseCode===null?"by provider liveness reap":`code ${u.lastCloseCode}`}${u.lastCloseReason?`, reason ${JSON.stringify(u.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),r&&a.push(e.onPhase(u=>{Hn.has(u.name)&&c(new V(`the pooled session for app "${t}" lost its compute binding (phase "${u.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(u){return s?(u(s),()=>{}):(i.add(u),()=>i.delete(u))},dispose(){i.clear();for(let u of a.splice(0))u()}}}async function*Me(e,t){let n=t.gone();if(n)throw n;let o=e[Symbol.asyncIterator](),r,s=new Promise((i,a)=>{r=t.onGone(c=>a(c))});s.catch(()=>{});try{for(;;){let i=await Promise.race([o.next(),s]);if(i.done)return;yield i.value}}finally{r?.(),o.return?.(void 0)}}function wt(e,t,n){let o=e[n];if(typeof o!="function")throw new Error(`app "${t}" has no function "${n}" (set URUN_FUNCTION)`);let r=o();if(typeof r.end!="function")throw new Error(`app "${t}" function "${n}" returned a session without end()`);return r}function qn(e,t){let{baseUrl:n,orgId:o,fnName:r,auth:s,subject:i}=e,a=p=>({session:p,responses:new ye(p),gone:yt(p,t)});if(s.lane==="jwt"){let p=(0,ce.App)(t,{baseUrl:n,orgId:o,jwt:s.jwt});return a(wt(p,t,r))}let{apiKey:c,gatewayUrl:u}=s,l=(0,ce.App)(t,{baseUrl:n,orgId:o,getAccessToken:async()=>(await(0,ce.createClientToken)(c,{baseUrl:u,expiresIn:300,allowedFunctions:[`${t}/${r}`],...i===void 0?{}:{subject:i}})).token});return a(wt(l,t,r))}function Jn(e){let t=e.session.id;if(typeof t!="string"||t.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return t}var Wn=new Set(["error","paused"]);function _t(e){let{auth:t,catalog:n}=e,o=null,r=i=>{let a=qn(e,i);return a.gone.onGone(()=>{o?.evict(i,a)}),a},s=new ve({defaultApp:e.defaultApp,fnName:e.fnName,openSession:r,closeSession:async i=>{i.gone.dispose(),await i.session.end()},listApps:t.lane==="api-key"?()=>ht({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:n?()=>ot(n):null,sessionKey:Jn});return o=s,e.defaultApp!==null&&s.seed(e.defaultApp,r(e.defaultApp)),s}function vt(e,t=we){let n=new WeakMap,o=new WeakMap,r=new WeakMap;return{createResponse:mt({sessionFor:s=>e.sessionFor(s),evict:(s,i)=>e.evict(s,i),createStream:async(s,i)=>Me(await s.responses.responses.create(i),s.gone)}),listModels:()=>e.modelList(),openAudio:async s=>{let{entry:i}=await e.sessionFor(s),a=n.get(i);return a||(a=(async()=>lt(i.session,await t()))(),n.set(i,a),a.catch(()=>n.delete(i))),a},openVideo:async s=>{let{entry:i}=await e.sessionFor(s),a=o.get(i);return a||(a=dt(i.session),o.set(i,a)),a},openVideoOut:async s=>{let{entry:i}=await e.sessionFor(s),a=r.get(i);return a||(a=ft(i.session),r.set(i,a)),a},sessionHandle:async s=>(await e.handleFor(s)).handle,createResponseOn:async(s,i)=>{let{entry:a}=await e.sessionForHandle(s);return Me(await a.responses.responses.create(i),a.gone)},onSessionEnd:async(s,i)=>{let{entry:a}=await e.sessionForHandle(s),c=a.session;if(typeof c.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let u=!1;return c.onPhase(l=>{if(u||!Wn.has(l.name))return;u=!0;let p=c.endsAt??null;i({timeLeftMs:p?Math.max(0,p.getTime()-Date.now()):null,reason:l.reason??`session ${l.name}`})})}}}var qt=require("http");var jt=require("crypto"),Vt=require("ws");var xt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Yn=1007,bt=1008,W=1011,De=1008,d=class extends Error{constructor(n,o=Yn){super(n);this.closeCode=o}closeCode},E=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,ke=["setup","clientContent","realtimeInput","toolResponse"];function St(e){let t;try{t=JSON.parse(e)}catch{throw new d("client message is not valid JSON")}let n=E(t);if(!n)throw new d("client message must be a JSON object");let o=ke.filter(a=>n[a]!==void 0),r=Object.keys(n).filter(a=>!ke.includes(a));if(r.length>0)throw new d(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${ke.join(", ")}`);if(o.length!==1)throw new d(`client message must contain exactly one of ${ke.join(", ")} (got ${o.length})`);let s=o[0],i=E(n[s]);if(!i)throw new d(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Rt(e,t){if(typeof e=="string")return e;let n=E(e),o=n?n.parts:void 0;if(!Array.isArray(o))throw new d(`${t}: expected a Content with a parts array`);let r=[];for(let s of o){let i=E(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new d(`${t}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new d(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new d(`${t}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
|
|
3
3
|
`)}var zn={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},X="urun.videoOut";function At(e){return{framing:pt,codec:e}}function Et(e){let{seq:t,ptsUs:n,codec:o,key:r}=e.header;return{[X]:{v:1,seq:t,ptsUs:n,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var Xn={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Qn=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",X],kt=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Zn(e){let t=E(e);if(!t)throw new d("setup.realtimeInputConfig must be an object");for(let r of Object.keys(t))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new d(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let n=E(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!n)throw new d("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(n??{}))if(r!=="disabled")throw new d(`automaticActivityDetection.${r} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new d("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let o="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!kt.includes(t.activityHandling))throw new d(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${kt.join(", ")}`);o=t.activityHandling}return{manualActivity:!0,activityHandling:o}}var eo=["temperature","maxOutputTokens","responseModalities"];function Ot(e){for(let[p,g]of Object.entries(Xn))if(e[p]!==void 0)throw new d(g);for(let p of Object.keys(e))if(!Qn.includes(p))throw new d(`unsupported setup field "${p}"`);if(typeof e.model!="string"||e.model.length===0)throw new d('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),n,o,r=!1,s=E(e.generationConfig);if(e.generationConfig!==void 0&&!s)throw new d("setup.generationConfig must be an object");if(s){for(let p of Object.keys(s))if(!eo.includes(p))throw new d(`unsupported generationConfig field "${p}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new d("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new d("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let p=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let g of p){let h=String(g).toUpperCase();if(h==="AUDIO"){r=!0;continue}if(h!=="TEXT")throw new d(`responseModalities ${JSON.stringify(g)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let i=[];e.systemInstruction!==void 0&&i.push({role:"system",content:Rt(e.systemInstruction,"setup.systemInstruction")});let a;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new d("setup.tools must be an array");a=[];for(let p of e.tools){let g=E(p);if(!g)throw new d("setup.tools entries must be objects");for(let h of Object.keys(g))if(h!=="functionDeclarations")throw new d(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(g.functionDeclarations))throw new d("tool.functionDeclarations must be an array");for(let h of g.functionDeclarations){let w=E(h);if(!w||typeof w.name!="string")throw new d("functionDeclarations entries require a string name");a.push({type:"function",name:w.name,description:w.description,parameters:w.parameters})}}a.length===0&&(a=void 0)}let c={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let p=E(e.sessionResumption);if(!p)throw new d("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let g of Object.keys(p))if(g!=="handle")throw new d(`unsupported sessionResumption field "${g}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(p.handle!==void 0&&(typeof p.handle!="string"||p.handle.length===0))throw new d("sessionResumption.handle must be a non-empty string when present");c={enabled:!0,handle:typeof p.handle=="string"?p.handle:null}}let u=e.realtimeInputConfig===void 0?zn:Zn(e.realtimeInputConfig),l=!1;if(e[X]!==void 0){if(!E(e[X]))throw new d(`setup["${X}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:i,tools:a,temperature:n,maxOutputTokens:o,audioModality:r,activity:u,sessionResumption:c,videoOut:l}}function It(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function Tt(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function Pt(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new d(`unsupported clientContent field "${o}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new d("clientContent.turns must be an array");let n=[];for(let o of t){let r=E(o);if(!r)throw new d("clientContent.turns entries must be Content objects");let s=r.role===void 0?"user":String(r.role).toLowerCase();if(s!=="user"&&s!=="model")throw new d(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);n.push({role:s==="model"?"assistant":"user",content:Rt(r,"clientContent.turns")})}return{items:n,turnComplete:e.turnComplete===!0}}var xe=16e3,Ct=24e3,to=`audio/pcm;rate=${Ct}`,Ut=Buffer.alloc(960).toString("base64");function no(e,t,n){if(t===n)return e;let o=Math.floor(e.length*n/t),r=new Int16Array(o),s=t/n,i=e.length-1;for(let a=0;a<o;a++){let c=a*s,u=Math.floor(c);if(u>=i){r[a]=e[i];continue}let l=c-u;r[a]=Math.round(e[u]+(e[u+1]-e[u])*l)}return r}function oo(e){let t=E(e);if(!t)throw new d("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new d(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(t.mimeType)}`);if(typeof t.data!="string"||t.data.length===0)throw new d("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(t.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new d("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function ro(e){let t=E(e);if(!t)throw new d("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new d(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(t.mimeType);if(n&&Number(n[1])!==xe)throw new d(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${xe} Hz (audio/pcm;rate=${xe})`);if(typeof t.data!="string"||t.data.length===0)throw new d("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length===0||o.length%2!==0)throw new d(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${o.length} bytes \u2014 not even)`);let r=new Int16Array(o.length/2);for(let i=0;i<r.length;i++)r[i]=o.readInt16LE(i*2);let s=no(r,xe,Ct);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function $t(e){if(e.mediaChunks!==void 0)throw new d('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new d("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",s=E(e[r]);if(!s||Object.keys(s).length!==0)throw new d(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let t=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!t.includes(o))throw new d(`unsupported realtimeInput field "${o}"`);let n=t.filter(o=>e[o]!==void 0);if(n.length!==1)throw new d(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${n.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:ro(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:oo(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new d("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new d("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function Lt(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new d(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new d("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let n=E(t);if(!n||typeof n.id!="string"||n.id.length===0)throw new d("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Nt(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function Mt(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:to,data:e}}]}}}}function Dt(e){let t=E(e)??{},n=Array.isArray(t.output)?t.output:[],o=[],r=[],s=typeof t.output_text=="string"?t.output_text:"";if(!s)for(let u of n){let l=E(u);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let p of l.content){let g=E(p);g?.type==="output_text"&&typeof g.text=="string"&&(s+=g.text)}}s&&r.push({role:"assistant",content:s});for(let u of n){let l=E(u);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new d(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,W);let p=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",g;try{g=JSON.parse(p)}catch{throw new d(`upstream function_call arguments are not valid JSON: ${p}`,W)}o.push({id:l.call_id,name:l.name,args:g}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:p})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let a=E(t.usage),c={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(c.usageMetadata=u)}return i.push(c),{messages:i,assistantItems:r}}var so=256,je=class{snapshots=new Map;store(t,n){for(this.snapshots.set(t,n);this.snapshots.size>so;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(t){return this.snapshots.get(t)}},le=e=>e.slice(0,120),Ve=class{constructor(t,n,o){this.ws=t;this.clients=n;this.registry=o;t.on("message",r=>this.onMessage(r)),t.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.()})}ws;clients;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;send(t){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(t))}fail(t){if(t instanceof L){this.ws.close(bt,le(t.message));return}if(t instanceof V){this.ws.close(De,le(t.message));return}if(t instanceof d){this.ws.close(t.closeCode,le(t.message));return}this.ws.close(W,le(String(t instanceof Error?t.message:t)))}onMessage(t){try{let n=St(typeof t=="string"?t:Buffer.concat(Array.isArray(t)?t:[t]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(r=>this.fail(r));return}if(!this.config)throw new d(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(n.kind==="clientContent"){let{items:r,turnComplete:s}=Pt(n.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let r=$t(n.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,o);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:Ut);return}this.transcript.push(...Lt(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(t){if(this.config)throw new d("setup may only be sent once, as the first client message");let n=Ot(t),o=n.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new d("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",De);if(s.model!==n.model)throw new d(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new d("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");this.transcript=[...s.transcript],this.proxyHandle=s.proxyHandle,this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i)))}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let r={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(u=>this.send(Et(u))),c=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),c()},r[X]=At(i.codec)}}this.send({setupComplete:r}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let t=this.config;if(!t)throw new d("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new d("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",W);return this.audio=(async()=>{let o=await n.call(this.clients,t.model);return this.detachAudio=o.onOutputAudio(r=>this.send(Mt(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(t){this.ensureAudioLane().then(n=>n.appendInputAudio(t)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let t=this.config;if(!t)throw new d("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new d("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",W);return this.video=Promise.resolve(n.call(this.clients,t.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(t){this.ensureVideoLane().then(n=>n.sendInputFrame(t)).catch(n=>this.fail(n))}onActivity(t,n){if(!n.activity.manualActivity)throw new d(`realtimeInput.${t} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(t==="activityStart"){if(this.activityOpen)throw new d("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new d("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(t){this.queue=this.queue.then(t,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let t=this.config;if(!t?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(t.model);this.proxyHandle=n;let o=(0,jt.randomUUID)();this.registry.store(o,{model:t.model,proxyHandle:n,transcript:[...this.transcript]}),this.send(It(o))}async handleUpstreamEnd(t){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Tt(t.timeLeftMs)),this.ws.close(W,le(`upstream session ended: ${t.reason}`))}async runTurn(){let t=this.config;if(!t||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let o=await this.clients.createResponse({model:t.model,input:[...this.transcript],stream:!0,tools:t.tools,temperature:t.temperature,max_output_tokens:t.maxOutputTokens}),r,s=!1;for await(let c of o){if(n.interrupted)break;let u=c;if(u.type==="error")throw new d(`upstream error: ${JSON.stringify(u)}`,W);if(u.type==="response.completed"){r=u.response,s=!0;continue}let l=Nt(u);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new d("upstream produced no response.completed event",W);let{messages:i,assistantItems:a}=Dt(r);this.transcript.push(...a);for(let c of i)this.send(c);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},io=(e,t)=>{let n=e.headers["x-goog-api-key"];if(typeof n=="string")return n;let o=e.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):t.searchParams.get("key")??void 0};function Bt(e,t){let n=new Vt.WebSocketServer({noServer:!0}),o=new je;e.on("upgrade",(r,s,i)=>{let a=new URL(r.url??"/","http://localhost");if(a.pathname!==xt){s.write(`HTTP/1.1 404 Not Found\r
|
|
4
4
|
Connection: close\r
|
|
5
5
|
\r
|
|
@@ -39,7 +39,7 @@ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:x}})}
|
|
|
39
39
|
|
|
40
40
|
`):l.write(`data: ${JSON.stringify({error:{message:x,type:"upstream_error"}})}
|
|
41
41
|
|
|
42
|
-
`)),l.end()})}}function Wt(e){let{clients:t,apiKey:n}=e,o=(0,qt.createServer)(Ao(e));return Bt(o,{clients:t,apiKey:n}),o}var Yt=te(require("os"),1),zt=te(require("path"),1),Xt=require("url"),Qt=require("util");var Kt="0.
|
|
42
|
+
`)),l.end()})}}function Wt(e){let{clients:t,apiKey:n}=e,o=(0,qt.createServer)(Ao(e));return Bt(o,{clients:t,apiKey:n}),o}var Yt=te(require("os"),1),zt=te(require("path"),1),Xt=require("url"),Qt=require("util");var Kt="0.4.0";var Zt=4141,Oo=Kt,Oe={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ze(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function en(e,t,n){let o={...e,...ze(t,n)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function tn(e,t,n){let o=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],r=n.indexOf("--"),s=r===-1?n:n.slice(0,r),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",c=s.includes("--skip-git-repo-check"),u=a&&!c?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...o,...i?[]:["-m",t],...u]}function nn(e,t){return t.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function on(e,t,n){let o=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(o){if(!n(o))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${o}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return o}let r=(0,Xt.fileURLToPath)(new URL("../pi-extension/standalone.cjs",t));if(!n(r))throw new Error(`pi extension entry not found at ${r} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return r}function rn(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function sn(e){if(e[0]!=="--port")return null;let t=rn(e[1]);return e.splice(0,2),t}function Xe(e){let t=e.indexOf("--port");if(t===-1)return Zt;let n=rn(e[t+1]);return e.splice(t,2),n}function an(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function Ke(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function me(e){let t=Io(Ke(e,"URUN_BASE_URL")),n=Ke(e,"URUN_ORG_ID"),o=Ke(e,"URUN_APP"),r=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),i=s?Ee(s,"URUN_API_URL"):gt,a=(e.URUN_JWT??"").trim();if(a)return{baseUrl:t,orgId:n,appId:o,fnName:r,apiUrl:i,auth:{lane:"jwt",jwt:a}};let c=(e.URUN_API_KEY??"").trim();if(c){let u=(e.URUN_GATEWAY_URL??"").trim(),l=u?Ee(u):void 0;return{baseUrl:t,orgId:n,appId:o,fnName:r,apiUrl:i,auth:{lane:"api-key",apiKey:c,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function Io(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function Ee(e,t="URUN_GATEWAY_URL"){let n=new URL(e),o=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!o)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Qe(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:Oo}}function To(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var Po=250;async function Ze(e,t=Po){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let o=(await n.json()).identity;if(o==null||typeof o!="object")return null;let{app:r,org:s,fn:i,base_url:a,proxy_version:c}=o;return typeof r!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof c!="string"?null:{app:r,org:s,fn:i,base_url:a,proxy_version:c}}catch{return null}}var un=2e3;async function Co(e,t=un){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function cn(e,t,n=Zt,o=un){if(e!=null)return{mode:"spawn",port:e};let r=await Ze(n);if(r!==null&&To(r,t)){let s=await Co(n,o);return s===null?{mode:"reuse",port:n,identity:r}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function ln(e,t=Yt.default.homedir()){return zt.default.join(t,".urun","logs",`compat-proxy-${e}.log`)}var Ye=["log","info","warn","error","debug","trace"];function dn(e,t=process,n=console){let o=t.stdout.write,r=t.stderr.write,s=(a,...c)=>e.write(a,...c);t.stdout.write=s,t.stderr.write=s;let i=Object.fromEntries(Ye.map(a=>[a,n[a]]));for(let a of Ye)n[a]=(...c)=>{e.write(`${(0,Qt.format)(...c)}
|
|
43
43
|
`)};return()=>{t.stdout.write=o,t.stderr.write=r;for(let a of Ye)n[a]=i[a]}}var Uo=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function pn(e){let t=e?.code;return typeof t=="string"&&Uo.has(t)}function Ie(e,t){try{return e.write(t),!0}catch(n){if(pn(n))return!1;throw n}}function fn(e){let t={stdout:!1,stderr:!1},n=[];for(let o of["stdout","stderr"]){let r=e.streams[o],s=i=>{pn(i)&&(t[o]=!0);let a=i?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${o} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
44
44
|
`)}catch{}};r.on("error",s),n.push([r,s])}return{isDead:o=>t[o],uninstall:()=>{for(let[o,r]of n)o.off("error",r)}}}function mn(e){let t=n=>{let o=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${o}
|
|
45
45
|
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
package/dist/proxy/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as k,b as $,c as h,d as C,e as U,f as N,g as O,h as L,i as G,j as E,k as I,l as y,n as _,o as P,p as W,q as j,r as B,s as D,t as v,u as K,v as M,w as F}from"../chunk-
|
|
2
|
+
import{a as k,b as $,c as h,d as C,e as U,f as N,g as O,h as L,i as G,j as E,k as I,l as y,n as _,o as P,p as W,q as j,r as B,s as D,t as v,u as K,v as M,w as F}from"../chunk-AIKXXK57.js";import"../chunk-F2TEK34X.js";import{b as T}from"../chunk-M6ICU4F5.js";import"../chunk-G3NMGP4N.js";import"../chunk-XHIIEA6Z.js";import"../chunk-5NXM4IO3.js";import{g as R}from"../chunk-CWJRDBDC.js";import"../chunk-UVAY7Q7Z.js";import{c as g}from"../chunk-YSFSRI3D.js";g();import{spawn as V}from"child_process";import{appendFileSync as Y,createWriteStream as re,existsSync as ne,mkdirSync as oe}from"fs";import ae from"path";import t from"process";g();import{ensureNodeWebRTC as Z,nodeWebRTCUnavailableReason as ee}from"@urun-sh/core/internal";var te={ensureWebRTC:Z,webrtcUnavailableReason:ee,audioBackend:R};async function J(e=te){try{await e.ensureWebRTC()}catch(r){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(r)}`}}let i=e.webrtcUnavailableReason();if(i)return{ok:!1,reason:`${i} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await e.audioBackend()).createSource()}catch(r){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(r)}`}}return{ok:!0,reason:null}}function ie(e,i){let r=(e.URUN_CATALOG_URL??"").trim(),l=r?_(r,"URUN_CATALOG_URL"):"",n=(e.URUN_CATALOG_ANON_KEY??"").trim();return!l||!n?(i(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
|
|
3
3
|
`),null):{catalogUrl:l,anonKey:n}}function se(e){return k({baseUrl:e.baseUrl,orgId:e.orgId,defaultApp:e.appId,fnName:e.fnName,apiUrl:e.apiUrl,auth:e.auth,catalog:ie(t.env,i=>t.stderr.write(i))})}async function le(e,i,r){let l=V(e,i,{stdio:"inherit",env:r});return new Promise(n=>{l.once("exit",o=>n(o??1)),l.once("error",o=>{t.stderr.write(`failed to launch ${e}: ${String(o)}
|
|
4
4
|
`),n(127)})})}function ue(){return L(t.env,import.meta.url,ne)}function q(e){for(let[i,r]of Object.entries(C(e)))t.stdout.write(`export ${i}=${r}
|
|
5
5
|
`)}async function H(e,i){let r=y(t.env),l=i?P(r):void 0,n=se(r),o=T({clients:$(n),identity:l});try{await new Promise((s,d)=>{o.once("error",d),o.listen(e,"127.0.0.1",s)})}catch(s){throw await n.closeAll().catch(()=>{}),s.code==="EADDRINUSE"?new Error(F(e,await W(e))):s}let u=o.address().port;return i&&(t.stdout.write(`urun openai proxy listening on http://127.0.0.1:${u}/v1
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
|
-
"@urun-sh/core": "^0.
|
|
73
|
+
"@urun-sh/core": "^0.4.0"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"openai": "4.104.0",
|
package/dist/chunk-FVEXRGKL.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{a as b}from"./chunk-F2TEK34X.js";import{a as v}from"./chunk-G3NMGP4N.js";import{a as P,c as h,d as U,e as _}from"./chunk-XHIIEA6Z.js";import{c as x,f as S,g as E,p as R}from"./chunk-CWJRDBDC.js";import{c as l}from"./chunk-YSFSRI3D.js";l();import{App as I,createClientToken as H}from"@urun-sh/core";l();function j(e){let n=e?.type;return n==="response.created"||n==="response.in_progress"}function D(e){let n=e?.type;return n==="response.completed"||n==="error"}function k(e){return async function(t){return(async function*(){for(let a=1;a<=2;a++){let{app:s,entry:o}=await e.sessionFor(t.model),i=!1,u=!1;try{let c=await e.createStream(o,t);for await(let d of c){if(D(d)&&(i=!0),j(d)){if(a>1)continue}else u=!0;yield d}}catch(c){if(a<2&&!u){await e.evict(s,o);continue}throw c}if(i)return;if(a<2&&!u){await e.evict(s,o);continue}return}})()}}l();var M=3,F="llm",W=new Set(["ended","expired","error"]);function A(e,n){let t=e.doc(F),r=typeof t.onConnectionState=="function",a=typeof e.onPhase=="function";if(!r&&!a)throw new Error(`session for app "${n}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,o=new Set,i=[],u=c=>{if(!s){s=c;for(let d of[...o])d(c);o.clear()}};return r&&i.push(t.onConnectionState(c=>{c.consecutiveFailures<M||u(new h(`the pooled session for app "${n}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),a&&i.push(e.onPhase(c=>{W.has(c.name)&&u(new h(`the pooled session for app "${n}" is gone: it reached terminal phase "${c.name}". The entry is evicted; retry to get a fresh session.`))})),{gone:()=>s,onGone(c){return s?(c(s),()=>{}):(o.add(c),()=>o.delete(c))},dispose(){o.clear();for(let c of i.splice(0))c()}}}async function*g(e,n){let t=n.gone();if(t)throw t;let r=e[Symbol.asyncIterator](),a,s=new Promise((o,i)=>{a=n.onGone(u=>i(u))});s.catch(()=>{});try{for(;;){let o=await Promise.race([r.next(),s]);if(o.done)return;yield o.value}}finally{a?.(),r.return?.(void 0)}}function O(e,n,t){let r=e[t];if(typeof r!="function")throw new Error(`app "${n}" has no function "${t}" (set URUN_FUNCTION)`);let a=r();if(typeof a.end!="function")throw new Error(`app "${n}" function "${t}" returned a session without end()`);return a}function B(e,n){let{baseUrl:t,orgId:r,fnName:a,auth:s,subject:o}=e,i=p=>({session:p,responses:new v(p),gone:A(p,n)});if(s.lane==="jwt"){let p=I(n,{baseUrl:t,orgId:r,jwt:s.jwt});return i(O(p,n,a))}let{apiKey:u,gatewayUrl:c}=s,d=I(n,{baseUrl:t,orgId:r,getAccessToken:async()=>(await H(u,{baseUrl:c,expiresIn:300,allowedFunctions:[`${n}/${a}`],...o===void 0?{}:{subject:o}})).token});return i(O(d,n,a))}function K(e){let n=e.session.id;if(typeof n!="string"||n.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return n}var q=new Set(["error","ended","expired"]);function xe(e){let{auth:n,catalog:t}=e,r=null,a=o=>{let i=B(e,o);return i.gone.onGone(()=>{r?.evict(o,i)}),i},s=new _({defaultApp:e.defaultApp,fnName:e.fnName,openSession:a,closeSession:async o=>{o.gone.dispose(),await o.session.end()},listApps:n.lane==="api-key"?()=>U({apiUrl:e.apiUrl,apiKey:n.apiKey}):null,listCatalog:t?()=>b(t):null,sessionKey:K});return r=s,e.defaultApp!==null&&s.seed(e.defaultApp,a(e.defaultApp)),s}function Se(e,n=E){let t=new WeakMap,r=new WeakMap,a=new WeakMap;return{createResponse:k({sessionFor:s=>e.sessionFor(s),evict:(s,o)=>e.evict(s,o),createStream:async(s,o)=>g(await s.responses.responses.create(o),s.gone)}),listModels:()=>e.modelList(),openAudio:async s=>{let{entry:o}=await e.sessionFor(s),i=t.get(o);return i||(i=(async()=>x(o.session,await n()))(),t.set(o,i),i.catch(()=>t.delete(o))),i},openVideo:async s=>{let{entry:o}=await e.sessionFor(s),i=r.get(o);return i||(i=S(o.session),r.set(o,i)),i},openVideoOut:async s=>{let{entry:o}=await e.sessionFor(s),i=a.get(o);return i||(i=R(o.session),a.set(o,i)),i},sessionHandle:async s=>(await e.handleFor(s)).handle,createResponseOn:async(s,o)=>{let{entry:i}=await e.sessionForHandle(s);return g(await i.responses.responses.create(o),i.gone)},onSessionEnd:async(s,o)=>{let{entry:i}=await e.sessionForHandle(s),u=i.session;if(typeof u.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let c=!1;return u.onPhase(d=>{if(c||!q.has(d.name))return;c=!0;let p=u.endsAt??null;o({timeLeftMs:p?Math.max(0,p.getTime()-Date.now()):null,reason:d.name==="expired"?"session reached its maximum length":`session ${d.name}`})})}}}l();import V from"os";import J from"path";import{fileURLToPath as X}from"url";import{format as z}from"util";var N="0.3.6";var T=4141,Q=N,Ie={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function Z(e,n="openai"){if(n==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Oe(e,n,t){let r={...e,...Z(n,t)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Ne(e,n,t){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],a=t.indexOf("--"),s=a===-1?t:t.slice(0,a),o=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=t[0]==="exec",u=s.includes("--skip-git-repo-check"),c=i&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...r,...o?[]:["-m",n],...c]}function $e(e,n){return n.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?n:["--provider","urun","--model",e,...n]}function Te(e,n,t){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!t(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let a=X(new URL("../pi-extension/standalone.cjs",n));if(!t(a))throw new Error(`pi extension entry not found at ${a} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return a}function C(e){let n=Number(e);if(!Number.isInteger(n)||n<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return n}function Ce(e){if(e[0]!=="--port")return null;let n=C(e[1]);return e.splice(0,2),n}function Ge(e){let n=e.indexOf("--port");if(n===-1)return T;let t=C(e[n+1]);return e.splice(n,2),t}function Le(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function y(e,n){let t=(e[n]??"").trim();if(!t)throw new Error(`${n} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return t}function je(e){let n=ee(y(e,"URUN_BASE_URL")),t=y(e,"URUN_ORG_ID"),r=y(e,"URUN_APP"),a=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),o=s?$(s,"URUN_API_URL"):P,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:n,orgId:t,appId:r,fnName:a,apiUrl:o,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let c=(e.URUN_GATEWAY_URL??"").trim(),d=c?$(c):void 0;return{baseUrl:n,orgId:t,appId:r,fnName:a,apiUrl:o,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function ee(e,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${n} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function $(e,n="URUN_GATEWAY_URL"){let t=new URL(e),r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!r)throw new Error(`${n} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function De(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:Q}}function ne(e,n){return e.app===n.app&&e.org===n.org&&e.fn===n.fn&&e.base_url===n.base_url&&e.proxy_version===n.proxy_version}var te=250;async function oe(e,n=te){try{let t=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(n)});if(!t.ok)return null;let r=(await t.json()).identity;if(r==null||typeof r!="object")return null;let{app:a,org:s,fn:o,base_url:i,proxy_version:u}=r;return typeof a!="string"||typeof s!="string"||typeof o!="string"||typeof i!="string"||typeof u!="string"?null:{app:a,org:s,fn:o,base_url:i,proxy_version:u}}catch{return null}}var G=2e3;async function re(e,n=G){try{let t=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(n)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function Me(e,n,t=T,r=G){if(e!=null)return{mode:"spawn",port:e};let a=await oe(t);if(a!==null&&ne(a,n)){let s=await re(t,r);return s===null?{mode:"reuse",port:t,identity:a}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function Fe(e,n=V.homedir()){return J.join(n,".urun","logs",`compat-proxy-${e}.log`)}var w=["log","info","warn","error","debug","trace"];function We(e,n=process,t=console){let r=n.stdout.write,a=n.stderr.write,s=(i,...u)=>e.write(i,...u);n.stdout.write=s,n.stderr.write=s;let o=Object.fromEntries(w.map(i=>[i,t[i]]));for(let i of w)t[i]=(...u)=>{e.write(`${z(...u)}
|
|
2
|
-
`)};return()=>{n.stdout.write=r,n.stderr.write=a;for(let i of w)t[i]=o[i]}}var se=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function L(e){let n=e?.code;return typeof n=="string"&&se.has(n)}function He(e,n){try{return e.write(n),!0}catch(t){if(L(t))return!1;throw t}}function Be(e){let n={stdout:!1,stderr:!1},t=[];for(let r of["stdout","stderr"]){let a=e.streams[r],s=o=>{L(o)&&(n[r]=!0);let i=o?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(o instanceof Error?o.message:o))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
3
|
-
`)}catch{}};a.on("error",s),t.push([a,s])}return{isDead:r=>n[r],uninstall:()=>{for(let[r,a]of t)r.off("error",a)}}}function Ke(e){let n=t=>{let r=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
4
|
-
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
|
5
|
-
`)}catch(a){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(a?.code??a)}) \u2014 the terminal is gone
|
|
6
|
-
`)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",n),e.proc.on("unhandledRejection",n),()=>{e.proc.off("uncaughtException",n),e.proc.off("unhandledRejection",n)}}function qe(e,n){let t="pass --port 0 for an OS-assigned ephemeral port";return n?`port ${e} is held by another urun-openai proxy serving app ${n.app} (org ${n.org}, fn ${n.fn}, version ${n.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${t}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${t}`}export{xe as a,Se as b,Ie as c,Z as d,Oe as e,Ne as f,$e as g,Te as h,Ce as i,Ge as j,Le as k,je as l,ee as m,$ as n,De as o,oe as p,Me as q,Fe as r,We as s,He as t,Be as u,Ke as v,qe as w};
|