@urun-sh/openai 0.5.2 → 0.5.4
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-4MSBS7M6.js +1 -0
- package/dist/{chunk-G3NMGP4N.js → chunk-GBBY3PCZ.js} +1 -1
- package/dist/chunk-K23AZPI4.js +1 -0
- package/dist/chunk-OI2OY32M.js +1 -0
- package/dist/chunk-RQBD4OAA.js +6 -0
- package/dist/{chunk-EWCEZIOX.js → chunk-STFRT5OY.js} +1 -1
- package/dist/{chunk-M6ICU4F5.js → chunk-VNM4M4P3.js} +12 -12
- 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 +16 -16
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +16 -16
- package/dist/hosted/index.d.cts +94 -13
- package/dist/hosted/index.d.ts +44 -11
- 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 +50 -50
- package/dist/proxy/cli.cjs +31 -31
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +13 -13
- package/dist/proxy/index.d.cts +1 -1
- package/dist/proxy/index.d.ts +1 -1
- package/dist/proxy/index.js +1 -1
- package/dist/{server-l1himPxc.d.ts → server-DuH_5OD9.d.ts} +2 -0
- package/dist/{server-BfME37pQ.d.cts → server-wmUnMewW.d.cts} +6 -0
- package/package.json +3 -3
- package/dist/chunk-F2TEK34X.js +0 -1
- package/dist/chunk-TE6632EU.js +0 -6
- package/dist/chunk-UVAY7Q7Z.js +0 -1
- package/dist/chunk-XHIIEA6Z.js +0 -1
package/dist/proxy/index.cjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";var _e=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,n)=>{for(var t in n)_e(e,t,{get:n[t],enumerable:!0})},ut=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of st(n))!it.call(e,r)&&r!==t&&_e(e,r,{get:()=>n[r],enumerable:!(o=rt(n,r))||o.enumerable});return e};var ct=e=>ut(_e({},"__esModule",{value:!0}),e);var
|
|
2
|
-
`)}var pt={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},j="urun.videoOut";function Ue(e){return{framing:Ce,codec:e}}function Me(e){let{seq:n,ptsUs:t,codec:o,key:r}=e.header;return{[j]:{v:1,seq:n,ptsUs:t,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var ft={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},mt=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",j],Pe=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ht(e){let n=A(e);if(!n)throw new a("setup.realtimeInputConfig must be an object");for(let r of Object.keys(n))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new a(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let t=A(n.automaticActivityDetection);if(n.automaticActivityDetection!==void 0&&!t)throw new a("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(t??{}))if(r!=="disabled")throw new a(`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 a("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(n.activityHandling!==void 0){if(!Pe.includes(n.activityHandling))throw new a(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${Pe.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var gt=["temperature","maxOutputTokens","responseModalities"];function Ve(e){for(let[f,m]of Object.entries(ft))if(e[f]!==void 0)throw new a(m);for(let f of Object.keys(e))if(!mt.includes(f))throw new a(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new a('setup.model is required (format "models/{model}")');let n=e.model.replace(/^models\//,""),t,o,r=!1,s=A(e.generationConfig);if(e.generationConfig!==void 0&&!s)throw new a("setup.generationConfig must be an object");if(s){for(let f of Object.keys(s))if(!gt.includes(f))throw new a(`unsupported generationConfig field "${f}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new a("generationConfig.temperature must be a number");t=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new a("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let f=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let m of f){let y=String(m).toUpperCase();if(y==="AUDIO"){r=!0;continue}if(y!=="TEXT")throw new a(`responseModalities ${JSON.stringify(m)} 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:Ne(e.systemInstruction,"setup.systemInstruction")});let l;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new a("setup.tools must be an array");l=[];for(let f of e.tools){let m=A(f);if(!m)throw new a("setup.tools entries must be objects");for(let y of Object.keys(m))if(y!=="functionDeclarations")throw new a(`unsupported tool "${y}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(m.functionDeclarations))throw new a("tool.functionDeclarations must be an array");for(let y of m.functionDeclarations){let w=A(y);if(!w||typeof w.name!="string")throw new a("functionDeclarations entries require a string name");l.push({type:"function",name:w.name,description:w.description,parameters:w.parameters})}}l.length===0&&(l=void 0)}let h={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let f=A(e.sessionResumption);if(!f)throw new a("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(f))if(m!=="handle")throw new a(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(f.handle!==void 0&&(typeof f.handle!="string"||f.handle.length===0))throw new a("sessionResumption.handle must be a non-empty string when present");h={enabled:!0,handle:typeof f.handle=="string"?f.handle:null}}let d=e.realtimeInputConfig===void 0?pt:ht(e.realtimeInputConfig),p=!1;if(e[j]!==void 0){if(!A(e[j]))throw new a(`setup["${j}"] must be an object (the v1 opt-in is {})`);p=!0}return{model:n,systemItems:i,tools:l,temperature:t,maxOutputTokens:o,audioModality:r,activity:d,sessionResumption:h,videoOut:p}}function De(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function Be(e){let n=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function He(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new a(`unsupported clientContent field "${o}"`);let n=e.turns===void 0?[]:e.turns;if(!Array.isArray(n))throw new a("clientContent.turns must be an array");let t=[];for(let o of n){let r=A(o);if(!r)throw new a("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 a(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);t.push({role:s==="model"?"assistant":"user",content:Ne(r,"clientContent.turns")})}return{items:t,turnComplete:e.turnComplete===!0}}var pe=16e3,Fe=24e3,yt=`audio/pcm;rate=${Fe}`,qe=Buffer.alloc(960).toString("base64");function wt(e,n,t){if(n===t)return e;let o=Math.floor(e.length*t/n),r=new Int16Array(o),s=n/t,i=e.length-1;for(let l=0;l<o;l++){let h=l*s,d=Math.floor(h);if(d>=i){r[l]=e[i];continue}let p=h-d;r[l]=Math.round(e[d]+(e[d+1]-e[d])*p)}return r}function _t(e){let n=A(e);if(!n)throw new a("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new a(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(n.mimeType)}`);if(typeof n.data!="string"||n.data.length===0)throw new a("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(n.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new a("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function kt(e){let n=A(e);if(!n)throw new a("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new a(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(n.mimeType);if(t&&Number(t[1])!==pe)throw new a(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${pe} Hz (audio/pcm;rate=${pe})`);if(typeof n.data!="string"||n.data.length===0)throw new a("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(n.data,"base64");if(o.length===0||o.length%2!==0)throw new a(`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=wt(r,pe,Fe);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function je(e){if(e.mediaChunks!==void 0)throw new a('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 a("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",s=A(e[r]);if(!s||Object.keys(s).length!==0)throw new a(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!n.includes(o))throw new a(`unsupported realtimeInput field "${o}"`);let t=n.filter(o=>e[o]!==void 0);if(t.length!==1)throw new a(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${t.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:kt(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:_t(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new a("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new a("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function Je(e){for(let n of Object.keys(e))if(n!=="functionResponses")throw new a(`unsupported toolResponse field "${n}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new a("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(n=>{let t=A(n);if(!t||typeof t.id!="string"||t.id.length===0)throw new a("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 We(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function Ge(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:yt,data:e}}]}}}}function Ke(e){let n=A(e)??{},t=Array.isArray(n.output)?n.output:[],o=[],r=[],s=typeof n.output_text=="string"?n.output_text:"";if(!s)for(let d of t){let p=A(d);if(!(p?.type!=="message"||!Array.isArray(p.content)))for(let f of p.content){let m=A(f);m?.type==="output_text"&&typeof m.text=="string"&&(s+=m.text)}}s&&r.push({role:"assistant",content:s});for(let d of t){let p=A(d);if(p?.type!=="function_call")continue;if(typeof p.call_id!="string"||typeof p.name!="string")throw new a(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,J);let f=typeof p.arguments=="string"&&p.arguments.length>0?p.arguments:"{}",m;try{m=JSON.parse(f)}catch{throw new a(`upstream function_call arguments are not valid JSON: ${f}`,J)}o.push({id:p.call_id,name:p.name,args:m}),r.push({type:"function_call",call_id:p.call_id,name:p.name,arguments:f})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let l=A(n.usage),h={serverContent:{turnComplete:!0}};if(l){let d={};typeof l.input_tokens=="number"&&(d.promptTokenCount=l.input_tokens),typeof l.output_tokens=="number"&&(d.responseTokenCount=l.output_tokens),typeof l.total_tokens=="number"&&(d.totalTokenCount=l.total_tokens),Object.keys(d).length>0&&(h.usageMetadata=d)}return i.push(h),{messages:i,assistantItems:r}}var vt=256,ve=class{snapshots=new Map;store(n,t){for(this.snapshots.set(n,t);this.snapshots.size>vt;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},se=e=>e.slice(0,120),xe=class{constructor(n,t,o){this.ws=n;this.clients=t;this.registry=o;n.on("message",r=>this.onMessage(r)),n.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(n){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(n))}fail(n){if(n instanceof q){this.ws.close(Le,se(n.message));return}if(n instanceof re){this.ws.close(ke,se(n.message));return}if(n instanceof a){this.ws.close(n.closeCode,se(n.message));return}this.ws.close(J,se(String(n instanceof Error?n.message:n)))}onMessage(n){try{let t=$e(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new a(`"${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}=He(t.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=je(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:qe);return}this.transcript.push(...Je(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(n){if(this.config)throw new a("setup may only be sent once, as the first client message");let t=Ve(n),o=t.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new a("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",ke);if(s.model!==t.model)throw new a(`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 a("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(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),l=i.onOutputFrame(d=>this.send(Me(d))),h=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{l(),h()},r[j]=Ue(i.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let n=this.config;if(!n)throw new a("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new a("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",J);return this.audio=(async()=>{let o=await t.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(r=>this.send(Ge(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(t=>t.appendInputAudio(n)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)throw new a("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new a("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",J);return this.video=Promise.resolve(t.call(this.clients,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(t=>t.sendInputFrame(n)).catch(t=>this.fail(t))}onActivity(n,t){if(!t.activity.manualActivity)throw new a(`realtimeInput.${n} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(n==="activityStart"){if(this.activityOpen)throw new a("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 a("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(n){this.queue=this.queue.then(n,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(n.model);this.proxyHandle=t;let o=(0,ze.randomUUID)();this.registry.store(o,{model:n.model,proxyHandle:t,transcript:[...this.transcript]}),this.send(De(o))}async handleUpstreamEnd(n){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(Be(n.timeLeftMs)),this.ws.close(J,se(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let o=await this.clients.createResponse({model:n.model,input:[...this.transcript],stream:!0,tools:n.tools,temperature:n.temperature,max_output_tokens:n.maxOutputTokens}),r,s=!1;for await(let h of o){if(t.interrupted)break;let d=h;if(d.type==="error")throw new a(`upstream error: ${JSON.stringify(d)}`,J);if(d.type==="response.completed"){r=d.response,s=!0;continue}let p=We(d);p&&this.send(p)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new a("upstream produced no response.completed event",J);let{messages:i,assistantItems:l}=Ke(r);this.transcript.push(...l);for(let h of i)this.send(h);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},xt=(e,n)=>{let t=e.headers["x-goog-api-key"];if(typeof t=="string")return t;let o=e.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function Xe(e,n){let t=new Ye.WebSocketServer({noServer:!0}),o=new ve;e.on("upgrade",(r,s,i)=>{let l=new URL(r.url??"/","http://localhost");if(l.pathname!==fe){s.write(`HTTP/1.1 404 Not Found\r
|
|
1
|
+
"use strict";var _e=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,n)=>{for(var t in n)_e(e,t,{get:n[t],enumerable:!0})},ut=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of st(n))!it.call(e,r)&&r!==t&&_e(e,r,{get:()=>n[r],enumerable:!(o=rt(n,r))||o.enumerable});return e};var ct=e=>ut(_e({},"__esModule",{value:!0}),e);var qt={};at(qt,{GEMINI_LIVE_PATH:()=>fe,VIDEO_OUT_SETUP_KEY:()=>j,createOpenAIProxy:()=>ot});module.exports=ct(qt);var tt=require("http");var ze=require("crypto"),Ye=require("ws");var q=class extends Error{},re=class extends Error{};var le=require("@urun-sh/core");var Ce="urun.videoOut.v2-ws";var fe="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",pt=1007,Le=1008,J=1011,ke=1008,a=class extends Error{constructor(t,o=pt){super(t);this.closeCode=o}closeCode},R=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,de=["setup","clientContent","realtimeInput","toolResponse"];function $e(e){let n;try{n=JSON.parse(e)}catch{throw new a("client message is not valid JSON")}let t=R(n);if(!t)throw new a("client message must be a JSON object");let o=de.filter(l=>t[l]!==void 0),r=Object.keys(t).filter(l=>!de.includes(l));if(r.length>0)throw new a(`unknown client message field(s) ${JSON.stringify(r)} \u2014 expected exactly one of ${de.join(", ")}`);if(o.length!==1)throw new a(`client message must contain exactly one of ${de.join(", ")} (got ${o.length})`);let s=o[0],i=R(t[s]);if(!i)throw new a(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Ne(e,n){if(typeof e=="string")return e;let t=R(e),o=t?t.parts:void 0;if(!Array.isArray(o))throw new a(`${n}: expected a Content with a parts array`);let r=[];for(let s of o){let i=R(s);if(i&&typeof i.text=="string"){r.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new a(`${n}: 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 a(`${n}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new a(`${n}: unsupported part ${JSON.stringify(s)}`)}return r.join(`
|
|
2
|
+
`)}var ft={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},j="urun.videoOut";function Me(e){return{framing:Ce,codec:e}}function Ue(e){let{seq:n,ptsUs:t,codec:o,key:r}=e.header;return{[j]:{v:1,seq:n,ptsUs:t,codec:o,key:r,data:Buffer.from(e.au).toString("base64")}}}var mt={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},gt=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",j],Pe=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ht(e){let n=R(e);if(!n)throw new a("setup.realtimeInputConfig must be an object");for(let r of Object.keys(n))if(!(r==="automaticActivityDetection"||r==="activityHandling"))throw new a(r==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${r}"`);let t=R(n.automaticActivityDetection);if(n.automaticActivityDetection!==void 0&&!t)throw new a("realtimeInputConfig.automaticActivityDetection must be an object");for(let r of Object.keys(t??{}))if(r!=="disabled")throw new a(`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 a("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(n.activityHandling!==void 0){if(!Pe.includes(n.activityHandling))throw new a(`unsupported activityHandling ${JSON.stringify(n.activityHandling)} \u2014 expected one of ${Pe.join(", ")}`);o=n.activityHandling}return{manualActivity:!0,activityHandling:o}}var yt=["temperature","maxOutputTokens","responseModalities"];function De(e){for(let[f,m]of Object.entries(mt))if(e[f]!==void 0)throw new a(m);for(let f of Object.keys(e))if(!gt.includes(f))throw new a(`unsupported setup field "${f}"`);if(typeof e.model!="string"||e.model.length===0)throw new a('setup.model is required (format "models/{model}")');let n=e.model.replace(/^models\//,""),t,o,r=!1,s=R(e.generationConfig);if(e.generationConfig!==void 0&&!s)throw new a("setup.generationConfig must be an object");if(s){for(let f of Object.keys(s))if(!yt.includes(f))throw new a(`unsupported generationConfig field "${f}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new a("generationConfig.temperature must be a number");t=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new a("generationConfig.maxOutputTokens must be a number");o=s.maxOutputTokens}if(s.responseModalities!==void 0){let f=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let m of f){let h=String(m).toUpperCase();if(h==="AUDIO"){r=!0;continue}if(h!=="TEXT")throw new a(`responseModalities ${JSON.stringify(m)} 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:Ne(e.systemInstruction,"setup.systemInstruction")});let l;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new a("setup.tools must be an array");l=[];for(let f of e.tools){let m=R(f);if(!m)throw new a("setup.tools entries must be objects");for(let h of Object.keys(m))if(h!=="functionDeclarations")throw new a(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(m.functionDeclarations))throw new a("tool.functionDeclarations must be an array");for(let h of m.functionDeclarations){let y=R(h);if(!y||typeof y.name!="string")throw new a("functionDeclarations entries require a string name");l.push({type:"function",name:y.name,description:y.description,parameters:y.parameters})}}l.length===0&&(l=void 0)}let g={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let f=R(e.sessionResumption);if(!f)throw new a("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(f))if(m!=="handle")throw new a(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(f.handle!==void 0&&(typeof f.handle!="string"||f.handle.length===0))throw new a("sessionResumption.handle must be a non-empty string when present");g={enabled:!0,handle:typeof f.handle=="string"?f.handle:null}}let d=e.realtimeInputConfig===void 0?ft:ht(e.realtimeInputConfig),p=!1;if(e[j]!==void 0){if(!R(e[j]))throw new a(`setup["${j}"] must be an object (the v1 opt-in is {})`);p=!0}return{model:n,systemItems:i,tools:l,temperature:t,maxOutputTokens:o,audioModality:r,activity:d,sessionResumption:g,videoOut:p}}function Ve(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function Be(e){let n=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(n*1e3)/1e3}s`}}}function He(e){for(let o of Object.keys(e))if(o!=="turns"&&o!=="turnComplete")throw new a(`unsupported clientContent field "${o}"`);let n=e.turns===void 0?[]:e.turns;if(!Array.isArray(n))throw new a("clientContent.turns must be an array");let t=[];for(let o of n){let r=R(o);if(!r)throw new a("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 a(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(r.role)})`);t.push({role:s==="model"?"assistant":"user",content:Ne(r,"clientContent.turns")})}return{items:t,turnComplete:e.turnComplete===!0}}var pe=16e3,Fe=24e3,wt=`audio/pcm;rate=${Fe}`,qe=Buffer.alloc(960).toString("base64");function _t(e,n,t){if(n===t)return e;let o=Math.floor(e.length*t/n),r=new Int16Array(o),s=n/t,i=e.length-1;for(let l=0;l<o;l++){let g=l*s,d=Math.floor(g);if(d>=i){r[l]=e[i];continue}let p=g-d;r[l]=Math.round(e[d]+(e[d+1]-e[d])*p)}return r}function kt(e){let n=R(e);if(!n)throw new a("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(n.mimeType))throw new a(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(n.mimeType)}`);if(typeof n.data!="string"||n.data.length===0)throw new a("realtimeInput.video.data must be non-empty base64");let t=Buffer.from(n.data,"base64");if(t.length<3||t[0]!==255||t[1]!==216)throw new a("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(t)}function vt(e){let n=R(e);if(!n)throw new a("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof n.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(n.mimeType))throw new a(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(n.mimeType)}`);let t=/;\s*rate=(\d+)/.exec(n.mimeType);if(t&&Number(t[1])!==pe)throw new a(`realtimeInput.audio.mimeType declares rate=${t[1]} \u2014 the Live spec input format is ${pe} Hz (audio/pcm;rate=${pe})`);if(typeof n.data!="string"||n.data.length===0)throw new a("realtimeInput.audio.data must be non-empty base64");let o=Buffer.from(n.data,"base64");if(o.length===0||o.length%2!==0)throw new a(`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=_t(r,pe,Fe);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function je(e){if(e.mediaChunks!==void 0)throw new a('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 a("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let r=e.activityStart!==void 0?"activityStart":"activityEnd",s=R(e[r]);if(!s||Object.keys(s).length!==0)throw new a(`realtimeInput.${r} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:r}}let n=["text","audio","audioStreamEnd","video"];for(let o of Object.keys(e))if(!n.includes(o))throw new a(`unsupported realtimeInput field "${o}"`);let t=n.filter(o=>e[o]!==void 0);if(t.length!==1)throw new a(`realtimeInput must carry exactly one of ${n.join(", ")} (got ${t.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:vt(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:kt(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new a("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new a("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function Je(e){for(let n of Object.keys(e))if(n!=="functionResponses")throw new a(`unsupported toolResponse field "${n}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new a("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(n=>{let t=R(n);if(!t||typeof t.id!="string"||t.id.length===0)throw new a("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 We(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function Ge(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:wt,data:e}}]}}}}function Ke(e){let n=R(e)??{},t=Array.isArray(n.output)?n.output:[],o=[],r=[],s=typeof n.output_text=="string"?n.output_text:"";if(!s)for(let d of t){let p=R(d);if(!(p?.type!=="message"||!Array.isArray(p.content)))for(let f of p.content){let m=R(f);m?.type==="output_text"&&typeof m.text=="string"&&(s+=m.text)}}s&&r.push({role:"assistant",content:s});for(let d of t){let p=R(d);if(p?.type!=="function_call")continue;if(typeof p.call_id!="string"||typeof p.name!="string")throw new a(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,J);let f=typeof p.arguments=="string"&&p.arguments.length>0?p.arguments:"{}",m;try{m=JSON.parse(f)}catch{throw new a(`upstream function_call arguments are not valid JSON: ${f}`,J)}o.push({id:p.call_id,name:p.name,args:m}),r.push({type:"function_call",call_id:p.call_id,name:p.name,arguments:f})}let i=[];o.length>0&&i.push({toolCall:{functionCalls:o}}),i.push({serverContent:{generationComplete:!0}});let l=R(n.usage),g={serverContent:{turnComplete:!0}};if(l){let d={};typeof l.input_tokens=="number"&&(d.promptTokenCount=l.input_tokens),typeof l.output_tokens=="number"&&(d.responseTokenCount=l.output_tokens),typeof l.total_tokens=="number"&&(d.totalTokenCount=l.total_tokens),Object.keys(d).length>0&&(g.usageMetadata=d)}return i.push(g),{messages:i,assistantItems:r}}var xt=256,ve=class{snapshots=new Map;store(n,t){for(this.snapshots.set(n,t);this.snapshots.size>xt;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(n){return this.snapshots.get(n)}},se=e=>e.slice(0,120),xe=class{constructor(n,t,o){this.ws=n;this.clients=t;this.registry=o;n.on("message",r=>this.onMessage(r)),n.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(n){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(n))}fail(n){if(n instanceof q){this.ws.close(Le,se(n.message));return}if(n instanceof re){this.ws.close(ke,se(n.message));return}if(n instanceof a){this.ws.close(n.closeCode,se(n.message));return}this.ws.close(J,se(String(n instanceof Error?n.message:n)))}onMessage(n){try{let t=$e(typeof n=="string"?n:Buffer.concat(Array.isArray(n)?n:[n]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new a(`"${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}=He(t.clientContent);this.transcript.push(...r),s&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=je(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:qe);return}this.transcript.push(...Je(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(n){if(this.config)throw new a("setup may only be sent once, as the first client message");let t=De(n),o=t.sessionResumption.handle;if(o!==null){let s=this.registry.get(o);if(!s)throw new a("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",ke);if(s.model!==t.model)throw new a(`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 a("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(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),l=i.onOutputFrame(d=>this.send(Ue(d))),g=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{l(),g()},r[j]=Me(i.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let n=this.config;if(!n)throw new a("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new a("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native rt-audio-in/rt-audio-out AudioBridge seam)",J);return this.audio=(async()=>{let o=await t.call(this.clients,n.model);return this.detachAudio=o.onOutputAudio(r=>this.send(Ge(r))),o})(),this.audio.catch(o=>this.fail(o)),this.audio}appendAudio(n){this.ensureAudioLane().then(t=>t.appendInputAudio(n)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let n=this.config;if(!n)throw new a("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new a("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",J);return this.video=Promise.resolve(t.call(this.clients,n.model)),this.video.catch(o=>this.fail(o)),this.video}appendVideoFrame(n){this.ensureVideoLane().then(t=>t.sendInputFrame(n)).catch(t=>this.fail(t))}onActivity(n,t){if(!t.activity.manualActivity)throw new a(`realtimeInput.${n} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(n==="activityStart"){if(this.activityOpen)throw new a("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 a("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(n){this.queue=this.queue.then(n,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let n=this.config;if(!n?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(n.model);this.proxyHandle=t;let o=(0,ze.randomUUID)();this.registry.store(o,{model:n.model,proxyHandle:t,transcript:[...this.transcript]}),this.send(Ve(o))}async handleUpstreamEnd(n){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(Be(n.timeLeftMs)),this.ws.close(J,se(`upstream session ended: ${n.reason}`))}async runTurn(){let n=this.config;if(!n||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let o=await this.clients.createResponse({model:n.model,input:[...this.transcript],stream:!0,tools:n.tools,temperature:n.temperature,max_output_tokens:n.maxOutputTokens}),r,s=!1;for await(let g of o){if(t.interrupted)break;let d=g;if(d.type==="error")throw new a(`upstream error: ${JSON.stringify(d)}`,J);if(d.type==="response.completed"){r=d.response,s=!0;continue}let p=We(d);p&&this.send(p)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new a("upstream produced no response.completed event",J);let{messages:i,assistantItems:l}=Ke(r);this.transcript.push(...l);for(let g of i)this.send(g);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},bt=(e,n)=>{let t=e.headers["x-goog-api-key"];if(typeof t=="string")return t;let o=e.headers.authorization;return typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):n.searchParams.get("key")??void 0};function Xe(e,n){let t=new Ye.WebSocketServer({noServer:!0}),o=new ve;e.on("upgrade",(r,s,i)=>{let l=new URL(r.url??"/","http://localhost");if(l.pathname!==fe){s.write(`HTTP/1.1 404 Not Found\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
|
-
no WS route for ${l.pathname}`),s.destroy();return}if(n.apiKey&&
|
|
5
|
+
no WS route for ${l.pathname}`),s.destroy();return}if(n.apiKey&&bt(r,l)!==n.apiKey){s.write(`HTTP/1.1 401 Unauthorized\r
|
|
6
6
|
Connection: close\r
|
|
7
7
|
\r
|
|
8
|
-
invalid local proxy api key`),s.destroy();return}t.handleUpgrade(r,s,i,
|
|
9
|
-
data: ${JSON.stringify(
|
|
8
|
+
invalid local proxy api key`),s.destroy();return}t.handleUpgrade(r,s,i,g=>{new xe(g,n.clients,o)})})}var Ae=class e{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,t,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=t,this.naiveInBytes+=o}modelEntry(n){let t=this.models[n];if(t)return t;let o=Object.keys(this.models).length>=Rt?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,t){let o=this,r=performance.now(),s=null,i=0;return(async function*(){for await(let g of n)g.type==="response.output_text.delta"&&typeof g.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+=g.delta.length,t!==void 0&&(o.modelEntry(t).tokens_out+=1)),yield g;let l=(performance.now()-(s??r))/1e3;i>0&&l>0&&(o.tokRates.push(i/l),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let t=[...n].sort((o,r)=>o-r);return t[Math.floor(t.length/2)]}snapshot(){let n=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:e.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:e.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:n},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}}}};function Oe(e){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function U(e,n,t){e.writeHead(n,{"content-type":"application/json"}),e.end(JSON.stringify(t))}function W(e,n,t,o="invalid_request_error"){U(e,n,{error:{message:t,type:o}})}function B(e,n,t,o){U(e,n,{type:"error",error:{type:t,message:o}})}function Ee(e,n,t){if(n==="anthropic"){U(e,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}U(e,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Rt=256,At=128;function Ie(e){return typeof e.model!="string"||!e.model.trim()?"(default)":e.model.trim().slice(0,At)}var Qe=64*1024*1024,me=class extends Error{};async function St(e){let n=[],t=0;for await(let r of e){if(t+=r.length,t>Qe)throw new me(`request body exceeds ${Qe} bytes`);n.push(r)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Q(e,n,t,o){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:t,finish_reason:o}]}}var Ot=256;function Et(e){if(typeof e=="string")return[{role:"user",content:e}];if(Array.isArray(e))return e;throw new Error("responses input must be a string or an array of messages/items")}var Se=class{conversations=new Map;thread(n,t){let o=Et(t);if(n==null)return o;let r=this.conversations.get(String(n));if(!r)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...r,...o]}remember(n,t,o){this.conversations.set(n,[...t,{role:"assistant",content:o}]);for(let r of this.conversations.keys()){if(this.conversations.size<=Ot)break;this.conversations.delete(r)}}};function ie(e){let n=e?.output;return Array.isArray(n)?n.filter(t=>t.type==="function_call"):[]}function z(e){return e.find(n=>n.type==="response.completed")?.response??null}function ge(e){let n=e?.usage;if(!n||typeof n!="object")return null;let t=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0,o=t(n.input_tokens),r=t(n.output_tokens);if(o===0&&r===0)return null;let s=t(n.total_tokens)||o+r;return{input_tokens:o,output_tokens:r,total_tokens:s}}function Ze(e){let n=ge(e);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function nt(e){let n=e?.output;if(!Array.isArray(n))return"";let t="";for(let o of n)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 ae(e){return e.type!=="response.function_call_arguments.delta"||typeof e.tool_index!="number"?null:{tool_index:e.tool_index,call_id:typeof e.call_id=="string"?e.call_id:void 0,name:typeof e.name=="string"?e.name:void 0,delta:typeof e.delta=="string"?e.delta:""}}var Y=class{calls=new Map;add(n){let t=this.calls.get(n.tool_index),o=!t;return t||(t={args:""},this.calls.set(n.tool_index,t)),n.call_id&&(t.id=n.call_id),n.name&&(t.name=n.name),t.args+=n.delta,{call:t,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,t])=>({type:"function_call",call_id:t.id??`call_${n}`,name:t.name??"",arguments:t.args}))}},It=["<tool_call>","<function="];function Tt(e){return It.find(n=>e.includes(n))}function Z(e,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${e}" (see catalog parser_defaults)`}function ee(e,n,t){if(!(!e||n>0))return Tt(t)}function Ct(e){if(Array.isArray(e))return e.map(n=>{let t=n.function;return!t||typeof t!="object"?n:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var he=class extends Error{};function Pt(e,n){return Array.isArray(n)?n.map(t=>{let o=t;if(o.type==="text")return{type:e==="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 he(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function Lt(e){let n=[];for(let t of e){if(t.role==="tool"){n.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&&n.push({role:"assistant",content:t.content});for(let o of t.tool_calls){let r=o.function??{};n.push({type:"function_call",call_id:o.id,name:r.name,arguments:r.arguments})}continue}n.push({...t,content:Pt(t.role,t.content)})}return n}function be(e){return ie(e).map((n,t)=>({index:t,id:n.call_id??n.id??`call_${t}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function et(e,n){let t=n?.output_text;return typeof t=="string"?t:e.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function $t(e,n,t,o,r){let s=e.stream===!0,i;try{i=t.thread(e.previous_response_id,e.input)}catch(u){W(o,400,String(u instanceof Error?u.message:u));return}e.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let l=`resp_${Math.random().toString(36).slice(2,14)}`,g=e.store!==!1,d=Ie(e);r.model(d);let p=Array.isArray(e.tools)&&e.tools.length>0,f;try{f=await n.createResponse({model:e.model,input:i,stream:s,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,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}:{}})}catch(u){if(u instanceof q){Ee(o,"openai",u);return}throw u}let m=[];if(s){Oe(o);let u=w=>{o.write(`event: ${String(w.type??"message")}
|
|
9
|
+
data: ${JSON.stringify(w)}
|
|
10
10
|
|
|
11
|
-
`)},
|
|
11
|
+
`)},S=w=>w.response&&typeof w.response=="object"?{...w,response:{...w.response,id:l}}:w,E=`item_${l.slice(5)}`,$=`rs_${l.slice(5)}`,P=!1,N=!1,c=0,x=()=>{P||(P=!0,u({type:"response.created",response:{id:l,object:"response",status:"in_progress"}}))},D=!1,C=0,M="",V=()=>{D&&(D=!1,u({type:"response.reasoning_text.done",item_id:$,output_index:C,content_index:0,text:M}),u({type:"response.output_item.done",output_index:C,item:{id:$,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:M}],status:"completed"}}))},L=!1,v=0,O="",H=w=>{L&&(L=!1,u({type:"response.output_text.done",item_id:E,output_index:v,content_index:0,text:O}),u({type:"response.content_part.done",item_id:E,output_index:v,content_index:0,part:{type:"output_text",text:O}}),u({type:"response.output_item.done",output_index:v,item:{id:E,type:"message",role:"assistant",status:w,content:[{type:"output_text",text:O}]}}))},F=new Y,b=null,X=-1,te=w=>{if(!b)return;let A=b;b=null,u({type:"response.function_call_arguments.done",item_id:A.fcId,output_index:A.outputIndex,arguments:A.args}),u({type:"response.output_item.done",output_index:A.outputIndex,item:{id:A.fcId,type:"function_call",call_id:A.callId??A.fcId,name:A.name??"",arguments:A.args,status:w}})},ne=!1;for await(let w of r.track(f,d)){m.push(w);let A=String(w.type??"");if(A==="response.created"||A==="response.in_progress"){P=!0,u(S(w));continue}if(A==="response.output_item.added"){N=!0,u(S(w));continue}if(A==="response.reasoning_text.delta"&&!N){x(),D||(D=!0,C=c++,u({type:"response.output_item.added",output_index:C,item:{id:$,type:"reasoning",summary:[],content:[],status:"in_progress"}})),M+=String(w.delta??""),u({type:"response.reasoning_text.delta",item_id:$,output_index:C,content_index:0,delta:w.delta});continue}if(A==="response.output_text.delta"&&!N){x(),V(),L||(L=!0,v=c++,u({type:"response.output_item.added",output_index:v,item:{id:E,type:"message",role:"assistant",status:"in_progress",content:[]}}),u({type:"response.content_part.added",item_id:E,output_index:v,content_index:0,part:{type:"output_text",text:""}})),O+=String(w.delta??""),u({type:A,item_id:E,output_index:v,content_index:0,delta:w.delta});continue}let I=N?null:ae(w);if(I){if(x(),V(),H("completed"),F.add(I),I.tool_index!==X){te("completed"),X=I.tool_index;let _=c++;b={fcId:`fc_${l.slice(5)}_${I.tool_index}`,outputIndex:_,callId:I.call_id,name:I.name,args:""},u({type:"response.output_item.added",output_index:_,item:{id:b.fcId,type:"function_call",call_id:b.callId??b.fcId,name:b.name??"",arguments:"",status:"in_progress"}})}b&&(I.call_id&&(b.callId=I.call_id),I.name&&(b.name=I.name),b.args+=I.delta,u({type:"response.function_call_arguments.delta",item_id:b.fcId,output_index:b.outputIndex,delta:I.delta}));continue}if(A==="response.completed"&&!N){let _=ie(w.response),T=ee(p,F.size+_.length,O);if(T){ne=!0,u({type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Z(d,T)}});break}V(),H("completed"),te("completed"),F.size===0&&_.forEach(G=>{let oe=c++,ce=G.id??G.call_id??`fc_${oe}`,we=G.arguments??"",Te={id:ce,type:"function_call",call_id:G.call_id??ce,name:G.name??""};u({type:"response.output_item.added",output_index:oe,item:{...Te,arguments:"",status:"in_progress"}}),u({type:"response.function_call_arguments.delta",item_id:ce,output_index:oe,delta:we}),u({type:"response.function_call_arguments.done",item_id:ce,output_index:oe,arguments:we}),u({type:"response.output_item.done",output_index:oe,item:{...Te,arguments:we,status:"completed"}})}),u(S(w));continue}u(S(w))}V(),H("incomplete"),te("incomplete"),g&&!ne&&t.remember(l,i,et(m,z(m))),o.write(`data: [DONE]
|
|
12
12
|
|
|
13
|
-
`),o.end();return}let
|
|
13
|
+
`),o.end();return}let h=null;for await(let u of r.track(f,d)){if(m.push(u),u.type==="error"){W(o,502,JSON.stringify(u),"upstream_error");return}u.type==="response.completed"&&(h=u.response)}if(h==null){W(o,502,"upstream produced no response.completed event","upstream_error");return}let y=et(m,h),k=ee(p,ie(h).length,y);if(k){W(o,502,Z(d,k),"upstream_error");return}g&&t.remember(l,i,y),U(o,200,{...h,id:l})}async function Nt(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){W(t,400,"chat/completions requires a messages array");return}let s=String(e.model??"urun"),i=`chatcmpl-${Math.random().toString(36).slice(2,14)}`,l;try{l=Lt(r)}catch(c){if(c instanceof he){W(t,400,c.message);return}throw c}let g=Ie(e);o.model(g);let d=Array.isArray(e.tools)&&e.tools.length>0,p;try{p=await n.createResponse({model:e.model,input:l,stream:!0,tools:Ct(e.tools),tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,max_output_tokens:e.max_completion_tokens??e.max_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{}})}catch(c){if(c instanceof q){Ee(t,"openai",c);return}throw c}if(e.stream===!0){Oe(t);let c=[],x=new Y,D="";t.write(`data: ${JSON.stringify(Q(i,s,{role:"assistant"},null))}
|
|
14
14
|
|
|
15
|
-
`);for await(let v of o.track(p,
|
|
15
|
+
`);for await(let v of o.track(p,g)){c.push(v);let O=ae(v);if(v.type==="response.output_text.delta"&&typeof v.delta=="string")D+=v.delta,t.write(`data: ${JSON.stringify(Q(i,s,{content:v.delta},null))}
|
|
16
16
|
|
|
17
17
|
`);else if(v.type==="response.reasoning_text.delta"&&typeof v.delta=="string")t.write(`data: ${JSON.stringify(Q(i,s,{reasoning_content:v.delta},null))}
|
|
18
18
|
|
|
@@ -20,22 +20,22 @@ data: ${JSON.stringify(g)}
|
|
|
20
20
|
|
|
21
21
|
`)}else if(v.type==="error"){t.write(`data: ${JSON.stringify({error:v})}
|
|
22
22
|
|
|
23
|
-
`),t.end();return}}let C=be(
|
|
23
|
+
`),t.end();return}}let C=be(z(c)),M=ee(d,x.size+C.length,D);if(M){t.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Z(g,M)}})}
|
|
24
24
|
|
|
25
25
|
`),t.end();return}x.size===0&&C.length>0&&t.write(`data: ${JSON.stringify(Q(i,s,{tool_calls:C},null))}
|
|
26
26
|
|
|
27
27
|
`);let V=x.size>0||C.length>0;t.write(`data: ${JSON.stringify(Q(i,s,{},V?"tool_calls":"stop"))}
|
|
28
28
|
|
|
29
|
-
`),
|
|
29
|
+
`),ge(z(c))&&t.write(`data: ${JSON.stringify({id:i,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s,choices:[],usage:Ze(z(c))})}
|
|
30
30
|
|
|
31
31
|
`),t.write(`data: [DONE]
|
|
32
32
|
|
|
33
|
-
`),t.end();return}let f="",m="",
|
|
33
|
+
`),t.end();return}let f="",m="",h=[],y=new Y;for await(let c of o.track(p,g)){h.push(c),c.type==="response.output_text.delta"&&typeof c.delta=="string"&&(f+=c.delta),c.type==="response.reasoning_text.delta"&&typeof c.delta=="string"&&(m+=c.delta);let x=ae(c);if(x&&y.add(x),c.type==="error"){W(t,502,JSON.stringify(c),"upstream_error");return}}let k=z(h),u=be(k),S=u.length>0?u:be({output:y.items()}),E=ee(d,S.length,f);if(E){W(t,502,Z(g,E),"upstream_error");return}let $=S.map(({index:c,...x})=>x),P={role:"assistant",content:f||null},N=m||nt(k);N&&(P.reasoning_content=N),$.length>0&&(P.tool_calls=$),U(t,200,{id:i,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:s,choices:[{index:0,message:P,finish_reason:$.length>0?"tool_calls":"stop"}],usage:Ze(k)})}function Mt(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>n.type==="text").map(n=>String(n.text??"")).join(""):""}var ue=class extends Error{};function ye(e){return new ue(`unsupported anthropic content block type "${e}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ut(e){if(Array.isArray(e))return e.map(n=>{let t=n;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function Dt(e){if(e==null)return;let n=e.type;if(n==="auto")return"auto";if(n==="none")return"none";if(n==="any")return"required";if(n==="tool")return{type:"function",name:e.name};throw new ue(`unsupported anthropic tool_choice type ${JSON.stringify(String(n))} \u2014 the proxy maps auto, none, any and tool`)}function Vt(e){if(typeof e=="string")return e;if(e==null)return"";if(!Array.isArray(e))throw ye(typeof e);let n="";for(let t of e){let o=String(t.type??"");if(o!=="text")throw ye(`tool_result > ${o}`);n+=String(t.text??"")}return n}function Bt(e){let{role:n,content:t}=e;if(typeof t=="string")return[{role:n,content:t}];if(t==null)return[];if(!Array.isArray(t))throw ye(typeof t);let o=[],r="",s=()=>{r&&(o.push({role:n,content:r}),r="")};for(let i of t){let l=String(i.type??"");if(l==="text")r+=String(i.text??"");else if(l==="tool_use")s(),o.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(l==="tool_result")s(),o.push({type:"function_call_output",call_id:i.tool_use_id,output:Vt(i.content)});else{if(l==="thinking"||l==="redacted_thinking")continue;throw ye(l)}}return s(),o}function Re(e){return ie(e).map((n,t)=>{let o;try{o=JSON.parse(n.arguments||"{}")}catch{throw new Error(`upstream function_call "${n.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:n.call_id??n.id??`toolu_${t}`,name:n.name??"",input:o}})}async function Ht(e,n,t,o){let r=e.messages;if(!Array.isArray(r)){B(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof e.max_tokens!="number"||!Number.isInteger(e.max_tokens)||e.max_tokens<1){B(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(e.top_k!==void 0){B(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(e.stop_sequences!==void 0&&(!Array.isArray(e.stop_sequences)||e.stop_sequences.some(c=>typeof c!="string"))){B(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let s=String(e.model??"urun"),i=`msg_${Math.random().toString(36).slice(2,14)}`,l=[],g;try{e.system&&l.push({role:"system",content:Mt(e.system)});for(let c of r)l.push(...Bt(c));g=Dt(e.tool_choice)}catch(c){if(c instanceof ue){B(t,400,"invalid_request_error",c.message);return}throw c}let d=Ie(e);o.model(d);let p=Array.isArray(e.tools)&&e.tools.length>0,f;try{f=await n.createResponse({model:e.model,input:l,stream:!0,tools:Ut(e.tools),tool_choice:g,temperature:e.temperature,max_output_tokens:e.max_tokens,top_p:e.top_p,stop:e.stop_sequences})}catch(c){if(c instanceof q){Ee(t,"anthropic",c);return}throw c}let m=(c,x)=>{t.destroyed||t.write(`event: ${c}
|
|
34
34
|
data: ${JSON.stringify({type:c,...x})}
|
|
35
35
|
|
|
36
|
-
`)};if(e.stream===!0){let c=o.track(f,d);
|
|
36
|
+
`)};if(e.stream===!0){let c=o.track(f,d);Oe(t),m("message_start",{message:{id:i,type:"message",role:"assistant",content:[],model:s,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let x=0,D="",C=0,M="none",V=()=>M,L=-1,v=-1,O=new Y,H=[],F=()=>{M!=="none"&&(M="none",m("content_block_stop",{index:L}))},b=(_,T)=>{F(),M=_,L=C++,m("content_block_start",{index:L,content_block:T})};for await(let _ of c){if(t.destroyed)break;H.push(_);let T=ae(_);if(_.type==="response.reasoning_text.delta"&&typeof _.delta=="string")V()!=="thinking"&&b("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:L,delta:{type:"thinking_delta",thinking:_.delta}});else if(_.type==="response.output_text.delta"&&typeof _.delta=="string")V()!=="text"&&b("text",{type:"text",text:""}),x+=1,D+=_.delta,m("content_block_delta",{index:L,delta:{type:"text_delta",text:_.delta}});else if(T){let{call:G}=O.add(T);(V()!=="tool"||T.tool_index!==v)&&(v=T.tool_index,b("tool",{type:"tool_use",id:G.id??`call_${T.tool_index}`,name:G.name??"",input:{}})),T.delta&&m("content_block_delta",{index:L,delta:{type:"input_json_delta",partial_json:T.delta}})}else if(_.type==="error"){m("error",{error:{type:"api_error",message:JSON.stringify(_)}}),t.end();return}}if(t.destroyed)return;let X=z(H),te=ie(X),ne=ee(p,O.size+te.length,D);if(ne){m("error",{error:{type:"api_error",message:Z(d,ne)}}),t.end();return}F();let w=[];if(O.size===0)try{w=Re(X)}catch(_){m("error",{error:{type:"api_error",message:String(_ instanceof Error?_.message:_)}}),t.end();return}C===0&&w.length===0&&(b("text",{type:"text",text:""}),F()),w.forEach(_=>{let T=C++;m("content_block_start",{index:T,content_block:{..._,input:{}}}),m("content_block_delta",{index:T,delta:{type:"input_json_delta",partial_json:JSON.stringify(_.input??{})}}),m("content_block_stop",{index:T})});let A=O.size>0||w.length>0,I=ge(X);m("message_delta",{delta:{stop_reason:A?"tool_use":"end_turn"},usage:I?{input_tokens:I.input_tokens,output_tokens:I.output_tokens}:{output_tokens:x}}),m("message_stop",{}),t.end();return}let h="",y="",k=[],u=new Y;for await(let c of o.track(f,d)){k.push(c),c.type==="response.output_text.delta"&&typeof c.delta=="string"&&(h+=c.delta),c.type==="response.reasoning_text.delta"&&typeof c.delta=="string"&&(y+=c.delta);let x=ae(c);if(x&&u.add(x),c.type==="error"){B(t,502,"api_error",JSON.stringify(c));return}if(t.destroyed)break}if(t.destroyed)return;let S=z(k),E;try{E=Re(S),E.length===0&&u.size>0&&(E=Re({output:u.items()}))}catch(c){B(t,502,"api_error",String(c instanceof Error?c.message:c));return}let $=ee(p,E.length,h);if($){B(t,502,"api_error",Z(d,$));return}let P=[],N=y||nt(S);N&&P.push({type:"thinking",thinking:N}),(h||E.length===0)&&P.push({type:"text",text:h}),P.push(...E),U(t,200,{id:i,type:"message",role:"assistant",content:P,model:s,stop_reason:E.length>0?"tool_use":"end_turn",usage:ge(S)??{input_tokens:0,output_tokens:0}})}function Ft(e){let{clients:n,apiKey:t,identity:o,statusOf:r}=e,s=typeof n=="function"?n:()=>n,i=new WeakMap,l=d=>{let p=i.get(d);return p||(p=new Se,i.set(d,p)),p},g=new Ae;return(d,p)=>{let f=new URL(d.url??"/","http://localhost"),m=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),h=(y,k,u,S)=>m?B(p,y,S,k):W(p,y,k,u);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){U(p,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){U(p,200,o?{identity:o,...g.snapshot()}:g.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let y=await s(d);if(d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){if(!y.openRouterModels){h(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}U(p,200,await y.openRouterModels());return}U(p,200,await y.listModels());return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let k;try{k=await St(d)}catch(S){if(S instanceof me){h(413,S.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let u=Buffer.byteLength(JSON.stringify(k));if(f.pathname==="/v1/responses"){g.request("responses",u,u),await $t(k,y,l(y),p,g);return}if(f.pathname==="/v1/chat/completions"){g.request("chat_completions",u,u),await Nt(k,y,p,g);return}if(f.pathname==="/v1/messages"){g.request("messages",u,u),await Ht(k,y,p,g);return}if(f.pathname==="/v1/messages/count_tokens"){g.request("count_tokens",u,u),B(p,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}h(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(y=>{let k=String(y instanceof Error?y.message:y);if(!p.headersSent){let u=r?.(y)??null;if(u){h(u.status,k,u.openaiType,u.anthropicType);return}h(500,k,"proxy_error","api_error");return}p.destroyed||(m?p.write(`event: error
|
|
37
37
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:k}})}
|
|
38
38
|
|
|
39
39
|
`):p.write(`data: ${JSON.stringify({error:{message:k,type:"upstream_error"}})}
|
|
40
40
|
|
|
41
|
-
`)),p.end()})}}function ot(e){let{clients:n,apiKey:t}=e,o=(0,tt.createServer)(
|
|
41
|
+
`)),p.end()})}}function ot(e){let{clients:n,apiKey:t}=e,o=(0,tt.createServer)(Ft(e));return Xe(o,{clients:n,apiKey:t}),o}0&&(module.exports={GEMINI_LIVE_PATH,VIDEO_OUT_SETUP_KEY,createOpenAIProxy});
|
package/dist/proxy/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { O as OpenAIProxyOptions, P as ProxyClients, a as ProxyIdentity, b as ProxyVideoOutLane, c as createOpenAIProxy } from '../server-
|
|
1
|
+
export { O as OpenAIProxyOptions, P as ProxyClients, a as ProxyIdentity, b as ProxyVideoOutLane, c as createOpenAIProxy } from '../server-wmUnMewW.cjs';
|
|
2
2
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CcDBEfvm.cjs';
|
|
3
3
|
import 'node:http';
|
|
4
4
|
import '../video-out-D20UuJ8G.cjs';
|
package/dist/proxy/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { O as OpenAIProxyOptions, P as ProxyClients, a as ProxyIdentity, b as ProxyVideoOutLane, c as createOpenAIProxy } from '../server-
|
|
1
|
+
export { O as OpenAIProxyOptions, P as ProxyClients, a as ProxyIdentity, b as ProxyVideoOutLane, c as createOpenAIProxy } from '../server-DuH_5OD9.js';
|
|
2
2
|
export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-C9uPKypK.js';
|
|
3
3
|
import 'node:http';
|
|
4
4
|
import '../video-out-CWesbk12.js';
|
package/dist/proxy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as t}from"../chunk-
|
|
1
|
+
import{b as t}from"../chunk-VNM4M4P3.js";import"../chunk-4MSBS7M6.js";import{a as r,h as o}from"../chunk-5NXM4IO3.js";import"../chunk-CWJRDBDC.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{r as GEMINI_LIVE_PATH,o as VIDEO_OUT_SETUP_KEY,t as createOpenAIProxy};
|
|
@@ -79,6 +79,12 @@ interface ProxyClients {
|
|
|
79
79
|
createResponse(params: ResponsesCreateParams): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
|
|
80
80
|
/** `listModels(...)` result (an OpenAI model list object). */
|
|
81
81
|
listModels(): Promise<unknown>;
|
|
82
|
+
/**
|
|
83
|
+
* The OpenRouter provider document (`GET /v1/models?format=openrouter`).
|
|
84
|
+
* Optional at the seam: hand-built test clients may omit it, in which case
|
|
85
|
+
* the format=openrouter branch answers 501 — loud, never a silent empty.
|
|
86
|
+
*/
|
|
87
|
+
openRouterModels?(): Promise<unknown>;
|
|
82
88
|
/**
|
|
83
89
|
* Open (or reuse) the NATIVE audio lanes on the pooled session `model` routes
|
|
84
90
|
* to — the same first-party machinery as RealtimeClient.enableAudio
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/openai",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.4",
|
|
4
4
|
"description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
|
-
"@urun-sh/core": "^0.5.
|
|
73
|
+
"@urun-sh/core": "^0.5.4"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"openai": "4.104.0",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"esbuild": "^0.28.1",
|
|
87
87
|
"reflect-metadata": "^0.2.2",
|
|
88
88
|
"tsup": "^8.5.0",
|
|
89
|
-
"vitest": "^
|
|
89
|
+
"vitest": "^4.1.11",
|
|
90
90
|
"werift": "^0.23.0",
|
|
91
91
|
"opusscript": "^0.1.1",
|
|
92
92
|
"happy-dom": "^20.9.0",
|
package/dist/chunk-F2TEK34X.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as o}from"./chunk-YSFSRI3D.js";o();async function r(t){let e=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!e.ok)throw new Error(`model_catalog fetch failed: ${e.status}`);return await e.json()}async function l(t){return{object:"list",data:(await r(t)).map(e=>({id:`${e.model_id}:${e.variant}`,object:"model",created:0,owned_by:"urun"}))}}export{r as a,l as b};
|
package/dist/chunk-TE6632EU.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{a as b}from"./chunk-F2TEK34X.js";import{a as E}from"./chunk-G3NMGP4N.js";import{a as R,c as h,d as P,e as _}from"./chunk-XHIIEA6Z.js";import{c as x,f as v,g as S,p as U}from"./chunk-CWJRDBDC.js";import{c as l}from"./chunk-YSFSRI3D.js";l();import{App as O,createClientToken as B}from"@urun-sh/core";l();function j(e){let n=e?.type;return n==="response.created"||n==="response.in_progress"}function D(e){let n=e?.type;return n==="response.completed"||n==="error"}function k(e){return async function(t){return(async function*(){for(let a=1;a<=2;a++){let{app:s,entry:r}=await e.sessionFor(t.model),i=!1,u=!1;try{let c=await e.createStream(r,t);for await(let d of c){if(D(d)&&(i=!0),j(d)){if(a>1)continue}else u=!0;yield d}}catch(c){if(a<2&&!u){await e.evict(s,r);continue}throw c}if(i)return;if(a<2&&!u){await e.evict(s,r);continue}return}})()}}l();var M=3,F="llm",W=new Set(["paused","error"]);function A(e,n){let t=e.doc(F),o=typeof t.onConnectionState=="function",a=typeof e.onPhase=="function";if(!o&&!a)throw new Error(`session for app "${n}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,r=new Set,i=[],u=c=>{if(!s){s=c;for(let d of[...r])d(c);r.clear()}};return o&&i.push(t.onConnectionState(c=>{c.consecutiveFailures<M||u(new h(`the pooled session for app "${n}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`))})),a&&i.push(e.onPhase(c=>{W.has(c.name)&&u(new h(`the pooled session for app "${n}" 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),()=>{}):(r.add(c),()=>r.delete(c))},dispose(){r.clear();for(let c of i.splice(0))c()}}}async function*g(e,n){let t=n.gone();if(t)throw t;let o=e[Symbol.asyncIterator](),a,s=new Promise((r,i)=>{a=n.onGone(u=>i(u))});s.catch(()=>{});try{for(;;){let r=await Promise.race([o.next(),s]);if(r.done)return;yield r.value}}finally{a?.(),o.return?.(void 0)}}function N(e,n,t){let o=e[t];if(typeof o!="function")throw new Error(`app "${n}" has no function "${t}" (set URUN_FUNCTION)`);let a=o();if(typeof a.end!="function")throw new Error(`app "${n}" function "${t}" returned a session without end()`);return a}function H(e,n){let{baseUrl:t,orgId:o,fnName:a,auth:s,subject:r}=e,i=p=>({session:p,responses:new E(p),gone:A(p,n)});if(s.lane==="jwt"){let p=O(n,{baseUrl:t,orgId:o,jwt:s.jwt});return i(N(p,n,a))}let{apiKey:u,gatewayUrl:c}=s,d=O(n,{baseUrl:t,orgId:o,getAccessToken:async()=>(await B(u,{baseUrl:c,expiresIn:300,allowedFunctions:[`${n}/${a}`],...r===void 0?{}:{subject:r}})).token});return i(N(d,n,a))}function K(e){let n=e.session.id;if(typeof n!="string"||n.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return n}var q=new Set(["error","paused"]);function xe(e){let{auth:n,catalog:t}=e,o=null,a=r=>{let i=H(e,r);return i.gone.onGone(()=>{o?.evict(r,i)}),i},s=new _({defaultApp:e.defaultApp,fnName:e.fnName,openSession:a,closeSession:async r=>{r.gone.dispose(),await r.session.end()},listApps:n.lane==="api-key"?()=>P({apiUrl:e.apiUrl,apiKey:n.apiKey}):null,listCatalog:t?()=>b(t):null,sessionKey:K});return o=s,e.defaultApp!==null&&s.seed(e.defaultApp,a(e.defaultApp)),s}function ve(e,n=S){let t=new WeakMap,o=new WeakMap,a=new WeakMap;return{createResponse:k({sessionFor:s=>e.sessionFor(s),evict:(s,r)=>e.evict(s,r),createStream:async(s,r)=>g(await s.responses.responses.create(r),s.gone)}),listModels:()=>e.modelList(),openAudio:async s=>{let{entry:r}=await e.sessionFor(s),i=t.get(r);return i||(i=(async()=>x(r.session,await n()))(),t.set(r,i),i.catch(()=>t.delete(r))),i},openVideo:async s=>{let{entry:r}=await e.sessionFor(s),i=o.get(r);return i||(i=v(r.session),o.set(r,i)),i},openVideoOut:async s=>{let{entry:r}=await e.sessionFor(s),i=a.get(r);return i||(i=U(r.session),a.set(r,i)),i},sessionHandle:async s=>(await e.handleFor(s)).handle,createResponseOn:async(s,r)=>{let{entry:i}=await e.sessionForHandle(s);return g(await i.responses.responses.create(r),i.gone)},onSessionEnd:async(s,r)=>{let{entry:i}=await e.sessionForHandle(s),u=i.session;if(typeof u.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let c=!1;return u.onPhase(d=>{if(c||!q.has(d.name))return;c=!0;let p=u.endsAt??null;r({timeLeftMs:p?Math.max(0,p.getTime()-Date.now()):null,reason:d.reason??`session ${d.name}`})})}}}l();import V from"os";import J from"path";import{fileURLToPath as X}from"url";import{format as z}from"util";var I="0.5.2";var C=4141,Q=I,Oe={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 Z(e,n="openai"){if(n==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Ne(e,n,t){let o={...e,...Z(n,t)};return delete o.URUN_API_KEY,delete o.URUN_JWT,o}function Ie(e,n,t){let o=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],a=t.indexOf("--"),s=a===-1?t:t.slice(0,a),r=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=t[0]==="exec",u=s.includes("--skip-git-repo-check"),c=i&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...o,...r?[]:["-m",n],...c]}function $e(e,n){return n.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?n:["--provider","urun","--model",e,...n]}function Ce(e,n){return n.some(o=>o==="--model"||o==="--provider"||o.startsWith("--model=")||o.startsWith("--provider="))?n:["--model",`urun/${e}`,...n]}function Te(e,n,t){let o=(e.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 a=X(new URL("../pi-extension/standalone.cjs",n));if(!t(a))throw new Error(`pi extension entry not found at ${a} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return a}function T(e){let n=Number(e);if(!Number.isInteger(n)||n<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return n}function Ge(e){if(e[0]!=="--port")return null;let n=T(e[1]);return e.splice(0,2),n}function Le(e){let n=e.indexOf("--port");if(n===-1)return C;let t=T(e[n+1]);return e.splice(n,2),t}function je(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function y(e,n){let t=(e[n]??"").trim();if(!t)throw new Error(`${n} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return t}function De(e){let n=ee(y(e,"URUN_BASE_URL")),t=y(e,"URUN_ORG_ID"),o=y(e,"URUN_APP"),a=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),r=s?$(s,"URUN_API_URL"):R,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:n,orgId:t,appId:o,fnName:a,apiUrl:r,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let c=(e.URUN_GATEWAY_URL??"").trim(),d=c?$(c):void 0;return{baseUrl:n,orgId:t,appId:o,fnName:a,apiUrl:r,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function ee(e,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${n} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function $(e,n="URUN_GATEWAY_URL"){let t=new URL(e),o=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!o)throw new Error(`${n} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Me(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:Q}}function ne(e,n){return e.app===n.app&&e.org===n.org&&e.fn===n.fn&&e.base_url===n.base_url&&e.proxy_version===n.proxy_version}var te=250;async function oe(e,n=te){try{let t=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(n)});if(!t.ok)return null;let o=(await t.json()).identity;if(o==null||typeof o!="object")return null;let{app:a,org:s,fn:r,base_url:i,proxy_version:u}=o;return typeof a!="string"||typeof s!="string"||typeof r!="string"||typeof i!="string"||typeof u!="string"?null:{app:a,org:s,fn:r,base_url:i,proxy_version:u}}catch{return null}}var G=2e3;async function re(e,n=G){try{let t=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(n)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function Fe(e,n,t=C,o=G){if(e!=null)return{mode:"spawn",port:e};let a=await oe(t);if(a!==null&&ne(a,n)){let s=await re(t,o);return s===null?{mode:"reuse",port:t,identity:a}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function We(e,n=V.homedir()){return J.join(n,".urun","logs",`compat-proxy-${e}.log`)}var w=["log","info","warn","error","debug","trace"];function Be(e,n=process,t=console){let o=n.stdout.write,a=n.stderr.write,s=(i,...u)=>e.write(i,...u);n.stdout.write=s,n.stderr.write=s;let r=Object.fromEntries(w.map(i=>[i,t[i]]));for(let i of w)t[i]=(...u)=>{e.write(`${z(...u)}
|
|
2
|
-
`)};return()=>{n.stdout.write=o,n.stderr.write=a;for(let i of w)t[i]=r[i]}}var se=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function L(e){let n=e?.code;return typeof n=="string"&&se.has(n)}function He(e,n){try{return e.write(n),!0}catch(t){if(L(t))return!1;throw t}}function Ke(e){let n={stdout:!1,stderr:!1},t=[];for(let o of["stdout","stderr"]){let a=e.streams[o],s=r=>{L(r)&&(n[o]=!0);let i=r?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${o} died (${String(i??(r instanceof Error?r.message:r))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
3
|
-
`)}catch{}};a.on("error",s),t.push([a,s])}return{isDead:o=>n[o],uninstall:()=>{for(let[o,a]of t)o.off("error",a)}}}function qe(e){let n=t=>{let o=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${o}
|
|
4
|
-
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
|
5
|
-
`)}catch(a){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(a?.code??a)}) \u2014 the terminal is gone
|
|
6
|
-
`)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",n),e.proc.on("unhandledRejection",n),()=>{e.proc.off("uncaughtException",n),e.proc.off("unhandledRejection",n)}}function Ye(e,n){let t="pass --port 0 for an OS-assigned ephemeral port";return n?`port ${e} is held by another urun-openai proxy serving app ${n.app} (org ${n.org}, fn ${n.fn}, version ${n.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${t}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${t}`}export{xe as a,ve as b,Oe as c,Z as d,Ne as e,Ie as f,$e as g,Ce as h,Te as i,Ge as j,Le as k,je as l,De as m,ee as n,$ as o,Me as p,oe as q,Fe as r,We as s,Be as t,He as u,Ke as v,qe as w,Ye as x};
|
package/dist/chunk-UVAY7Q7Z.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as a}from"./chunk-YSFSRI3D.js";a();function g(e,n,r,t){let o=e.response??{},i={request_id:r,consumer_id:t,stream:!0,kind:"chat",messages:n};return typeof o.instructions=="string"&&(i.instructions=o.instructions),Array.isArray(o.modalities)&&(i.modalities=o.modalities),typeof o.temperature=="number"&&(i.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(i.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(i.tools=o.tools),i}function _(e,n,r){let t={request_id:n,consumer_id:r,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(t.model=e.model),e.tools!==void 0&&(t.tools=e.tools),e.tool_choice!==void 0&&(t.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(t.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(t.max_output_tokens=e.max_output_tokens),typeof e.reasoning_effort=="string"&&(t.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(t.chat_template_kwargs=e.chat_template_kwargs),t}a();function f(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 n=e,r=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:r.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}a();var k="llm-resp";async function*d(e,n){let r=`${k}:${n}`,t=`resp_${n}`;yield{type:"response.created",response:{id:t,status:"in_progress"}};let o=new Map;for await(let i of e.stream(r).messages()){let s=i;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:t,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:t,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let u of s.tool_calls){let c=typeof u.index=="number"?u.index:0,p=o.get(c)??{};u.id&&(p.id=u.id),u.function?.name&&(p.name=u.function.name),o.set(c,p),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${c}`,tool_index:c,call_id:p.id,name:p.name,delta:u.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:t,status:"completed",...s.body}};return}else if(s.t==="error"){yield f(s);return}}}a();var w="llm",y=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(w).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,r){let t=_(n,r,this.consumerId);return this.write(t),d(this.session,r)}sendResponseCreate(n,r,t){let o=g(n,r,t,this.consumerId);return this.write(o),d(this.session,t)}};export{g as a,_ as b,f as c,d,y as e};
|
package/dist/chunk-XHIIEA6Z.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as f}from"./chunk-YSFSRI3D.js";f();var A="https://api.urun.sh/v1";function c(o){return o.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var p=class extends Error{},l=class extends Error{},u="urs1.";function y(o,t){return u+Buffer.from(JSON.stringify([o,t]),"utf8").toString("base64url")}function m(o){if(!o.startsWith(u))return null;try{let t=JSON.parse(Buffer.from(o.slice(u.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 $(o){let t=o.fetchImpl??fetch,e=`${o.apiUrl.replace(/\/+$/,"")}/apps`,s=await t(e,{headers:{Authorization:`Bearer ${o.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${e} \u2192 ${s.status}`);let n=await s.json();if(!Array.isArray(n.apps))throw new Error(`org apps listing returned no "apps" array (GET ${e})`);if(n.truncated===!0)throw new Error(`org apps listing was truncated (GET ${e} returned ${n.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return n.apps}var w=6e4,g=class{constructor(t){this.opts=t}opts;pool=new Map;appsCache=null;seed(t,e){this.pool.set(t,Promise.resolve(e))}async deployedApps(){if(!this.opts.listApps)return[];let t=this.opts.appsTtlMs??w;if(this.appsCache&&Date.now()-this.appsCache.at<t)return this.appsCache.apps;let e=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:e},e}servable(t){return t.filter(e=>e.function_name===this.opts.fnName&&e.deployment_status==="active").map(e=>e.app_slug)}async availableIds(){let t=this.opts.defaultApp,e=new Set(t===null?[]:[t]);if(this.opts.listApps)for(let n of this.servable(await this.deployedApps()))e.add(n);for(let n of this.pool.keys())e.add(n);let s=[...e].filter(n=>n!==t).sort();return t===null?s:[t,...s]}async noDefaultApp(t){let e=await this.availableIds(),s=e.length>0?e.join(", "):"(none deployed)";throw new p(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: ${s}`:`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: ${s}`)}async resolveApp(t){let e=(t??"").trim(),s=this.opts.defaultApp;if(!e||e==="urun")return s===null?this.noDefaultApp(e):s;let n=c(e);if(n===s)return s;if(this.pool.has(n))return n;if(this.opts.listApps){let a=await this.deployedApps(),r=this.servable(a);if(r.includes(n))return n;let i=r.filter(d=>d.startsWith(`${n}-`));if(i.length===1)return i[0];if(i.length>1)throw new p(`model "${e}" is ambiguous across deployed apps ${i.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let h=a.find(d=>d.app_slug===n||d.app_slug.startsWith(`${n}-`));if(h)throw new p(`model "${e}" maps to app "${h.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${e}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let r=(await this.opts.listCatalog()).find(i=>e===i.model_id||e===`${i.model_id}:${i.variant}`||n===c(i.model_id)||n===c(`${i.model_id}-${i.variant}`));if(r)throw new p(`model "${e}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${r.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return s===null?this.noDefaultApp(e):s}async sessionFor(t){let e=await this.resolveApp(t),s=this.pool.get(e);return s||(s=Promise.resolve(this.opts.openSession(e)),this.pool.set(e,s),s.catch(()=>this.pool.delete(e))),{app:e,entry:await s}}keyOf(t){let e=this.opts.sessionKey;if(!e)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let s=e(t);if(typeof s!="string"||s.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return s}async handleFor(t){let{app:e,entry:s}=await this.sessionFor(t);return{app:e,handle:y(e,this.keyOf(s))}}async sessionForHandle(t){let e=m(t);if(!e)throw new l(`malformed session handle ${JSON.stringify(t)} \u2014 not issued by this proxy`);let{app:s,key:n}=e,a=this.pool.get(s),r=a?await a.then(i=>i,()=>null):null;if(r===null)throw new l(`the session behind this handle (app "${s}") 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(r)!==n)throw new l(`the session behind this handle (app "${s}") 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:s,entry:r}}async evict(t,e){let s=this.pool.get(t);!s||await s.then(a=>a,()=>null)!==e||this.pool.get(t)!==s||(this.pool.delete(t),await this.opts.closeSession(e).catch(()=>{}))}async modelList(){return{object:"list",data:(await this.availableIds()).map(e=>({id:e,object:"model",created:0,owned_by:"urun"}))}}async closeAll(){let t=[...this.pool.values()];this.pool.clear();let e=[];if(await Promise.all(t.map(async s=>{try{await this.opts.closeSession(await s)}catch(n){e.push(String(n instanceof Error?n.message:n))}})),e.length>0)throw new Error(`failed to close ${e.length} pooled session(s): ${e.join("; ")}`)}};export{A as a,p as b,l as c,$ as d,g as e};
|