@urun-sh/openai 0.5.3 → 0.5.5
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-5BZCM3RS.js +4 -0
- package/dist/chunk-DMD5UENK.js +1 -0
- package/dist/{chunk-G3NMGP4N.js → chunk-GBBY3PCZ.js} +1 -1
- package/dist/chunk-I2Q3B3OG.js +6 -0
- package/dist/chunk-K23AZPI4.js +1 -0
- package/dist/chunk-OI2OY32M.js +1 -0
- package/dist/chunk-QVF7NF7G.js +44 -0
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +6 -0
- package/dist/gemini-live.d.ts +6 -0
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +36 -22
- package/dist/hosted/bin.js +4 -4
- package/dist/hosted/index.cjs +32 -18
- package/dist/hosted/index.d.cts +140 -198
- package/dist/hosted/index.d.ts +63 -82
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -18
- package/dist/index.d.ts +2 -18
- package/dist/index.js +1 -1
- package/dist/models-NYMZrklp.d.cts +38 -0
- package/dist/models-NYMZrklp.d.ts +38 -0
- package/dist/pi-extension/index.cjs +6 -6
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +49 -49
- package/dist/proxy/cli.cjs +41 -37
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +30 -21
- package/dist/proxy/index.d.cts +468 -2
- package/dist/proxy/index.d.ts +173 -2
- package/dist/proxy/index.js +6 -1
- package/dist/responses-turn-KOAoIqZ-.d.ts +200 -0
- package/dist/responses-turn-OrO4euEN.d.cts +513 -0
- package/package.json +3 -3
- package/dist/chunk-F2TEK34X.js +0 -1
- package/dist/chunk-FVD4NMXJ.js +0 -1
- package/dist/chunk-M6ICU4F5.js +0 -40
- package/dist/chunk-ODHCPZHI.js +0 -6
- package/dist/chunk-UVAY7Q7Z.js +0 -1
- package/dist/chunk-XHIIEA6Z.js +0 -1
- package/dist/server-BfME37pQ.d.cts +0 -200
- package/dist/server-l1himPxc.d.ts +0 -82
package/dist/proxy/cli.cjs
CHANGED
|
@@ -1,60 +1,64 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var bn=Object.create;var nt=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var An=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var On=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Rn(t))!En.call(e,r)&&r!==n&&nt(e,r,{get:()=>t[r],enumerable:!(o=Sn(t,r))||o.enumerable});return e};var te=(e,t,n)=>(n=e!=null?bn(An(e)):{},On(t||!e||!e.__esModule?nt(n,"default",{value:e,enumerable:!0}):n,e));var In=()=>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=In();var et=require("child_process"),Y=require("fs"),kn=te(require("path"),1),_=te(require("process"),1);var le=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 Tn="llm-resp";async function*Ce(e,t){let n=`${Tn}:${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 Pn="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(Pn).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 Cn(){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=Cn(),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 Un(e,n);return await o.startInbound(s),o}function Un(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 $n=24e3,ce=480,Ln=111;async function Nn(){let e=await import("opusscript"),t=e.default??e;return new t($n,1,2048)}async function we(){let e=await import("werift"),t=await Nn();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>=ce;){let l=c.subarray(u,u+ce);u+=ce;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),g=t.encode(p,ce);r=r+1&65535,s=s+ce>>>0;let h=new e.RtpHeader({version:2,payloadType:Ln,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 Mn="h264";function Dn(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 jn(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;Dn(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=jn(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:Mn,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 Vn(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Bn(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(Bn(l)&&(a=!0),Vn(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 Fn(e,t){return Ne+Buffer.from(JSON.stringify([e,t]),"utf8").toString("base64url")}function Gn(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 Hn=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??Hn;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:Fn(n,this.keyOf(o))}}async sessionForHandle(t){let n=Gn(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 qn=3,Jn="llm",Wn=new Set(["paused","error"]);function yt(e,t){let n=e.doc(Jn),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<qn||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=>{Wn.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 Kn(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,le.App)(t,{baseUrl:n,orgId:o,jwt:s.jwt});return a(wt(p,t,r))}let{apiKey:c,gatewayUrl:u}=s,l=(0,le.App)(t,{baseUrl:n,orgId:o,getAccessToken:async()=>(await(0,le.createClientToken)(c,{baseUrl:u,expiresIn:300,allowedFunctions:[`${t}/${r}`],...i===void 0?{}:{subject:i}})).token});return a(wt(l,t,r))}function Yn(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 zn=new Set(["error","paused"]);function _t(e){let{auth:t,catalog:n}=e,o=null,r=i=>{let a=Kn(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:Yn});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||!zn.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",Qn=1007,bt=1008,W=1011,De=1008,d=class extends Error{constructor(n,o=Qn){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
|
-
`)}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 eo={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},to=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",X],kt=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function no(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 oo=["temperature","maxOutputTokens","responseModalities"];function Ot(e){for(let[p,g]of Object.entries(eo))if(e[p]!==void 0)throw new d(g);for(let p of Object.keys(e))if(!to.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(!oo.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:no(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,ro=`audio/pcm;rate=${Ct}`,Ut=Buffer.alloc(960).toString("base64");function so(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 io(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 ao(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=so(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:ao(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:io(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:ro,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 uo=256,je=class{snapshots=new Map;store(t,n){for(this.snapshots.set(t,n);this.snapshots.size>uo;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(t){return this.snapshots.get(t)}},de=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,de(t.message));return}if(t instanceof V){this.ws.close(De,de(t.message));return}if(t instanceof d){this.ws.close(t.closeCode,de(t.message));return}this.ws.close(W,de(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,de(`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}}},co=(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
|
|
2
|
+
"use strict";var qn=Object.create;var mt=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var Jn=Object.getOwnPropertyNames;var Kn=Object.getPrototypeOf,zn=Object.prototype.hasOwnProperty;var Yn=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jn(e))!zn.call(n,r)&&r!==t&&mt(n,r,{get:()=>e[r],enumerable:!(o=Wn(e,r))||o.enumerable});return n};var le=(n,e,t)=>(t=n!=null?qn(Kn(n)):{},Yn(e||!n||!n.__esModule?mt(t,"default",{value:n,enumerable:!0}):t,n));var Xn=()=>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,E=Xn();var pt=require("child_process"),X=require("fs"),Gn=le(require("path"),1),_=le(require("process"),1);var _e=require("@urun-sh/core");async function gt(n){let t=await(n.fetchImpl??fetch)(`${n.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`}});if(!t.ok)throw new Error(`model_catalog fetch failed: ${t.status}`);return await t.json()}function ht(n,e,t,o){let r=n.response??{},s={request_id:t,consumer_id:o,stream:!0,kind:"chat",messages:e};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 yt(n,e,t){let o={request_id:e,consumer_id:t,stream:!!n.stream,kind:"responses",input:n.input};return n.model&&(o.model=n.model),n.tools!==void 0&&(o.tools=n.tools),n.tool_choice!==void 0&&(o.tool_choice=n.tool_choice),typeof n.temperature=="number"&&(o.temperature=n.temperature),typeof n.max_output_tokens=="number"&&(o.max_output_tokens=n.max_output_tokens),typeof n.top_p=="number"&&(o.top_p=n.top_p),Array.isArray(n.stop)&&n.stop.length>0&&(o.stop=n.stop),typeof n.reasoning_effort=="string"&&(o.reasoning_effort=n.reasoning_effort),n.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=n.chat_template_kwargs),o}function wt(n){if(n instanceof Error)return{type:"error",error:{type:"urun_error",code:n.name||null,message:n.message}};if(n&&typeof n=="object"&&n.t==="error"){let e=n,t=e.body??{};return{type:"error",error:{type:"urun_error",code:e.code??null,message:t.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(n)}}}var Qn="llm-resp";async function*Ge(n,e){let t=`${Qn}:${e}`,o=`resp_${e}`;yield{type:"response.created",response:{id:o,status:"in_progress"}};let r=new Map;for await(let s of n.stream(t).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 u=typeof a.index=="number"?a.index:0,c=r.get(u)??{};a.id&&(c.id=a.id),a.function?.name&&(c.name=a.function.name),r.set(u,c),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:c.id,name:c.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 wt(i);return}}}var Zn="llm",Re=class{constructor(e){this.session=e;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(e){e.session_tag=this.sessionTag,this.session.doc(Zn).set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,t){let o=yt(e,t,this.consumerId);return this.write(o),Ge(this.session,t)}sendResponseCreate(e,t,o){let r=ht(e,t,o,this.consumerId);return this.write(r),Ge(this.session,o)}};var _t=0;function eo(){return _t+=1,`req_${Date.now().toString(36)}_${_t.toString(36)}`}var Ee=class{transport;constructor(e){this.transport=new Re(e)}responses={create:async e=>{let t=eo(),o=this.transport.sendResponses(e,t);return Object.assign((async function*(){yield*o})(),{requestId:t})}}};var He=class{constructor(e,t){this.backend=e;this.opts=t}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let t=Buffer.from(e,"base64"),o=Math.floor(t.byteLength/2),r=new Int16Array(o);for(let s=0;s<o;s++)r[s]=t.readInt16LE(s*2);this.source.onData(r)}async startInbound(e){if(e==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(e),this.sink.onframe=t=>{let o=Buffer.from(t.samples.buffer,t.samples.byteOffset,t.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function xt(n,e,t=1e4){let o=new He(e,{sampleRate:24e3}),r=await o.startOutbound();await n.stream("rt-audio-in").attach(r);let s=await to(n,t);return await o.startInbound(s),o}function to(n,e){let t=n.stream("rt-audio-out");return t.track!=null?Promise.resolve(t.track):new Promise((o,r)=>{let s,i=setTimeout(()=>{s?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(i),s?.(),o(u))};s=t.on?.("track",a),t.track!=null&&a(t.track)})}var vt="rt-video-in",kt=256e3;function bt(n){let e=n.stream(vt),t=e.emit;if(typeof t!="function")throw new Error(`enableSessionVideo: session.stream('${vt}') 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>kt)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${kt}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await t.call(e,o)}}}var no=24e3,we=480,oo=111;async function ro(){let n=await import("opusscript"),e=n.default??n;return new e(no,1,2048)}async function Ae(){let n=await import("werift"),e=await ro();return{createSource:()=>{let t=new n.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:t,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let c=0;for(;u.length-c>=we;){let l=u.subarray(c,c+we);c+=we;let d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),p=e.encode(d,we);r=r+1&65535,s=s+we>>>0;let m=new n.RtpHeader({version:2,payloadType:oo,sequenceNumber:r,timestamp:s,ssrc:o,marker:!1}),y=new n.RtpPacket(m,p);t.writeRtp(y)}i=u.slice(c)}}},createSink:t=>{let o={onframe:null};return t.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);o.onframe?.({samples:a})}),o}}}var Oe=require("@urun-sh/core"),qe="rt-video-out";var so="h264";function io(n,e){if(!Number.isInteger(n.seq)||n.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${n.seq})`);if(!Number.isInteger(n.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${n.ptsUs})`);if(typeof n.codec!="string"||n.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof n.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function ao(n){if(n.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${n.byteLength} byte(s), no header length)`);let e=n[0]|n[1]<<8;if(n.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${n.byteLength-2} present)`);let t;try{t=JSON.parse(new TextDecoder().decode(n.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let o=t;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;io(r,"decodeVideoOutRecord");let s=n.subarray(2+e);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 St="urun.videoOut.v2-ws";function Rt(n){let e=n.stream(qe);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${qe}') 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 t=new Set,o=new Set,r=new Set,s=u=>{for(let c of o)c(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${qe}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let c;try{c=ao(u)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of t)l(c)}for(let u of r)u()};return{codec:so,onOutputFrame:u=>(t.add(u),i||(i=!0,a().catch(c=>s(c instanceof Error?c:new Error(String(c))))),()=>t.delete(u)),onLaneError:u=>(o.add(u),()=>o.delete(u)),onEnd:u=>(r.add(u),()=>r.delete(u))}}function uo(n){let e=n?.type;return e==="response.created"||e==="response.in_progress"}function co(n){let e=n?.type;return e==="response.completed"||e==="error"}function Et(n){return async function(t){return(async function*(){for(let r=1;r<=2;r++){let{app:s,entry:i}=await n.sessionFor(t.model),a=!1,u=!1;try{let c=await n.createStream(i,t);for await(let l of c){if(co(l)&&(a=!0),uo(l)){if(r>1)continue}else u=!0;yield l}}catch(c){if(r<2&&!u){await n.evict(s,i);continue}throw c}if(a)return;if(r<2&&!u){await n.evict(s,i);continue}return}})()}}function z(n){return n.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var lo={chat:!0,code:!0,agent:!0,vl:!0},At={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function po(n){let e=n.toLowerCase();return Object.hasOwn(At,e)?At[e]:null}function We(n){let e=n.engine_args?.context_length;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function It(n,e){let t=e.filter(s=>z(`${s.model_id}-${s.variant}`)===n);if(t.length===1)return t[0];if(t.length>1)return Ot(t);let o=e.filter(s=>z(s.model_id)===n),r=new Set(o.map(s=>s.variant));return o.length>0&&r.size===1?Ot(o):null}function Ot(n){let e=n[0],t=i=>n.every(a=>(a[i]??void 0)===(e[i]??void 0))?e[i]:void 0,o=n.map(We),r=o[0],s=r!=null&&o.every(i=>i===r)?r:null;return{model_id:e.model_id,variant:e.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),engine_args:s!==null?{context_length:s}:{},updated_at:t("updated_at")}}function Pt(n){let e=n.updated_at?Date.parse(n.updated_at):NaN;return Number.isFinite(e)?Math.floor(e/1e3):0}function Tt(n,e){let t=It(n,e);if(!t)return{id:n,object:"model",created:0,owned_by:"urun"};let o=We(t);return{id:n,object:"model",created:Pt(t),owned_by:"urun",name:`${t.model_id}:${t.variant}`,...t.description?{description:t.description}:{},...t.task?{task:t.task}:{},...t.engine?{engine:t.engine}:{},...t.gpu_spec?{gpu_spec:t.gpu_spec}:{},...o!==null?{context_length:o}:{}}}function Ct(n,e){let t=[];for(let o of n){let r=It(o,e);if(!r||!r.task||lo[r.task]!==!0)continue;let s=We(r),i={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};s!==null&&(i.max_tokens={type:"integer",min:1,max:s,unit:"token"}),t.push({schema_version:"2.4",id:o,name:`${r.model_id}:${r.variant}`,created:Pt(r),quantization:po(r.variant),description:r.description??"",hugging_face_id:r.hf_repo?r.hf_repo.split("@")[0]??r.hf_repo:"",input_modalities:[{type:"text",...s!==null?{supported_inputs:{max_context_length:{value:s,unit:"token"}}}:{}},...r.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:i}]})}return{data:t}}var $t="https://api.urun.sh/v1",C=class extends Error{},N=class extends Error{},Je="urs1.";function fo(n,e){return Je+Buffer.from(JSON.stringify([n,e]),"utf8").toString("base64url")}function mo(n){if(!n.startsWith(Je))return null;try{let e=JSON.parse(Buffer.from(n.slice(Je.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function Lt(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/apps`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}function go(n,e){let t=e.filter(s=>z(`${s.model_id}-${s.variant}`)===n);if(t.length>0)return t;let o=e.filter(s=>z(s.model_id)===n);return new Set(o.map(s=>s.variant)).size===1?o:[]}function ho(n){let e=n.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function yo(n){let e=n.map(ho),t=e[0];return t!=null&&e.every(o=>o===t)?t:null}var Ut=6e4,Ie=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,t){this.pool.set(e,Promise.resolve(t))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Ut;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let t=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:t},t}async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Ut;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let t=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:t},t}servable(e){return e.filter(t=>t.function_name===this.opts.fnName&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=this.opts.defaultApp,t=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())t.add(r);let o=[...t].filter(r=>r!==e).sort();return e===null?o:[e,...o]}async noDefaultApp(e){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new C(e===""?`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 "${e}" 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(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):o;let r=z(t);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(c=>c.startsWith(`${r}-`));if(a.length===1)return a[0];if(a.length>1)throw new C(`model "${t}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=s.find(c=>c.app_slug===r||c.app_slug.startsWith(`${r}-`));if(u)throw new C(`model "${t}" maps to app "${u.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>t===a.model_id||t===`${a.model_id}:${a.variant}`||r===z(a.model_id)||r===z(`${a.model_id}-${a.variant}`));if(i)throw new C(`model "${t}" 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(t):o}async sessionFor(e){let t=await this.resolveApp(e),o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(t)),this.pool.set(t,o),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(e);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(e){let{app:t,entry:o}=await this.sessionFor(e);return{app:t,handle:fo(t,this.keyOf(o))}}async sessionForHandle(e){let t=mo(e);if(!t)throw new N(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,s=this.pool.get(o),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new N(`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 N(`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(e,t){let o=this.pool.get(e);!o||await o.then(s=>s,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=await this.availableIds(),t=await this.catalogRows().catch(()=>[]);return{object:"list",data:e.map(o=>Tt(o,t))}}async openRouterModels(){let e=await this.availableIds(),t=await this.catalogRows();return Ct(e,t)}async supportsImages(e,t){let o=await this.resolveApp(e),r=await this.catalogRows(),s=go(o,r);return s.length===0||!s.every(i=>(i.task??void 0)==="image")?!1:yo(s)===t}async closeAll(){let e=[...this.pool.values()];this.pool.clear();let t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};var wo=3,_o="llm",vo=new Set(["paused","error"]);function Nt(n,e){let t=n.doc(_o),o=typeof t.onConnectionState=="function",r=typeof n.onPhase=="function";if(!o&&!r)throw new Error(`session for app "${e}" 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=[],u=c=>{if(!s){s=c;for(let l of[...i])l(c);i.clear()}};return o&&a.push(t.onConnectionState(c=>{c.consecutiveFailures<wo||u(new N(`the pooled session for app "${e}" 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.`))})),r&&a.push(n.onPhase(c=>{vo.has(c.name)&&u(new N(`the pooled session for app "${e}" lost its compute binding (phase "${c.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(c){return s?(c(s),()=>{}):(i.add(c),()=>i.delete(c))},dispose(){i.clear();for(let c of a.splice(0))c()}}}async function*Ke(n,e){let t=e.gone();if(t)throw t;let o=n[Symbol.asyncIterator](),r,s=new Promise((i,a)=>{r=e.onGone(u=>a(u))});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 Mt(n,e,t,o){let r=n[t];if(typeof r!="function")throw new Error(`app "${e}" has no function "${t}" (set URUN_FUNCTION)`);let s=o?r(void 0,o):r();if(typeof s.end!="function")throw new Error(`app "${e}" function "${t}" returned a session without end()`);return s}function ko(n,e){let{baseUrl:t,orgId:o,fnName:r,auth:s,subject:i}=n,a=n.sessionStartOptions?.(e),u=p=>({session:p,responses:new Ee(p),gone:Nt(p,e)});if(s.lane==="jwt"){let p=(0,_e.App)(e,{baseUrl:t,orgId:o,jwt:s.jwt});return u(Mt(p,e,r,a))}let{apiKey:c,gatewayUrl:l}=s,d=(0,_e.App)(e,{baseUrl:t,orgId:o,getAccessToken:async()=>(await(0,_e.createClientToken)(c,{baseUrl:l,expiresIn:300,allowedFunctions:[`${e}/${r}`],...i===void 0?{}:{subject:i}})).token});return u(Mt(d,e,r,a))}function xo(n){let e=n.session.id;if(typeof e!="string"||e.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 e}var bo=new Set(["error","paused"]);function Dt(n){let{auth:e,catalog:t}=n,o=null,r=i=>{let a=ko(n,i);return n.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&n.onSessionOpen(i,a.session.id),a.gone.onGone(()=>{o?.evict(i,a)}),a},s=new Ie({defaultApp:n.defaultApp,fnName:n.fnName,openSession:r,closeSession:async i=>{if(i.gone.dispose(),n.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Lt({apiUrl:n.apiUrl,apiKey:e.apiKey}):null,listCatalog:t?()=>gt(t):null,sessionKey:xo});return o=s,n.defaultApp!==null&&s.seed(n.defaultApp,r(n.defaultApp)),s}function jt(n,e=Ae){let t=new WeakMap,o=new WeakMap,r=new WeakMap;return{createResponse:Et({sessionFor:s=>n.sessionFor(s),evict:(s,i)=>n.evict(s,i),createStream:async(s,i)=>Ke(await s.responses.responses.create(i),s.gone)}),listModels:()=>n.modelList(),openRouterModels:()=>n.openRouterModels(),openAudio:async s=>{let{entry:i}=await n.sessionFor(s),a=t.get(i);return a||(a=(async()=>xt(i.session,await e()))(),t.set(i,a),a.catch(()=>t.delete(i))),a},openVideo:async s=>{let{entry:i}=await n.sessionFor(s),a=o.get(i);return a||(a=bt(i.session),o.set(i,a)),a},openVideoOut:async s=>{let{entry:i}=await n.sessionFor(s),a=r.get(i);return a||(a=Rt(i.session),r.set(i,a)),a},sessionHandle:async s=>(await n.handleFor(s)).handle,createResponseOn:async(s,i)=>{let{entry:a}=await n.sessionForHandle(s);return Ke(await a.responses.responses.create(i),a.gone)},onSessionEnd:async(s,i)=>{let{entry:a}=await n.sessionForHandle(s),u=a.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(l=>{if(c||!bo.has(l.name))return;c=!0;let d=u.endsAt??null;i({timeLeftMs:d?Math.max(0,d.getTime()-Date.now()):null,reason:l.reason??`session ${l.name}`})})}}}var mn=require("http");var rn=require("crypto"),sn=require("ws");var Bt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Ro=1007,Vt=1008,Y=1011,Ce=1008,f=class extends Error{constructor(t,o=Ro){super(t);this.closeCode=o}closeCode},A=n=>typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null,Pe=["setup","clientContent","realtimeInput","toolResponse"];function Gt(n){let e;try{e=JSON.parse(n)}catch{throw new f("client message is not valid JSON")}let t=A(e);if(!t)throw new f("client message must be a JSON object");let o=Pe.filter(a=>t[a]!==void 0),r=Object.keys(t).filter(a=>!Pe.includes(a));if(r.length>0)throw new f(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${Pe.join(", ")}`);if(o.length!==1)throw new f(`client message must contain exactly one of ${Pe.join(", ")} (got ${o.length})`);let s=o[0],i=A(t[s]);if(!i)throw new f(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ht(n,e){if(typeof n=="string")return n;let t=A(n),o=t?t.parts:void 0;if(!Array.isArray(o))throw new f(`${e}: expected a Content with a parts array`);let r=[];for(let s of o){let i=A(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new f(`${e}: 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 f(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new f(`${e}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
|
|
3
|
+
`)}var Eo={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},oe="urun.videoOut";function qt(n){return{framing:St,codec:n}}function Wt(n){let{seq:e,ptsUs:t,codec:o,key:r}=n.header;return{[oe]:{v:1,seq:e,ptsUs:t,codec:o,key:r,data:Buffer.from(n.au).toString("base64")}}}var Ao={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Oo=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",oe],Ft=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Io(n){let e=A(n);if(!e)throw new f("setup.realtimeInputConfig must be an object");for(let r of Object.keys(e))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new f(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let t=A(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!t)throw new f("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(t??{}))if(r!=="disabled")throw new f(`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(t?.disabled!==!0)throw new f("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(e.activityHandling!==void 0){if(!Ft.includes(e.activityHandling))throw new f(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Ft.join(", ")}`);o=e.activityHandling}return{manualActivity:!0,activityHandling:o}}var Po=["temperature","maxOutputTokens","responseModalities"];function Jt(n){for(let[d,p]of Object.entries(Ao))if(n[d]!==void 0)throw new f(p);for(let d of Object.keys(n))if(!Oo.includes(d))throw new f(`unsupported setup field "${d}"`);if(typeof n.model!="string"||n.model.length===0)throw new f('setup.model is required (format "models/{model}")');let e=n.model.replace(/^models\//,""),t,o,r=!1,s=A(n.generationConfig);if(n.generationConfig!==void 0&&!s)throw new f("setup.generationConfig must be an object");if(s){for(let d of Object.keys(s))if(!Po.includes(d))throw new f(`unsupported generationConfig field "${d}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new f("generationConfig.temperature must be a number");t=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new f("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let d=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of d){let m=String(p).toUpperCase();if(m==="AUDIO"){r=!0;continue}if(m!=="TEXT")throw new f(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge rt-audio-out lane)`)}}}let i=[];n.systemInstruction!==void 0&&i.push({role:"system",content:Ht(n.systemInstruction,"setup.systemInstruction")});let a;if(n.tools!==void 0){if(!Array.isArray(n.tools))throw new f("setup.tools must be an array");a=[];for(let d of n.tools){let p=A(d);if(!p)throw new f("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new f(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new f("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let y=A(m);if(!y||typeof y.name!="string")throw new f("functionDeclarations entries require a string name");a.push({type:"function",name:y.name,description:y.description,parameters:y.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(n.sessionResumption!==void 0){let d=A(n.sessionResumption);if(!d)throw new f("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(d))if(p!=="handle")throw new f(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(d.handle!==void 0&&(typeof d.handle!="string"||d.handle.length===0))throw new f("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof d.handle=="string"?d.handle:null}}let c=n.realtimeInputConfig===void 0?Eo:Io(n.realtimeInputConfig),l=!1;if(n[oe]!==void 0){if(!A(n[oe]))throw new f(`setup["${oe}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:i,tools:a,temperature:t,maxOutputTokens:o,audioModality:r,activity:c,sessionResumption:u,videoOut:l}}function Kt(n){return{sessionResumptionUpdate:{newHandle:n,resumable:!0}}}function zt(n){let e=Math.max(0,n??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Yt(n){for(let o of Object.keys(n))if(o!=="turns"&&o!=="turnComplete")throw new f(`unsupported clientContent field "${o}"`);let e=n.turns===void 0?[]:n.turns;if(!Array.isArray(e))throw new f("clientContent.turns must be an array");let t=[];for(let o of e){let r=A(o);if(!r)throw new f("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 f(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);t.push({role:s==="model"?"assistant":"user",content:Ht(r,"clientContent.turns")})}return{items:t,turnComplete:n.turnComplete===!0}}var Te=16e3,Xt=24e3,To=`audio/pcm;rate=${Xt}`,Qt=Buffer.alloc(960).toString("base64");function Co(n,e,t){if(e===t)return n;let o=Math.floor(n.length*t/e),r=new Int16Array(o),s=e/t,i=n.length-1;for(let a=0;a<o;a++){let u=a*s,c=Math.floor(u);if(c>=i){r[a]=n[i];continue}let l=u-c;r[a]=Math.round(n[c]+(n[c+1]-n[c])*l)}return r}function Uo(n){let e=A(n);if(!e)throw new f("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new f(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new f("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(e.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new f("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function $o(n){let e=A(n);if(!e)throw new f("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new f(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(e.mimeType);if(t&&Number(t[1])!==Te)throw new f(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${Te} Hz (audio/pcm;rate=${Te})`);if(typeof e.data!="string"||e.data.length===0)throw new f("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(e.data,"base64");if(o.length===0||o.length%2!==0)throw new f(`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=Co(r,Te,Xt);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Zt(n){if(n.mediaChunks!==void 0)throw new f('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(n.activityStart!==void 0||n.activityEnd!==void 0){if(Object.keys(n).length!==1||n.activityStart!==void 0&&n.activityEnd!==void 0)throw new f("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=n.activityStart!==void 0?"activityStart":"activityEnd",s=A(n[r]);if(!s||Object.keys(s).length!==0)throw new f(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let e=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(n))if(!e.includes(o))throw new f(`unsupported realtimeInput field "${o}"`);let t=e.filter(o=>n[o]!==void 0);if(t.length!==1)throw new f(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${t.length})`);if(n.audio!==void 0)return{kind:"audio",base64Pcm24k:$o(n.audio)};if(n.video!==void 0)return{kind:"video",jpegFrame:Uo(n.video)};if(n.audioStreamEnd!==void 0){if(n.audioStreamEnd!==!0)throw new f("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof n.text!="string"||n.text.length===0)throw new f("realtimeInput.text must be a non-empty string");return{kind:"text",text:n.text}}function en(n){for(let e of Object.keys(n))if(e!=="functionResponses")throw new f(`unsupported toolResponse field "${e}"`);if(!Array.isArray(n.functionResponses)||n.functionResponses.length===0)throw new f("toolResponse.functionResponses must be a non-empty array");return n.functionResponses.map(e=>{let t=A(e);if(!t||typeof t.id!="string"||t.id.length===0)throw new f("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:t.id,output:JSON.stringify(t.response??null)}})}function tn(n){return n.type!=="response.output_text.delta"||typeof n.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:n.delta}]}}}}function nn(n){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:To,data:n}}]}}}}function on(n){let e=A(n)??{},t=Array.isArray(e.output)?e.output:[],o=[],r=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let c of t){let l=A(c);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let d of l.content){let p=A(d);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&r.push({role:"assistant",content:s});for(let c of t){let l=A(c);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new f(`upstream function_call item is missing call_id/name: ${JSON.stringify(c)}`,Y);let d=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",p;try{p=JSON.parse(d)}catch{throw new f(`upstream function_call arguments are not valid JSON: ${d}`,Y)}o.push({id:l.call_id,name:l.name,args:p}),r.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:d})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let a=A(e.usage),u={serverContent:{turnComplete:!0}};if(a){let c={};typeof a.input_tokens=="number"&&(c.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(c.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(c.totalTokenCount=a.total_tokens),Object.keys(c).length>0&&(u.usageMetadata=c)}return i.push(u),{messages:i,assistantItems:r}}var Lo=256,ze=class{snapshots=new Map;store(e,t,o){for(this.snapshots.set(`${e}\0${t}`,o);this.snapshots.size>Lo;){let r=this.snapshots.keys().next().value;this.snapshots.delete(r)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},No="local",ve=n=>n.slice(0,120),Ye=class{constructor(e,t,o){this.ws=e;this.call=t;this.registry=o;this.clients=t.clients,this.scope=t.scope,e.on("message",r=>this.onMessage(r)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof C){this.ws.close(Vt,ve(e.message));return}if(e instanceof N){this.ws.close(Ce,ve(e.message));return}if(e instanceof f){this.ws.close(e.closeCode,ve(e.message));return}this.ws.close(Y,ve(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Gt(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new f(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let o=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:s}=Yt(t.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=Zt(t.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:Qt);return}this.transcript.push(...en(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new f("setup may only be sent once, as the first client message");let t=Jt(e),o=t.sessionResumption.handle;if(o!==null){let s=this.registry.get(this.scope,o);if(!s)throw new f("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",Ce);if(s.model!==t.model)throw new f(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new f("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(o)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==s.proxyHandle)throw new f(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Ce);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...t.systemItems);this.config=t;let r={};if(t.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,t.model),a=i.onOutputFrame(c=>this.send(Wt(c))),u=i.onLaneError(c=>this.fail(c));this.detachVideoOut=()=>{a(),u()},r[oe]=qt(i.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new f("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new f("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",Y);return this.audio=(async()=>{let o=await t.call(this.clients,e.model);return this.detachAudio=o.onOutputAudio(r=>this.send(nn(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new f("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new f("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Y);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new f(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new f("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new f("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let o=(0,rn.randomUUID)();this.registry.store(this.scope,o,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(o),this.send(Kt(o))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(zt(e.timeLeftMs)),this.ws.close(Y,ve(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let o=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),r,s=!1;for await(let u of o){if(t.interrupted)break;let c=u;if(c.type==="error")throw new f(`upstream error: ${JSON.stringify(c)}`,Y);if(c.type==="response.completed"){r=c.response,s=!0;continue}let l=tn(c);l&&this.send(l)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new f("upstream produced no response.completed event",Y);let{messages:i,assistantItems:a}=on(r);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},re=class extends Error{constructor(t,o){super(o);this.status=t;this.name="UpgradeAuthError"}status};function Mo(n,e,t){let o=new Set;(u=>{if(typeof u=="string")u!==""&&o.add(u);else if(Array.isArray(u))for(let c of u)c!==""&&o.add(c)})(n.headers["x-goog-api-key"]);let s=n.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&o.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&o.add(i),o.size>1)throw new re(401,`contradictory credentials: ${o.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&i!==void 0&&i!=="")throw new re(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of o)a=u;if(a===void 0&&t)throw new re(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function an(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let o=new sn.WebSocketServer({noServer:!0}),r=new ze;n.on("upgrade",(i,a,u)=>{let c=new URL(i.url??"/","http://localhost");c.pathname===Bt&&(a.on("error",()=>{}),(async()=>{let l=Mo(i,c,t),d;if(e.authenticate)d=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new re(401,"invalid local proxy api key");d={clients:e.clients,scope:No}}o.handleUpgrade(i,a,u,p=>{new Ye(p,d,r)})})().catch(l=>{let d=502;(l instanceof re||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(d=l.status);let p=d===401?"Unauthorized":d===403?"Forbidden":d===502?"Bad Gateway":"Internal Server Error",m=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${d} ${p}\r
|
|
4
4
|
Connection: close\r
|
|
5
5
|
\r
|
|
6
|
-
|
|
6
|
+
${m}\r
|
|
7
|
+
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of o.clients)i.close(1001,"server closing");await new Promise((i,a)=>o.close(u=>u===void 0?i():a(u)))})(),s)}var te=require("ws");function pe(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,128)}var se=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,o){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=o}modelEntry(e){let t=this.models[e];if(t)return t;let o=Object.keys(this.models).length>=256?"(other)":e;return this.models[o]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t){let o=this,r=performance.now(),s=null,i=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(s===null&&(s=performance.now(),o.ttftMs.push(s-r),o.ttftMs.length>512&&o.ttftMs.shift()),i+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,t!==void 0&&(o.modelEntry(t).tokens_out+=1)),yield u;let a=(performance.now()-(s??r))/1e3;i>0&&a>0&&(o.tokRates.push(i/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((o,r)=>o-r);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,o)=>t+o,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Do=256;function jo(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var ie=class extends Error{},de=class{conversations=new Map;thread(e,t){let o=jo(t);if(e==null)return o;let r=this.conversations.get(String(e));if(!r)throw new ie(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...r,...o]}remember(e,t,o,r=!0){this.conversations.set(e,[...t,...o]);for(let s of this.conversations.keys()){if(this.conversations.size<=Do)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},un=new WeakMap;function ke(n){let e=un.get(n);return e||(e=new de,un.set(n,e)),e}function fe(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function ee(n){return n.find(e=>e.type==="response.completed")?.response??null}function me(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var Z=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),o=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},Fo=["<tool_call>","<function="];function Bo(n){return Fo.find(e=>n.includes(e))}function ae(n,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} 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 "${n}" (see catalog parser_defaults)`}function ue(n,e,t){if(!(!n||e>0))return Bo(t)}function Xe(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}function Vo(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let o of e){if(o===null||typeof o!="object")continue;let r=o;r.type==="message"?t.push({role:"assistant",content:r.content??""}):r.type==="function_call"&&t.push({type:"function_call",call_id:r.call_id,name:r.name,arguments:r.arguments})}return t}function Qe(n,e){let t=Vo(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var j=class extends Error{constructor(t,o,r=400,s){super(t);this.code=o;this.status=r;this.param=s}code;status;param};function ge(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof ie?new j(t.message,"previous_response_not_found",400,"previous_response_id"):new j(String(t instanceof Error?t.message:t),"invalid_input")}}async function Ze(n,e,t,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new j("instructions must be a string","invalid_instructions");let r=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:o,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...r!==void 0?{instructions:r}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}async function xe(n){let{body:e,clients:t,store:o,stats:r}=n,s=ge(o,e);e.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=`resp_${Math.random().toString(36).slice(2,14)}`,a=n.remember??e.store!==!1,u=e.store!==!1,c=pe(e);r.model(c);let l=Array.isArray(e.tools)&&e.tools.length>0,d=await Ze(t,e,s,!0);return{responseId:i,events:Go({events:d,conversation:s,responseId:i,modelKey:c,requestHadTools:l,remember:a,persist:u,store:o,stats:r})}}async function*Go(n){let{events:e,conversation:t,responseId:o,modelKey:r,requestHadTools:s,remember:i,persist:a,store:u,stats:c}=n,l=[],d=v=>v.response&&typeof v.response=="object"?{...v,response:{...v.response,id:o}}:v,p=`item_${o.slice(5)}`,m=`rs_${o.slice(5)}`,y=!1,x=!1,h=0;function*k(){y||(y=!0,yield{type:"response.created",response:{id:o,object:"response",status:"in_progress"}})}let w=!1,T=0,M="";function*H(){w&&(w=!1,yield{type:"response.reasoning_text.done",item_id:m,output_index:T,content_index:0,text:M},yield{type:"response.output_item.done",output_index:T,item:{id:m,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:M}],status:"completed"}})}let g=!1,b=0,F="";function*D(v){g&&(g=!1,yield{type:"response.output_text.done",item_id:p,output_index:b,content_index:0,text:F},yield{type:"response.content_part.done",item_id:p,output_index:b,content_index:0,part:{type:"output_text",text:F}},yield{type:"response.output_item.done",output_index:b,item:{id:p,type:"message",role:"assistant",status:v,content:[{type:"output_text",text:F}]}})}let B=new Z,O=null,q=-1;function*P(v){if(!O)return;let S=O;O=null,yield{type:"response.function_call_arguments.done",item_id:S.fcId,output_index:S.outputIndex,arguments:S.args},yield{type:"response.output_item.done",output_index:S.outputIndex,item:{id:S.fcId,type:"function_call",call_id:S.callId??S.fcId,name:S.name??"",arguments:S.args,status:v}}}let U=!1;for await(let v of c.track(e,r)){l.push(v);let S=String(v.type??"");if(S==="response.created"||S==="response.in_progress"){y=!0,yield d(v);continue}if(S==="response.output_item.added"){x=!0,yield d(v);continue}if(S==="response.reasoning_text.delta"&&!x){yield*k(),w||(w=!0,T=h++,yield{type:"response.output_item.added",output_index:T,item:{id:m,type:"reasoning",summary:[],content:[],status:"in_progress"}}),M+=String(v.delta??""),yield{type:"response.reasoning_text.delta",item_id:m,output_index:T,content_index:0,delta:v.delta};continue}if(S==="response.output_text.delta"&&!x){yield*k(),yield*H(),g||(g=!0,b=h++,yield{type:"response.output_item.added",output_index:b,item:{id:p,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:p,output_index:b,content_index:0,part:{type:"output_text",text:""}}),F+=String(v.delta??""),yield{type:S,item_id:p,output_index:b,content_index:0,delta:v.delta};continue}let I=x?null:me(v);if(I){if(yield*k(),yield*H(),yield*D("completed"),B.add(I),I.tool_index!==q){yield*P("completed"),q=I.tool_index;let K=h++;O={fcId:`fc_${o.slice(5)}_${I.tool_index}`,outputIndex:K,callId:I.call_id,name:I.name,args:""},yield{type:"response.output_item.added",output_index:K,item:{id:O.fcId,type:"function_call",call_id:O.callId??O.fcId,name:O.name??"",arguments:"",status:"in_progress"}}}O&&(I.call_id&&(O.callId=I.call_id),I.name&&(O.name=I.name),O.args+=I.delta,yield{type:"response.function_call_arguments.delta",item_id:O.fcId,output_index:O.outputIndex,delta:I.delta});continue}if(S==="response.completed"&&!x){let K=fe(v.response),Se=ue(s,B.size+K.length,F);if(Se){U=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ae(r,Se)}};break}if(yield*H(),yield*D("completed"),yield*P("completed"),B.size===0)for(let Q of K){let W=h++,ce=Q.id??Q.call_id??`fc_${W}`,ne=Q.arguments??"",R={id:ce,type:"function_call",call_id:Q.call_id??ce,name:Q.name??""};yield{type:"response.output_item.added",output_index:W,item:{...R,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ce,output_index:W,delta:ne},yield{type:"response.function_call_arguments.done",item_id:ce,output_index:W,arguments:ne},yield{type:"response.output_item.done",output_index:W,item:{...R,arguments:ne,status:"completed"}}}yield d(v);continue}yield d(v)}if(yield*H(),yield*D("incomplete"),yield*P("incomplete"),i&&!U){let v=ee(l);u.remember(o,t,Qe(v,Xe(l,v)),a)}}var Ho="/v1/responses",qo=64*1024*1024,Wo=8*1024*1024,Jo=16,cn=32,ln=3600*1e3,Ko=/^[A-Za-z0-9._-]{1,256}$/;function $(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var zo=$(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function nt(){let n,e;return{promise:new Promise((o,r)=>{n=o,e=r}),resolve:n,reject:e}}async function Yo(n){for(;n.bufferedAmount>Wo&&n.readyState===te.WebSocket.OPEN;){let{promise:e,resolve:t}=nt();setTimeout(t,5),await e}}var et=class extends de{constructor(t){super();this.shared=t}shared;thread(t,o){if(t==null)return super.thread(t,o);try{return super.thread(t,o)}catch(r){if(!(r instanceof ie))throw r;return this.shared.thread(t,o)}}remember(t,o,r,s=!0){s?this.shared.remember(t,o,r):super.remember(t,o,r)}forget(t){super.forget(t),this.shared.forget(t)}},tt=class{constructor(e,t,o,r){this.ws=e;this.clients=t;this.stats=o;this.statusOf=r;this.store=new et(ke(t)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame($(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ln/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ln).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,t){if(this.closed)return;if(t){this.sendFrame($(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let o;try{o=JSON.parse(e.toString())}catch{this.sendFrame($(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(o===null||typeof o!="object"||Array.isArray(o)){this.sendFrame($(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let r=o;if(r.type!=="response.create"){this.sendFrame($(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(r.type??null)}; only "response.create" is supported`}));return}if("stream"in r){this.sendFrame($(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in r){this.sendFrame($(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(r.stream_id!==void 0){if(typeof r.stream_id!="string"||!Ko.test(r.stream_id)){this.sendFrame(zo);return}if(s=r.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=cn){this.sendFrame($(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${cn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=r.generate===!1?()=>this.runWarmup(r,s):()=>this.runTurn(r,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,t){if(!this.closed){await this.acquire();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let r;try{r=await xe({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0})}catch(i){this.failTurn(i,t,e);return}this.laneOfResponse.set(r.responseId,t??null);let s=r.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==te.WebSocket.OPEN)break;this.send(i,t),await Yo(this.ws)}}finally{this.activeTurns.delete(s)}}catch(o){this.failTurn(o,t,e)}finally{this.release()}}}runWarmup(e,t){if(this.closed)return;let o=`resp_${Math.random().toString(36).slice(2,14)}`;try{let r=ge(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,r,[],e.store!==!1),this.laneOfResponse.set(o,t??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},t)}catch(r){this.failTurn(r,t,e)}}failTurn(e,t,o){this.sendFrame(this.errorFrameOf(e,t));let r=o.previous_response_id;typeof r=="string"&&this.laneOfResponse.get(r)===(t??null)&&(this.store.forget(r),this.laneOfResponse.delete(r))}errorFrameOf(e,t){let o=String(e instanceof Error?e.message:e);if(e instanceof j)return $(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof C)return $(404,{type:"invalid_request_error",code:"model_not_found",message:o},t);if(e instanceof N)return $(503,{type:"upstream_error",code:"session_gone",message:o},t);let r=this.statusOf?.(e)??null;return r?$(r.status,{type:r.openaiType,message:o},t):$(500,{type:"upstream_error",message:o},t)}async acquire(){for(;this.active>=Jo;){let{promise:e,resolve:t}=nt();this.waiters.push(t),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,t){if(this.closed||this.ws.readyState!==te.WebSocket.OPEN)return;let o=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(o))}sendFrame(e){this.closed||this.ws.readyState!==te.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Ue(n,e,t){let o=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",r=`${t}\r
|
|
8
|
+
`;n.end(`HTTP/1.1 ${e} ${o}\r
|
|
7
9
|
Connection: close\r
|
|
10
|
+
Content-Type: text/plain; charset=utf-8\r
|
|
11
|
+
Content-Length: ${Buffer.byteLength(r)}\r
|
|
8
12
|
\r
|
|
9
|
-
|
|
10
|
-
data: ${JSON.stringify(
|
|
13
|
+
${r}`)}function dn(n,e){let t=new te.WebSocketServer({noServer:!0,maxPayload:qo}),o=new se,r=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,c=(l,d,p)=>{let m;try{m=new URL(l.url??"/","http://localhost")}catch{Ue(d,400,"malformed upgrade URL");return}if(d.on("error",()=>d.destroy()),d.on("close",()=>i.delete(d)),m.pathname!==Ho){i.add(d);return}s.add(d);let y=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ue(d,401,"invalid local proxy api key");return}let x;try{x=await a(l)}catch(h){let k=e.statusOf?.(h)??null;Ue(d,k?.status??500,"upstream resolver rejected the connection");return}u||d.destroyed||(y=!0,t.handleUpgrade(l,d,p,h=>{s.delete(d),r.add(h),h.on("close",()=>r.delete(h));try{new tt(h,x,o,e.statusOf)}catch{r.delete(h),h.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!y&&!d.destroyed&&Ue(d,500,"responses websocket upgrade failed")}).finally(()=>s.delete(d))};return n.on("upgrade",c),{stats:o,close:()=>{let{promise:l,resolve:d}=nt();if(u)return d(),l;u=!0,n.off("upgrade",c);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of r)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of r)m.readyState!==te.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),t.close(()=>{clearTimeout(p),d()}),l}}}function st(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function G(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function V(n,e,t,o="invalid_request_error"){G(n,e,{error:{message:t,type:o}})}function J(n,e,t,o){G(n,e,{type:"error",error:{type:t,message:o}})}function $e(n,e,t){if(e==="anthropic"){G(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}G(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var pn=64*1024*1024,Le=class extends Error{};async function Xo(n){let e=[],t=0;for await(let r of n){if(t+=r.length,t>pn)throw new Le(`request body exceeds ${pn} bytes`);e.push(r)}let o=Buffer.concat(e).toString("utf8");return o?JSON.parse(o):{}}function he(n,e,t,o){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:o}]}}function Ne(n){let e=n?.usage;if(!e||typeof e!="object")return null;let t=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0,o=t(e.input_tokens),r=t(e.output_tokens);if(o===0&&r===0)return null;let s=t(e.total_tokens)||o+r;return{input_tokens:o,output_tokens:r,total_tokens:s}}function fn(n){let e=Ne(n);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function gn(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let o of e)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let r of o.content)r.type==="reasoning_text"&&(t+=String(r.text??""));return t}function Qo(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var Me=class extends Error{};function Zo(n,e){return Array.isArray(e)?e.map(t=>{let o=t;if(o.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let r=o.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new Me(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function er(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let o of t.tool_calls){let r=o.function??{};e.push({type:"function_call",call_id:o.id,name:r.name,arguments:r.arguments})}continue}e.push({...t,content:Zo(t.role,t.content)})}return e}function ot(n){return fe(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function tr(n,e,t,o,r){if(n.stream===!0){let h;try{h=await xe({body:n,clients:e,store:t,stats:r})}catch(k){if(k instanceof C){$e(o,"openai",k);return}if(k instanceof j){V(o,k.status,k.message);return}throw k}st(o);for await(let k of h.events)o.write(`event: ${String(k.type??"message")}
|
|
14
|
+
data: ${JSON.stringify(k)}
|
|
11
15
|
|
|
12
|
-
`)
|
|
16
|
+
`);o.write(`data: [DONE]
|
|
13
17
|
|
|
14
|
-
`),o.end();return}let h=null;for await(let
|
|
18
|
+
`),o.end();return}let i;try{i=ge(t,n)}catch(h){if(h instanceof j){V(o,h.status,h.message);return}throw h}n.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(n.input)));let a=`resp_${Math.random().toString(36).slice(2,14)}`,u=n.store!==!1,c=pe(n);r.model(c);let l=Array.isArray(n.tools)&&n.tools.length>0,d;try{d=await Ze(e,n,i,!1)}catch(h){if(h instanceof C){$e(o,"openai",h);return}if(h instanceof j){V(o,h.status,h.message);return}throw h}let p=[],m=null;for await(let h of r.track(d,c)){if(p.push(h),h.type==="error"){V(o,502,JSON.stringify(h),"upstream_error");return}h.type==="response.completed"&&(m=h.response)}if(m==null){V(o,502,"upstream produced no response.completed event","upstream_error");return}let y=Xe(p,m),x=ue(l,fe(m).length,y);if(x){V(o,502,ae(c,x),"upstream_error");return}u&&t.remember(a,i,Qe(m,y),u),G(o,200,{...m,id:a})}async function nr(n,e,t,o){let r=n.messages;if(!Array.isArray(r)){V(t,400,"chat/completions requires a messages array");return}let s=String(n.model??"urun"),i=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,a;try{a=er(r)}catch(g){if(g instanceof Me){V(t,400,g.message);return}throw g}let u=pe(n);o.model(u);let c=Array.isArray(n.tools)&&n.tools.length>0,l;try{l=await e.createResponse({model:n.model,input:a,stream:!0,tools:Qo(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,top_p:n.top_p,stop:n.stop,max_output_tokens:n.max_completion_tokens??n.max_tokens,...n.reasoning_effort!==void 0?{reasoning_effort:n.reasoning_effort}:{},...n.chat_template_kwargs!==void 0?{chat_template_kwargs:n.chat_template_kwargs}:{}})}catch(g){if(g instanceof C){$e(t,"openai",g);return}throw g}if(n.stream===!0){st(t);let g=[],b=new Z,F="";t.write(`data: ${JSON.stringify(he(i,s,{role:"assistant"},null))}
|
|
15
19
|
|
|
16
|
-
`);for await(let
|
|
20
|
+
`);for await(let P of o.track(l,u)){g.push(P);let U=me(P);if(P.type==="response.output_text.delta"&&typeof P.delta=="string")F+=P.delta,t.write(`data: ${JSON.stringify(he(i,s,{content:P.delta},null))}
|
|
17
21
|
|
|
18
|
-
`);else if(
|
|
22
|
+
`);else if(P.type==="response.reasoning_text.delta"&&typeof P.delta=="string")t.write(`data: ${JSON.stringify(he(i,s,{reasoning_content:P.delta},null))}
|
|
19
23
|
|
|
20
|
-
`);else if(
|
|
24
|
+
`);else if(U){let{call:v,isNew:S}=b.add(U),I=S?{index:U.tool_index,id:v.id??`call_${U.tool_index}`,type:"function",function:{name:v.name??"",arguments:U.delta}}:{index:U.tool_index,function:{arguments:U.delta}};t.write(`data: ${JSON.stringify(he(i,s,{tool_calls:[I]},null))}
|
|
21
25
|
|
|
22
|
-
`)}else if(
|
|
26
|
+
`)}else if(P.type==="error"){t.write(`data: ${JSON.stringify({error:P})}
|
|
23
27
|
|
|
24
|
-
`),
|
|
28
|
+
`),t.end();return}}let D=ot(ee(g)),B=ue(c,b.size+D.length,F);if(B){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ae(u,B)}})}
|
|
25
29
|
|
|
26
|
-
`),
|
|
30
|
+
`),t.end();return}b.size===0&&D.length>0&&t.write(`data: ${JSON.stringify(he(i,s,{tool_calls:D},null))}
|
|
27
31
|
|
|
28
|
-
`);let
|
|
32
|
+
`);let O=b.size>0||D.length>0;t.write(`data: ${JSON.stringify(he(i,s,{},O?"tool_calls":"stop"))}
|
|
29
33
|
|
|
30
|
-
`),
|
|
34
|
+
`),Ne(ee(g))&&t.write(`data: ${JSON.stringify({id:i,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s,choices:[],usage:fn(ee(g))})}
|
|
31
35
|
|
|
32
|
-
`),
|
|
36
|
+
`),t.write(`data: [DONE]
|
|
33
37
|
|
|
34
|
-
`),
|
|
35
|
-
data: ${JSON.stringify({type:
|
|
38
|
+
`),t.end();return}let d="",p="",m=[],y=new Z;for await(let g of o.track(l,u)){m.push(g),g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(d+=g.delta),g.type==="response.reasoning_text.delta"&&typeof g.delta=="string"&&(p+=g.delta);let b=me(g);if(b&&y.add(b),g.type==="error"){V(t,502,JSON.stringify(g),"upstream_error");return}}let x=ee(m),h=ot(x),k=h.length>0?h:ot({output:y.items()}),w=ue(c,k.length,d);if(w){V(t,502,ae(u,w),"upstream_error");return}let T=k.map(({index:g,...b})=>b),M={role:"assistant",content:d||null},H=p||gn(x);H&&(M.reasoning_content=H),T.length>0&&(M.tool_calls=T),G(t,200,{id:i,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:s,choices:[{index:0,message:M,finish_reason:T.length>0?"tool_calls":"stop"}],usage:fn(x)})}function or(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var be=class extends Error{};function De(n){return new be(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function rr(n){if(Array.isArray(n))return n.map(e=>{let t=e;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function sr(n){if(n==null)return;let e=n.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:n.name};throw new be(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function ir(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw De(typeof n);let e="";for(let t of n){let o=String(t.type??"");if(o!=="text")throw De(`tool_result > ${o}`);e+=String(t.text??"")}return e}function ar(n){let{role:e,content:t}=n;if(typeof t=="string")return[{role:e,content:t}];if(t==null)return[];if(!Array.isArray(t))throw De(typeof t);let o=[],r="",s=()=>{r&&(o.push({role:e,content:r}),r="")};for(let i of t){let a=String(i.type??"");if(a==="text")r+=String(i.text??"");else if(a==="tool_use")s(),o.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),o.push({type:"function_call_output",call_id:i.tool_use_id,output:ir(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw De(a)}}return s(),o}function rt(n){return fe(n).map((e,t)=>{let o;try{o=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${t}`,name:e.name??"",input:o}})}async function ur(n,e,t,o){let r=n.messages;if(!Array.isArray(r)){J(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof n.max_tokens!="number"||!Number.isInteger(n.max_tokens)||n.max_tokens<1){J(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){J(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(n.stop_sequences!==void 0&&(!Array.isArray(n.stop_sequences)||n.stop_sequences.some(g=>typeof g!="string"))){J(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(n.model??"urun"),i=`msg_${Math.random().toString(36).slice(2,14)}`,a=[],u;try{n.system&&a.push({role:"system",content:or(n.system)});for(let g of r)a.push(...ar(g));u=sr(n.tool_choice)}catch(g){if(g instanceof be){J(t,400,"invalid_request_error",g.message);return}throw g}let c=pe(n);o.model(c);let l=Array.isArray(n.tools)&&n.tools.length>0,d;try{d=await e.createResponse({model:n.model,input:a,stream:!0,tools:rr(n.tools),tool_choice:u,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences})}catch(g){if(g instanceof C){$e(t,"anthropic",g);return}throw g}let p=(g,b)=>{t.destroyed||t.write(`event: ${g}
|
|
39
|
+
data: ${JSON.stringify({type:g,...b})}
|
|
36
40
|
|
|
37
|
-
`)};if(
|
|
38
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:
|
|
41
|
+
`)};if(n.stream===!0){let g=o.track(d,c);st(t),p("message_start",{message:{id:i,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let b=0,F="",D=0,B="none",O=()=>B,q=-1,P=-1,U=new Z,v=[],S=()=>{B!=="none"&&(B="none",p("content_block_stop",{index:q}))},I=(R,L)=>{S(),B=R,q=D++,p("content_block_start",{index:q,content_block:L})};for await(let R of g){if(t.destroyed)break;v.push(R);let L=me(R);if(R.type==="response.reasoning_text.delta"&&typeof R.delta=="string")O()!=="thinking"&&I("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:R.delta}});else if(R.type==="response.output_text.delta"&&typeof R.delta=="string")O()!=="text"&&I("text",{type:"text",text:""}),b+=1,F+=R.delta,p("content_block_delta",{index:q,delta:{type:"text_delta",text:R.delta}});else if(L){let{call:ft}=U.add(L);(O()!=="tool"||L.tool_index!==P)&&(P=L.tool_index,I("tool",{type:"tool_use",id:ft.id??`call_${L.tool_index}`,name:ft.name??"",input:{}})),L.delta&&p("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:L.delta}})}else if(R.type==="error"){p("error",{error:{type:"api_error",message:JSON.stringify(R)}}),t.end();return}}if(t.destroyed)return;let K=ee(v),Se=fe(K),Q=ue(l,U.size+Se.length,F);if(Q){p("error",{error:{type:"api_error",message:ae(c,Q)}}),t.end();return}S();let W=[];if(U.size===0)try{W=rt(K)}catch(R){p("error",{error:{type:"api_error",message:String(R instanceof Error?R.message:R)}}),t.end();return}D===0&&W.length===0&&(I("text",{type:"text",text:""}),S()),W.forEach(R=>{let L=D++;p("content_block_start",{index:L,content_block:{...R,input:{}}}),p("content_block_delta",{index:L,delta:{type:"input_json_delta",partial_json:JSON.stringify(R.input??{})}}),p("content_block_stop",{index:L})});let ce=U.size>0||W.length>0,ne=Ne(K);p("message_delta",{delta:{stop_reason:ce?"tool_use":"end_turn"},usage:ne?{input_tokens:ne.input_tokens,output_tokens:ne.output_tokens}:{output_tokens:b}}),p("message_stop",{}),t.end();return}let m="",y="",x=[],h=new Z;for await(let g of o.track(d,c)){x.push(g),g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(m+=g.delta),g.type==="response.reasoning_text.delta"&&typeof g.delta=="string"&&(y+=g.delta);let b=me(g);if(b&&h.add(b),g.type==="error"){J(t,502,"api_error",JSON.stringify(g));return}if(t.destroyed)break}if(t.destroyed)return;let k=ee(x),w;try{w=rt(k),w.length===0&&h.size>0&&(w=rt({output:h.items()}))}catch(g){J(t,502,"api_error",String(g instanceof Error?g.message:g));return}let T=ue(l,w.length,m);if(T){J(t,502,"api_error",ae(c,T));return}let M=[],H=y||gn(k);H&&M.push({type:"thinking",thinking:H}),(m||w.length===0)&&M.push({type:"text",text:m}),M.push(...w),G(t,200,{id:i,type:"message",role:"assistant",content:M,model:s,stop_reason:w.length>0?"tool_use":"end_turn",usage:Ne(k)??{input_tokens:0,output_tokens:0}})}function cr(n){let{clients:e,apiKey:t,identity:o,statusOf:r}=n,s=typeof e=="function"?e:()=>e,i=new se;return(a,u)=>{let c=new URL(a.url??"/","http://localhost"),l=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),d=(p,m,y,x)=>l?J(u,p,x,m):V(u,p,m,y);(async()=>{if(a.method==="GET"&&c.pathname==="/healthz"){G(u,200,{ok:!0});return}if(a.method==="GET"&&c.pathname==="/stats"){G(u,200,o?{identity:o,...i.snapshot()}:i.snapshot());return}if(t&&(a.headers.authorization??"")!==`Bearer ${t}`){d(401,"invalid local proxy api key","authentication_error","authentication_error");return}let p=await s(a);if(a.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){if(!p.openRouterModels){d(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}G(u,200,await p.openRouterModels());return}G(u,200,await p.listModels());return}if(a.method!=="POST"){d(404,`no route for ${a.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let m;try{m=await Xo(a)}catch(x){if(x instanceof Le){d(413,x.message,"request_too_large","request_too_large");return}d(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let y=Buffer.byteLength(JSON.stringify(m));if(c.pathname==="/v1/responses"){i.request("responses",y,y),await tr(m,p,ke(p),u,i);return}if(c.pathname==="/v1/chat/completions"){i.request("chat_completions",y,y),await nr(m,p,u,i);return}if(c.pathname==="/v1/messages"){i.request("messages",y,y),await ur(m,p,u,i);return}if(c.pathname==="/v1/messages/count_tokens"){i.request("count_tokens",y,y),J(u,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}d(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let m=String(p instanceof Error?p.message:p);if(!u.headersSent){let y=r?.(p)??null;if(y){d(y.status,m,y.openaiType,y.anthropicType);return}d(500,m,"proxy_error","api_error");return}u.destroyed||(l?u.write(`event: error
|
|
42
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:m}})}
|
|
39
43
|
|
|
40
|
-
`):
|
|
44
|
+
`):u.write(`data: ${JSON.stringify({error:{message:m,type:"upstream_error"}})}
|
|
41
45
|
|
|
42
|
-
`)),
|
|
43
|
-
`)};return()=>{
|
|
44
|
-
`)}catch{}};r.on("error",s),
|
|
45
|
-
`)}catch{}
|
|
46
|
-
`)}catch(r){try{
|
|
47
|
-
`)}catch{}}
|
|
48
|
-
`),null):{catalogUrl:o,anonKey:r}}function
|
|
49
|
-
`),r(127)})})}function
|
|
50
|
-
`)}async function
|
|
51
|
-
`),
|
|
46
|
+
`)),u.end()})}}function hn(n){let{clients:e,apiKey:t}=n,o=(0,mn.createServer)(cr(n)),r=dn(o,{clients:e,apiKey:t,statusOf:n.statusOf}),s=o.close.bind(o);return o.close=(i=>(r.close(),s(i))),an(o,{clients:e,apiKey:t}),o}var wn=le(require("os"),1),_n=le(require("path"),1),vn=require("url"),kn=require("util");var yn="0.5.5";var xn=4141,dr=yn,Fe={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ut(n,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${n}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${n}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function bn(n,e,t){let o={...n,...ut(e,t)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function Sn(n,e,t){let o=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${n}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],r=t.indexOf("--"),s=r===-1?t:t.slice(0,r),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=t[0]==="exec",u=s.includes("--skip-git-repo-check"),c=a&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...o,...i?[]:["-m",e],...c]}function Rn(n,e){return e.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?e:["--provider","urun","--model",n,...e]}function En(n,e){return e.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?e:["--model",`urun/${n}`,...e]}function An(n,e,t){let o=(n.URUN_PI_EXTENSION_ENTRY??"").trim();if(o){if(!t(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,vn.fileURLToPath)(new URL("../pi-extension/standalone.cjs",e));if(!t(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 On(n){let e=Number(n);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${n}`);return e}function In(n){if(n[0]!=="--port")return null;let e=On(n[1]);return n.splice(0,2),e}function ct(n){let e=n.indexOf("--port");if(e===-1)return xn;let t=On(n[e+1]);return n.splice(e,2),t}function Pn(n){if(n===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 n}function it(n,e){let t=(n[e]??"").trim();if(!t)throw new Error(`${e} 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 ye(n){let e=pr(it(n,"URUN_BASE_URL")),t=it(n,"URUN_ORG_ID"),o=it(n,"URUN_APP"),r=(n.URUN_FUNCTION??"serve").trim()||"serve",s=(n.URUN_API_URL??"").trim(),i=s?je(s,"URUN_API_URL"):$t,a=(n.URUN_JWT??"").trim();if(a)return{baseUrl:e,orgId:t,appId:o,fnName:r,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(n.URUN_API_KEY??"").trim();if(u){let c=(n.URUN_GATEWAY_URL??"").trim(),l=c?je(c):void 0;return{baseUrl:e,orgId:t,appId:o,fnName:r,apiUrl:i,auth:{lane:"api-key",apiKey:u,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 pr(n,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(n).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${n} \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 n}function je(n,e="URUN_GATEWAY_URL"){let t=new URL(n),o=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!o)throw new Error(`${e} must be https (got ${n}) \u2014 the org API key rides the request's Authorization header`);return n}function lt(n){return{app:n.appId,org:n.orgId,fn:n.fnName,base_url:n.baseUrl,proxy_version:dr}}function fr(n,e){return n.app===e.app&&n.org===e.org&&n.fn===e.fn&&n.base_url===e.base_url&&n.proxy_version===e.proxy_version}var mr=250;async function dt(n,e=mr){try{let t=await fetch(`http://127.0.0.1:${n}/stats`,{signal:AbortSignal.timeout(e)});if(!t.ok)return null;let o=(await t.json()).identity;if(o==null||typeof o!="object")return null;let{app:r,org:s,fn:i,base_url:a,proxy_version:u}=o;return typeof r!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:r,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var Tn=2e3;async function gr(n,e=Tn){try{let t=await fetch(`http://127.0.0.1:${n}/v1/models`,{signal:AbortSignal.timeout(e)});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 Cn(n,e,t=xn,o=Tn){if(n!=null)return{mode:"spawn",port:n};let r=await dt(t);if(r!==null&&fr(r,e)){let s=await gr(t,o);return s===null?{mode:"reuse",port:t,identity:r}:{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 Un(n,e=wn.default.homedir()){return _n.default.join(e,".urun","logs",`compat-proxy-${n}.log`)}var at=["log","info","warn","error","debug","trace"];function $n(n,e=process,t=console){let o=e.stdout.write,r=e.stderr.write,s=(a,...u)=>n.write(a,...u);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(at.map(a=>[a,t[a]]));for(let a of at)t[a]=(...u)=>{n.write(`${(0,kn.format)(...u)}
|
|
47
|
+
`)};return()=>{e.stdout.write=o,e.stderr.write=r;for(let a of at)t[a]=i[a]}}var hr=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Ln(n){let e=n?.code;return typeof e=="string"&&hr.has(e)}function Be(n,e){try{return n.write(e),!0}catch(t){if(Ln(t))return!1;throw t}}function Nn(n){let e={stdout:!1,stderr:!1},t=[];for(let o of["stdout","stderr"]){let r=n.streams[o],s=i=>{Ln(i)&&(e[o]=!0);let a=i?.code;try{n.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
|
|
48
|
+
`)}catch{}};r.on("error",s),t.push([r,s])}return{isDead:o=>e[o],uninstall:()=>{for(let[o,r]of t)o.off("error",r)}}}function Mn(n){let e=t=>{let o=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{n.appendSync(n.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${o}
|
|
49
|
+
`)}catch{}n.restore();try{n.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${n.logPath}
|
|
50
|
+
`)}catch(r){try{n.appendSync(n.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(r?.code??r)}) \u2014 the terminal is gone
|
|
51
|
+
`)}catch{}}n.killChild(),n.exit(1)};return n.proc.on("uncaughtException",e),n.proc.on("unhandledRejection",e),()=>{n.proc.off("uncaughtException",e),n.proc.off("unhandledRejection",e)}}function Dn(n,e){let t="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${n} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${n}, or ${t}`:`port ${n} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${t}`}var Ve=require("@urun-sh/core/internal");var yr={ensureWebRTC:Ve.ensureNodeWebRTC,webrtcUnavailableReason:Ve.nodeWebRTCUnavailableReason,audioBackend:Ae};async function jn(n=yr){try{await n.ensureWebRTC()}catch(t){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(t)}`}}let e=n.webrtcUnavailableReason();if(e)return{ok:!1,reason:`${e} \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 n.audioBackend()).createSource()}catch(t){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(t)}`}}return{ok:!0,reason:null}}function wr(n,e){let t=(n.URUN_CATALOG_URL??"").trim(),o=t?je(t,"URUN_CATALOG_URL"):"",r=(n.URUN_CATALOG_ANON_KEY??"").trim();return!o||!r?(e(`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
|
|
52
|
+
`),null):{catalogUrl:o,anonKey:r}}function _r(n){return Dt({baseUrl:n.baseUrl,orgId:n.orgId,defaultApp:n.appId,fnName:n.fnName,apiUrl:n.apiUrl,auth:n.auth,catalog:wr(_.default.env,e=>_.default.stderr.write(e))})}async function Fn(n,e,t){let o=(0,pt.spawn)(n,e,{stdio:"inherit",env:t});return new Promise(r=>{o.once("exit",s=>r(s??1)),o.once("error",s=>{_.default.stderr.write(`failed to launch ${n}: ${String(s)}
|
|
53
|
+
`),r(127)})})}function Bn(){return An(_.default.env,E,X.existsSync)}function Hn(n){for(let[e,t]of Object.entries(ut(n)))_.default.stdout.write(`export ${e}=${t}
|
|
54
|
+
`)}async function Vn(n,e){let t=ye(_.default.env),o=e?lt(t):void 0,r=_r(t),s=hn({clients:jt(r),identity:o});try{await new Promise((a,u)=>{s.once("error",u),s.listen(n,"127.0.0.1",a)})}catch(a){throw await r.closeAll().catch(()=>{}),a.code==="EADDRINUSE"?new Error(Dn(n,await dt(n))):a}let i=s.address().port;return e&&(_.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${i}/v1
|
|
55
|
+
`),Hn(i)),{port:i,close:async()=>{let a=new Promise(u=>s.close(()=>u()));s.closeAllConnections(),await a,await r.closeAll()}}}async function vr(){let n=_.default.argv.slice(2),e=In(n),t=n.shift()??"proxy";if(t==="env")return Hn(Pn(e??ct(n))),0;if(t==="selftest"){let{ok:r,reason:s}=await jn();return r?(_.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
|
|
52
56
|
`),0):(_.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
|
|
53
|
-
`),1)}if(
|
|
57
|
+
`),1)}if(t==="proxy"){let r=e??ct(n),s=await Vn(r,!0);return await new Promise(i=>{_.default.once("SIGINT",i),_.default.once("SIGTERM",i)}),await s.close(),0}let o=t==="run"?n.shift():t;{if(!o)throw new Error(`launch needs an agent (${Object.keys(Fe).join("|")}) or \`-- <cmd>\``);if(o==="pi"){let w=ye(_.default.env);return Fn("pi",["-e",Bn(),...Rn(w.appId,n)],_.default.env)}if(o==="omp"){let w=ye(_.default.env);return Fn("omp",["-e",Bn(),...En(w.appId,n)],_.default.env)}let r,s,i="openai";if(o==="--"){if(r=n.shift()??"",s=n,!r)throw new Error("`-- <cmd>` needs a command to launch")}else{let w=Fe[o];if(!w)throw new Error(`unknown command/agent ${o}; commands: proxy | env; agents: ${Object.keys(Fe).join(" | ")} \u2014 or \`-- <cmd>\``);r=w.bin,s=[...w.args??[],...n],i=w.env}let a=await Cn(e,lt(ye(_.default.env))),u=null,c=a.port;a.mode==="reuse"?_.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${c} (app ${a.identity.app}, fn ${a.identity.fn}, v${a.identity.proxy_version})
|
|
54
58
|
`):a.reason&&_.default.stderr.write(`urun compat: ${a.reason}
|
|
55
|
-
`);let l=null,
|
|
56
|
-
`)}),_.default.stdout.write(`urun openai proxy on http://127.0.0.1:${
|
|
57
|
-
`),l
|
|
58
|
-
`),
|
|
59
|
-
`),
|
|
59
|
+
`);let l=null,d=null,p=null,m=null;a.mode!=="reuse"&&(u=await Vn(a.port,!1),c=u.port,m=Un(c),(0,X.mkdirSync)(Gn.default.dirname(m),{recursive:!0}),p=(0,X.createWriteStream)(m,{flags:"a"}),d=Nn({streams:_.default,note:w=>(0,X.appendFileSync)(m,w)}).uninstall,p.on("error",w=>{l?.(),l=null,Be(_.default.stderr,`urun compat: proxy log ${m} failed: ${String(w)} \u2014 proxy output continues on the terminal
|
|
60
|
+
`)}),_.default.stdout.write(`urun openai proxy on http://127.0.0.1:${c}/v1 \u2014 proxy logs: ${m}
|
|
61
|
+
`),l=$n(p)),o==="codex"&&(s=Sn(c,ye(_.default.env).appId,s));let y=(0,pt.spawn)(r,s,{stdio:"inherit",env:bn(_.default.env,c,i)}),x=m!==null?Mn({logPath:m,appendSync:X.appendFileSync,restore:()=>{l?.(),l=null},writeStderr:w=>_.default.stderr.write(w),killChild:()=>y.kill("SIGTERM"),exit:w=>_.default.exit(w),proc:_.default}):null,h=await new Promise(w=>{y.once("exit",T=>w(T??1)),y.once("error",T=>{l?.(),l=null,Be(_.default.stderr,`failed to launch ${r}: ${String(T)}
|
|
62
|
+
`),w(127)})});x?.();let k=null;try{u&&await u.close()}catch(w){k=w}finally{l?.(),l=null,d?.(),d=null,p?.end()}return k!==null&&Be(_.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${h} preserved): ${String(k instanceof Error?k.message:k)}
|
|
63
|
+
`),h}}vr().then(n=>_.default.exit(n),n=>{_.default.stderr.write(`${String(n instanceof Error?n.message:n)}
|
|
60
64
|
`),_.default.exit(1)});
|