@urun-sh/openai 0.6.38 → 0.6.40

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.
Files changed (44) hide show
  1. package/dist/{chunk-B26FENQ3.js → chunk-BWYY4IPR.js} +1 -1
  2. package/dist/chunk-G5VRFFBE.js +64 -0
  3. package/dist/chunk-G7CSAISC.js +1 -0
  4. package/dist/{chunk-7AI75MPZ.js → chunk-HPUX2H65.js} +6 -6
  5. package/dist/{chunk-5MH6NSR2.js → chunk-L4QBHSVY.js} +1 -1
  6. package/dist/chunk-L6CT7ZVO.js +23 -0
  7. package/dist/chunk-PT5N7AY7.js +2 -0
  8. package/dist/{chunk-3JWYIKHM.js → chunk-QTHFMDZY.js} +1 -1
  9. package/dist/chunk-Z3QCHKJB.js +1 -0
  10. package/dist/{composite-ClDE3ViI.d.ts → composite-B--rGI5m.d.ts} +8 -2
  11. package/dist/{composite-F94H40CD.d.cts → composite-B-F2J0NK.d.cts} +40 -2
  12. package/dist/gemini-live.cjs +2 -2
  13. package/dist/gemini-live.d.cts +2 -2
  14. package/dist/gemini-live.d.ts +2 -2
  15. package/dist/gemini-live.js +1 -1
  16. package/dist/hosted/bin.cjs +48 -48
  17. package/dist/hosted/bin.js +1 -1
  18. package/dist/hosted/index.cjs +46 -46
  19. package/dist/hosted/index.d.cts +3 -3
  20. package/dist/hosted/index.d.ts +3 -3
  21. package/dist/hosted/index.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/pi-extension/index.js +1 -1
  27. package/dist/pi-extension/standalone.cjs +55 -55
  28. package/dist/pooler/bin.cjs +7 -7
  29. package/dist/pooler/bin.js +25 -25
  30. package/dist/proxy/cli.cjs +51 -51
  31. package/dist/proxy/cli.js +1 -1
  32. package/dist/proxy/index.cjs +26 -26
  33. package/dist/proxy/index.d.cts +35 -5
  34. package/dist/proxy/index.d.ts +11 -5
  35. package/dist/proxy/index.js +1 -1
  36. package/dist/{translator-Ddd65sXR.d.ts → translator-BqpmZ-vh.d.ts} +1 -1
  37. package/dist/{translator-CO8W_hmJ.d.cts → translator-Dox25ky9.d.cts} +1 -1
  38. package/dist/{video-out-BsuLqlID.d.cts → video-out-DnCKUUO2.d.cts} +13 -0
  39. package/dist/{video-out-Cawtm7SF.d.ts → video-out-REmiQMBJ.d.ts} +7 -0
  40. package/package.json +3 -3
  41. package/dist/chunk-6M5JK4YC.js +0 -1
  42. package/dist/chunk-UQV3ZXCW.js +0 -2
  43. package/dist/chunk-YOFTYCYH.js +0 -64
  44. package/dist/chunk-ZA2LMA3I.js +0 -23
@@ -1,12 +1,12 @@
1
1
  import { Server } from 'node:http';
2
- import { c as LedgerOutcome, I as InferenceRecord, i as RouteTarget, S as SessionGoneError, k as billingIdentityOf, P as ProxyClients, M as ModelRouter, j as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, R as RealtimeCompanionsFor } from '../composite-F94H40CD.cjs';
2
+ import { c as LedgerOutcome, I as InferenceRecord, j as RouteTarget, S as SessionGoneError, l as billingIdentityOf, P as ProxyClients, M as ModelRouter, k as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, R as RealtimeCompanionsFor } from '../composite-B-F2J0NK.cjs';
3
3
  import * as _prometheus_io_client from '@prometheus-io/client';
4
4
  import { Registry } from '@prometheus-io/client';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
6
6
  import { U as UrunResponses } from '../ResponsesClient-6QsC7NPJ.cjs';
7
7
  import { b as UrunSessionLike } from '../types-CHPtJx6d.cjs';
8
8
  import { C as CatalogRow } from '../models-D7F0bLJ3.cjs';
9
- import '../video-out-BsuLqlID.cjs';
9
+ import '../video-out-DnCKUUO2.cjs';
10
10
 
11
11
  /**
12
12
  * The container's metrics port — a MODULE CONSTANT, not an env var, per the
@@ -905,7 +905,7 @@ declare class ConversationBackhauls {
905
905
  * immediately and its resume metadata is retained — no resource keepalive,
906
906
  * no resume loss.
907
907
  */
908
- connectionFor(caller: CallerIdentity): PrivateConversationConnection;
908
+ connectionFor(caller: CallerIdentity, explicitSessionId?: string): PrivateConversationConnection;
909
909
  /**
910
910
  * Drain-time LOCAL release: detach every conversation's sessions (native
911
911
  * detach — the named sessions pause server-side, nothing is ended). Handles
@@ -1,12 +1,12 @@
1
1
  import { Server } from 'node:http';
2
- import { c as LedgerOutcome, I as InferenceRecord, i as RouteTarget, S as SessionGoneError, k as billingIdentityOf, P as ProxyClients, M as ModelRouter, j as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, R as RealtimeCompanionsFor } from '../composite-ClDE3ViI.js';
2
+ import { c as LedgerOutcome, I as InferenceRecord, j as RouteTarget, S as SessionGoneError, l as billingIdentityOf, P as ProxyClients, M as ModelRouter, k as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, R as RealtimeCompanionsFor } from '../composite-B--rGI5m.js';
3
3
  import * as _prometheus_io_client from '@prometheus-io/client';
4
4
  import { Registry } from '@prometheus-io/client';
5
5
  import { createClientToken, SessionPhaseName } from '@urun-sh/core';
6
6
  import { U as UrunResponses } from '../ResponsesClient-gfg7qUoE.js';
7
7
  import { b as UrunSessionLike } from '../types-CHPtJx6d.js';
8
8
  import { C as CatalogRow } from '../models-D7F0bLJ3.js';
9
- import '../video-out-Cawtm7SF.js';
9
+ import '../video-out-REmiQMBJ.js';
10
10
 
11
11
  declare const METRICS_PORT = 9464;
12
12
 
@@ -390,7 +390,7 @@ declare class ConversationBackhauls {
390
390
  private evictOverflow;
391
391
  private dropHandleIndexFor;
392
392
 
393
- connectionFor(caller: CallerIdentity): PrivateConversationConnection;
393
+ connectionFor(caller: CallerIdentity, explicitSessionId?: string): PrivateConversationConnection;
394
394
 
395
395
  detachAll(): Promise<void>;
396
396
  }
@@ -1 +1 @@
1
- import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-ZA2LMA3I.js";import"../chunk-UQV3ZXCW.js";import"../chunk-CAR4AEQJ.js";import"../chunk-YOFTYCYH.js";import"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-5MH6NSR2.js";import"../chunk-B26FENQ3.js";import"../chunk-KKCUIOL4.js";import"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import"../chunk-7AI75MPZ.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
1
+ import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-L6CT7ZVO.js";import"../chunk-PT5N7AY7.js";import"../chunk-CAR4AEQJ.js";import"../chunk-G5VRFFBE.js";import"../chunk-QTHFMDZY.js";import"../chunk-Z3QCHKJB.js";import"../chunk-G7CSAISC.js";import"../chunk-L4QBHSVY.js";import"../chunk-BWYY4IPR.js";import"../chunk-KKCUIOL4.js";import"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import"../chunk-HPUX2H65.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var X=Object.create;var h=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty;var re=(e,t)=>{for(var n in t)h(e,n,{get:t[n],enumerable:!0})},L=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ee(t))!ne.call(e,o)&&o!==n&&h(e,o,{get:()=>t[o],enumerable:!(r=Z(t,o))||r.enumerable});return e};var S=(e,t,n)=>(n=e!=null?X(te(e)):{},L(t||!e||!e.__esModule?h(n,"default",{value:e,enumerable:!0}):n,e)),oe=e=>L(h({},"__esModule",{value:!0}),e);var ye={};re(ye,{RT_VIDEO_OUT_STREAM:()=>y,SUPPORTED_REALTIME_CLIENT_EVENTS:()=>T,SUPPORTED_RESPONSES_EVENTS:()=>x,UrunRealtime:()=>k,UrunResponses:()=>v,VIDEO_OUT_DEFAULT_CODEC:()=>b,VIDEO_OUT_FRAMING:()=>R,VIDEO_OUT_WS_FRAMING:()=>F,consumeVideoOut:()=>G,decodeVideoOutRecord:()=>E,encodeVideoOutRecord:()=>H,isSupportedClientEvent:()=>Y,isSupportedResponsesEvent:()=>J,listModels:()=>N,negotiateSessionVideoOutQuic:()=>q,nodeAudioBackend:()=>C,openSessionVideoOutLane:()=>j,toErrorEvent:()=>m,weriftAudioBackend:()=>M});module.exports=oe(ye);async function I(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let r;await new Promise((o,s)=>{let a=e.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{a(),s(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}function U(e,t,n,r){let o=e.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:t};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function V(e,t,n){let r={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(r.model=e.model),e.tools!==void 0&&(r.tools=e.tools),e.tool_choice!==void 0&&(r.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(r.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(r.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(r.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(r.stop=e.stop),typeof e.reasoning_effort=="string"&&(r.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(r.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(r.response_format=e.response_format),typeof e.voice=="string"&&(r.voice=e.voice),typeof e.language=="string"&&(r.language=e.language),r}function m(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:t.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var se="llm-resp";async function*ie(e,t){let n=`resp_${e}`,r=new Map;for await(let o of t){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let u=typeof a.index=="number"?a.index:0,i=r.get(u)??{};a.id&&(i.id=a.id),a.function?.name&&(i.name=a.function.name),r.set(u,i),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:i.id,name:i.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield m(s);return}}}async function*O(e,t){let n=`${se}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*ie(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var g=class{constructor(t,n=15e3,r){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?t.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let r=V(t,n,this.consumerId);return this.write(r),O(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=U(t,n,r,this.consumerId);return this.write(o),O(this.session,r)})}async writeGated(t,n){try{await I(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var D="audio",A=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function P(e,t,n=1e4){let r=new A(t,{sampleRate:24e3}),o=await r.startOutbound();await e.stream(D).attach(o);let s=await de(e,n);return await r.startInbound(s),r}function de(e,t){let n=e.stream(D);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,a=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),u=i=>{i!=null&&(clearTimeout(a),s?.(),r(i))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var ue=24e3,w=480,ce=111;async function pe(){let e=await import("opusscript"),t=e.default??e;return new t(ue,1,2048)}async function M(){let e=await import("werift"),t=await pe();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:u=>{let i=new Int16Array(a.length+u.length);i.set(a,0),i.set(u,a.length);let d=0;for(;i.length-d>=w;){let c=i.subarray(d,d+w);d+=w;let l=Buffer.from(c.buffer,c.byteOffset,c.byteLength),K=t.encode(l,w);o=o+1&65535,s=s+w>>>0;let z=new e.RtpHeader({version:2,payloadType:ce,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),Q=new e.RtpPacket(z,K);n.writeRtp(Q)}a=i.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let a;try{a=t.decode(s.payload)}catch{return}let u=new Int16Array(a.length/2);for(let i=0;i<u.length;i++)u[i]=a.readInt16LE(i*2);r.onframe?.({samples:u})}),r}}}async function C(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:r=>t.onData({samples:r,sampleRate:24e3})}},createSink:t=>{let n={onframe:null},r=new e.nonstandard.RTCAudioSink(t);return r.ondata=o=>{n.onframe?.(o)},n}}}var B=0;function le(){return B+=1,`rt_${Date.now().toString(36)}_${B.toString(36)}`}var k=class{constructor(t,n={}){this.session=t;this.opts=n;this.transport=new g(t)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await P(this.session,this.opts.audioBackend),this.audio.onOutputAudio(t=>this.emit({type:"response.audio.delta",delta:t}))}on(t,n){return this.handlers.add(n),()=>this.handlers.delete(n)}emit(t){for(let n of this.handlers)n(t)}send(t){switch(t.type){case"conversation.item.create":{let n=(t.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:t.item?.role??"user",content:n});return}case"response.create":{let n=le();this.currentRequestId=n,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:t.response},this.conversation,n);for await(let o of r)this.emit(o)}catch(r){this.emit(m(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(t.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};var $=0;function fe(){return $+=1,`req_${Date.now().toString(36)}_${$.toString(36)}`}var v=class{transport;constructor(t,n){this.transport=new g(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=fe(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function me(e){let n=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}async function N(e){return{object:"list",data:(await me(e)).map(n=>({id:`${n.model_id}:${n.variant}`,object:"model",created:0,owned_by:"urun"}))}}var f=require("@urun-sh/core"),y="rt-video-out",R="urun.videoOut.v1",b="h264";function W(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function H(e,t){if(W(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let r=new Uint8Array(2+n.byteLength+t.byteLength);return r[0]=n.byteLength&255,r[1]=n.byteLength>>8,r.set(n,2),r.set(t,2+n.byteLength),r}function E(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;W(o,"decodeVideoOutRecord");let s=e.subarray(2+t);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}async function q(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await t.call(e),r=n.sessionId??e.sessionId;if(typeof r!="string"||r.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:r,stream:y,codec:b,framing:R}}var F="urun.videoOut.v2-ws";function j(e){let t=e.stream(y);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${y}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=i=>{for(let d of r)d(i)},a=!1,u=async()=>{for await(let i of t.messages()){if(!(i instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${y}" delivered a non-BINARY \xA75 payload (${typeof i}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=E(i)}catch(c){s(c instanceof Error?c:new Error(String(c)));continue}for(let c of n)c(d)}for(let i of o)i()};return{codec:b,onOutputFrame:i=>(n.add(i),a||(a=!0,u().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(i)),onLaneError:i=>(r.add(i),()=>r.delete(i)),onEnd:i=>(o.add(i),()=>o.delete(i))}}function ge(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function G(e,t,n){let r=n??(typeof globalThis.WebTransport=="function"?(d,c)=>new globalThis.WebTransport(d,c):void 0);if(!r)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let o=r(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:ge(d)}))});await o.ready;let s=await o.createBidirectionalStream();await s.writable.getWriter().write((0,f.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=s.readable.getReader(),u=new f.WtControlDecoder,i=!1;for(;!i;){let{value:d,done:c}=await a.read();if(c)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let l of u.push(d)){if(l.t==="hello-ack"){i=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(l.t)} before hello-ack)`)}}await(0,f.consumeWtDataStreams)(o.incomingUnidirectionalStreams,{onData:(d,c)=>{if(d===e.stream){if(c===f.STREAM_END){t.onEnd?.();return}if(!(c instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(E(c))}catch(l){t.onLaneError(l instanceof Error?l:new Error(String(l)))}}},onLaneError:d=>t.onLaneError(d)})}var T=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],x=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function Y(e){return T.includes(e)}function J(e){return x.includes(e)}0&&(module.exports={RT_VIDEO_OUT_STREAM,SUPPORTED_REALTIME_CLIENT_EVENTS,SUPPORTED_RESPONSES_EVENTS,UrunRealtime,UrunResponses,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeVideoOutRecord,encodeVideoOutRecord,isSupportedClientEvent,isSupportedResponsesEvent,listModels,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,toErrorEvent,weriftAudioBackend});
1
+ "use strict";var X=Object.create;var h=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty;var re=(e,t)=>{for(var n in t)h(e,n,{get:t[n],enumerable:!0})},L=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ee(t))!ne.call(e,o)&&o!==n&&h(e,o,{get:()=>t[o],enumerable:!(r=Z(t,o))||r.enumerable});return e};var S=(e,t,n)=>(n=e!=null?X(te(e)):{},L(t||!e||!e.__esModule?h(n,"default",{value:e,enumerable:!0}):n,e)),oe=e=>L(h({},"__esModule",{value:!0}),e);var ye={};re(ye,{RT_VIDEO_OUT_STREAM:()=>y,SUPPORTED_REALTIME_CLIENT_EVENTS:()=>T,SUPPORTED_RESPONSES_EVENTS:()=>x,UrunRealtime:()=>k,UrunResponses:()=>v,VIDEO_OUT_DEFAULT_CODEC:()=>E,VIDEO_OUT_FRAMING:()=>R,VIDEO_OUT_WS_FRAMING:()=>q,consumeVideoOut:()=>G,decodeVideoOutRecord:()=>b,encodeVideoOutRecord:()=>F,isSupportedClientEvent:()=>Y,isSupportedResponsesEvent:()=>J,listModels:()=>N,negotiateSessionVideoOutQuic:()=>H,nodeAudioBackend:()=>M,openSessionVideoOutLane:()=>j,toErrorEvent:()=>f,weriftAudioBackend:()=>C});module.exports=oe(ye);async function I(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let r;await new Promise((o,s)=>{let a=e.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{a(),s(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}function U(e,t,n,r){let o=e.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:t};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function V(e,t,n){let r={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(r.model=e.model),e.tools!==void 0&&(r.tools=e.tools),e.tool_choice!==void 0&&(r.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(r.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(r.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(r.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(r.stop=e.stop),typeof e.reasoning_effort=="string"&&(r.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(r.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(r.response_format=e.response_format),typeof e.voice=="string"&&(r.voice=e.voice),typeof e.language=="string"&&(r.language=e.language),r}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 t=e,n=t.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:t.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var se="llm-resp";async function*ie(e,t){let n=`resp_${e}`,r=new Map;for await(let o of t){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let u=typeof a.index=="number"?a.index:0,i=r.get(u)??{};a.id&&(i.id=a.id),a.function?.name&&(i.name=a.function.name),r.set(u,i),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:i.id,name:i.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield f(s);return}}}async function*O(e,t){let n=`${se}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*ie(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var g=class{constructor(t,n=15e3,r){this.session=t;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?t.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){return this.writeGated(n,()=>{let r=V(t,n,this.consumerId);return this.write(r),O(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=U(t,n,r,this.consumerId);return this.write(o),O(this.session,r)})}async writeGated(t,n){try{await I(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var D="audio",A=class{constructor(t,n){this.backend=t;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(t){this.dataEmit=t}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(t,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(n)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function P(e,t,n=1e4){let r=new A(t,{sampleRate:24e3}),o=await r.startOutbound(),s=e.stream(D);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let a=await de(e,n);return await r.startInbound(a),r}function de(e,t){let n=e.stream(D);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,a=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),u=i=>{i!=null&&(clearTimeout(a),s?.(),r(i))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var ue=24e3,w=480,ce=111;async function le(){let e=await import("opusscript"),t=e.default??e;return new t(ue,1,2048)}async function C(){let e=await import("werift"),t=await le();return{createSource:()=>{let n=new e.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,a=new Int16Array(0);return{track:n,onData:u=>{let i=new Int16Array(a.length+u.length);i.set(a,0),i.set(u,a.length);let d=0;for(;i.length-d>=w;){let c=i.subarray(d,d+w);d+=w;let p=Buffer.from(c.buffer,c.byteOffset,c.byteLength),K=t.encode(p,w);o=o+1&65535,s=s+w>>>0;let z=new e.RtpHeader({version:2,payloadType:ce,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),Q=new e.RtpPacket(z,K);n.writeRtp(Q)}a=i.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let a;try{a=t.decode(s.payload)}catch{return}let u=new Int16Array(a.length/2);for(let i=0;i<u.length;i++)u[i]=a.readInt16LE(i*2);r.onframe?.({samples:u})}),r}}}async function M(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:r=>t.onData({samples:r,sampleRate:24e3})}},createSink:t=>{let n={onframe:null},r=new e.nonstandard.RTCAudioSink(t);return r.ondata=o=>{n.onframe?.(o)},n}}}var B=0;function pe(){return B+=1,`rt_${Date.now().toString(36)}_${B.toString(36)}`}var k=class{constructor(t,n={}){this.session=t;this.opts=n;this.transport=new g(t)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await P(this.session,this.opts.audioBackend),this.audio.onOutputAudio(t=>this.emit({type:"response.audio.delta",delta:t}))}on(t,n){return this.handlers.add(n),()=>this.handlers.delete(n)}emit(t){for(let n of this.handlers)n(t)}send(t){switch(t.type){case"conversation.item.create":{let n=(t.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:t.item?.role??"user",content:n});return}case"response.create":{let n=pe();this.currentRequestId=n,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:t.response},this.conversation,n);for await(let o of r)this.emit(o)}catch(r){this.emit(f(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(t.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};var $=0;function me(){return $+=1,`req_${Date.now().toString(36)}_${$.toString(36)}`}var v=class{transport;constructor(t,n){this.transport=new g(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=me(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function fe(e){let n=await(e.fetchImpl??fetch)(`${e.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}async function N(e){return{object:"list",data:(await fe(e)).map(n=>({id:`${n.model_id}:${n.variant}`,object:"model",created:0,owned_by:"urun"}))}}var m=require("@urun-sh/core"),y="rt-video-out",R="urun.videoOut.v1",E="h264";function W(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function F(e,t){if(W(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let r=new Uint8Array(2+n.byteLength+t.byteLength);return r[0]=n.byteLength&255,r[1]=n.byteLength>>8,r.set(n,2),r.set(t,2+n.byteLength),r}function b(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(a){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(a)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;W(o,"decodeVideoOutRecord");let s=e.subarray(2+t);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}async function H(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await t.call(e),r=n.sessionId??e.sessionId;if(typeof r!="string"||r.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:r,stream:y,codec:E,framing:R}}var q="urun.videoOut.v2-ws";function j(e){let t=e.stream(y);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${y}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=i=>{for(let d of r)d(i)},a=!1,u=async()=>{for await(let i of t.messages()){if(!(i instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${y}" delivered a non-BINARY \xA75 payload (${typeof i}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=b(i)}catch(c){s(c instanceof Error?c:new Error(String(c)));continue}for(let c of n)c(d)}for(let i of o)i()};return{codec:E,onOutputFrame:i=>(n.add(i),a||(a=!0,u().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(i)),onLaneError:i=>(r.add(i),()=>r.delete(i)),onEnd:i=>(o.add(i),()=>o.delete(i))}}function ge(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function G(e,t,n){let r=n??(typeof globalThis.WebTransport=="function"?(d,c)=>new globalThis.WebTransport(d,c):void 0);if(!r)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let o=r(e.url,{serverCertificateHashes:e.certHashes.map(d=>({algorithm:"sha-256",value:ge(d)}))});await o.ready;let s=await o.createBidirectionalStream();await s.writable.getWriter().write((0,m.encodeWtControlFrame)({t:"hello",token:e.token,sessionId:e.sessionId}));let a=s.readable.getReader(),u=new m.WtControlDecoder,i=!1;for(;!i;){let{value:d,done:c}=await a.read();if(c)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let p of u.push(d)){if(p.t==="hello-ack"){i=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(p.t)} before hello-ack)`)}}await(0,m.consumeWtDataStreams)(o.incomingUnidirectionalStreams,{onData:(d,c)=>{if(d===e.stream){if(c===m.STREAM_END){t.onEnd?.();return}if(!(c instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(b(c))}catch(p){t.onLaneError(p instanceof Error?p:new Error(String(p)))}}},onLaneError:d=>t.onLaneError(d)})}var T=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],x=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function Y(e){return T.includes(e)}function J(e){return x.includes(e)}0&&(module.exports={RT_VIDEO_OUT_STREAM,SUPPORTED_REALTIME_CLIENT_EVENTS,SUPPORTED_RESPONSES_EVENTS,UrunRealtime,UrunResponses,VIDEO_OUT_DEFAULT_CODEC,VIDEO_OUT_FRAMING,VIDEO_OUT_WS_FRAMING,consumeVideoOut,decodeVideoOutRecord,encodeVideoOutRecord,isSupportedClientEvent,isSupportedResponsesEvent,listModels,negotiateSessionVideoOutQuic,nodeAudioBackend,openSessionVideoOutLane,toErrorEvent,weriftAudioBackend});
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { b as UrunSessionLike, L as LaneMessage } from './types-CHPtJx6d.cjs';
2
- import { A as AudioBackend } from './video-out-BsuLqlID.cjs';
3
- export { b as AudioSink, c as AudioSource, d as RT_VIDEO_OUT_STREAM, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-BsuLqlID.cjs';
2
+ import { A as AudioBackend } from './video-out-DnCKUUO2.cjs';
3
+ export { b as AudioSink, c as AudioSource, d as RT_VIDEO_OUT_STREAM, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-DnCKUUO2.cjs';
4
4
  export { U as UrunResponses } from './ResponsesClient-6QsC7NPJ.cjs';
5
5
  export { M as ModelList, a as ModelObject, l as listModels } from './models-D7F0bLJ3.cjs';
6
6
  export { RealtimeClientEvent, RealtimeServerEvent } from 'openai/resources/beta/realtime/realtime';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { b as UrunSessionLike, L as LaneMessage } from './types-CHPtJx6d.js';
2
- import { A as AudioBackend } from './video-out-Cawtm7SF.js';
3
- export { b as AudioSink, c as AudioSource, d as RT_VIDEO_OUT_STREAM, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-Cawtm7SF.js';
2
+ import { A as AudioBackend } from './video-out-REmiQMBJ.js';
3
+ export { b as AudioSink, c as AudioSource, d as RT_VIDEO_OUT_STREAM, e as VIDEO_OUT_DEFAULT_CODEC, f as VIDEO_OUT_FRAMING, g as VIDEO_OUT_WS_FRAMING, i as VideoOutEndpoint, j as VideoOutLane, k as VideoOutRecord, l as VideoOutRecordHeader, m as VideoOutSink, n as VideoOutWtConnect, o as VideoOutWtSession, p as consumeVideoOut, q as decodeVideoOutRecord, t as encodeVideoOutRecord, u as negotiateSessionVideoOutQuic, v as nodeAudioBackend, w as openSessionVideoOutLane, x as weriftAudioBackend } from './video-out-REmiQMBJ.js';
4
4
  export { U as UrunResponses } from './ResponsesClient-gfg7qUoE.js';
5
5
  export { M as ModelList, a as ModelObject, l as listModels } from './models-D7F0bLJ3.js';
6
6
  export { RealtimeClientEvent, RealtimeServerEvent } from 'openai/resources/beta/realtime/realtime';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{b as S}from"./chunk-CAR4AEQJ.js";import{c as d,g as v,h as f,i as R,j as y,k as O,l as h,m as x,n as g,o as k,p as A,q as T}from"./chunk-6M5JK4YC.js";import{a as _}from"./chunk-4NMMWAKD.js";import{c as i,f as a}from"./chunk-GX243AIV.js";import"./chunk-7KRHHEKZ.js";import{c as o}from"./chunk-YSFSRI3D.js";o();o();var p=0;function V(){return p+=1,`rt_${Date.now().toString(36)}_${p.toString(36)}`}var s=class{constructor(e,t={}){this.session=e;this.opts=t;this.transport=new a(e)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await d(this.session,this.opts.audioBackend),this.audio.onOutputAudio(e=>this.emit({type:"response.audio.delta",delta:e}))}on(e,t){return this.handlers.add(t),()=>this.handlers.delete(t)}emit(e){for(let t of this.handlers)t(e)}send(e){switch(e.type){case"conversation.item.create":{let t=(e.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:e.item?.role??"user",content:t});return}case"response.create":{let t=V();this.currentRequestId=t,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:e.response},this.conversation,t);for await(let E of r)this.emit(E)}catch(r){this.emit(i(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(e.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};o();var l=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],m=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function w(n){return l.includes(n)}function I(n){return m.includes(n)}export{R as RT_VIDEO_OUT_STREAM,l as SUPPORTED_REALTIME_CLIENT_EVENTS,m as SUPPORTED_RESPONSES_EVENTS,s as UrunRealtime,_ as UrunResponses,O as VIDEO_OUT_DEFAULT_CODEC,y as VIDEO_OUT_FRAMING,k as VIDEO_OUT_WS_FRAMING,T as consumeVideoOut,x as decodeVideoOutRecord,h as encodeVideoOutRecord,w as isSupportedClientEvent,I as isSupportedResponsesEvent,S as listModels,g as negotiateSessionVideoOutQuic,f as nodeAudioBackend,A as openSessionVideoOutLane,i as toErrorEvent,v as weriftAudioBackend};
1
+ import{b as S}from"./chunk-CAR4AEQJ.js";import{c as d,g as v,h as f,i as R,j as y,k as O,l as h,m as x,n as g,o as k,p as A,q as T}from"./chunk-Z3QCHKJB.js";import{a as _}from"./chunk-4NMMWAKD.js";import{c as i,f as a}from"./chunk-GX243AIV.js";import"./chunk-7KRHHEKZ.js";import{c as o}from"./chunk-YSFSRI3D.js";o();o();var p=0;function V(){return p+=1,`rt_${Date.now().toString(36)}_${p.toString(36)}`}var s=class{constructor(e,t={}){this.session=e;this.opts=t;this.transport=new a(e)}session;opts;transport;handlers=new Set;conversation=[];active=null;audio=null;currentRequestId=null;async enableAudio(){if(!this.opts.audioBackend)throw new Error("audioBackend required for audio");this.audio=await d(this.session,this.opts.audioBackend),this.audio.onOutputAudio(e=>this.emit({type:"response.audio.delta",delta:e}))}on(e,t){return this.handlers.add(t),()=>this.handlers.delete(t)}emit(e){for(let t of this.handlers)t(e)}send(e){switch(e.type){case"conversation.item.create":{let t=(e.item?.content??[]).map(r=>r.text??"").join("");this.conversation.push({role:e.item?.role??"user",content:t});return}case"response.create":{let t=V();this.currentRequestId=t,this.active=(async()=>{try{let r=await this.transport.sendResponseCreate({type:"response.create",response:e.response},this.conversation,t);for await(let E of r)this.emit(E)}catch(r){this.emit(i(r))}})();return}case"input_audio_buffer.append":this.audio?.appendInputAudio(e.audio);return;case"input_audio_buffer.commit":case"input_audio_buffer.clear":return;case"response.cancel":return;default:return}}async drain(){this.active&&await this.active}};o();var l=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],m=["response.created","response.output_text.delta","response.output_item.added","response.function_call_arguments.delta","response.image_generation_call.partial_image","response.completed","error"];function w(n){return l.includes(n)}function I(n){return m.includes(n)}export{R as RT_VIDEO_OUT_STREAM,l as SUPPORTED_REALTIME_CLIENT_EVENTS,m as SUPPORTED_RESPONSES_EVENTS,s as UrunRealtime,_ as UrunResponses,O as VIDEO_OUT_DEFAULT_CODEC,y as VIDEO_OUT_FRAMING,k as VIDEO_OUT_WS_FRAMING,T as consumeVideoOut,x as decodeVideoOutRecord,h as encodeVideoOutRecord,w as isSupportedClientEvent,I as isSupportedResponsesEvent,S as listModels,g as negotiateSessionVideoOutQuic,f as nodeAudioBackend,A as openSessionVideoOutLane,i as toErrorEvent,v as weriftAudioBackend};
@@ -1,4 +1,4 @@
1
- import{a as z}from"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import{h as W,m as Q}from"../chunk-7AI75MPZ.js";import{c as C}from"../chunk-YSFSRI3D.js";C();import{createAssistantMessageEventStream as he}from"@earendil-works/pi-ai";import{mkdirSync as we,openSync as _e,writeSync as ke}from"fs";import{dirname as ve}from"path";C();import{appendFileSync as de,mkdirSync as pe}from"fs";import fe from"os";import{dirname as ge,join as me}from"path";import{format as ye}from"util";function J(t=fe.homedir()){return me(t,".urun","logs","pi-extension.log")}var V=!1;function te(t,e){let n=J();try{pe(ge(n),{recursive:!0}),de(n,`${new Date().toISOString()} [console.${t}] [urun] ${ye(...e)}
1
+ import{a as z}from"../chunk-4NMMWAKD.js";import"../chunk-GX243AIV.js";import"../chunk-7KRHHEKZ.js";import{h as W,m as Q}from"../chunk-HPUX2H65.js";import{c as C}from"../chunk-YSFSRI3D.js";C();import{createAssistantMessageEventStream as he}from"@earendil-works/pi-ai";import{mkdirSync as we,openSync as _e,writeSync as ke}from"fs";import{dirname as ve}from"path";C();import{appendFileSync as de,mkdirSync as pe}from"fs";import fe from"os";import{dirname as ge,join as me}from"path";import{format as ye}from"util";function J(t=fe.homedir()){return me(t,".urun","logs","pi-extension.log")}var V=!1;function te(t,e){let n=J();try{pe(ge(n),{recursive:!0}),de(n,`${new Date().toISOString()} [console.${t}] [urun] ${ye(...e)}
2
2
  `)}catch(o){if(!V){V=!0;try{process.stderr.write(`[urun] pi-extension quiet console: cannot write ${n} (${String(o)}); further urun-side console output will be dropped
3
3
  `)}catch{}}}}var f=t=>(...e)=>te(t,e),j={log:f("log"),info:f("info"),warn:f("warn"),error:f("error"),debug:f("debug"),trace:f("trace"),dir:f("dir"),table:f("table"),group:f("group"),groupCollapsed:f("groupCollapsed"),groupEnd:f("groupEnd"),count:f("count"),countReset:f("countReset"),time:f("time"),timeLog:f("timeLog"),timeEnd:f("timeEnd"),assert:(t,...e)=>{t||te("assert",e.length>0?e:["Assertion failed"])}};function q(t){try{process.stderr.write(t)}catch{}}C();async function ne(t){let e=await Q(t),n=e.filter(o=>o.function_name===t.fnName&&o.deployment_status==="active").map(o=>o.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var ae="urun-serve",xe="serve",Re=131072,be=16384,oe=3,Te=42e4,Ee=6e4,re=2,Se=15e3;function Ae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||W,fnName:(t.URUN_FUNCTION??"").trim()||xe}}function Ue(t){let e=(t.URUN_BASE_URL??"").trim(),n=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!n)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let o=(t.URUN_JWT??"").trim();if(o)return{baseUrl:e,orgId:n,auth:{lane:"jwt",jwt:o}};let s=(t.URUN_API_KEY??"").trim();if(!s)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let l=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:n,auth:{lane:"api-key",apiKey:s,gatewayUrl:l}}}function Ie(t){let e=null;return n=>{e===null&&(we(ve(t),{recursive:!0}),e=_e(t,"a"));let o=n.detail?` ${JSON.stringify(n.detail)}`:"";ke(e,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${o}
4
4
  `)}}function Pe(t){let e=Ie(J());return async(n,o,s)=>{let{baseUrl:l,orgId:i,auth:p}=Ue(n),{App:k,createClientToken:a}=await t(),m=(p.lane==="jwt"?k(o,{baseUrl:l,orgId:i,jwt:p.jwt,diagnosticSink:e}):k(o,{baseUrl:l,orgId:i,diagnosticSink:e,getAccessToken:async()=>(await a(p.apiKey,{baseUrl:p.gatewayUrl,expiresIn:300,allowedFunctions:[`${o}/${s}`]})).token}))[s];if(typeof m!="function")throw new Error(`urun pi extension: app "${o}" has no function "${s}"`);let h=m();if(typeof h.end!="function")throw new Error(`urun pi extension: app "${o}" function "${s}" returned a session without end()`);let A=h.connect;return typeof A=="function"&&await A.call(h),h}}var Ce=Pe(async()=>{let{createRequire:t}=await import("module"),e=t(import.meta.url);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function Ne(t,e){try{return Promise.resolve(t.end()).then(()=>{},n=>e(n))}catch(n){return e(n),Promise.resolve()}}function $e(t){if(t?.hasUI===!1)return!0;if(t?.hasUI===!0)return!1;let e=process.argv.slice(2);if(e.includes("-p")||e.includes("--print"))return!0;let n=e.indexOf("--mode");return n!==-1&&(e[n+1]==="json"||e[n+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function le(t,e){return`uRun: releasing the pooled "${t}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${e instanceof Error?e.message:String(e)}`}var H=class{constructor(e,n,o,s=(l,i)=>j.warn(le(l,i))){this.open=e;this.env=n;this.fnName=o;this.onReleaseError=s}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(e){let n=this.pool.get(e);if(!n){let o=Promise.resolve(this.open(this.env,e,this.fnName)).then(s=>({session:s,responses:new z(s)}));n=o,this.pool.set(e,o),o.catch(()=>{this.pool.get(e)===o&&this.pool.delete(e)})}return n}evict(e){let n=this.pool.get(e);if(!n)return Promise.resolve();this.pool.delete(e);let o=n.then(s=>Ne(s.session,l=>this.onReleaseError(e,l)),()=>{});return this.releasing.add(o),o.then(()=>this.releasing.delete(o)),o}closeAll(){let e=[...this.pool.keys()].map(n=>this.evict(n));return Promise.all([...e,...this.releasing]).then(()=>{})}};function Le(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let n of t.messages){if(n.role==="toolResult"){e.push({type:"function_call_output",call_id:n.toolCallId,output:De(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let s="",l=()=>{s&&(e.push({role:"assistant",content:s}),s="")};for(let i of n.content)if(i.type==="text")s+=String(i.text??"");else if(i.type==="toolCall")l(),e.push({type:"function_call",call_id:String(i.id??""),name:String(i.name??""),arguments:JSON.stringify(i.arguments??{})});else{if(i.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(i.type)}"`)}l();continue}let o=n.role==="assistant"?"assistant":"user";e.push({role:o,content:Me(n.content)})}return Oe(e)}function Oe(t){let e=[];for(let n of t){let o=e[e.length-1];o&&"role"in o&&"role"in n&&o.role===n.role?o.content=[o.content,n.content].filter(s=>s.length>0).join(`