@urun-sh/openai 0.6.53 → 0.6.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4UE7XH7T.js +21 -0
- package/dist/chunk-BVM4ZQ2Y.js +2 -0
- package/dist/{chunk-K5TQMHAY.js → chunk-HLSJAQHY.js} +2 -2
- package/dist/{chunk-XGAF2NDT.js → chunk-KNWFUWXY.js} +1 -1
- package/dist/{chunk-X5BLQXHK.js → chunk-KV3UXLNF.js} +1 -1
- package/dist/chunk-MYNG74AX.js +1 -0
- package/dist/{chunk-C452ZIU5.js → chunk-N3Y2GDQK.js} +5 -5
- package/dist/{chunk-7IT4XK2K.js → chunk-PPEND4SP.js} +18 -18
- package/dist/{chunk-ZWDQPTSH.js → chunk-Z74YK7AL.js} +1 -1
- package/dist/{composite-4ppY0Kv6.d.cts → composite-C1oeSkNz.d.cts} +19 -0
- package/dist/{composite-BKEde6hP.d.ts → composite-CmDZAzTq.d.ts} +6 -0
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +44 -43
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +44 -43
- package/dist/hosted/index.d.cts +106 -2
- package/dist/hosted/index.d.ts +45 -2
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +5 -5
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +22 -22
- package/dist/pooler/bin.cjs +12 -12
- package/dist/pooler/bin.js +8 -8
- package/dist/proxy/cli.cjs +35 -35
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +18 -18
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-5PA6542H.js +0 -20
- package/dist/chunk-64VO62LW.js +0 -1
- package/dist/chunk-D7PBMXB6.js +0 -2
package/dist/hosted/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Server } from 'node:http';
|
|
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-
|
|
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-C1oeSkNz.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';
|
|
@@ -309,6 +309,87 @@ declare class OrgResolver {
|
|
|
309
309
|
/** Test/ops seam: forget every cached binding. */
|
|
310
310
|
clear(): void;
|
|
311
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* URU-677 — THE MEMBERSHIP GATE (user rung only). A removed org member's
|
|
314
|
+
* pre-removal WorkOS access token stays cryptographically valid ~10 minutes
|
|
315
|
+
* after the removal, and before this gate the user rung trusted the token's
|
|
316
|
+
* own `org_id` claim with platform-level trust and NO control-plane
|
|
317
|
+
* membership re-check — so a removed member could keep serving (and
|
|
318
|
+
* billing) inference against the org for the whole stale-token window. The
|
|
319
|
+
* gate closes it: AFTER the local crypto verify and BEFORE the mint/binding
|
|
320
|
+
* (so a removed member is refused before any control-plane mint, dial, or
|
|
321
|
+
* ledger row), it asks the control plane's membership-check endpoint
|
|
322
|
+
* whether the token's `sub` is an active member of the token's `org_id`.
|
|
323
|
+
*
|
|
324
|
+
* FAIL-CLOSED EVERYWHERE: `active: false` is a 403, and so is every other
|
|
325
|
+
* outcome — a transport error, a timeout, a non-200 (including the
|
|
326
|
+
* endpoint's own 401), or an unparseable body. The gate never passes on
|
|
327
|
+
* "could not check"; the caller-facing message differs (not-a-member vs
|
|
328
|
+
* could-not-confirm) but the refusal does not. Org API keys and machine
|
|
329
|
+
* tokens NEVER pass through this gate (resolveCaller routes them to their
|
|
330
|
+
* own rungs) — only the WorkOS user rung consults it.
|
|
331
|
+
*/
|
|
332
|
+
/**
|
|
333
|
+
* How long one membership verdict is reused before the control plane is
|
|
334
|
+
* re-asked. The URU-677 stale-token window is ~10 minutes; this TTL bounds
|
|
335
|
+
* the serving window after a removal to ≈ TTL + requests already in flight,
|
|
336
|
+
* while keeping the signed-in user's request rate off the control plane.
|
|
337
|
+
* The value is the shared contract across the sibling gates (hub, infra).
|
|
338
|
+
*/
|
|
339
|
+
declare const MEMBERSHIP_VERDICT_TTL_MS = 5000;
|
|
340
|
+
/**
|
|
341
|
+
* The membership check's hard upper bound (~1500ms per the shared
|
|
342
|
+
* contract): a control-plane outage must refuse quickly, not park the
|
|
343
|
+
* caller's request until the HTTP client's own timeouts fire.
|
|
344
|
+
*/
|
|
345
|
+
declare const MEMBERSHIP_CHECK_TIMEOUT_MS = 1500;
|
|
346
|
+
/** The most distinct (org, subject) pairs one replica remembers (bounded memory). */
|
|
347
|
+
declare const MAX_CACHED_MEMBERSHIPS = 4096;
|
|
348
|
+
/** The URU-677 membership gate's inputs (see {@link MembershipGate}). */
|
|
349
|
+
interface MembershipGateOptions {
|
|
350
|
+
/** The control-plane edge-functions base URL (URUN_CONTROL_PLANE_URL, no trailing slash). */
|
|
351
|
+
url: string;
|
|
352
|
+
/** The shared secret presented as `Authorization: Bearer` (URUN_CONTROL_PLANE_TOKEN). */
|
|
353
|
+
token: string;
|
|
354
|
+
/** Injected in tests; production uses the platform fetch. */
|
|
355
|
+
fetchImpl?: typeof fetch;
|
|
356
|
+
/** Injected in tests so verdict TTL expiry is exercised without wall-clock waits. */
|
|
357
|
+
now?: () => number;
|
|
358
|
+
/** Injected in tests; production uses {@link MEMBERSHIP_CHECK_TIMEOUT_MS}. */
|
|
359
|
+
timeoutMs?: number;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* A refused membership check — 403, never a pass. The caller's line is the
|
|
363
|
+
* `message` (ENG-538: short, honest, no internals); `detail` carries the
|
|
364
|
+
* operator's evidence (why a fail-closed lookup refused) to the relay's
|
|
365
|
+
* operator sink, never to the caller.
|
|
366
|
+
*/
|
|
367
|
+
declare class MembershipRefusalError extends Error {
|
|
368
|
+
/** The wire status. */
|
|
369
|
+
readonly status = 403;
|
|
370
|
+
/** Operator-only evidence: why a fail-closed lookup refused. */
|
|
371
|
+
readonly detail?: string;
|
|
372
|
+
constructor(message: string, detail?: string);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* The URU-677 gate: one bounded POST per cold (org, subject), verdicts
|
|
376
|
+
* cached in-process for {@link MEMBERSHIP_VERDICT_TTL_MS}.
|
|
377
|
+
*/
|
|
378
|
+
declare class MembershipGate {
|
|
379
|
+
private readonly opts;
|
|
380
|
+
private readonly cache;
|
|
381
|
+
private readonly fetchImpl;
|
|
382
|
+
private readonly now;
|
|
383
|
+
private readonly timeoutMs;
|
|
384
|
+
constructor(opts: MembershipGateOptions);
|
|
385
|
+
/**
|
|
386
|
+
* Refuse (403) unless the control plane says `subject` is an ACTIVE member
|
|
387
|
+
* of `orgId`. Verdicts — active and inactive BOTH — are cached for the
|
|
388
|
+
* TTL; a failed lookup is NOT cached (a control-plane blip is not a
|
|
389
|
+
* verdict, and the next request retries immediately).
|
|
390
|
+
*/
|
|
391
|
+
assertActive(orgId: string, subject: string): Promise<void>;
|
|
392
|
+
}
|
|
312
393
|
|
|
313
394
|
/** Live gauges for the proxy's /metrics surface. */
|
|
314
395
|
interface DecisionPoolStats {
|
|
@@ -1375,6 +1456,29 @@ interface HostedConfig {
|
|
|
1375
1456
|
* client_01KNNB76BG5TEGZBHR0PA3M8AG`.
|
|
1376
1457
|
*/
|
|
1377
1458
|
userIssuers?: readonly string[];
|
|
1459
|
+
/**
|
|
1460
|
+
* URU-677 — THE MEMBERSHIP GATE (user rung only): launcher-injected
|
|
1461
|
+
* external inputs for the control-plane membership check that closes the
|
|
1462
|
+
* stale-token window a removed org member's pre-removal WorkOS access
|
|
1463
|
+
* token otherwise keeps open (~10 minutes). BOTH set ⇒ the gate is
|
|
1464
|
+
* ENABLED (fail-closed on any lookup failure or timeout, ~1500ms bound).
|
|
1465
|
+
* Either missing ⇒ the gate is DISABLED — deliberately NOT a
|
|
1466
|
+
* refuse-to-start half-configuration: the gate is an additive hardening
|
|
1467
|
+
* of the user rung, and an unconfigured gate must never break existing
|
|
1468
|
+
* deployments. The user rung logs ONE loud line at its first use
|
|
1469
|
+
* ("member gate disabled — removed-member window remains open") so the
|
|
1470
|
+
* open window stays visible to operators.
|
|
1471
|
+
*
|
|
1472
|
+
* URUN_CONTROL_PLANE_URL the control plane's edge-functions base URL
|
|
1473
|
+
* (no trailing slash) hosting
|
|
1474
|
+
* POST /membership-check;
|
|
1475
|
+
* URUN_CONTROL_PLANE_TOKEN the shared secret the gate presents as
|
|
1476
|
+
* `Authorization: Bearer` on that call.
|
|
1477
|
+
*/
|
|
1478
|
+
memberGate?: {
|
|
1479
|
+
url: string;
|
|
1480
|
+
token: string;
|
|
1481
|
+
};
|
|
1378
1482
|
}
|
|
1379
1483
|
/**
|
|
1380
1484
|
* Read and VALIDATE the deployment's external inputs. Every failure is loud
|
|
@@ -1698,4 +1802,4 @@ declare function bearerTokenOf(headerValue: string | undefined): string | null;
|
|
|
1698
1802
|
*/
|
|
1699
1803
|
declare function createEdgeIdentityServer(): Server;
|
|
1700
1804
|
|
|
1701
|
-
export { ANONYMOUS_KEY_ID, BIND_HOST, BUCKET_DOMAIN, BoundedLabel, type CallerIdentity, ControlPlaneUnavailableError, type ConversationBackhaulOptions, ConversationBackhauls, ConversationCapacityError, DEFAULT_PORT, EDGE_IDENTITY_PORT, EDGE_KEY_FINGERPRINT_HEADER, EDGE_KEY_ID_HEADER, type HostedConfig, type HostedProxyOptions, InferenceMetrics, LEDGER_FUNCTION_PATH, LEDGER_WRITE_TIMEOUT_MS, LedgerClient, type LedgerClientOptions, LedgerDuplicateError, LedgerSurfaceError, MAX_CACHED_KEYS, MAX_CONVERSATIONS, MAX_CONVERSATION_HANDLES, MAX_MODEL_LABELS, MAX_ORG_LABELS, MAX_TENANTS, METRICS_PATH, METRICS_PORT, NO_MODEL_LABEL, ORG_BINDING_TTL_MS, OTHER_LABEL, OrgResolver, type OrgResolverOptions, type PrivateConversationBackhaul, type PrivateConversationConnection, ProxyAuthError, READINESS_TIMEOUT_MS, READINESS_TTL_MS, SERVE_FUNCTION, TIER_DOMAIN, TenantRegistry, type TenantRegistryOptions, bearerFrom, bearerTokenOf, createEdgeIdentityServer, createHostedProxy, createMetricsServer, edgeBucketId, edgeTierFingerprint, laneOf, parseLedgerRecorded, resolveHostedConfig, statusClassOf, tenantSubject };
|
|
1805
|
+
export { ANONYMOUS_KEY_ID, BIND_HOST, BUCKET_DOMAIN, BoundedLabel, type CallerIdentity, ControlPlaneUnavailableError, type ConversationBackhaulOptions, ConversationBackhauls, ConversationCapacityError, DEFAULT_PORT, EDGE_IDENTITY_PORT, EDGE_KEY_FINGERPRINT_HEADER, EDGE_KEY_ID_HEADER, type HostedConfig, type HostedProxyOptions, InferenceMetrics, LEDGER_FUNCTION_PATH, LEDGER_WRITE_TIMEOUT_MS, LedgerClient, type LedgerClientOptions, LedgerDuplicateError, LedgerSurfaceError, MAX_CACHED_KEYS, MAX_CACHED_MEMBERSHIPS, MAX_CONVERSATIONS, MAX_CONVERSATION_HANDLES, MAX_MODEL_LABELS, MAX_ORG_LABELS, MAX_TENANTS, MEMBERSHIP_CHECK_TIMEOUT_MS, MEMBERSHIP_VERDICT_TTL_MS, METRICS_PATH, METRICS_PORT, MembershipGate, type MembershipGateOptions, MembershipRefusalError, NO_MODEL_LABEL, ORG_BINDING_TTL_MS, OTHER_LABEL, OrgResolver, type OrgResolverOptions, type PrivateConversationBackhaul, type PrivateConversationConnection, ProxyAuthError, READINESS_TIMEOUT_MS, READINESS_TTL_MS, SERVE_FUNCTION, TIER_DOMAIN, TenantRegistry, type TenantRegistryOptions, bearerFrom, bearerTokenOf, createEdgeIdentityServer, createHostedProxy, createMetricsServer, edgeBucketId, edgeTierFingerprint, laneOf, parseLedgerRecorded, resolveHostedConfig, statusClassOf, tenantSubject };
|
package/dist/hosted/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Server } from 'node:http';
|
|
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-
|
|
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-CmDZAzTq.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';
|
|
@@ -131,6 +131,44 @@ declare class OrgResolver {
|
|
|
131
131
|
clear(): void;
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
+
declare const MEMBERSHIP_VERDICT_TTL_MS = 5000;
|
|
135
|
+
|
|
136
|
+
declare const MEMBERSHIP_CHECK_TIMEOUT_MS = 1500;
|
|
137
|
+
|
|
138
|
+
declare const MAX_CACHED_MEMBERSHIPS = 4096;
|
|
139
|
+
|
|
140
|
+
interface MembershipGateOptions {
|
|
141
|
+
|
|
142
|
+
url: string;
|
|
143
|
+
|
|
144
|
+
token: string;
|
|
145
|
+
|
|
146
|
+
fetchImpl?: typeof fetch;
|
|
147
|
+
|
|
148
|
+
now?: () => number;
|
|
149
|
+
|
|
150
|
+
timeoutMs?: number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
declare class MembershipRefusalError extends Error {
|
|
154
|
+
|
|
155
|
+
readonly status = 403;
|
|
156
|
+
|
|
157
|
+
readonly detail?: string;
|
|
158
|
+
constructor(message: string, detail?: string);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
declare class MembershipGate {
|
|
162
|
+
private readonly opts;
|
|
163
|
+
private readonly cache;
|
|
164
|
+
private readonly fetchImpl;
|
|
165
|
+
private readonly now;
|
|
166
|
+
private readonly timeoutMs;
|
|
167
|
+
constructor(opts: MembershipGateOptions);
|
|
168
|
+
|
|
169
|
+
assertActive(orgId: string, subject: string): Promise<void>;
|
|
170
|
+
}
|
|
171
|
+
|
|
134
172
|
interface DecisionPoolStats {
|
|
135
173
|
|
|
136
174
|
requested: number;
|
|
@@ -499,6 +537,11 @@ interface HostedConfig {
|
|
|
499
537
|
};
|
|
500
538
|
|
|
501
539
|
userIssuers?: readonly string[];
|
|
540
|
+
|
|
541
|
+
memberGate?: {
|
|
542
|
+
url: string;
|
|
543
|
+
token: string;
|
|
544
|
+
};
|
|
502
545
|
}
|
|
503
546
|
|
|
504
547
|
declare function resolveHostedConfig(env?: NodeJS.ProcessEnv): HostedConfig;
|
|
@@ -565,4 +608,4 @@ declare function bearerTokenOf(headerValue: string | undefined): string | null;
|
|
|
565
608
|
|
|
566
609
|
declare function createEdgeIdentityServer(): Server;
|
|
567
610
|
|
|
568
|
-
export { ANONYMOUS_KEY_ID, BIND_HOST, BUCKET_DOMAIN, BoundedLabel, type CallerIdentity, ControlPlaneUnavailableError, type ConversationBackhaulOptions, ConversationBackhauls, ConversationCapacityError, DEFAULT_PORT, EDGE_IDENTITY_PORT, EDGE_KEY_FINGERPRINT_HEADER, EDGE_KEY_ID_HEADER, type HostedConfig, type HostedProxyOptions, InferenceMetrics, LEDGER_FUNCTION_PATH, LEDGER_WRITE_TIMEOUT_MS, LedgerClient, type LedgerClientOptions, LedgerDuplicateError, LedgerSurfaceError, MAX_CACHED_KEYS, MAX_CONVERSATIONS, MAX_CONVERSATION_HANDLES, MAX_MODEL_LABELS, MAX_ORG_LABELS, MAX_TENANTS, METRICS_PATH, METRICS_PORT, NO_MODEL_LABEL, ORG_BINDING_TTL_MS, OTHER_LABEL, OrgResolver, type OrgResolverOptions, type PrivateConversationBackhaul, type PrivateConversationConnection, ProxyAuthError, READINESS_TIMEOUT_MS, READINESS_TTL_MS, SERVE_FUNCTION, TIER_DOMAIN, TenantRegistry, type TenantRegistryOptions, bearerFrom, bearerTokenOf, createEdgeIdentityServer, createHostedProxy, createMetricsServer, edgeBucketId, edgeTierFingerprint, laneOf, parseLedgerRecorded, resolveHostedConfig, statusClassOf, tenantSubject };
|
|
611
|
+
export { ANONYMOUS_KEY_ID, BIND_HOST, BUCKET_DOMAIN, BoundedLabel, type CallerIdentity, ControlPlaneUnavailableError, type ConversationBackhaulOptions, ConversationBackhauls, ConversationCapacityError, DEFAULT_PORT, EDGE_IDENTITY_PORT, EDGE_KEY_FINGERPRINT_HEADER, EDGE_KEY_ID_HEADER, type HostedConfig, type HostedProxyOptions, InferenceMetrics, LEDGER_FUNCTION_PATH, LEDGER_WRITE_TIMEOUT_MS, LedgerClient, type LedgerClientOptions, LedgerDuplicateError, LedgerSurfaceError, MAX_CACHED_KEYS, MAX_CACHED_MEMBERSHIPS, MAX_CONVERSATIONS, MAX_CONVERSATION_HANDLES, MAX_MODEL_LABELS, MAX_ORG_LABELS, MAX_TENANTS, MEMBERSHIP_CHECK_TIMEOUT_MS, MEMBERSHIP_VERDICT_TTL_MS, METRICS_PATH, METRICS_PORT, MembershipGate, type MembershipGateOptions, MembershipRefusalError, NO_MODEL_LABEL, ORG_BINDING_TTL_MS, OTHER_LABEL, OrgResolver, type OrgResolverOptions, type PrivateConversationBackhaul, type PrivateConversationConnection, ProxyAuthError, READINESS_TIMEOUT_MS, READINESS_TTL_MS, SERVE_FUNCTION, TIER_DOMAIN, TenantRegistry, type TenantRegistryOptions, bearerFrom, bearerTokenOf, createEdgeIdentityServer, createHostedProxy, createMetricsServer, edgeBucketId, edgeTierFingerprint, laneOf, parseLedgerRecorded, resolveHostedConfig, statusClassOf, tenantSubject };
|
package/dist/hosted/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as
|
|
1
|
+
import{A as g,B as x,C as H,D as B,E as P,F as v,G as y,H as u,I as G,J as h,K as U,L as b,M as X,N as F,O as K,P as Y,Q as k,R as V,S as j,T as W,U as q,V as w,W as z,X as J,Y as Q,Z,a as r,b as o,c as t,d as E,e as _,f as n,g as a,h as T,i,j as s,k as M,l as O,m as p,n as I,o as R,p as S,q as A,r as C,s as D,t as N,u as f,v as L,w as d,x as l,y as m,z as c}from"../chunk-4UE7XH7T.js";import"../chunk-HLSJAQHY.js";import"../chunk-CAR4AEQJ.js";import"../chunk-PPEND4SP.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import"../chunk-BVM4ZQ2Y.js";import"../chunk-KNWFUWXY.js";import"../chunk-Z74YK7AL.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{A as ANONYMOUS_KEY_ID,G as BIND_HOST,R as BUCKET_DOMAIN,i as BoundedLabel,d as ControlPlaneUnavailableError,k as ConversationBackhauls,Y as ConversationCapacityError,y as DEFAULT_PORT,O as EDGE_IDENTITY_PORT,I as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,s as InferenceMetrics,V as LEDGER_FUNCTION_PATH,j as LEDGER_WRITE_TIMEOUT_MS,z as LedgerClient,W as LedgerDuplicateError,q as LedgerSurfaceError,c as MAX_CACHED_KEYS,B as MAX_CACHED_MEMBERSHIPS,F as MAX_CONVERSATIONS,K as MAX_CONVERSATION_HANDLES,_ as MAX_MODEL_LABELS,n as MAX_ORG_LABELS,U as MAX_TENANTS,H as MEMBERSHIP_CHECK_TIMEOUT_MS,x as MEMBERSHIP_VERDICT_TTL_MS,o as METRICS_PATH,r as METRICS_PORT,v as MembershipGate,P as MembershipRefusalError,E as NO_MODEL_LABEL,m as ORG_BINDING_TTL_MS,t as OTHER_LABEL,g as OrgResolver,L as ProxyAuthError,Q as READINESS_TIMEOUT_MS,J as READINESS_TTL_MS,u as SERVE_FUNCTION,S as TIER_DOMAIN,X as TenantRegistry,l as bearerFrom,N as bearerTokenOf,f as createEdgeIdentityServer,Z as createHostedProxy,M as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,w as parseLedgerRecorded,h as resolveHostedConfig,T as statusClassOf,b as tenantSubject};
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ne=Object.create;var _=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var se=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ae=(e,t)=>{for(var n in t)_(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of oe(t))!ie.call(e,o)&&o!==n&&_(e,o,{get:()=>t[o],enumerable:!(r=re(t,o))||r.enumerable});return e};var O=(e,t,n)=>(n=e!=null?ne(se(e)):{},V(t||!e||!e.__esModule?_(n,"default",{value:e,enumerable:!0}):n,e)),de=e=>V(_({},"__esModule",{value:!0}),e);var be={};ae(be,{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:()=>K,consumeVideoOut:()=>Q,decodeVideoOutRecord:()=>S,encodeVideoOutRecord:()=>Y,isSupportedClientEvent:()=>X,isSupportedResponsesEvent:()=>Z,listModels:()=>j,negotiateSessionVideoOutQuic:()=>J,nodeAudioBackend:()=>W,openSessionVideoOutLane:()=>z,toErrorEvent:()=>m,weriftAudioBackend:()=>N});module.exports=de(be);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)})}var B=require("@urun-sh/core/internal");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),typeof o.model=="string"&&o.model&&(s.model=o.model),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 ue="llm-resp";async function*ce(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=`${ue}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*ce(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)})}cancelTurn(t){try{(0,B.gcRequest)(this.session.doc("llm"),t)}catch{}}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 $="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 F(e,t,n=1e4){try{return await pe(e,t,n)}catch(r){try{t.dispose?.()}catch{}throw r}}async function pe(e,t,n){let r=new R(t,{sampleRate:24e3}),o=await r.startOutbound(),s=e.stream($);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let a=await fe(e,n);return await r.startInbound(a),r}function fe(e,t){let n=e.stream($);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 me=24e3,w=480,ge=111,he=50,k=null;async function ye(){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(me,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>=he}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 N(){let e=await import("werift");await ye();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 ee=new e.RtpHeader({version:2,payloadType:ge,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),te=new e.RtpPacket(ee,U);n.writeRtp(te)}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 W(){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 H=0;function _e(){return H+=1,`rt_${Date.now().toString(36)}_${H.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 F(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=_e();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 q=0;function ke(){return q+=1,`req_${Date.now().toString(36)}_${q.toString(36)}`}var E=class{transport;constructor(t,n){this.transport=new g(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=ke(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function ve(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 j(e){return{object:"list",data:(await ve(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 G(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 Y(e,t){if(G(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;G(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 J(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 K="urun.videoOut.v2-ws";function z(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 Ee(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 Q(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:Ee(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 X(e){return L.includes(e)}function Z(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});
|
|
1
|
+
"use strict";var ne=Object.create;var _=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var se=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ae=(e,t)=>{for(var n in t)_(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of oe(t))!ie.call(e,o)&&o!==n&&_(e,o,{get:()=>t[o],enumerable:!(r=re(t,o))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?ne(se(e)):{},V(t||!e||!e.__esModule?_(n,"default",{value:e,enumerable:!0}):n,e)),de=e=>V(_({},"__esModule",{value:!0}),e);var be={};ae(be,{RT_VIDEO_OUT_STREAM:()=>h,SUPPORTED_REALTIME_CLIENT_EVENTS:()=>x,SUPPORTED_RESPONSES_EVENTS:()=>I,UrunRealtime:()=>v,UrunResponses:()=>E,VIDEO_OUT_DEFAULT_CODEC:()=>b,VIDEO_OUT_FRAMING:()=>L,VIDEO_OUT_WS_FRAMING:()=>J,consumeVideoOut:()=>z,decodeVideoOutRecord:()=>S,encodeVideoOutRecord:()=>Y,isSupportedClientEvent:()=>X,isSupportedResponsesEvent:()=>Z,listModels:()=>j,negotiateSessionVideoOutQuic:()=>K,nodeAudioBackend:()=>W,openSessionVideoOutLane:()=>Q,toErrorEvent:()=>m,weriftAudioBackend:()=>F});module.exports=de(be);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)})}var B=require("@urun-sh/core/internal");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),typeof o.model=="string"&&o.model&&(s.model=o.model),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 ue="llm-resp";async function*ce(e,t){let n=`resp_${e}`,r=new Map;for await(let o of t){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let u=typeof a.index=="number"?a.index:0,i=r.get(u)??{};a.id&&(i.id=a.id),a.function?.name&&(i.name=a.function.name),r.set(u,i),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:i.id,name:i.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield m(s);return}}}async function*O(e,t){let n=`${ue}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*ce(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),O(this.session,n)})}sendResponseCreate(t,n,r){return this.writeGated(r,()=>{let o=D(t,n,r,this.consumerId);return this.write(o),O(this.session,r)})}cancelTurn(t){try{(0,B.gcRequest)(this.session.doc("llm"),t)}catch{}}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 $="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 N(e,t,n=1e4){try{return await pe(e,t,n)}catch(r){try{t.dispose?.()}catch{}throw r}}async function pe(e,t,n){let r=new R(t,{sampleRate:24e3}),o=await r.startOutbound(),s=e.stream($);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let a=await fe(e,n);return await r.startInbound(a),r}function fe(e,t){let n=e.stream($);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 me=24e3,w=480,ge=111,he=50,k=null;async function ye(){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(me,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>=he}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 ye();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 ee=new e.RtpHeader({version:2,payloadType:ge,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),te=new e.RtpPacket(ee,U);n.writeRtp(te)}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 W(){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 H=0;function _e(){return H+=1,`rt_${Date.now().toString(36)}_${H.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 N(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=_e();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 q=0;function ke(){return q+=1,`req_${Date.now().toString(36)}_${q.toString(36)}`}var E=class{transport;constructor(t,n){this.transport=new g(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=ke(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};async function ve(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 j(e){return{object:"list",data:(await ve(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",L="urun.videoOut.v1",b="h264";function G(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 Y(e,t){if(G(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;G(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 K(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:L}}var J="urun.videoOut.v2-ws";function Q(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 Ee(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:Ee(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 x=["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 X(e){return x.includes(e)}function Z(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.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as S}from"./chunk-CAR4AEQJ.js";import{
|
|
1
|
+
import{b as S}from"./chunk-CAR4AEQJ.js";import{d,h as v,i as f,j as R,k as y,l as O,m as h,n as x,o as g,p as k,q as A,r as T}from"./chunk-MYNG74AX.js";import{a as _}from"./chunk-526ZJAOW.js";import{c as i,f as a}from"./chunk-AWCC5WRB.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 Le=Object.create;var j=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var je=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var Je=(e,t)=>{for(var n in t)j(e,n,{get:t[n],enumerable:!0})},ie=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fe(t))!Ke.call(e,o)&&o!==n&&j(e,o,{get:()=>t[o],enumerable:!(r=De(t,o))||r.enumerable});return e};var ae=(e,t,n)=>(n=e!=null?Le(je(e)):{},ie(t||!e||!e.__esModule?j(n,"default",{value:e,enumerable:!0}):n,e)),Be=e=>ie(j({},"__esModule",{value:!0}),e);var Rt={};Je(Rt,{SessionPool:()=>G,URUN_API:()=>te,applyServeUsage:()=>Ce,coalesceSameRole:()=>
|
|
1
|
+
"use strict";var Le=Object.create;var j=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var je=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var Je=(e,t)=>{for(var n in t)j(e,n,{get:t[n],enumerable:!0})},ie=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fe(t))!Ke.call(e,o)&&o!==n&&j(e,o,{get:()=>t[o],enumerable:!(r=De(t,o))||r.enumerable});return e};var ae=(e,t,n)=>(n=e!=null?Le(je(e)):{},ie(t||!e||!e.__esModule?j(n,"default",{value:e,enumerable:!0}):n,e)),Be=e=>ie(j({},"__esModule",{value:!0}),e);var Rt={};Je(Rt,{SessionPool:()=>G,URUN_API:()=>te,applyServeUsage:()=>Ce,coalesceSameRole:()=>Pe,createFileDiagnosticSink:()=>Ee,createUrunExtension:()=>Me,default:()=>bt,makeSessionFactory:()=>Ae,makeStreamSimple:()=>Oe,notify:()=>ee,piDiagnosticLogPath:()=>H,resolveSessionEnv:()=>xe,toResponsesInput:()=>$e});module.exports=Be(Rt);var qe=()=>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=qe();var ke=require("@earendil-works/pi-ai"),O=require("fs"),Te=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)})}var ge=require("@urun-sh/core/internal");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),typeof o.model=="string"&&o.model&&(i.model=o.model),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 He="llm-resp";async function*Ge(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=`${He}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*Ge(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)})}cancelTurn(t){try{(0,ge.gcRequest)(this.session.doc("llm"),t)}catch{}}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 fe=0;function We(){return fe+=1,`req_${Date.now().toString(36)}_${fe.toString(36)}`}var J=class{transport;constructor(t,n){this.transport=new K(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=We(),r=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var B=require("fs"),he=ae(require("os"),1),q=require("path"),ye=require("util");function H(e=he.default.homedir()){return(0,q.join)(e,".urun","logs","pi-extension.log")}var me=!1;function we(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,ye.format)(...t)}
|
|
2
2
|
`)}catch(r){if(!me){me=!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)=>we(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||we("assert",t.length>0?t:["Assertion failed"])}};function Q(e){try{process.stderr.write(e)}catch{}}var Qe=require("crypto");var Z="https://api.urun.sh/v1";async function _e(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 ve(e){let t=await _e(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",Ze="serve",et=131072,tt=16384,be=3,nt=42e4,rt=6e4,Re=2,ot=15e3;function st(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()||Ze}}function xe(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 Ee(e){let t=null;return n=>{t===null&&((0,
|
|
4
|
-
`)}}function Ae(e){let t=Ee(H());return async(n,r,o)=>{let{baseUrl:i,orgId:a,auth:c}=xe(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
|
|
3
|
+
`)}catch{}}}}var m=e=>(...t)=>we(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||we("assert",t.length>0?t:["Assertion failed"])}};function Q(e){try{process.stderr.write(e)}catch{}}var Qe=require("crypto");var Z="https://api.urun.sh/v1";async function _e(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 ve(e){let t=await _e(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",Ze="serve",et=131072,tt=16384,be=3,nt=42e4,rt=6e4,Re=2,ot=15e3;function st(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()||Ze}}function xe(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 Ee(e){let t=null;return n=>{t===null&&((0,O.mkdirSync)((0,Te.dirname)(e),{recursive:!0}),t=(0,O.openSync)(e,"a"));let r=n.detail?` ${JSON.stringify(n.detail)}`:"";(0,O.writeSync)(t,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${r}
|
|
4
|
+
`)}}function Ae(e){let t=Ee(H());return async(n,r,o)=>{let{baseUrl:i,orgId:a,auth:c}=xe(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 I=_.connect;return typeof I=="function"&&await I.call(_),_}}var it=Ae(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 at(e,t){try{return Promise.resolve(e.end()).then(()=>{},n=>t(n))}catch(n){return t(n),Promise.resolve()}}function lt(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 Ie(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(Ie(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=>at(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:dt(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:ut(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
6
|
`):t.push({...n})}return t}function ut(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&"text"in t?String(t.text):"").join(""):""}function dt(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 ct(e){if(!(!Array.isArray(e)||e.length===0))return e.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters}))}function Se(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 pt(e){let t=e?.output;return Array.isArray(t)?t.filter(n=>n.type==="function_call"):[]}function Ce(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 gt(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 ft=["<tool_call>","<function="];function mt(e,t){let n=ft.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 ht(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 yt(e){return new Promise(t=>setTimeout(t,e))}function wt(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*_t(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
|
|
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(vt),streamSimple:
|
|
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 Oe(e,t={},n){let r=t.connectDeadlineMs??nt,o=t.stallTimeoutMs??rt,i=t.phaseHeartbeatMs??ot;return(a,c,f)=>{let l=(0,ke.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,I=!1,D=()=>{I=!0,y.abort()};_&&(_.aborted?D():_.addEventListener("abort",D,{once:!0}));let M=!1,$,ne=()=>{$&&clearTimeout($),$=setTimeout(()=>{M=!0,y.abort()},o)},F=()=>{$&&clearTimeout($),$=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=Se(p.name,b),l.push({type:"toolcall_end",contentIndex:x,toolCall:p,partial:s})},Ue=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=Se(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 Ne=async R=>{let{responses:S}=await wt(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 P,E;for(let u=1;u<=be;u++)try{let w=await S.responses.create({model:a.id,input:R,stream:!0,tools:ct(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 _t(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"){P=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(!P)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<be&&ht(w)&&!U){await yt(u*500);continue}throw w}if(E)throw E;return P};try{let R=$e(c),S;for(let u=1;u<=Re;u++)try{S=await Ne(R);break}catch(w){let A=M||w instanceof z;if(u>=Re||!A||U||I)throw w;F(),e.evict(a.id),M=!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(F(),W(),oe(),Y(),!s.content.some(u=>u.type==="toolCall"))for(let u of pt(S))Ue(u);if(!s.content.some(u=>u.type==="thinking")){let u=gt(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 P=s.content.filter(u=>u.type==="toolCall").length;if((c.tools?.length??0)>0&&P===0){let u=mt(a.id,re);if(u)throw u}let E=P>0?"toolUse":S?.status==="incomplete"?"length":"stop";s.stopReason=E,Ce(s.usage,S),l.push({type:"done",reason:E,message:s}),l.end(s)}catch(R){if(p=!0,F(),I||_?.aborted&&!M)s.stopReason="aborted",s.errorMessage="aborted by user",l.push({type:"error",reason:"aborted",error:s});else{let S=M?`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{F(),x(),_&&_.removeEventListener("abort",D),p&&e.evict(a.id)}})(),l}}function vt(e){return{id:e,name:`uRun ${e}`,api:te,reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:et,maxTokens:tt}}function Me(e={}){return async t=>{let n=e.env??process.env,{apiKey:r,apiUrl:o,fnName:i}=st(n),a=await ve({apiUrl:o,apiKey:r,fnName:i,fetchImpl:e.fetchImpl}),c=new G(e.openSession??it,n,i,(l,s)=>{let y=Ie(l,s);lt(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(vt),streamSimple:Oe(c,e.timing??{},t)};t.registerProvider("urun",f)}}var bt=Me();0&&(module.exports={SessionPool,URUN_API,applyServeUsage,coalesceSameRole,createFileDiagnosticSink,createUrunExtension,makeSessionFactory,makeStreamSimple,notify,piDiagnosticLogPath,resolveSessionEnv,toResponsesInput});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as z}from"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import{h as W,o as Q}from"../chunk-
|
|
1
|
+
import{a as z}from"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import{h as W,o as Q}from"../chunk-N3Y2GDQK.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(`
|