@inferencesh/sdk 0.5.11 → 0.5.12

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.
@@ -5,7 +5,7 @@
5
5
  * These are created once per provider instance with access to dispatch.
6
6
  */
7
7
  import { ToolInvocationStatusAwaitingInput, ToolTypeClient, ChatStatusBusy, } from '../types';
8
- import { StreamManager } from '../http/stream';
8
+ import { StreamableManager } from '../http/streamable';
9
9
  import { PollManager } from '../http/poll';
10
10
  import { isAdHocConfig, extractClientToolHandlers } from './types';
11
11
  import * as api from './api';
@@ -99,11 +99,10 @@ export function createActions(ctx) {
99
99
  return;
100
100
  }
101
101
  // Single unified stream with TypedEvents (both Chat and ChatMessage events)
102
- const manager = new StreamManager({
103
- createEventSource: () => api.createUnifiedStream(client, id),
104
- autoReconnect: true,
105
- maxReconnects: 3,
106
- reconnectDelayMs: 3000,
102
+ const { url, headers } = api.getChatStreamConfig(client, id);
103
+ const manager = new StreamableManager({
104
+ url,
105
+ headers,
107
106
  onError: (error) => {
108
107
  console.warn('[AgentSDK] Stream error:', error);
109
108
  callbacks.onError?.(error);
@@ -112,7 +111,7 @@ export function createActions(ctx) {
112
111
  dispatch({ type: 'SET_STATUS', payload: 'streaming' });
113
112
  callbacks.onStatusChange?.('streaming');
114
113
  },
115
- onStop: () => {
114
+ onEnd: () => {
116
115
  // Only reset if this is an unexpected stop (stream died, max reconnects exhausted).
117
116
  // If stopStream() was called intentionally, it clears the manager ref first,
118
117
  // so getStreamManager() will be undefined and we skip the duplicate dispatch.
@@ -133,7 +132,7 @@ export function createActions(ctx) {
133
132
  updateMessage(message);
134
133
  });
135
134
  setStreamManager(manager);
136
- manager.connect();
135
+ manager.start();
137
136
  };
138
137
  /** Poll-based alternative to streaming for restricted environments */
139
138
  const pollChat = (id) => {
@@ -69,6 +69,9 @@ export declare function alwaysAllowTool(client: AgentClient, chatId: string, too
69
69
  */
70
70
  export declare function uploadFile(client: AgentClient, file: globalThis.File): Promise<UploadedFile>;
71
71
  /**
72
- * Create a unified stream for chat events
72
+ * Get streamable config for chat streaming (NDJSON)
73
73
  */
74
- export declare function createUnifiedStream(client: AgentClient, chatId: string): Promise<EventSource | null>;
74
+ export declare function getChatStreamConfig(client: AgentClient, chatId: string): {
75
+ url: string;
76
+ headers: Record<string, string>;
77
+ };
package/dist/agent/api.js CHANGED
@@ -204,8 +204,8 @@ export async function uploadFile(client, file) {
204
204
  return result;
205
205
  }
206
206
  /**
207
- * Create a unified stream for chat events
207
+ * Get streamable config for chat streaming (NDJSON)
208
208
  */
209
- export function createUnifiedStream(client, chatId) {
210
- return client.http.createEventSource(`/chats/${chatId}/stream`);
209
+ export function getChatStreamConfig(client, chatId) {
210
+ return client.http.getStreamableConfig(`/chats/${chatId}/stream`);
211
211
  }
@@ -6,7 +6,7 @@
6
6
  import type { Dispatch } from 'react';
7
7
  import type { ChatDTO, ChatMessageDTO, AgentTool, AgentConfig as GeneratedAgentConfig, CoreAppConfig } from '../types';
8
8
  import type { HttpClient } from '../http/client';
9
- import type { StreamManager } from '../http/stream';
9
+ import type { StreamableManager } from '../http/streamable';
10
10
  import type { PollManager } from '../http/poll';
11
11
  /**
12
12
  * Minimal file interface returned by upload (just needs uri and content_type)
@@ -21,7 +21,7 @@ export interface UploadedFile {
21
21
  */
22
22
  export interface AgentClient {
23
23
  /** HTTP client for API requests */
24
- http: Pick<HttpClient, 'request' | 'createEventSource' | 'getStreamDefault' | 'getPollIntervalMs'>;
24
+ http: Pick<HttpClient, 'request' | 'getStreamableConfig' | 'getStreamDefault' | 'getPollIntervalMs'>;
25
25
  /** Files API for uploads */
26
26
  files: {
27
27
  upload: (data: string | Blob | globalThis.File) => Promise<UploadedFile>;
@@ -209,7 +209,7 @@ export type ChatAction = {
209
209
  * Context for action creators
210
210
  */
211
211
  /** Union of manager types used for real-time updates */
212
- export type UpdateManager = StreamManager<unknown> | PollManager<unknown>;
212
+ export type UpdateManager = StreamableManager<unknown> | PollManager<unknown>;
213
213
  export interface ActionsContext {
214
214
  client: AgentClient;
215
215
  dispatch: Dispatch<ChatAction>;
@@ -1,4 +1,4 @@
1
- import { StreamManager } from '../http/stream';
1
+ import { StreamableManager } from '../http/streamable';
2
2
  import { PollManager } from '../http/poll';
3
3
  import { ToolTypeClient, ToolInvocationStatusAwaitingInput, ChatStatusBusy, } from '../types';
4
4
  /**
@@ -144,11 +144,12 @@ export class Agent {
144
144
  streamUntilIdle(options) {
145
145
  if (!this.chatId)
146
146
  return Promise.resolve();
147
+ const { url, headers } = this.http.getStreamableConfig(`/chats/${this.chatId}/stream`);
147
148
  return new Promise((resolve) => {
148
149
  this.stream?.stop();
149
- this.stream = new StreamManager({
150
- createEventSource: async () => this.http.createEventSource(`/chats/${this.chatId}/stream`),
151
- autoReconnect: true,
150
+ this.stream = new StreamableManager({
151
+ url,
152
+ headers,
152
153
  });
153
154
  this.stream.addEventListener('chats', (chat) => {
154
155
  options.onChat?.(chat);
@@ -173,7 +174,7 @@ export class Agent {
173
174
  }
174
175
  }
175
176
  });
176
- this.stream.connect();
177
+ this.stream.start();
177
178
  });
178
179
  }
179
180
  /** Poll until chat becomes idle, dispatching callbacks on changes */
package/dist/api/tasks.js CHANGED
@@ -1,4 +1,4 @@
1
- import { StreamManager } from '../http/stream';
1
+ import { StreamableManager } from '../http/streamable';
2
2
  import { PollManager } from '../http/poll';
3
3
  import { TaskStatusCompleted, TaskStatusFailed, TaskStatusCancelled, } from '../types';
4
4
  import { parseStatus } from '../utils';
@@ -84,15 +84,14 @@ export class TasksAPI {
84
84
  if (!useStream) {
85
85
  return this.pollUntilTerminal(task, options);
86
86
  }
87
- // Wait for completion with optional updates via SSE
87
+ // Wait for completion with optional updates via NDJSON streaming
88
88
  // Accumulate state across partial updates to preserve fields like session_id
89
89
  let accumulatedTask = { ...task };
90
+ const { url, headers } = this.http.getStreamableConfig(`/tasks/${task.id}/stream`);
90
91
  return new Promise((resolve, reject) => {
91
- const streamManager = new StreamManager({
92
- createEventSource: async () => this.http.createEventSource(`/tasks/${task.id}/stream`),
93
- autoReconnect,
94
- maxReconnects,
95
- reconnectDelayMs,
92
+ const streamManager = new StreamableManager({
93
+ url,
94
+ headers,
96
95
  onData: (data) => {
97
96
  // Merge new data, preserving existing fields if not in update
98
97
  accumulatedTask = { ...accumulatedTask, ...data };
@@ -134,7 +133,7 @@ export class TasksAPI {
134
133
  streamManager.stop();
135
134
  },
136
135
  });
137
- streamManager.connect();
136
+ streamManager.start();
138
137
  });
139
138
  }
140
139
  /** Poll GET /tasks/{id}/status until terminal, full-fetch on status change. */
@@ -76,8 +76,17 @@ export declare class HttpClient {
76
76
  * Execute the actual HTTP request (internal)
77
77
  */
78
78
  private executeRequest;
79
+ /**
80
+ * Get URL and headers for NDJSON streaming.
81
+ * Returns the full URL and auth headers needed for streamable requests.
82
+ */
83
+ getStreamableConfig(endpoint: string): {
84
+ url: string;
85
+ headers: Record<string, string>;
86
+ };
79
87
  /**
80
88
  * Create an EventSource for SSE streaming
89
+ * @deprecated Use getStreamableConfig() with StreamableManager instead
81
90
  */
82
91
  createEventSource(endpoint: string): Promise<EventSource | null>;
83
92
  }
@@ -161,8 +161,33 @@ export class HttpClient {
161
161
  }
162
162
  return apiResponse.data;
163
163
  }
164
+ /**
165
+ * Get URL and headers for NDJSON streaming.
166
+ * Returns the full URL and auth headers needed for streamable requests.
167
+ */
168
+ getStreamableConfig(endpoint) {
169
+ const targetUrl = new URL(`${this.baseUrl}${endpoint}`);
170
+ const isProxyMode = !!this.proxyUrl;
171
+ let url;
172
+ const headers = { ...this.resolveHeaders() };
173
+ if (isProxyMode) {
174
+ const proxyUrlWithQuery = new URL(this.proxyUrl, typeof window !== 'undefined' ? window.location.origin : 'http://localhost');
175
+ proxyUrlWithQuery.searchParams.set('__inf_target', targetUrl.toString());
176
+ url = proxyUrlWithQuery.toString();
177
+ headers['x-inf-target-url'] = targetUrl.toString();
178
+ }
179
+ else {
180
+ url = targetUrl.toString();
181
+ const token = this.getAuthToken();
182
+ if (token) {
183
+ headers['Authorization'] = `Bearer ${token}`;
184
+ }
185
+ }
186
+ return { url, headers };
187
+ }
164
188
  /**
165
189
  * Create an EventSource for SSE streaming
190
+ * @deprecated Use getStreamableConfig() with StreamableManager instead
166
191
  */
167
192
  createEventSource(endpoint) {
168
193
  const targetUrl = new URL(`${this.baseUrl}${endpoint}`);
@@ -56,7 +56,13 @@ export declare class StreamableManager<T> {
56
56
  private options;
57
57
  private abortController;
58
58
  private isRunning;
59
+ private eventListeners;
59
60
  constructor(options: StreamableManagerOptions<T>);
61
+ /**
62
+ * Add a listener for typed events (e.g., 'chats', 'chat_messages').
63
+ * Used when server sends events with {"event": "eventName", "data": ...} format.
64
+ */
65
+ addEventListener<E = unknown>(eventName: string, callback: (data: E) => void): () => void;
60
66
  start(): Promise<void>;
61
67
  stop(): void;
62
68
  }
@@ -79,8 +79,28 @@ export class StreamableManager {
79
79
  constructor(options) {
80
80
  this.abortController = null;
81
81
  this.isRunning = false;
82
+ this.eventListeners = new Map();
82
83
  this.options = options;
83
84
  }
85
+ /**
86
+ * Add a listener for typed events (e.g., 'chats', 'chat_messages').
87
+ * Used when server sends events with {"event": "eventName", "data": ...} format.
88
+ */
89
+ addEventListener(eventName, callback) {
90
+ const listeners = this.eventListeners.get(eventName) || new Set();
91
+ listeners.add(callback);
92
+ this.eventListeners.set(eventName, listeners);
93
+ // Return cleanup function
94
+ return () => {
95
+ const listeners = this.eventListeners.get(eventName);
96
+ if (listeners) {
97
+ listeners.delete(callback);
98
+ if (listeners.size === 0) {
99
+ this.eventListeners.delete(eventName);
100
+ }
101
+ }
102
+ };
103
+ }
84
104
  async start() {
85
105
  if (this.isRunning)
86
106
  return;
@@ -95,13 +115,20 @@ export class StreamableManager {
95
115
  })) {
96
116
  if (!this.isRunning)
97
117
  break;
118
+ const wrapper = message;
119
+ // Handle typed events ({"event": "...", "data": ...})
120
+ if (wrapper.event && this.eventListeners.has(wrapper.event)) {
121
+ const listeners = this.eventListeners.get(wrapper.event);
122
+ const eventData = wrapper.data !== undefined ? wrapper.data : message;
123
+ listeners.forEach(callback => callback(eventData));
124
+ continue;
125
+ }
98
126
  // Check if it's a partial update
99
127
  if (typeof message === 'object' &&
100
128
  message !== null &&
101
129
  'data' in message &&
102
130
  'fields' in message &&
103
- Array.isArray(message.fields)) {
104
- const wrapper = message;
131
+ Array.isArray(wrapper.fields)) {
105
132
  if (this.options.onPartialData && wrapper.data !== undefined) {
106
133
  this.options.onPartialData(wrapper.data, wrapper.fields);
107
134
  }
@@ -109,6 +136,10 @@ export class StreamableManager {
109
136
  this.options.onData?.(wrapper.data);
110
137
  }
111
138
  }
139
+ else if (wrapper.data !== undefined) {
140
+ // Has data wrapper but no fields - unwrap
141
+ this.options.onData?.(wrapper.data);
142
+ }
112
143
  else {
113
144
  this.options.onData?.(message);
114
145
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { HttpClient, HttpClientConfig, ErrorHandler, createHttpClient } from './http/client';
2
2
  export { StreamManager, StreamManagerOptions, PartialDataWrapper } from './http/stream';
3
+ export { StreamableManager, StreamableManagerOptions, StreamableMessage, streamable, streamableRaw } from './http/streamable';
3
4
  export { PollManager, PollManagerOptions } from './http/poll';
4
5
  export { InferenceError, RequirementsNotMetException, SessionError, SessionNotFoundError, SessionExpiredError, SessionEndedError, WorkerLostError, isRequirementsNotMetException, isInferenceError, isSessionError, } from './http/errors';
5
6
  export { TasksAPI, RunOptions } from './api/tasks';
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // HTTP utilities
2
2
  export { HttpClient, createHttpClient } from './http/client';
3
3
  export { StreamManager } from './http/stream';
4
+ export { StreamableManager, streamable, streamableRaw } from './http/streamable';
4
5
  export { PollManager } from './http/poll';
5
6
  export { InferenceError, RequirementsNotMetException, SessionError, SessionNotFoundError, SessionExpiredError, SessionEndedError, WorkerLostError,
6
7
  // Type guards (use these instead of instanceof for reliability)
@@ -40,6 +40,7 @@ export function createHandler(options) {
40
40
  // Handle streaming responses
41
41
  const contentType = response.headers.get("content-type");
42
42
  if (contentType?.includes("text/event-stream") ||
43
+ contentType?.includes("application/x-ndjson") ||
43
44
  contentType?.includes("application/octet-stream")) {
44
45
  if (response.body) {
45
46
  const reader = response.body.getReader();
@@ -110,12 +110,13 @@ export async function processProxyRequest(adapter, options) {
110
110
  const userAgent = firstValue(adapter.header("user-agent"));
111
111
  const proxyId = `@inferencesh/sdk-proxy/${adapter.framework}`;
112
112
  // 6. Make upstream request
113
+ const accept = firstValue(adapter.header("accept"));
113
114
  const response = await fetch(targetUrl, {
114
115
  method: adapter.method,
115
116
  headers: {
116
117
  ...forwardHeaders,
117
118
  authorization: firstValue(adapter.header("authorization")) ?? `Bearer ${apiKey}`,
118
- accept: "application/json",
119
+ accept: accept || "application/json",
119
120
  "content-type": contentType || "application/json",
120
121
  "user-agent": userAgent || proxyId,
121
122
  "x-inf-proxy": proxyId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencesh/sdk",
3
- "version": "0.5.11",
3
+ "version": "0.5.12",
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",