@urun-sh/openai 0.6.42 → 0.6.44

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 (61) hide show
  1. package/dist/{ResponsesClient-gfg7qUoE.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
  2. package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
  3. package/dist/chunk-64VO62LW.js +1 -0
  4. package/dist/chunk-BA3NCMS5.js +6 -0
  5. package/dist/chunk-DMRZZTYI.js +4 -0
  6. package/dist/chunk-FNAZ2XBE.js +20 -0
  7. package/dist/chunk-G6AFKOVS.js +1 -0
  8. package/dist/{chunk-4NMMWAKD.js → chunk-HB5KNEY5.js} +1 -1
  9. package/dist/chunk-J3KCHTSA.js +6 -0
  10. package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
  11. package/dist/chunk-VQSCBUKT.js +66 -0
  12. package/dist/{chunk-QTHFMDZY.js → chunk-X5BLQXHK.js} +1 -1
  13. package/dist/chunk-XNRPTMSL.js +1 -0
  14. package/dist/chunk-Y774TOE7.js +2 -0
  15. package/dist/{composite-B-F2J0NK.d.cts → composite-DM2sT1Sp.d.cts} +320 -4
  16. package/dist/{composite-B--rGI5m.d.ts → composite-DNNAm0PY.d.ts} +91 -4
  17. package/dist/gemini-live.cjs +2 -2
  18. package/dist/gemini-live.d.cts +4 -4
  19. package/dist/gemini-live.d.ts +4 -4
  20. package/dist/gemini-live.js +1 -1
  21. package/dist/hosted/bin.cjs +49 -47
  22. package/dist/hosted/bin.js +1 -1
  23. package/dist/hosted/index.cjs +45 -43
  24. package/dist/hosted/index.d.cts +54 -10
  25. package/dist/hosted/index.d.ts +11 -5
  26. package/dist/hosted/index.js +1 -1
  27. package/dist/index.cjs +1 -1
  28. package/dist/index.d.cts +4 -4
  29. package/dist/index.d.ts +4 -4
  30. package/dist/index.js +1 -1
  31. package/dist/pi-extension/index.cjs +7 -7
  32. package/dist/pi-extension/index.d.cts +2 -2
  33. package/dist/pi-extension/index.d.ts +2 -2
  34. package/dist/pi-extension/index.js +1 -1
  35. package/dist/pi-extension/standalone.cjs +55 -55
  36. package/dist/pooler/bin.cjs +40 -41
  37. package/dist/pooler/bin.js +39 -40
  38. package/dist/proxy/cli.cjs +55 -53
  39. package/dist/proxy/cli.js +1 -1
  40. package/dist/proxy/conformance-probe.cjs +1 -1
  41. package/dist/proxy/conformance-probe.js +1 -1
  42. package/dist/proxy/index.cjs +34 -32
  43. package/dist/proxy/index.d.cts +37 -214
  44. package/dist/proxy/index.d.ts +17 -65
  45. package/dist/proxy/index.js +1 -1
  46. package/dist/{translator-Dox25ky9.d.cts → translator-C6MpaZS-.d.cts} +1 -1
  47. package/dist/{translator-BqpmZ-vh.d.ts → translator-CaOqL-V8.d.ts} +1 -1
  48. package/dist/{types-CHPtJx6d.d.cts → types-DiYzfHYN.d.cts} +2 -0
  49. package/dist/{types-CHPtJx6d.d.ts → types-DiYzfHYN.d.ts} +2 -0
  50. package/dist/{video-out-DnCKUUO2.d.cts → video-out-A8qMuI36.d.cts} +17 -3
  51. package/dist/{video-out-REmiQMBJ.d.ts → video-out-IoTqIbAw.d.ts} +6 -2
  52. package/package.json +2 -2
  53. package/dist/chunk-G7CSAISC.js +0 -1
  54. package/dist/chunk-GX243AIV.js +0 -1
  55. package/dist/chunk-HPUX2H65.js +0 -6
  56. package/dist/chunk-IFYB6QUQ.js +0 -64
  57. package/dist/chunk-KKCUIOL4.js +0 -1
  58. package/dist/chunk-OZ7HE3VG.js +0 -23
  59. package/dist/chunk-QNJKRB7Q.js +0 -2
  60. package/dist/chunk-XKCWX72M.js +0 -6
  61. package/dist/chunk-Z3QCHKJB.js +0 -1
@@ -1,12 +1,12 @@
1
1
  import { Server } from 'node:http';
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';
2
+ import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-DM2sT1Sp.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
- import { U as UrunResponses } from '../ResponsesClient-6QsC7NPJ.cjs';
7
- import { b as UrunSessionLike } from '../types-CHPtJx6d.cjs';
6
+ import { U as UrunResponses } from '../ResponsesClient-BJDe9EBw.cjs';
7
+ import { b as UrunSessionLike } from '../types-DiYzfHYN.cjs';
8
8
  import { C as CatalogRow } from '../models-D7F0bLJ3.cjs';
9
- import '../video-out-DnCKUUO2.cjs';
9
+ import '../video-out-A8qMuI36.cjs';
10
10
 
11
11
  /**
12
12
  * The container's metrics port — a MODULE CONSTANT, not an env var, per the
@@ -197,6 +197,13 @@ declare function createMetricsServer(metrics: InferenceMetrics): Server;
197
197
  * trust class — the same issuer already backs the org_trusted_jwks row the
198
198
  * session create gate verifies against — and it keeps every structural
199
199
  * property above: no org in URL/headers, no standing credential, loud 401/502.
200
+ *
201
+ * THE THIRD RUNG (WorkOS user tokens): a bearer whose `iss` is a pinned
202
+ * WorkOS user-management issuer (the console's signed-in user) verifies
203
+ * against THAT issuer's public JWKS and resolves to the token's own
204
+ * `org_id` claim — the same org identity the federated verifier in
205
+ * session-api-ts resolves for the same token. Same properties: pinned
206
+ * issuers only, no standing credential, loud 401/502.
200
207
  */
201
208
 
202
209
  /**
@@ -235,15 +242,18 @@ interface CallerIdentity {
235
242
  apiKey: string;
236
243
  orgId: string;
237
244
  /**
238
- * THE CREDENTIAL KIND (lane 07): `'machine'` names the second rung — the
245
+ * THE CREDENTIAL KIND (lane 07): `'machine'` names the machine rung — the
239
246
  * bearer is a platform machine token the caller's runtime pod minted from
240
247
  * its render-injected identity, and `apiKey` carries that TOKEN (it remains
241
- * the caller's own credential downstream, never a proxy-held secret). The
242
- * kind is load-bearing for the hops that must NOT treat the bearer as an
243
- * org API key (the client-token mint rides the session-api machine rung
244
- * instead; ledger/usage rows record no api_key_id for a machine caller).
248
+ * the caller's own credential downstream, never a proxy-held secret).
249
+ * `'user'` names the WorkOS user rung: the bearer is a console user's
250
+ * WorkOS access token, verified against the pinned issuer's JWKS, riding
251
+ * the federated (jwt) backhaul lane. The kind is load-bearing for the hops
252
+ * that must NOT treat the bearer as an org API key (the client-token mint
253
+ * rides the session-api machine rung instead; ledger/usage rows record no
254
+ * api_key_id for a machine or user caller).
245
255
  */
246
- credential?: 'api-key' | 'machine';
256
+ credential?: 'api-key' | 'machine' | 'user';
247
257
  /** 'platform' | 'distributor' — organizations.billing_audience (ENG-490). */
248
258
  billingAudience?: string;
249
259
  /** False = refuse NEW /v1 requests (402); in-flight requests always finish. */
@@ -272,6 +282,14 @@ interface OrgResolverOptions {
272
282
  mint?: typeof createClientToken;
273
283
  /** Injected in tests so cache expiry is exercised without wall-clock waits. */
274
284
  now?: () => number;
285
+ /**
286
+ * WHICH CREDENTIAL KIND this resolver verifies (default 'api-key'). 'user'
287
+ * is the user rung's binding read: the SAME mint endpoint (POST
288
+ * /api/client-tokens, post-federated-user-rung) is called with the caller's
289
+ * VERIFIED WorkOS token so the binding carries the SAME ENG-509 admission
290
+ * verdict a key call gets — admission applies, never ADMIT-by-default.
291
+ */
292
+ credential?: 'api-key' | 'user';
275
293
  }
276
294
  /**
277
295
  * Key → org resolution with a short bounded cache.
@@ -564,6 +582,11 @@ type PoolEntry = {
564
582
  session: OwnedSession;
565
583
  responses: UrunResponses;
566
584
  gone: SessionGoneWatch;
585
+ /** Armed when the entry's audio bridge opens; the release paths call it —
586
+ * the bridge's opusscript codec holds ~230 KB of the SHARED WASM heap that
587
+ * GC never reclaims, and retiring a lane without disposing wedges the whole
588
+ * process (every opus call throws 'offset is out of bounds'). */
589
+ audioDispose?: () => void;
567
590
  };
568
591
  /**
569
592
  * The replica's DECISION POOL wiring (serving-plan.md Phase 2) — built from
@@ -1322,6 +1345,27 @@ interface HostedConfig {
1322
1345
  issuers: readonly string[];
1323
1346
  tokenTtlS: number;
1324
1347
  };
1348
+ /**
1349
+ * THE USER-TOKEN RUNG (WorkOS): launcher-injected WorkOS user-management
1350
+ * issuer URLs whose user access tokens the proxy accepts as caller
1351
+ * credentials. ABSENT ⇒ the rung is OFF and every JWT-shaped bearer rides
1352
+ * the machine rung (or the key rung when the machine rung is unconfigured
1353
+ * too), byte-identically to before.
1354
+ *
1355
+ * URUN_WORKOS_ISSUERS the accepted WorkOS issuers, comma-separated —
1356
+ * the token's `iss` must match EXACTLY. The
1357
+ * signing keys verify against WorkOS's public
1358
+ * JWKS (derived: `https://api.workos.com/sso/
1359
+ * jwks/{client_id}`, the client id being the
1360
+ * issuer's last path segment). Per-env values:
1361
+ * prod `https://api.workos.com/user_management/
1362
+ * client_01KNNB76YVGNH78X98A1X3S56C`, sandbox
1363
+ * `https://api.workos.com/user_management/
1364
+ * client_01KTMETP4NVDADM9F9920CDC60`, dev
1365
+ * `https://api.workos.com/user_management/
1366
+ * client_01KNNB76BG5TEGZBHR0PA3M8AG`.
1367
+ */
1368
+ userIssuers?: readonly string[];
1325
1369
  }
1326
1370
  /**
1327
1371
  * Read and VALIDATE the deployment's external inputs. Every failure is loud
@@ -1,12 +1,12 @@
1
1
  import { Server } from 'node:http';
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';
2
+ import { c as LedgerOutcome, I as InferenceRecord, m as RouteTarget, S as SessionGoneError, p as billingIdentityOf, P as ProxyClients, M as ModelRouter, n as UsageRowReporter, b as InferenceUsageRecord, e as LedgerWrite, d as LedgerRecorded, L as LedgerFailure, l as RealtimeCompanionsFor } from '../composite-DNNAm0PY.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
- import { U as UrunResponses } from '../ResponsesClient-gfg7qUoE.js';
7
- import { b as UrunSessionLike } from '../types-CHPtJx6d.js';
6
+ import { U as UrunResponses } from '../ResponsesClient-75VdSOY-.js';
7
+ import { b as UrunSessionLike } from '../types-DiYzfHYN.js';
8
8
  import { C as CatalogRow } from '../models-D7F0bLJ3.js';
9
- import '../video-out-REmiQMBJ.js';
9
+ import '../video-out-IoTqIbAw.js';
10
10
 
11
11
  declare const METRICS_PORT = 9464;
12
12
 
@@ -95,7 +95,7 @@ interface CallerIdentity {
95
95
  apiKey: string;
96
96
  orgId: string;
97
97
 
98
- credential?: 'api-key' | 'machine';
98
+ credential?: 'api-key' | 'machine' | 'user';
99
99
 
100
100
  billingAudience?: string;
101
101
 
@@ -116,6 +116,8 @@ interface OrgResolverOptions {
116
116
  mint?: typeof createClientToken;
117
117
 
118
118
  now?: () => number;
119
+
120
+ credential?: 'api-key' | 'user';
119
121
  }
120
122
 
121
123
  declare class OrgResolver {
@@ -250,6 +252,8 @@ type PoolEntry = {
250
252
  session: OwnedSession;
251
253
  responses: UrunResponses;
252
254
  gone: SessionGoneWatch;
255
+
256
+ audioDispose?: () => void;
253
257
  };
254
258
 
255
259
  interface DecisionPools {
@@ -489,6 +493,8 @@ interface HostedConfig {
489
493
  issuers: readonly string[];
490
494
  tokenTtlS: number;
491
495
  };
496
+
497
+ userIssuers?: readonly string[];
492
498
  }
493
499
 
494
500
  declare function resolveHostedConfig(env?: NodeJS.ProcessEnv): HostedConfig;
@@ -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-OZ7HE3VG.js";import"../chunk-QNJKRB7Q.js";import"../chunk-CAR4AEQJ.js";import"../chunk-IFYB6QUQ.js";import"../chunk-QTHFMDZY.js";import"../chunk-Z3QCHKJB.js";import"../chunk-G7CSAISC.js";import"../chunk-L4QBHSVY.js";import"../chunk-XKCWX72M.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};
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-FNAZ2XBE.js";import"../chunk-DMRZZTYI.js";import"../chunk-CAR4AEQJ.js";import"../chunk-VQSCBUKT.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-Y774TOE7.js";import"../chunk-MJSK6W3W.js";import"../chunk-BA3NCMS5.js";import"../chunk-XNRPTMSL.js";import"../chunk-HB5KNEY5.js";import"../chunk-G6AFKOVS.js";import"../chunk-7KRHHEKZ.js";import"../chunk-J3KCHTSA.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:()=>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});
1
+ "use strict";var te=Object.create;var y=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty;var ie=(e,t)=>{for(var n in t)y(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of re(t))!se.call(e,o)&&o!==n&&y(e,o,{get:()=>t[o],enumerable:!(r=ne(t,o))||r.enumerable});return e};var O=(e,t,n)=>(n=e!=null?te(oe(e)):{},V(t||!e||!e.__esModule?y(n,"default",{value:e,enumerable:!0}):n,e)),ae=e=>V(y({},"__esModule",{value:!0}),e);var Ee={};ie(Ee,{RT_VIDEO_OUT_STREAM:()=>h,SUPPORTED_REALTIME_CLIENT_EVENTS:()=>L,SUPPORTED_RESPONSES_EVENTS:()=>I,UrunRealtime:()=>v,UrunResponses:()=>E,VIDEO_OUT_DEFAULT_CODEC:()=>b,VIDEO_OUT_FRAMING:()=>x,VIDEO_OUT_WS_FRAMING:()=>J,consumeVideoOut:()=>z,decodeVideoOutRecord:()=>S,encodeVideoOutRecord:()=>G,isSupportedClientEvent:()=>Q,isSupportedResponsesEvent:()=>X,listModels:()=>q,negotiateSessionVideoOutQuic:()=>Y,nodeAudioBackend:()=>N,openSessionVideoOutLane:()=>K,toErrorEvent:()=>m,weriftAudioBackend:()=>F});module.exports=ae(Ee);async function P(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 D(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 C(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 M=require("@urun-sh/core/internal");var de="llm-resp";async function*ue(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*A(e,t){let n=`${de}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*ue(t,e.stream(n).messages())}finally{try{(0,M.gcRequest)(e.doc("llm"),t)}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=C(t,n,this.consumerId);return this.write(r),A(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=D(t,n,r,this.consumerId);return this.write(o),A(this.session,r)})}async writeGated(t,n){try{await P(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 B="audio",R=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,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(t,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let a=0;a<o;a++)s[a]=r.readInt16LE(a*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(a=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(a instanceof Error?a.message:String(a)))}))}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)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function $(e,t,n=1e4){try{return await le(e,t,n)}catch(r){try{t.dispose?.()}catch{}throw r}}async function le(e,t,n){let r=new R(t,{sampleRate:24e3}),o=await r.startOutbound(),s=e.stream(B);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let a=await pe(e,n);return await r.startInbound(a),r}function pe(e,t){let n=e.stream(B);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 fe=24e3,w=480,me=111,ge=50,k=null;async function he(){if(k)return;let e=await import("opusscript");k=e.default??e}function we(){if(!k)throw new Error("[opus-guard] opusscript module not loaded");return new k(fe,1,2048)}var T=class{constructor(t=we){this.build=t;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let t=this.build();return this.inner=t,t}get wedged(){return this._wedged||this.consecutiveFailures>=ge}encode(t,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(t,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(t){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(t);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let t=this.inner;this.inner=null;try{t?.delete?.()}catch{}}};async function F(){let e=await import("werift");await he();let t=new T;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),U=t.encode(p,w);if(U===null){a=i.slice(d);break}o=o+1&65535,s=s+w>>>0;let Z=new e.RtpHeader({version:2,payloadType:me,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),ee=new e.RtpPacket(Z,U);n.writeRtp(ee)}a=i.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let a;try{a=t.decode(s.payload)}catch(i){if(t.wedged)throw i;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},dispose:()=>t.dispose()}}async function N(){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 W=0;function ye(){return W+=1,`rt_${Date.now().toString(36)}_${W.toString(36)}`}var v=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 $(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=ye();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 H=0;function _e(){return H+=1,`req_${Date.now().toString(36)}_${H.toString(36)}`}var E=class{transport;constructor(t,n){this.transport=new g(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=_e(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function ke(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 q(e){return{object:"list",data:(await ke(e)).map(n=>({id:`${n.model_id}:${n.variant}`,object:"model",created:0,owned_by:"urun"}))}}var f=require("@urun-sh/core"),h="rt-video-out",x="urun.videoOut.v1",b="h264";function j(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 G(e,t){if(j(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 S(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;j(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 Y(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:h,codec:b,framing:x}}var J="urun.videoOut.v2-ws";function K(e){let t=e.stream(h);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${h}') 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: "${h}" delivered a non-BINARY \xA75 payload (${typeof i}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=S(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 ve(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 z(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:ve(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 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,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(S(c))}catch(p){t.onLaneError(p instanceof Error?p:new Error(String(p)))}}},onLaneError:d=>t.onLaneError(d)})}var L=["session.update","conversation.item.create","response.create","response.cancel","input_audio_buffer.append","input_audio_buffer.commit","input_audio_buffer.clear"],I=["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 Q(e){return L.includes(e)}function X(e){return I.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,7 +1,7 @@
1
- import { b as UrunSessionLike, L as LaneMessage } from './types-CHPtJx6d.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
- export { U as UrunResponses } from './ResponsesClient-6QsC7NPJ.cjs';
1
+ import { b as UrunSessionLike, L as LaneMessage } from './types-DiYzfHYN.cjs';
2
+ import { A as AudioBackend } from './video-out-A8qMuI36.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-A8qMuI36.cjs';
4
+ export { U as UrunResponses } from './ResponsesClient-BJDe9EBw.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';
7
7
  export { ResponseStreamEvent } from 'openai/resources/responses/responses';
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { b as UrunSessionLike, L as LaneMessage } from './types-CHPtJx6d.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
- export { U as UrunResponses } from './ResponsesClient-gfg7qUoE.js';
1
+ import { b as UrunSessionLike, L as LaneMessage } from './types-DiYzfHYN.js';
2
+ import { A as AudioBackend } from './video-out-IoTqIbAw.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-IoTqIbAw.js';
4
+ export { U as UrunResponses } from './ResponsesClient-75VdSOY-.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';
7
7
  export { ResponseStreamEvent } from 'openai/resources/responses/responses';
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-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
+ 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-64VO62LW.js";import{a as _}from"./chunk-HB5KNEY5.js";import{c as i,f as a}from"./chunk-G6AFKOVS.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,8 +1,8 @@
1
- "use strict";var Ue=Object.create;var F=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var je=(e,t)=>{for(var n in t)F(e,n,{get:t[n],enumerable:!0})},ie=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Le(t))!Fe.call(e,o)&&o!==n&&F(e,o,{get:()=>t[o],enumerable:!(r=Ne(t,o))||r.enumerable});return e};var ae=(e,t,n)=>(n=e!=null?Ue(De(e)):{},ie(t||!e||!e.__esModule?F(n,"default",{value:e,enumerable:!0}):n,e)),Ke=e=>ie(F({},"__esModule",{value:!0}),e);var vt={};je(vt,{SessionPool:()=>G,URUN_API:()=>te,applyServeUsage:()=>Pe,coalesceSameRole:()=>$e,createFileDiagnosticSink:()=>Te,createUrunExtension:()=>Ce,default:()=>_t,makeSessionFactory:()=>xe,makeStreamSimple:()=>Ie,notify:()=>ee,piDiagnosticLogPath:()=>H,resolveSessionEnv:()=>ke,toResponsesInput:()=>Ae});module.exports=Ke(vt);var Je=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,g=Je();var Re=require("@earendil-works/pi-ai"),M=require("fs"),Se=require("path");async function le(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let r;await new Promise((o,i)=>{let a=e.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{a(),i(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 ue(e,t,n,r){let o=e.response??{},i={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:t};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 de(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 ce(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 Be="llm-resp";async function*qe(e,t){let n=`resp_${e}`,r=new Map;for await(let o of t){let i=o;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,f=r.get(c)??{};a.id&&(f.id=a.id),a.function?.name&&(f.name=a.function.name),r.set(c,f),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:f.id,name:f.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...i.body}};return}else if(i.t==="error"){yield ce(i);return}}}async function*V(e,t){let n=`${Be}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*qe(t,e.stream(n).messages())}finally{try{e.doc("llm").set({requests:{[t]:null}})}catch{}}}var K=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=de(t,n,this.consumerId);return this.write(r),V(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=ue(t,n,r,this.consumerId);return this.write(o),V(this.session,r)})}async writeGated(t,n){try{await le(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 pe=0;function Ge(){return pe+=1,`req_${Date.now().toString(36)}_${pe.toString(36)}`}var J=class{transport;constructor(t,n){this.transport=new K(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=Ge(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var B=require("fs"),fe=ae(require("os"),1),q=require("path"),me=require("util");function H(e=fe.default.homedir()){return(0,q.join)(e,".urun","logs","pi-extension.log")}var ge=!1;function he(e,t){let n=H();try{(0,B.mkdirSync)((0,q.dirname)(n),{recursive:!0}),(0,B.appendFileSync)(n,`${new Date().toISOString()} [console.${e}] [urun] ${(0,me.format)(...t)}
2
- `)}catch(r){if(!ge){ge=!0;try{process.stderr.write(`[urun] pi-extension quiet console: cannot write ${n} (${String(r)}); further urun-side console output will be dropped
3
- `)}catch{}}}}var m=e=>(...t)=>he(e,t),X={log:m("log"),info:m("info"),warn:m("warn"),error:m("error"),debug:m("debug"),trace:m("trace"),dir:m("dir"),table:m("table"),group:m("group"),groupCollapsed:m("groupCollapsed"),groupEnd:m("groupEnd"),count:m("count"),countReset:m("countReset"),time:m("time"),timeLog:m("timeLog"),timeEnd:m("timeEnd"),assert:(e,...t)=>{e||he("assert",t.length>0?t:["Assertion failed"])}};function Q(e){try{process.stderr.write(e)}catch{}}var Ve=require("crypto");var Z="https://api.urun.sh/v1";async function ye(e){let t=e.fetchImpl??fetch,n=`${e.apiUrl.replace(/\/+$/,"")}/apps`,r=await t(n,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}async function we(e){let t=await ye(e),n=t.filter(r=>r.function_name===e.fnName&&r.deployment_status==="active").map(r=>r.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${e.fnName}" (GET ${e.apiUrl}/apps returned ${t.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var te="urun-serve",Xe="serve",Qe=131072,Ze=16384,_e=3,et=42e4,tt=6e4,ve=2,nt=15e3;function rt(e){let t=(e.URUN_API_KEY??"").trim();if(!t)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:t,apiUrl:(e.URUN_API_URL??"").trim()||Z,fnName:(e.URUN_FUNCTION??"").trim()||Xe}}function ke(e){let t=(e.URUN_BASE_URL??"").trim(),n=(e.URUN_ORG_ID??"").trim();if(!t)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \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 r=(e.URUN_JWT??"").trim();if(r)return{baseUrl:t,orgId:n,auth:{lane:"jwt",jwt:r}};let o=(e.URUN_API_KEY??"").trim();if(!o)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let i=(e.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:t,orgId:n,auth:{lane:"api-key",apiKey:o,gatewayUrl:i}}}function Te(e){let t=null;return n=>{t===null&&((0,M.mkdirSync)((0,Se.dirname)(e),{recursive:!0}),t=(0,M.openSync)(e,"a"));let r=n.detail?` ${JSON.stringify(n.detail)}`:"";(0,M.writeSync)(t,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${r}
4
- `)}}function xe(e){let t=Te(H());return async(n,r,o)=>{let{baseUrl:i,orgId:a,auth:c}=ke(n),{App:f,createClientToken:l}=await e(),y=(c.lane==="jwt"?f(r,{baseUrl:i,orgId:a,jwt:c.jwt,diagnosticSink:t}):f(r,{baseUrl:i,orgId:a,diagnosticSink:t,getAccessToken:async()=>(await l(c.apiKey,{baseUrl:c.gatewayUrl,expiresIn:300,allowedFunctions:[`${r}/${o}`]})).token}))[o];if(typeof y!="function")throw new Error(`urun pi extension: app "${r}" has no function "${o}"`);let _=y();if(typeof _.end!="function")throw new Error(`urun pi extension: app "${r}" function "${o}" returned a session without end()`);let $=_.connect;return typeof $=="function"&&await $.call(_),_}}var ot=xe(async()=>{let{createRequire:e}=await import("module"),t=e(g);if(typeof globalThis.RTCPeerConnection>"u")try{t.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 t("@urun-sh/core")});function st(e,t){try{return Promise.resolve(e.end()).then(()=>{},n=>t(n))}catch(n){return t(n),Promise.resolve()}}function it(e){if(e?.hasUI===!1)return!0;if(e?.hasUI===!0)return!1;let t=process.argv.slice(2);if(t.includes("-p")||t.includes("--print"))return!0;let n=t.indexOf("--mode");return n!==-1&&(t[n+1]==="json"||t[n+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function Ee(e,t){return`uRun: releasing the pooled "${e}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${t instanceof Error?t.message:String(t)}`}var G=class{constructor(t,n,r,o=(i,a)=>X.warn(Ee(i,a))){this.open=t;this.env=n;this.fnName=r;this.onReleaseError=o}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(t){let n=this.pool.get(t);if(!n){let r=Promise.resolve(this.open(this.env,t,this.fnName)).then(o=>({session:o,responses:new J(o)}));n=r,this.pool.set(t,r),r.catch(()=>{this.pool.get(t)===r&&this.pool.delete(t)})}return n}evict(t){let n=this.pool.get(t);if(!n)return Promise.resolve();this.pool.delete(t);let r=n.then(o=>st(o.session,i=>this.onReleaseError(t,i)),()=>{});return this.releasing.add(r),r.then(()=>this.releasing.delete(r)),r}closeAll(){let t=[...this.pool.keys()].map(n=>this.evict(n));return Promise.all([...t,...this.releasing]).then(()=>{})}};function Ae(e){let t=[];e.systemPrompt&&t.push({role:"system",content:e.systemPrompt});for(let n of e.messages){if(n.role==="toolResult"){t.push({type:"function_call_output",call_id:n.toolCallId,output:lt(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let o="",i=()=>{o&&(t.push({role:"assistant",content:o}),o="")};for(let a of n.content)if(a.type==="text")o+=String(a.text??"");else if(a.type==="toolCall")i(),t.push({type:"function_call",call_id:String(a.id??""),name:String(a.name??""),arguments:JSON.stringify(a.arguments??{})});else{if(a.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(a.type)}"`)}i();continue}let r=n.role==="assistant"?"assistant":"user";t.push({role:r,content:at(n.content)})}return $e(t)}function $e(e){let t=[];for(let n of e){let r=t[t.length-1];r&&"role"in r&&"role"in n&&r.role===n.role?r.content=[r.content,n.content].filter(o=>o.length>0).join(`
1
+ "use strict";var Ne=Object.create;var F=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var Ke=(e,t)=>{for(var n in t)F(e,n,{get:t[n],enumerable:!0})},ie=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of De(t))!je.call(e,o)&&o!==n&&F(e,o,{get:()=>t[o],enumerable:!(r=Le(t,o))||r.enumerable});return e};var ae=(e,t,n)=>(n=e!=null?Ne(Fe(e)):{},ie(t||!e||!e.__esModule?F(n,"default",{value:e,enumerable:!0}):n,e)),Je=e=>ie(F({},"__esModule",{value:!0}),e);var bt={};Ke(bt,{SessionPool:()=>G,URUN_API:()=>te,applyServeUsage:()=>Ie,coalesceSameRole:()=>Pe,createFileDiagnosticSink:()=>xe,createUrunExtension:()=>Me,default:()=>vt,makeSessionFactory:()=>Ee,makeStreamSimple:()=>Ce,notify:()=>ee,piDiagnosticLogPath:()=>H,resolveSessionEnv:()=>Te,toResponsesInput:()=>$e});module.exports=Je(bt);var Be=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,g=Be();var Se=require("@earendil-works/pi-ai"),M=require("fs"),ke=require("path");async function le(e,t,n){if(e.synced===!0||typeof e.onSynced!="function")return;let r;await new Promise((o,i)=>{let a=e.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{a(),i(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 ue(e,t,n,r){let o=e.response??{},i={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:t};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 de(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 ce(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 pe=require("@urun-sh/core/internal");var qe="llm-resp";async function*He(e,t){let n=`resp_${e}`,r=new Map;for await(let o of t){let i=o;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let c=typeof a.index=="number"?a.index:0,f=r.get(c)??{};a.id&&(f.id=a.id),a.function?.name&&(f.name=a.function.name),r.set(c,f),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:f.id,name:f.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...i.body}};return}else if(i.t==="error"){yield ce(i);return}}}async function*V(e,t){let n=`${qe}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*He(t,e.stream(n).messages())}finally{try{(0,pe.gcRequest)(e.doc("llm"),t)}catch{}}}var K=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=de(t,n,this.consumerId);return this.write(r),V(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=ue(t,n,r,this.consumerId);return this.write(o),V(this.session,r)})}async writeGated(t,n){try{await le(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 ge=0;function ze(){return ge+=1,`req_${Date.now().toString(36)}_${ge.toString(36)}`}var J=class{transport;constructor(t,n){this.transport=new K(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=ze(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var B=require("fs"),me=ae(require("os"),1),q=require("path"),he=require("util");function H(e=me.default.homedir()){return(0,q.join)(e,".urun","logs","pi-extension.log")}var fe=!1;function ye(e,t){let n=H();try{(0,B.mkdirSync)((0,q.dirname)(n),{recursive:!0}),(0,B.appendFileSync)(n,`${new Date().toISOString()} [console.${e}] [urun] ${(0,he.format)(...t)}
2
+ `)}catch(r){if(!fe){fe=!0;try{process.stderr.write(`[urun] pi-extension quiet console: cannot write ${n} (${String(r)}); further urun-side console output will be dropped
3
+ `)}catch{}}}}var m=e=>(...t)=>ye(e,t),X={log:m("log"),info:m("info"),warn:m("warn"),error:m("error"),debug:m("debug"),trace:m("trace"),dir:m("dir"),table:m("table"),group:m("group"),groupCollapsed:m("groupCollapsed"),groupEnd:m("groupEnd"),count:m("count"),countReset:m("countReset"),time:m("time"),timeLog:m("timeLog"),timeEnd:m("timeEnd"),assert:(e,...t)=>{e||ye("assert",t.length>0?t:["Assertion failed"])}};function Q(e){try{process.stderr.write(e)}catch{}}var Xe=require("crypto");var Z="https://api.urun.sh/v1";async function we(e){let t=e.fetchImpl??fetch,n=`${e.apiUrl.replace(/\/+$/,"")}/apps`,r=await t(n,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}async function _e(e){let t=await we(e),n=t.filter(r=>r.function_name===e.fnName&&r.deployment_status==="active").map(r=>r.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${e.fnName}" (GET ${e.apiUrl}/apps returned ${t.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var te="urun-serve",Qe="serve",Ze=131072,et=16384,ve=3,tt=42e4,nt=6e4,be=2,rt=15e3;function ot(e){let t=(e.URUN_API_KEY??"").trim();if(!t)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:t,apiUrl:(e.URUN_API_URL??"").trim()||Z,fnName:(e.URUN_FUNCTION??"").trim()||Qe}}function Te(e){let t=(e.URUN_BASE_URL??"").trim(),n=(e.URUN_ORG_ID??"").trim();if(!t)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \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 r=(e.URUN_JWT??"").trim();if(r)return{baseUrl:t,orgId:n,auth:{lane:"jwt",jwt:r}};let o=(e.URUN_API_KEY??"").trim();if(!o)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let i=(e.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:t,orgId:n,auth:{lane:"api-key",apiKey:o,gatewayUrl:i}}}function xe(e){let t=null;return n=>{t===null&&((0,M.mkdirSync)((0,ke.dirname)(e),{recursive:!0}),t=(0,M.openSync)(e,"a"));let r=n.detail?` ${JSON.stringify(n.detail)}`:"";(0,M.writeSync)(t,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${r}
4
+ `)}}function Ee(e){let t=xe(H());return async(n,r,o)=>{let{baseUrl:i,orgId:a,auth:c}=Te(n),{App:f,createClientToken:l}=await e(),y=(c.lane==="jwt"?f(r,{baseUrl:i,orgId:a,jwt:c.jwt,diagnosticSink:t}):f(r,{baseUrl:i,orgId:a,diagnosticSink:t,getAccessToken:async()=>(await l(c.apiKey,{baseUrl:c.gatewayUrl,expiresIn:300,allowedFunctions:[`${r}/${o}`]})).token}))[o];if(typeof y!="function")throw new Error(`urun pi extension: app "${r}" has no function "${o}"`);let _=y();if(typeof _.end!="function")throw new Error(`urun pi extension: app "${r}" function "${o}" returned a session without end()`);let $=_.connect;return typeof $=="function"&&await $.call(_),_}}var st=Ee(async()=>{let{createRequire:e}=await import("module"),t=e(g);if(typeof globalThis.RTCPeerConnection>"u")try{t.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 t("@urun-sh/core")});function it(e,t){try{return Promise.resolve(e.end()).then(()=>{},n=>t(n))}catch(n){return t(n),Promise.resolve()}}function at(e){if(e?.hasUI===!1)return!0;if(e?.hasUI===!0)return!1;let t=process.argv.slice(2);if(t.includes("-p")||t.includes("--print"))return!0;let n=t.indexOf("--mode");return n!==-1&&(t[n+1]==="json"||t[n+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function Ae(e,t){return`uRun: releasing the pooled "${e}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${t instanceof Error?t.message:String(t)}`}var G=class{constructor(t,n,r,o=(i,a)=>X.warn(Ae(i,a))){this.open=t;this.env=n;this.fnName=r;this.onReleaseError=o}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(t){let n=this.pool.get(t);if(!n){let r=Promise.resolve(this.open(this.env,t,this.fnName)).then(o=>({session:o,responses:new J(o)}));n=r,this.pool.set(t,r),r.catch(()=>{this.pool.get(t)===r&&this.pool.delete(t)})}return n}evict(t){let n=this.pool.get(t);if(!n)return Promise.resolve();this.pool.delete(t);let r=n.then(o=>it(o.session,i=>this.onReleaseError(t,i)),()=>{});return this.releasing.add(r),r.then(()=>this.releasing.delete(r)),r}closeAll(){let t=[...this.pool.keys()].map(n=>this.evict(n));return Promise.all([...t,...this.releasing]).then(()=>{})}};function $e(e){let t=[];e.systemPrompt&&t.push({role:"system",content:e.systemPrompt});for(let n of e.messages){if(n.role==="toolResult"){t.push({type:"function_call_output",call_id:n.toolCallId,output:ut(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let o="",i=()=>{o&&(t.push({role:"assistant",content:o}),o="")};for(let a of n.content)if(a.type==="text")o+=String(a.text??"");else if(a.type==="toolCall")i(),t.push({type:"function_call",call_id:String(a.id??""),name:String(a.name??""),arguments:JSON.stringify(a.arguments??{})});else{if(a.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(a.type)}"`)}i();continue}let r=n.role==="assistant"?"assistant":"user";t.push({role:r,content:lt(n.content)})}return Pe(t)}function Pe(e){let t=[];for(let n of e){let r=t[t.length-1];r&&"role"in r&&"role"in n&&r.role===n.role?r.content=[r.content,n.content].filter(o=>o.length>0).join(`
5
5
 
6
- `):t.push({...n})}return t}function at(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&"text"in t?String(t.text):"").join(""):""}function lt(e){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let t="";for(let n of e){let r=String(n.type??"");if(r!=="text")throw new Error(`urun pi extension: unsupported toolResult content part "${r}" \u2014 the serve lane carries text tool results only`);t+=String(n.text??"")}return t}function ut(e){if(!(!Array.isArray(e)||e.length===0))return e.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters}))}function be(e,t){if(!t.trim())return{};try{return JSON.parse(t)}catch{throw new Error(`uRun serve error: tool call "${e}" arguments are not valid JSON: ${t}`)}}function dt(e){let t=e?.output;return Array.isArray(t)?t.filter(n=>n.type==="function_call"):[]}function Pe(e,t){let n=t?.usage;if(!n||typeof n!="object")return;let r=typeof n.input_tokens=="number"?n.input_tokens:void 0,o=typeof n.output_tokens=="number"?n.output_tokens:void 0;r===void 0||o===void 0||(e.input=r,e.output=o,e.totalTokens=typeof n.total_tokens=="number"?n.total_tokens:r+o)}function ct(e){let t=e?.output;if(!Array.isArray(t))return"";let n="";for(let r of t)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}var pt=["<tool_call>","<function="];function gt(e,t){let n=pt.find(r=>t.includes(r));if(n)return new Error(`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${e}" (see catalog parser_defaults)`)}var z=class extends Error{};function ft(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return/\b529\b/.test(t)||/overloaded/i.test(t)||n===529||n==="529"}function mt(e){return new Promise(t=>setTimeout(t,e))}function ht(e,t,n,r){return new Promise((o,i)=>{let a=!1,c=s=>{a||(a=!0,clearTimeout(f),r?.removeEventListener("abort",l),s())},f=setTimeout(()=>c(()=>i(n())),t),l=()=>c(()=>i(new Error("aborted")));if(r?.aborted){l();return}r?.addEventListener("abort",l,{once:!0}),Promise.resolve(e).then(s=>c(()=>o(s)),s=>c(()=>i(s)))})}async function*yt(e,t){let n=e[Symbol.asyncIterator](),r,o=new Promise((i,a)=>{r=()=>a(new Error("aborted")),t.addEventListener("abort",r,{once:!0})});try{for(;;){if(t.aborted)throw new Error("aborted");let i=await Promise.race([n.next(),o]);if(i.done)return;yield i.value}}finally{r&&t.removeEventListener("abort",r),n.return?.(void 0)}}function ee(e,t){if(e?.hasUI===!1){Q(`${t}
7
- `);return}let n=e?.sendMessage;if(typeof n=="function")try{n.call(e,{customType:"urun-status",content:t,display:!0},{triggerTurn:!1})}catch{}}function Ie(e,t={},n){let r=t.connectDeadlineMs??et,o=t.stallTimeoutMs??tt,i=t.phaseHeartbeatMs??nt;return(a,c,f)=>{let l=(0,Re.createAssistantMessageEventStream)(),s={role:"assistant",content:[],api:a.api,provider:a.provider,model:a.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},y=new AbortController,_=f?.signal,$=!1,L=()=>{$=!0,y.abort()};_&&(_.aborted?L():_.addEventListener("abort",L,{once:!0}));let O=!1,P,ne=()=>{P&&clearTimeout(P),P=setTimeout(()=>{O=!0,y.abort()},o)},D=()=>{P&&clearTimeout(P),P=void 0},k=null,T=null,v=null,re="",U=!1,W=()=>{if(!T)return;let p=T;T=null,l.push({type:"thinking_end",contentIndex:s.content.indexOf(p),content:p.thinking,partial:s})},oe=()=>{if(!k)return;let p=k;k=null,l.push({type:"text_end",contentIndex:s.content.indexOf(p),content:p.text,partial:s})},Y=()=>{if(!v)return;let{call:p,args:b,contentIndex:x}=v;v=null,p.arguments=be(p.name,b),l.push({type:"toolcall_end",contentIndex:x,toolCall:p,partial:s})},Me=p=>{let b={type:"toolCall",id:String(p.call_id??p.id??`call_${s.content.length}`),name:String(p.name??""),arguments:{}};s.content.push(b);let x=s.content.length-1;l.push({type:"toolcall_start",contentIndex:x,partial:s});let N=typeof p.arguments=="string"?p.arguments:"";N&&l.push({type:"toolcall_delta",contentIndex:x,delta:N,partial:s}),b.arguments=be(b.name,N),l.push({type:"toolcall_end",contentIndex:x,toolCall:b,partial:s})};return(async()=>{l.push({type:"start",partial:s});let p=!1,b,x=()=>{b&&clearInterval(b),b=void 0},N=Date.now();b=setInterval(()=>{let R=Math.round((Date.now()-N)/1e3);ee(n,`uRun: still opening the "${a.id}" session\u2026 (${R}s \u2014 serve apps scale to zero, first turn can cold-start ~6min)`)},i);let Oe=async R=>{let{responses:S}=await ht(e.acquire(a.id),r,()=>new Error(`uRun session for "${a.id}" did not connect within ${Math.round(r/1e3)}s \u2014 likely cold-starting (scaled to zero) or queued behind capacity. Retry shortly.`),y.signal);x();let I,E;for(let u=1;u<=_e;u++)try{let w=await S.responses.create({model:a.id,input:R,stream:!0,tools:ut(c.tools),max_output_tokens:a.maxTokens,...f?.reasoning!=null&&f.reasoning!=="off"&&a.reasoning!==!1?{}:{chat_template_kwargs:{enable_thinking:!1}}});ne();for await(let A of yt(w,y.signal)){ne();let h=A;if(h.type==="response.output_text.delta"){let d=typeof h.delta=="string"?h.delta:"";d&&(U=!0,W(),Y(),k||(k={type:"text",text:""},s.content.push(k),l.push({type:"text_start",contentIndex:s.content.length-1,partial:s})),k.text+=d,re+=d,l.push({type:"text_delta",contentIndex:s.content.indexOf(k),delta:d,partial:s}))}else if(h.type==="response.reasoning_text.delta"){let d=typeof h.delta=="string"?h.delta:"";d&&(U=!0,T||(T={type:"thinking",thinking:""},s.content.push(T),l.push({type:"thinking_start",contentIndex:s.content.length-1,partial:s})),T.thinking+=d,l.push({type:"thinking_delta",contentIndex:s.content.indexOf(T),delta:d,partial:s}))}else if(h.type==="response.function_call_arguments.delta"&&typeof h.tool_index=="number"){let d=h;if(U=!0,W(),oe(),!v||v.toolIndex!==d.tool_index){Y();let se={type:"toolCall",id:d.call_id??`call_${d.tool_index}`,name:d.name??"",arguments:{}};s.content.push(se),v={call:se,args:"",contentIndex:s.content.length-1,toolIndex:d.tool_index},l.push({type:"toolcall_start",contentIndex:v.contentIndex,partial:s})}d.call_id&&(v.call.id=d.call_id),d.name&&(v.call.name=d.name);let C=typeof d.delta=="string"?d.delta:"";C&&(v.args+=C,l.push({type:"toolcall_delta",contentIndex:v.contentIndex,delta:C,partial:s}))}else if(h.type==="response.completed"){I=h.response;break}else if(h.type==="error"){let d=h.error,C=new Error(`uRun serve error: ${d?.message??"unknown error"}`);throw C.code=d?.code??null,C}}if(!I)throw new z(`uRun backhaul for "${a.id}" closed before the turn completed \u2014 the serving session ended mid-turn (its pod was restarted, drained or deleted).`);E=void 0;break}catch(w){if(E=w,y.signal.aborted)throw w;if(u<_e&&ft(w)&&!U){await mt(u*500);continue}throw w}if(E)throw E;return I};try{let R=Ae(c),S;for(let u=1;u<=ve;u++)try{S=await Oe(R);break}catch(w){let A=O||w instanceof z;if(u>=ve||!A||U||$)throw w;D(),e.evict(a.id),O=!1,y=new AbortController,ee(n,`uRun: the "${a.id}" session ended mid-turn \u2014 re-homing to a fresh assignment and replaying the turn\u2026`)}if(D(),W(),oe(),Y(),!s.content.some(u=>u.type==="toolCall"))for(let u of dt(S))Me(u);if(!s.content.some(u=>u.type==="thinking")){let u=ct(S);if(u){let w={type:"thinking",thinking:""};s.content.push(w);let A=s.content.length-1;l.push({type:"thinking_start",contentIndex:A,partial:s}),w.thinking=u,l.push({type:"thinking_delta",contentIndex:A,delta:u,partial:s}),l.push({type:"thinking_end",contentIndex:A,content:u,partial:s})}}let I=s.content.filter(u=>u.type==="toolCall").length;if((c.tools?.length??0)>0&&I===0){let u=gt(a.id,re);if(u)throw u}let E=I>0?"toolUse":S?.status==="incomplete"?"length":"stop";s.stopReason=E,Pe(s.usage,S),l.push({type:"done",reason:E,message:s}),l.end(s)}catch(R){if(p=!0,D(),$||_?.aborted&&!O)s.stopReason="aborted",s.errorMessage="aborted by user",l.push({type:"error",reason:"aborted",error:s});else{let S=O?`uRun stream stalled \u2014 no output for ${Math.round(o/1e3)}s; the model may be hung. Retry, or Ctrl-C to abort.`:R instanceof Error?R.message:String(R);s.stopReason="error",s.errorMessage=S,l.push({type:"error",reason:"error",error:s})}l.end(s)}finally{D(),x(),_&&_.removeEventListener("abort",L),p&&e.evict(a.id)}})(),l}}function wt(e){return{id:e,name:`uRun ${e}`,api:te,reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:Qe,maxTokens:Ze}}function Ce(e={}){return async t=>{let n=e.env??process.env,{apiKey:r,apiUrl:o,fnName:i}=rt(n),a=await we({apiUrl:o,apiKey:r,fnName:i,fetchImpl:e.fetchImpl}),c=new G(e.openSession??ot,n,i,(l,s)=>{let y=Ee(l,s);it(t)?Q(`${y}
8
- `):X.warn(y)});t.on("session_shutdown",()=>c.closeAll());let f={name:"uRun",api:te,baseUrl:"urun://session",apiKey:"$URUN_API_KEY",models:a.map(wt),streamSimple:Ie(c,e.timing??{},t)};t.registerProvider("urun",f)}}var _t=Ce();0&&(module.exports={SessionPool,URUN_API,applyServeUsage,coalesceSameRole,createFileDiagnosticSink,createUrunExtension,makeSessionFactory,makeStreamSimple,notify,piDiagnosticLogPath,resolveSessionEnv,toResponsesInput});
6
+ `):t.push({...n})}return t}function lt(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&"text"in t?String(t.text):"").join(""):""}function ut(e){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let t="";for(let n of e){let r=String(n.type??"");if(r!=="text")throw new Error(`urun pi extension: unsupported toolResult content part "${r}" \u2014 the serve lane carries text tool results only`);t+=String(n.text??"")}return t}function dt(e){if(!(!Array.isArray(e)||e.length===0))return e.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters}))}function Re(e,t){if(!t.trim())return{};try{return JSON.parse(t)}catch{throw new Error(`uRun serve error: tool call "${e}" arguments are not valid JSON: ${t}`)}}function ct(e){let t=e?.output;return Array.isArray(t)?t.filter(n=>n.type==="function_call"):[]}function Ie(e,t){let n=t?.usage;if(!n||typeof n!="object")return;let r=typeof n.input_tokens=="number"?n.input_tokens:void 0,o=typeof n.output_tokens=="number"?n.output_tokens:void 0;r===void 0||o===void 0||(e.input=r,e.output=o,e.totalTokens=typeof n.total_tokens=="number"?n.total_tokens:r+o)}function pt(e){let t=e?.output;if(!Array.isArray(t))return"";let n="";for(let r of t)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}var gt=["<tool_call>","<function="];function ft(e,t){let n=gt.find(r=>t.includes(r));if(n)return new Error(`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${e}" (see catalog parser_defaults)`)}var z=class extends Error{};function mt(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return/\b529\b/.test(t)||/overloaded/i.test(t)||n===529||n==="529"}function ht(e){return new Promise(t=>setTimeout(t,e))}function yt(e,t,n,r){return new Promise((o,i)=>{let a=!1,c=s=>{a||(a=!0,clearTimeout(f),r?.removeEventListener("abort",l),s())},f=setTimeout(()=>c(()=>i(n())),t),l=()=>c(()=>i(new Error("aborted")));if(r?.aborted){l();return}r?.addEventListener("abort",l,{once:!0}),Promise.resolve(e).then(s=>c(()=>o(s)),s=>c(()=>i(s)))})}async function*wt(e,t){let n=e[Symbol.asyncIterator](),r,o=new Promise((i,a)=>{r=()=>a(new Error("aborted")),t.addEventListener("abort",r,{once:!0})});try{for(;;){if(t.aborted)throw new Error("aborted");let i=await Promise.race([n.next(),o]);if(i.done)return;yield i.value}}finally{r&&t.removeEventListener("abort",r),n.return?.(void 0)}}function ee(e,t){if(e?.hasUI===!1){Q(`${t}
7
+ `);return}let n=e?.sendMessage;if(typeof n=="function")try{n.call(e,{customType:"urun-status",content:t,display:!0},{triggerTurn:!1})}catch{}}function Ce(e,t={},n){let r=t.connectDeadlineMs??tt,o=t.stallTimeoutMs??nt,i=t.phaseHeartbeatMs??rt;return(a,c,f)=>{let l=(0,Se.createAssistantMessageEventStream)(),s={role:"assistant",content:[],api:a.api,provider:a.provider,model:a.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},y=new AbortController,_=f?.signal,$=!1,L=()=>{$=!0,y.abort()};_&&(_.aborted?L():_.addEventListener("abort",L,{once:!0}));let O=!1,P,ne=()=>{P&&clearTimeout(P),P=setTimeout(()=>{O=!0,y.abort()},o)},D=()=>{P&&clearTimeout(P),P=void 0},k=null,T=null,v=null,re="",U=!1,W=()=>{if(!T)return;let p=T;T=null,l.push({type:"thinking_end",contentIndex:s.content.indexOf(p),content:p.thinking,partial:s})},oe=()=>{if(!k)return;let p=k;k=null,l.push({type:"text_end",contentIndex:s.content.indexOf(p),content:p.text,partial:s})},Y=()=>{if(!v)return;let{call:p,args:b,contentIndex:x}=v;v=null,p.arguments=Re(p.name,b),l.push({type:"toolcall_end",contentIndex:x,toolCall:p,partial:s})},Oe=p=>{let b={type:"toolCall",id:String(p.call_id??p.id??`call_${s.content.length}`),name:String(p.name??""),arguments:{}};s.content.push(b);let x=s.content.length-1;l.push({type:"toolcall_start",contentIndex:x,partial:s});let N=typeof p.arguments=="string"?p.arguments:"";N&&l.push({type:"toolcall_delta",contentIndex:x,delta:N,partial:s}),b.arguments=Re(b.name,N),l.push({type:"toolcall_end",contentIndex:x,toolCall:b,partial:s})};return(async()=>{l.push({type:"start",partial:s});let p=!1,b,x=()=>{b&&clearInterval(b),b=void 0},N=Date.now();b=setInterval(()=>{let R=Math.round((Date.now()-N)/1e3);ee(n,`uRun: still opening the "${a.id}" session\u2026 (${R}s \u2014 serve apps scale to zero, first turn can cold-start ~6min)`)},i);let Ue=async R=>{let{responses:S}=await yt(e.acquire(a.id),r,()=>new Error(`uRun session for "${a.id}" did not connect within ${Math.round(r/1e3)}s \u2014 likely cold-starting (scaled to zero) or queued behind capacity. Retry shortly.`),y.signal);x();let I,E;for(let u=1;u<=ve;u++)try{let w=await S.responses.create({model:a.id,input:R,stream:!0,tools:dt(c.tools),max_output_tokens:a.maxTokens,...f?.reasoning!=null&&f.reasoning!=="off"&&a.reasoning!==!1?{}:{chat_template_kwargs:{enable_thinking:!1}}});ne();for await(let A of wt(w,y.signal)){ne();let h=A;if(h.type==="response.output_text.delta"){let d=typeof h.delta=="string"?h.delta:"";d&&(U=!0,W(),Y(),k||(k={type:"text",text:""},s.content.push(k),l.push({type:"text_start",contentIndex:s.content.length-1,partial:s})),k.text+=d,re+=d,l.push({type:"text_delta",contentIndex:s.content.indexOf(k),delta:d,partial:s}))}else if(h.type==="response.reasoning_text.delta"){let d=typeof h.delta=="string"?h.delta:"";d&&(U=!0,T||(T={type:"thinking",thinking:""},s.content.push(T),l.push({type:"thinking_start",contentIndex:s.content.length-1,partial:s})),T.thinking+=d,l.push({type:"thinking_delta",contentIndex:s.content.indexOf(T),delta:d,partial:s}))}else if(h.type==="response.function_call_arguments.delta"&&typeof h.tool_index=="number"){let d=h;if(U=!0,W(),oe(),!v||v.toolIndex!==d.tool_index){Y();let se={type:"toolCall",id:d.call_id??`call_${d.tool_index}`,name:d.name??"",arguments:{}};s.content.push(se),v={call:se,args:"",contentIndex:s.content.length-1,toolIndex:d.tool_index},l.push({type:"toolcall_start",contentIndex:v.contentIndex,partial:s})}d.call_id&&(v.call.id=d.call_id),d.name&&(v.call.name=d.name);let C=typeof d.delta=="string"?d.delta:"";C&&(v.args+=C,l.push({type:"toolcall_delta",contentIndex:v.contentIndex,delta:C,partial:s}))}else if(h.type==="response.completed"){I=h.response;break}else if(h.type==="error"){let d=h.error,C=new Error(`uRun serve error: ${d?.message??"unknown error"}`);throw C.code=d?.code??null,C}}if(!I)throw new z(`uRun backhaul for "${a.id}" closed before the turn completed \u2014 the serving session ended mid-turn (its pod was restarted, drained or deleted).`);E=void 0;break}catch(w){if(E=w,y.signal.aborted)throw w;if(u<ve&&mt(w)&&!U){await ht(u*500);continue}throw w}if(E)throw E;return I};try{let R=$e(c),S;for(let u=1;u<=be;u++)try{S=await Ue(R);break}catch(w){let A=O||w instanceof z;if(u>=be||!A||U||$)throw w;D(),e.evict(a.id),O=!1,y=new AbortController,ee(n,`uRun: the "${a.id}" session ended mid-turn \u2014 re-homing to a fresh assignment and replaying the turn\u2026`)}if(D(),W(),oe(),Y(),!s.content.some(u=>u.type==="toolCall"))for(let u of ct(S))Oe(u);if(!s.content.some(u=>u.type==="thinking")){let u=pt(S);if(u){let w={type:"thinking",thinking:""};s.content.push(w);let A=s.content.length-1;l.push({type:"thinking_start",contentIndex:A,partial:s}),w.thinking=u,l.push({type:"thinking_delta",contentIndex:A,delta:u,partial:s}),l.push({type:"thinking_end",contentIndex:A,content:u,partial:s})}}let I=s.content.filter(u=>u.type==="toolCall").length;if((c.tools?.length??0)>0&&I===0){let u=ft(a.id,re);if(u)throw u}let E=I>0?"toolUse":S?.status==="incomplete"?"length":"stop";s.stopReason=E,Ie(s.usage,S),l.push({type:"done",reason:E,message:s}),l.end(s)}catch(R){if(p=!0,D(),$||_?.aborted&&!O)s.stopReason="aborted",s.errorMessage="aborted by user",l.push({type:"error",reason:"aborted",error:s});else{let S=O?`uRun stream stalled \u2014 no output for ${Math.round(o/1e3)}s; the model may be hung. Retry, or Ctrl-C to abort.`:R instanceof Error?R.message:String(R);s.stopReason="error",s.errorMessage=S,l.push({type:"error",reason:"error",error:s})}l.end(s)}finally{D(),x(),_&&_.removeEventListener("abort",L),p&&e.evict(a.id)}})(),l}}function _t(e){return{id:e,name:`uRun ${e}`,api:te,reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:Ze,maxTokens:et}}function Me(e={}){return async t=>{let n=e.env??process.env,{apiKey:r,apiUrl:o,fnName:i}=ot(n),a=await _e({apiUrl:o,apiKey:r,fnName:i,fetchImpl:e.fetchImpl}),c=new G(e.openSession??st,n,i,(l,s)=>{let y=Ae(l,s);at(t)?Q(`${y}
8
+ `):X.warn(y)});t.on("session_shutdown",()=>c.closeAll());let f={name:"uRun",api:te,baseUrl:"urun://session",apiKey:"$URUN_API_KEY",models:a.map(_t),streamSimple:Ce(c,e.timing??{},t)};t.registerProvider("urun",f)}}var vt=Me();0&&(module.exports={SessionPool,URUN_API,applyServeUsage,coalesceSameRole,createFileDiagnosticSink,createUrunExtension,makeSessionFactory,makeStreamSimple,notify,piDiagnosticLogPath,resolveSessionEnv,toResponsesInput});
@@ -1,7 +1,7 @@
1
1
  import { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
2
  import { Api, AssistantMessage, Model, Context, SimpleStreamOptions, AssistantMessageEventStream } from '@earendil-works/pi-ai';
3
- import { U as UrunResponses } from '../ResponsesClient-6QsC7NPJ.cjs';
4
- import { b as UrunSessionLike } from '../types-CHPtJx6d.cjs';
3
+ import { U as UrunResponses } from '../ResponsesClient-BJDe9EBw.cjs';
4
+ import { b as UrunSessionLike } from '../types-DiYzfHYN.cjs';
5
5
 
6
6
  /** Where the pi lane's quiet diagnostics land (the compat log convention). */
7
7
  declare function piDiagnosticLogPath(home?: string): string;
@@ -1,7 +1,7 @@
1
1
  import { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
2
  import { Api, AssistantMessage, Model, Context, SimpleStreamOptions, AssistantMessageEventStream } from '@earendil-works/pi-ai';
3
- import { U as UrunResponses } from '../ResponsesClient-gfg7qUoE.js';
4
- import { b as UrunSessionLike } from '../types-CHPtJx6d.js';
3
+ import { U as UrunResponses } from '../ResponsesClient-75VdSOY-.js';
4
+ import { b as UrunSessionLike } from '../types-DiYzfHYN.js';
5
5
 
6
6
  declare function piDiagnosticLogPath(home?: string): string;
7
7
 
@@ -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-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)}
1
+ import{a as z}from"../chunk-HB5KNEY5.js";import"../chunk-G6AFKOVS.js";import"../chunk-7KRHHEKZ.js";import{h as W,m as Q}from"../chunk-J3KCHTSA.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(`