@inferencesh/sdk 0.38.6 → 0.38.8

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.
@@ -1,6 +1,6 @@
1
1
  import { HttpClient } from '../http/client.js';
2
2
  import type { Response } from '../http/response.js';
3
- import { LiveSession, type LiveHandlers, type WebSocketConstructor } from '../live/session.js';
3
+ import { LiveSession, type LiveHandlers, type RealtimeOptions, type WebSocketConstructor } from '../live/session.js';
4
4
  import type { JsonSchema } from '../live/schema.js';
5
5
  import { CursorListRequest, CursorListResponse, SocketAccess, SocketDTO, TaskDTO as Task } from '../types.js';
6
6
  import type { TasksAPI } from './tasks.js';
@@ -21,6 +21,8 @@ export interface OpenSocketOptions {
21
21
  inputSchema?: JsonSchema | null;
22
22
  /** The function's output schema: frames arrive at `onUpdate` as fields. */
23
23
  outputSchema?: JsonSchema | null;
24
+ /** The binary frames sent are live media (a microphone); see LiveSessionOptions.realtime. */
25
+ realtime?: boolean | RealtimeOptions;
24
26
  }
25
27
  /**
26
28
  * Sockets API: the duplex connection of a stream task.
@@ -56,6 +56,7 @@ export class SocketsAPI {
56
56
  webSocket: options.webSocket,
57
57
  inputSchema: options.inputSchema,
58
58
  outputSchema: options.outputSchema,
59
+ realtime: options.realtime,
59
60
  });
60
61
  session.connect();
61
62
  return session;
package/dist/index.d.ts CHANGED
@@ -27,8 +27,8 @@ export { SearchAPI } from './api/search.js';
27
27
  export { ProjectsAPI } from './api/projects.js';
28
28
  export { MCPServersAPI } from './api/mcp-servers.js';
29
29
  export { LiveSession, accessUrl } from './live/session.js';
30
- export type { LiveState, LiveEnd, LiveHandlers, LiveSessionOptions, LiveUpdate, WebSocketLike, WebSocketConstructor } from './live/session.js';
31
- export { STREAM_FORMAT, CLEAR_KEY, ERROR_KEY, REDIAL_CODES } from './live/protocol.js';
30
+ export type { LiveState, LiveEnd, LiveHandlers, LiveSessionOptions, RealtimeOptions, LiveUpdate, WebSocketLike, WebSocketConstructor } from './live/session.js';
31
+ export { STREAM_FORMAT, CLEAR_KEY, ERROR_KEY, REDIAL_CODES, RELAY_KEY } from './live/protocol.js';
32
32
  export { isLiveField, parseMediaType, pcmFormat, splitLiveSchema, binaryLiveField, alternativeLabel, alternativeTag, } from './live/schema.js';
33
33
  export type { JsonSchema, MediaType, PCMFormat, LiveField } from './live/schema.js';
34
34
  export { tool, appTool, agentTool, webhookTool, httpTool, callTool, mcpTool, internalTools, string, number, integer, boolean, enumOf, object, array, optional, } from './tool-builder.js';
package/dist/index.js CHANGED
@@ -29,7 +29,7 @@ export { ProjectsAPI } from './api/projects.js';
29
29
  export { MCPServersAPI } from './api/mcp-servers.js';
30
30
  // Live: the socket of a stream task and the live fields of its schemas
31
31
  export { LiveSession, accessUrl } from './live/session.js';
32
- export { STREAM_FORMAT, CLEAR_KEY, ERROR_KEY, REDIAL_CODES } from './live/protocol.js';
32
+ export { STREAM_FORMAT, CLEAR_KEY, ERROR_KEY, REDIAL_CODES, RELAY_KEY } from './live/protocol.js';
33
33
  export { isLiveField, parseMediaType, pcmFormat, splitLiveSchema, binaryLiveField, alternativeLabel, alternativeTag, } from './live/schema.js';
34
34
  // Tool Builder (fluent API)
35
35
  export { tool, appTool, agentTool, webhookTool, httpTool, callTool, mcpTool, internalTools, string, number, integer, boolean, enumOf, object, array, optional, } from './tool-builder.js';
@@ -11,6 +11,12 @@ export declare const CLEAR_KEY = "$clear";
11
11
  * else the caller should be told went wrong. The stream goes on.
12
12
  */
13
13
  export declare const ERROR_KEY = "$error";
14
+ /**
15
+ * `{"$relay": "waiting" | "paired"}`: written by the relay, not the app, to a
16
+ * client that dialed with `?signals=paired`. "waiting" on attach says this
17
+ * relay reports pairing; "paired" says the worker is there.
18
+ */
19
+ export declare const RELAY_KEY = "$relay";
14
20
  /**
15
21
  * Relay close codes that mean "dial again". 1012: the relay is restarting and
16
22
  * closed an end that still waited for its peer. 1013: the peer did not come in
@@ -13,6 +13,12 @@ export const CLEAR_KEY = '$clear';
13
13
  * else the caller should be told went wrong. The stream goes on.
14
14
  */
15
15
  export const ERROR_KEY = '$error';
16
+ /**
17
+ * `{"$relay": "waiting" | "paired"}`: written by the relay, not the app, to a
18
+ * client that dialed with `?signals=paired`. "waiting" on attach says this
19
+ * relay reports pairing; "paired" says the worker is there.
20
+ */
21
+ export const RELAY_KEY = '$relay';
16
22
  /**
17
23
  * Relay close codes that mean "dial again". 1012: the relay is restarting and
18
24
  * closed an end that still waited for its peer. 1013: the peer did not come in
@@ -80,6 +80,8 @@ export interface WebSocketLike {
80
80
  }) => void) | null;
81
81
  send(data: string | ArrayBuffer | ArrayBufferView): void;
82
82
  close(code?: number, reason?: string): void;
83
+ /** Bytes queued and not yet sent; browsers and `ws` have it. */
84
+ readonly bufferedAmount?: number;
83
85
  }
84
86
  export type WebSocketConstructor = new (url: string) => WebSocketLike;
85
87
  export interface LiveSessionOptions {
@@ -99,6 +101,27 @@ export interface LiveSessionOptions {
99
101
  inputSchema?: JsonSchema | null;
100
102
  /** The function's output schema: frames arrive at onUpdate as fields. */
101
103
  outputSchema?: JsonSchema | null;
104
+ /**
105
+ * The binary frames sent are live media, a microphone: perishable, so late
106
+ * is worse than lost. The session then holds them until the app can read
107
+ * them (the relay says the socket paired, or the app's first frame
108
+ * arrives), keeping only the newest few, and drops a frame rather than
109
+ * queue it behind a full send buffer. Leave it off for binary data that
110
+ * must all arrive (a file sent in chunks).
111
+ */
112
+ realtime?: boolean | RealtimeOptions;
113
+ }
114
+ export interface RealtimeOptions {
115
+ /** Binary frames kept while the app cannot read yet, the newest (default 5: 100 ms of 20 ms frames). */
116
+ holdFrames?: number;
117
+ /** Bytes the WebSocket may have queued before a binary frame is dropped (default 8192: about 250 ms of 16 kHz audio). */
118
+ maxBufferedAmount?: number;
119
+ /**
120
+ * How long to wait, once open, for the relay to say it will report pairing.
121
+ * A relay that does not (an older one) is treated as today: frames go out
122
+ * once the socket is open. Default 1500 ms.
123
+ */
124
+ signalTimeoutMs?: number;
102
125
  }
103
126
  /**
104
127
  * Where to dial. A browser cannot set headers on a WebSocket, so the
@@ -121,13 +144,29 @@ export declare class LiveSession {
121
144
  private readonly inputKnown;
122
145
  private readonly inputBinary;
123
146
  private resolveEnded;
147
+ private readonly realtime;
148
+ /** Realtime: binary frames may go out now. Set per connection. */
149
+ private released;
150
+ private held;
151
+ private signalTimer;
152
+ private dropped;
124
153
  /** Settles when the session has ended, however it ended. */
125
154
  readonly ended: Promise<LiveEnd>;
126
155
  constructor(options: LiveSessionOptions);
127
156
  get state(): LiveState;
128
157
  get isOpen(): boolean;
158
+ /** Realtime: binary frames dropped, as stale (held past holdFrames) or behind a full send buffer. */
159
+ get droppedFrames(): number;
129
160
  /** Dials the relay. The session reports its progress through onState. */
130
161
  connect(): void;
162
+ /**
163
+ * `{"$relay": "waiting" | "paired"}`, written by the relay itself to a
164
+ * client that dialed with ?signals=paired. True when the frame was one.
165
+ */
166
+ private relaySignal;
167
+ /** Realtime: the app can read now. Sends the newest held frames and stops holding. */
168
+ private release;
169
+ private clearSignalTimer;
131
170
  private deliverText;
132
171
  /** `{"error": {"message": ...}}` from an app on an older SDK, unless the output has an `error` field. */
133
172
  private legacyError;
@@ -1,6 +1,7 @@
1
- import { CLEAR_KEY, ERROR_KEY, REDIAL_CODES } from './protocol.js';
1
+ import { CLEAR_KEY, ERROR_KEY, REDIAL_CODES, RELAY_KEY } from './protocol.js';
2
2
  import { binaryLiveField, splitLiveSchema } from './schema.js';
3
3
  const WS_OPEN = 1;
4
+ const REALTIME_DEFAULTS = { holdFrames: 5, maxBufferedAmount: 8192, signalTimeoutMs: 1500 };
4
5
  const MAX_REDIALS = 5;
5
6
  function globalWebSocket() {
6
7
  const ctor = globalThis.WebSocket;
@@ -23,6 +24,11 @@ export class LiveSession {
23
24
  this.current = 'connecting';
24
25
  this.closedByCaller = false;
25
26
  this.redials = 0;
27
+ /** Realtime: binary frames may go out now. Set per connection. */
28
+ this.released = false;
29
+ this.held = [];
30
+ this.signalTimer = null;
31
+ this.dropped = 0;
26
32
  this.watched = false;
27
33
  this.access = options.access;
28
34
  this.handlers = options.handlers ?? {};
@@ -34,6 +40,7 @@ export class LiveSession {
34
40
  this.outputFields = new Set(Object.keys(options.outputSchema?.properties ?? {}));
35
41
  this.inputKnown = !!options.inputSchema;
36
42
  this.inputBinary = binaryLiveField(splitLiveSchema(options.inputSchema).live)?.key;
43
+ this.realtime = options.realtime ? { ...REALTIME_DEFAULTS, ...(options.realtime === true ? {} : options.realtime) } : null;
37
44
  this.ended = new Promise((resolve) => {
38
45
  this.resolveEnded = resolve;
39
46
  });
@@ -44,15 +51,36 @@ export class LiveSession {
44
51
  get isOpen() {
45
52
  return this.ws?.readyState === WS_OPEN;
46
53
  }
54
+ /** Realtime: binary frames dropped, as stale (held past holdFrames) or behind a full send buffer. */
55
+ get droppedFrames() {
56
+ return this.dropped;
57
+ }
47
58
  /** Dials the relay. The session reports its progress through onState. */
48
59
  connect() {
49
60
  this.setState('connecting');
50
61
  this.watchTask();
51
- const ws = new this.WebSocket(accessUrl(this.access));
62
+ // Realtime: ask the relay to say when the app is there (see release).
63
+ const ws = new this.WebSocket(accessUrl(this.access) + (this.realtime ? '&signals=paired' : ''));
52
64
  ws.binaryType = 'arraybuffer';
53
65
  this.ws = ws;
54
- ws.onopen = () => this.setState('waiting');
66
+ this.released = false;
67
+ this.clearSignalTimer();
68
+ ws.onopen = () => {
69
+ this.setState('waiting');
70
+ const realtime = this.realtime;
71
+ if (realtime) {
72
+ // A relay that reports pairing says so first thing. One that says
73
+ // nothing is an older relay: send as soon as open, as before.
74
+ this.signalTimer = setTimeout(() => {
75
+ this.signalTimer = null;
76
+ this.release();
77
+ }, realtime.signalTimeoutMs);
78
+ }
79
+ };
55
80
  ws.onmessage = (event) => {
81
+ if (typeof event.data === 'string' && this.relaySignal(event.data))
82
+ return;
83
+ this.release(); // the app is there: it reads what we send
56
84
  if (this.current !== 'live') {
57
85
  this.setState('live');
58
86
  this.task?.stop(); // the app is there; the task's fate now shows on the socket
@@ -66,6 +94,8 @@ export class LiveSession {
66
94
  if (this.ws !== ws)
67
95
  return;
68
96
  this.ws = null;
97
+ this.released = false;
98
+ this.clearSignalTimer();
69
99
  const waiting = this.current !== 'live';
70
100
  if (!this.closedByCaller && waiting && REDIAL_CODES.has(event.code) && this.redials < MAX_REDIALS) {
71
101
  this.redials += 1;
@@ -75,6 +105,42 @@ export class LiveSession {
75
105
  this.end({ code: event.code, reason: event.reason, byCaller: this.closedByCaller, taskEnded: false });
76
106
  };
77
107
  }
108
+ /**
109
+ * `{"$relay": "waiting" | "paired"}`, written by the relay itself to a
110
+ * client that dialed with ?signals=paired. True when the frame was one.
111
+ */
112
+ relaySignal(text) {
113
+ if (!text.startsWith(`{"${RELAY_KEY}"`))
114
+ return false;
115
+ let signal;
116
+ try {
117
+ signal = JSON.parse(text)[RELAY_KEY];
118
+ }
119
+ catch {
120
+ return false;
121
+ }
122
+ if (signal === 'waiting')
123
+ this.clearSignalTimer(); // it will say when it pairs: hold until then
124
+ else if (signal === 'paired')
125
+ this.release();
126
+ return true;
127
+ }
128
+ /** Realtime: the app can read now. Sends the newest held frames and stops holding. */
129
+ release() {
130
+ if (this.released)
131
+ return;
132
+ this.released = true;
133
+ this.clearSignalTimer();
134
+ const held = this.held;
135
+ this.held = [];
136
+ for (const frame of held)
137
+ this.sendBinary(frame);
138
+ }
139
+ clearSignalTimer() {
140
+ if (this.signalTimer)
141
+ clearTimeout(this.signalTimer);
142
+ this.signalTimer = null;
143
+ }
78
144
  deliverText(text) {
79
145
  let patch;
80
146
  try {
@@ -165,8 +231,29 @@ export class LiveSession {
165
231
  }
166
232
  /** One item of the input's binary live field. */
167
233
  sendBinary(data) {
168
- if (this.isOpen)
169
- this.ws.send(data);
234
+ const realtime = this.realtime;
235
+ if (!realtime) {
236
+ if (this.isOpen)
237
+ this.ws.send(data);
238
+ return;
239
+ }
240
+ if (!this.released) {
241
+ // The app cannot read yet: keep the newest few, so what it hears
242
+ // first is what was just said, not what was said during its cold start.
243
+ this.held.push(data);
244
+ if (this.held.length > realtime.holdFrames) {
245
+ this.held.shift();
246
+ this.dropped += 1;
247
+ }
248
+ return;
249
+ }
250
+ if (!this.isOpen)
251
+ return;
252
+ if ((this.ws.bufferedAmount ?? 0) > realtime.maxBufferedAmount) {
253
+ this.dropped += 1; // the network is behind: this frame would arrive late
254
+ return;
255
+ }
256
+ this.ws.send(data);
170
257
  }
171
258
  /**
172
259
  * One item of an input live field, or a new value of an ordinary one: a
package/dist/types.d.ts CHANGED
@@ -1694,6 +1694,7 @@ export interface AppUIRef {
1694
1694
  * sandbox:
1695
1695
  * host_network: true # share the host's network namespace
1696
1696
  * capabilities: [SYS_PTRACE] # Linux capabilities the app's processes keep
1697
+ * user_namespaces: true # unprivileged user namespaces (Chromium's sandbox)
1697
1698
  * The API reads it from the package when the version is deployed and stores
1698
1699
  * it on the version (server-owned: no caller writes it). Engines enforce the
1699
1700
  * copy the task dispatch carries, and store review shows it. The empty value
@@ -1711,6 +1712,13 @@ export interface AppSandbox {
1711
1712
  * them.
1712
1713
  */
1713
1714
  capabilities?: string[];
1715
+ /**
1716
+ * UserNamespaces lets the app's processes create unprivileged user
1717
+ * namespaces, which Chromium's sandbox needs. The container's seccomp
1718
+ * profile allows clone, unshare, setns and chroot; it gains no
1719
+ * capability on the host.
1720
+ */
1721
+ user_namespaces?: boolean;
1714
1722
  }
1715
1723
  /**
1716
1724
  * AppVersionDTO is the API response for an app version.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencesh/sdk",
3
- "version": "0.38.6",
3
+ "version": "0.38.8",
4
4
  "description": "Official JavaScript/TypeScript SDK for inference.sh - Run AI models with a simple API",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",