@inferencesh/sdk 0.5.8 → 0.5.10

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/api/files.js CHANGED
@@ -1,3 +1,42 @@
1
+ /**
2
+ * Parse a data URI and return the media type and decoded data.
3
+ *
4
+ * Supports formats:
5
+ * - data:image/jpeg;base64,/9j/4AAQ...
6
+ * - data:text/plain,Hello%20World
7
+ * - data:;base64,SGVsbG8= (defaults to text/plain)
8
+ */
9
+ function parseDataUri(uri) {
10
+ // Match: data:[<mediatype>][;base64],<data>
11
+ const match = uri.match(/^data:([^;,]*)?(?:;(base64))?,(.*)$/s);
12
+ if (!match) {
13
+ throw new Error('Invalid data URI format');
14
+ }
15
+ const mediaType = match[1] || 'text/plain';
16
+ const isBase64 = match[2] === 'base64';
17
+ let dataStr = match[3];
18
+ if (isBase64) {
19
+ // Handle URL-safe base64 (- and _ instead of + and /)
20
+ dataStr = dataStr.replace(/-/g, '+').replace(/_/g, '/');
21
+ // Add padding if needed
22
+ const padding = 4 - (dataStr.length % 4);
23
+ if (padding !== 4) {
24
+ dataStr += '='.repeat(padding);
25
+ }
26
+ const binaryStr = atob(dataStr);
27
+ const bytes = new Uint8Array(binaryStr.length);
28
+ for (let i = 0; i < binaryStr.length; i++) {
29
+ bytes[i] = binaryStr.charCodeAt(i);
30
+ }
31
+ return { mediaType, data: bytes };
32
+ }
33
+ else {
34
+ // URL-encoded data
35
+ const decoded = decodeURIComponent(dataStr);
36
+ const encoder = new TextEncoder();
37
+ return { mediaType, data: encoder.encode(decoded) };
38
+ }
39
+ }
1
40
  /**
2
41
  * Files API
3
42
  */
@@ -27,11 +66,26 @@ export class FilesAPI {
27
66
  * Upload a file (Blob or base64 string)
28
67
  */
29
68
  async upload(data, options = {}) {
69
+ // Determine content type
70
+ let contentType = options.contentType;
71
+ if (!contentType) {
72
+ if (data instanceof Blob) {
73
+ contentType = data.type;
74
+ }
75
+ else if (typeof data === 'string' && data.startsWith('data:')) {
76
+ // Extract media type from data URI
77
+ const match = data.match(/^data:([^;,]*)?/);
78
+ contentType = match?.[1] || 'application/octet-stream';
79
+ }
80
+ else {
81
+ contentType = 'application/octet-stream';
82
+ }
83
+ }
30
84
  // Step 1: Create the file record
31
85
  const fileRequest = {
32
86
  uri: '', // Empty URI as it will be set by the server
33
87
  filename: options.filename,
34
- content_type: options.contentType || (data instanceof Blob ? data.type : 'application/octet-stream'),
88
+ content_type: contentType,
35
89
  path: options.path,
36
90
  size: data instanceof Blob ? data.size : undefined,
37
91
  };
@@ -50,16 +104,8 @@ export class FilesAPI {
50
104
  else {
51
105
  // If it's a base64 string, convert it to a Blob
52
106
  if (data.startsWith('data:')) {
53
- const matches = data.match(/^data:([^;]+);base64,(.+)$/);
54
- if (!matches) {
55
- throw new Error('Invalid base64 data URI format');
56
- }
57
- const binaryStr = atob(matches[2]);
58
- const bytes = new Uint8Array(binaryStr.length);
59
- for (let i = 0; i < binaryStr.length; i++) {
60
- bytes[i] = binaryStr.charCodeAt(i);
61
- }
62
- contentToUpload = new Blob([bytes], { type: matches[1] });
107
+ const parsed = parseDataUri(data);
108
+ contentToUpload = new Blob([parsed.data.buffer], { type: parsed.mediaType });
63
109
  }
64
110
  else {
65
111
  // Assume it's a clean base64 string
@@ -68,7 +114,7 @@ export class FilesAPI {
68
114
  for (let i = 0; i < binaryStr.length; i++) {
69
115
  bytes[i] = binaryStr.charCodeAt(i);
70
116
  }
71
- contentToUpload = new Blob([bytes], { type: options.contentType || 'application/octet-stream' });
117
+ contentToUpload = new Blob([bytes.buffer], { type: options.contentType || 'application/octet-stream' });
72
118
  }
73
119
  }
74
120
  // Upload to S3 using the signed URL
package/dist/api/tasks.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { StreamManager } from '../http/stream';
2
2
  import { PollManager } from '../http/poll';
3
3
  import { TaskStatusCompleted, TaskStatusFailed, TaskStatusCancelled, } from '../types';
4
+ import { parseStatus } from '../utils';
4
5
  //TODO: This is ugly...
5
6
  function stripTask(task) {
6
7
  return {
@@ -97,15 +98,15 @@ export class TasksAPI {
97
98
  accumulatedTask = { ...accumulatedTask, ...data };
98
99
  const stripped = stripTask(accumulatedTask);
99
100
  onUpdate?.(stripped);
100
- if (data.status === TaskStatusCompleted) {
101
+ if (parseStatus(data.status) === TaskStatusCompleted) {
101
102
  streamManager.stop();
102
103
  resolve(stripped);
103
104
  }
104
- else if (data.status === TaskStatusFailed) {
105
+ else if (parseStatus(data.status) === TaskStatusFailed) {
105
106
  streamManager.stop();
106
107
  reject(new Error(data.error || 'task failed'));
107
108
  }
108
- else if (data.status === TaskStatusCancelled) {
109
+ else if (parseStatus(data.status) === TaskStatusCancelled) {
109
110
  streamManager.stop();
110
111
  reject(new Error('task cancelled'));
111
112
  }
@@ -115,15 +116,15 @@ export class TasksAPI {
115
116
  accumulatedTask = { ...accumulatedTask, ...data };
116
117
  const stripped = stripTask(accumulatedTask);
117
118
  onPartialUpdate?.(stripped, fields);
118
- if (data.status === TaskStatusCompleted) {
119
+ if (parseStatus(data.status) === TaskStatusCompleted) {
119
120
  streamManager.stop();
120
121
  resolve(stripped);
121
122
  }
122
- else if (data.status === TaskStatusFailed) {
123
+ else if (parseStatus(data.status) === TaskStatusFailed) {
123
124
  streamManager.stop();
124
125
  reject(new Error(data.error || 'task failed'));
125
126
  }
126
- else if (data.status === TaskStatusCancelled) {
127
+ else if (parseStatus(data.status) === TaskStatusCancelled) {
127
128
  streamManager.stop();
128
129
  reject(new Error('task cancelled'));
129
130
  }
@@ -155,15 +156,15 @@ export class TasksAPI {
155
156
  const fullTask = await this.http.request('get', `/tasks/${task.id}`);
156
157
  const stripped = stripTask(fullTask);
157
158
  onUpdate?.(stripped);
158
- if (fullTask.status === TaskStatusCompleted) {
159
+ if (parseStatus(fullTask.status) === TaskStatusCompleted) {
159
160
  poller.stop();
160
161
  resolve(stripped);
161
162
  }
162
- else if (fullTask.status === TaskStatusFailed) {
163
+ else if (parseStatus(fullTask.status) === TaskStatusFailed) {
163
164
  poller.stop();
164
165
  reject(new Error(fullTask.error || 'task failed'));
165
166
  }
166
- else if (fullTask.status === TaskStatusCancelled) {
167
+ else if (parseStatus(fullTask.status) === TaskStatusCancelled) {
167
168
  poller.stop();
168
169
  reject(new Error('task cancelled'));
169
170
  }
@@ -191,7 +192,7 @@ export class TasksAPI {
191
192
  * Feature/unfeature a task
192
193
  */
193
194
  async feature(taskId, featured) {
194
- return this.http.request('post', `/tasks/${taskId}/featured`, { data: { featured } });
195
+ return this.http.request('post', `/tasks/${taskId}/featured`, { data: { is_featured: featured } });
195
196
  }
196
197
  }
197
198
  export function createTasksAPI(http) {
@@ -80,7 +80,9 @@ export class HttpClient {
80
80
  if (options.params) {
81
81
  Object.entries(options.params).forEach(([key, value]) => {
82
82
  if (value !== undefined && value !== null) {
83
- targetUrl.searchParams.append(key, String(value));
83
+ // Serialize arrays and objects as JSON, primitives as strings
84
+ const serialized = typeof value === 'object' ? JSON.stringify(value) : String(value);
85
+ targetUrl.searchParams.append(key, serialized);
84
86
  }
85
87
  });
86
88
  }
@@ -23,10 +23,12 @@ export declare class InferenceError extends Error {
23
23
  *
24
24
  * @example
25
25
  * ```typescript
26
+ * import { isRequirementsNotMetException } from '@inferencesh/sdk';
27
+ *
26
28
  * try {
27
29
  * const task = await client.run(params);
28
30
  * } catch (e) {
29
- * if (e instanceof RequirementsNotMetException) {
31
+ * if (isRequirementsNotMetException(e)) {
30
32
  * for (const err of e.errors) {
31
33
  * console.log(`Missing ${err.type}: ${err.key}`);
32
34
  * if (err.action) {
@@ -130,3 +132,16 @@ export declare class SessionEndedError extends SessionError {
130
132
  export declare class WorkerLostError extends SessionError {
131
133
  constructor(sessionId: string, responseBody?: string);
132
134
  }
135
+ /**
136
+ * Type guard for RequirementsNotMetException.
137
+ * Handles cross-module issues where instanceof may fail.
138
+ */
139
+ export declare function isRequirementsNotMetException(err: unknown): err is RequirementsNotMetException;
140
+ /**
141
+ * Type guard for InferenceError.
142
+ */
143
+ export declare function isInferenceError(err: unknown): err is InferenceError;
144
+ /**
145
+ * Type guard for SessionError (or any subclass).
146
+ */
147
+ export declare function isSessionError(err: unknown): err is SessionError;
@@ -25,10 +25,12 @@ export class InferenceError extends Error {
25
25
  *
26
26
  * @example
27
27
  * ```typescript
28
+ * import { isRequirementsNotMetException } from '@inferencesh/sdk';
29
+ *
28
30
  * try {
29
31
  * const task = await client.run(params);
30
32
  * } catch (e) {
31
- * if (e instanceof RequirementsNotMetException) {
33
+ * if (isRequirementsNotMetException(e)) {
32
34
  * for (const err of e.errors) {
33
35
  * console.log(`Missing ${err.type}: ${err.key}`);
34
36
  * if (err.action) {
@@ -152,3 +154,44 @@ export class WorkerLostError extends SessionError {
152
154
  this.name = 'WorkerLostError';
153
155
  }
154
156
  }
157
+ // =============================================================================
158
+ // Type Guards
159
+ // =============================================================================
160
+ // These handle cross-module/bundle issues where instanceof may fail.
161
+ // Use these instead of instanceof for reliable error checking.
162
+ /**
163
+ * Type guard for RequirementsNotMetException.
164
+ * Handles cross-module issues where instanceof may fail.
165
+ */
166
+ export function isRequirementsNotMetException(err) {
167
+ if (err instanceof RequirementsNotMetException)
168
+ return true;
169
+ if (typeof err !== 'object' || err === null)
170
+ return false;
171
+ const e = err;
172
+ return e.name === 'RequirementsNotMetException' ||
173
+ (e.statusCode === 412 && Array.isArray(e.errors));
174
+ }
175
+ /**
176
+ * Type guard for InferenceError.
177
+ */
178
+ export function isInferenceError(err) {
179
+ if (err instanceof InferenceError)
180
+ return true;
181
+ if (typeof err !== 'object' || err === null)
182
+ return false;
183
+ const e = err;
184
+ return e.name === 'InferenceError' && typeof e.statusCode === 'number';
185
+ }
186
+ /**
187
+ * Type guard for SessionError (or any subclass).
188
+ */
189
+ export function isSessionError(err) {
190
+ if (err instanceof SessionError)
191
+ return true;
192
+ if (typeof err !== 'object' || err === null)
193
+ return false;
194
+ const e = err;
195
+ return typeof e.sessionId === 'string' && typeof e.statusCode === 'number' &&
196
+ ['SessionError', 'SessionNotFoundError', 'SessionExpiredError', 'SessionEndedError', 'WorkerLostError'].includes(e.name);
197
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { HttpClient, HttpClientConfig, ErrorHandler, createHttpClient } from './http/client';
2
2
  export { StreamManager, StreamManagerOptions, PartialDataWrapper } from './http/stream';
3
3
  export { PollManager, PollManagerOptions } from './http/poll';
4
- export { InferenceError, RequirementsNotMetException, SessionError, SessionNotFoundError, SessionExpiredError, SessionEndedError, WorkerLostError, } from './http/errors';
4
+ export { InferenceError, RequirementsNotMetException, SessionError, SessionNotFoundError, SessionExpiredError, SessionEndedError, WorkerLostError, isRequirementsNotMetException, isInferenceError, isSessionError, } from './http/errors';
5
5
  export { TasksAPI, RunOptions } from './api/tasks';
6
6
  export { FilesAPI, UploadFileOptions } from './api/files';
7
7
  export { AgentsAPI, Agent, AgentOptions, SendMessageOptions, AgentRunOptions } from './api/agents';
@@ -13,6 +13,7 @@ export { FlowRunsAPI } from './api/flow-runs';
13
13
  export { EnginesAPI } from './api/engines';
14
14
  export { tool, appTool, agentTool, webhookTool, internalTools, string, number, integer, boolean, enumOf, object, array, optional, } from './tool-builder';
15
15
  export type { ClientTool, ClientToolHandler } from './tool-builder';
16
+ export { parseStatus, isTerminalStatus } from './utils';
16
17
  export * from './types';
17
18
  export type { TaskDTO as Task } from './types';
18
19
  import { HttpClient, HttpClientConfig } from './http/client';
package/dist/index.js CHANGED
@@ -2,7 +2,9 @@
2
2
  export { HttpClient, createHttpClient } from './http/client';
3
3
  export { StreamManager } from './http/stream';
4
4
  export { PollManager } from './http/poll';
5
- export { InferenceError, RequirementsNotMetException, SessionError, SessionNotFoundError, SessionExpiredError, SessionEndedError, WorkerLostError, } from './http/errors';
5
+ export { InferenceError, RequirementsNotMetException, SessionError, SessionNotFoundError, SessionExpiredError, SessionEndedError, WorkerLostError,
6
+ // Type guards (use these instead of instanceof for reliability)
7
+ isRequirementsNotMetException, isInferenceError, isSessionError, } from './http/errors';
6
8
  // API modules
7
9
  export { TasksAPI } from './api/tasks';
8
10
  export { FilesAPI } from './api/files';
@@ -15,6 +17,8 @@ export { FlowRunsAPI } from './api/flow-runs';
15
17
  export { EnginesAPI } from './api/engines';
16
18
  // Tool Builder (fluent API)
17
19
  export { tool, appTool, agentTool, webhookTool, internalTools, string, number, integer, boolean, enumOf, object, array, optional, } from './tool-builder';
20
+ // Status utilities (handle both int and string status values)
21
+ export { parseStatus, isTerminalStatus } from './utils';
18
22
  // Types - includes TaskStatus constants and all DTOs
19
23
  export * from './types';
20
24
  // =============================================================================
package/dist/types.d.ts CHANGED
@@ -367,6 +367,11 @@ export interface ApiAppRunRequest {
367
367
  * Session timeout in seconds (1-3600). Only valid when session="new"
368
368
  */
369
369
  session_timeout?: number;
370
+ /**
371
+ * Schedule execution for a specific time (ISO 8601 UTC, e.g. "2026-02-24T15:30:00Z").
372
+ * Task stays queued until this time. Past timestamps run immediately.
373
+ */
374
+ run_at?: string;
370
375
  }
371
376
  /**
372
377
  * ApiAgentRunRequest is the request body for /agents/run endpoint.
@@ -442,9 +447,9 @@ export interface ToolResultRequest {
442
447
  result: string;
443
448
  }
444
449
  /**
445
- * WebhookEvent is the envelope for task webhook deliveries.
450
+ * WebhookPayload is the envelope for outbound webhook deliveries (e.g., task webhooks).
446
451
  */
447
- export interface WebhookEvent<T extends any> {
452
+ export interface WebhookPayload<T extends any> {
448
453
  event: string;
449
454
  timestamp: string;
450
455
  data: T;
@@ -533,6 +538,7 @@ export interface CreateAgentRequest {
533
538
  export interface SDKTypes {
534
539
  }
535
540
  export interface SkillPublishRequest {
541
+ namespace?: string;
536
542
  name: string;
537
543
  description: string;
538
544
  category: string;
@@ -1936,21 +1942,17 @@ export interface HFCacheInfo {
1936
1942
  /**
1937
1943
  * TaskStatus represents the state of a task in its lifecycle.
1938
1944
  * DESIGN NOTES:
1939
- * - Stored as int in DB for compact storage and efficient equality checks.
1940
- * - The int values are ordered to allow SQL range queries (status < ?) for performance.
1941
- * - IMPORTANT: If you add new statuses in the MIDDLE of the sequence, you must:
1942
- * 1. Write a migration to shift existing values
1943
- * 2. Update SDKs and frontends
1944
- * - ALTERNATIVE: Add new statuses at the END to avoid migrations, but then you
1945
- * cannot use range comparisons (< >) and must use explicit checks (IN, NOT IN).
1946
- * - Kubernetes/Temporal use strings and explicit checks for maximum flexibility.
1947
- * Consider switching to strings if range comparisons become a maintenance burden.
1945
+ * - Stored as int in DB for compact storage. New statuses can be added with any int value.
1946
+ * - Logical ordering is defined by statusOrder map, NOT by the int values.
1947
+ * - To add a new status: add const with next available int, add to statusOrder at correct position.
1948
+ * - SQL queries use explicit lists (IN, NOT IN) via helper functions, not range comparisons.
1949
+ * - This design allows future migration to string-based storage without breaking changes.
1948
1950
  */
1949
1951
  export type TaskStatus = number;
1950
1952
  export declare const TaskStatusUnknown: TaskStatus;
1951
1953
  export declare const TaskStatusReceived: TaskStatus;
1952
1954
  export declare const TaskStatusQueued: TaskStatus;
1953
- export declare const TaskStatusScheduled: TaskStatus;
1955
+ export declare const TaskStatusDispatched: TaskStatus;
1954
1956
  export declare const TaskStatusPreparing: TaskStatus;
1955
1957
  export declare const TaskStatusServing: TaskStatus;
1956
1958
  export declare const TaskStatusSettingUp: TaskStatus;
@@ -2012,8 +2014,6 @@ export interface Task extends BaseModel, PermissionModel {
2012
2014
  logs: TaskLog[];
2013
2015
  telemetry: TimescaleTask[];
2014
2016
  usage_events: (UsageEvent | undefined)[];
2015
- transaction_id?: string;
2016
- transaction?: Transaction;
2017
2017
  /**
2018
2018
  * Secret refs for billing (tracks ownership to determine partner fee)
2019
2019
  */
@@ -2028,6 +2028,10 @@ export interface Task extends BaseModel, PermissionModel {
2028
2028
  * Session timeout in seconds (only used when session="new")
2029
2029
  */
2030
2030
  session_timeout?: number;
2031
+ /**
2032
+ * Scheduled execution time (UTC). Scheduler skips task until this time.
2033
+ */
2034
+ run_at?: string;
2031
2035
  }
2032
2036
  export interface TaskEvent {
2033
2037
  id: string;
@@ -2074,6 +2078,7 @@ export interface TaskDTO extends BaseModel, PermissionModelDTO {
2074
2078
  engine?: EngineStateSummary;
2075
2079
  worker_id?: string;
2076
2080
  worker?: WorkerStateSummary;
2081
+ run_at?: string;
2077
2082
  webhook?: string;
2078
2083
  setup?: any;
2079
2084
  input: any;
@@ -2084,8 +2089,6 @@ export interface TaskDTO extends BaseModel, PermissionModelDTO {
2084
2089
  logs: TaskLog[];
2085
2090
  telemetry: TimescaleTask[];
2086
2091
  usage_events: (UsageEvent | undefined)[];
2087
- transaction_id?: string;
2088
- transaction?: Transaction;
2089
2092
  session_id?: string;
2090
2093
  session_timeout?: number;
2091
2094
  }
@@ -2116,6 +2119,10 @@ export interface Team extends BaseModel {
2116
2119
  * Personal teams start with SetupCompleted=false and a generated temporary username
2117
2120
  */
2118
2121
  setup_completed: boolean;
2122
+ /**
2123
+ * MaxConcurrency limits total active tasks for this team (0 = use default)
2124
+ */
2125
+ max_concurrency: number;
2119
2126
  }
2120
2127
  export interface TeamDTO extends BaseModel {
2121
2128
  type: TeamType;
@@ -2124,6 +2131,7 @@ export interface TeamDTO extends BaseModel {
2124
2131
  avatar_url: string;
2125
2132
  email: string;
2126
2133
  setup_completed: boolean;
2134
+ max_concurrency: number;
2127
2135
  }
2128
2136
  export type TeamRole = string;
2129
2137
  export declare const TeamRoleOwner: TeamRole;
@@ -2204,130 +2212,9 @@ export interface ToolParameterProperty {
2204
2212
  items?: ToolParameterProperty;
2205
2213
  required?: string[];
2206
2214
  }
2207
- /**
2208
- * TransactionType represents the type of credit transaction
2209
- */
2210
- export type TransactionType = string;
2211
- export declare const TransactionTypeCredit: TransactionType;
2212
- export declare const TransactionTypeDebit: TransactionType;
2213
- /**
2214
- * Transaction represents a single credit transaction
2215
- */
2216
- export interface Transaction extends BaseModel {
2217
- PermissionModel: PermissionModel;
2218
- type: TransactionType;
2219
- amount: number;
2220
- reference: string;
2221
- notes: string;
2222
- /**
2223
- * Metadata for the transaction
2224
- */
2225
- metadata: {
2226
- [key: string]: any;
2227
- };
2228
- /**
2229
- * SideEffectsProcessed tracks whether side effects (notifications, auto-recharge,
2230
- * billing status changes) have been processed for this transaction.
2231
- * Set to true via WithSkipTxSideEffects context to skip side effects (e.g. migrations).
2232
- */
2233
- side_effects_processed: boolean;
2234
- }
2235
- /**
2236
- * PaymentRecordStatus represents the status of a payment
2237
- */
2238
- export type PaymentRecordStatus = number;
2239
- export declare const PaymentRecordStatusPending: PaymentRecordStatus;
2240
- export declare const PaymentRecordStatusComplete: PaymentRecordStatus;
2241
- export declare const PaymentRecordStatusFailed: PaymentRecordStatus;
2242
- export declare const PaymentRecordStatusExpired: PaymentRecordStatus;
2243
- /**
2244
- * PaymentRecordType represents the type of payment
2245
- */
2246
- export type PaymentRecordType = string;
2247
- export declare const PaymentRecordTypeCheckout: PaymentRecordType;
2248
- export declare const PaymentRecordTypeAutoRecharge: PaymentRecordType;
2249
- /**
2250
- * PaymentRecord stores Stripe payment details for both checkout sessions and direct charges
2251
- */
2252
- export interface PaymentRecord extends BaseModel, PermissionModel {
2253
- type: PaymentRecordType;
2254
- status: PaymentRecordStatus;
2255
- amount: number;
2256
- service_fee: number;
2257
- stripe_customer_id: string;
2258
- payment_intent_id: string;
2259
- receipt_url: string;
2260
- /**
2261
- * Checkout-specific fields (only set for checkout type)
2262
- */
2263
- session_id: string;
2264
- session_url: string;
2265
- }
2266
2215
  export type UsageEventResourceTier = string;
2267
2216
  export declare const UsageEventResourceTierPrivate: UsageEventResourceTier;
2268
2217
  export declare const UsageEventResourceTierCloud: UsageEventResourceTier;
2269
- /**
2270
- * MetaItemType is the type discriminator for MetaItem
2271
- */
2272
- export type MetaItemType = string;
2273
- export declare const MetaItemTypeText: MetaItemType;
2274
- export declare const MetaItemTypeImage: MetaItemType;
2275
- export declare const MetaItemTypeVideo: MetaItemType;
2276
- export declare const MetaItemTypeAudio: MetaItemType;
2277
- export declare const MetaItemTypeRaw: MetaItemType;
2278
- /**
2279
- * VideoResolution represents standard video resolution presets
2280
- */
2281
- export type VideoResolution = string;
2282
- export declare const VideoRes480P: VideoResolution;
2283
- export declare const VideoRes720P: VideoResolution;
2284
- export declare const VideoRes1080P: VideoResolution;
2285
- export declare const VideoRes1440P: VideoResolution;
2286
- export declare const VideoRes4K: VideoResolution;
2287
- /**
2288
- * MetaItem represents metadata about an input or output item
2289
- */
2290
- export interface MetaItem {
2291
- type: MetaItemType;
2292
- /**
2293
- * Text fields
2294
- */
2295
- tokens?: number;
2296
- /**
2297
- * Image/Video shared fields
2298
- */
2299
- width?: number;
2300
- height?: number;
2301
- resolution_mp?: number;
2302
- /**
2303
- * Image specific fields
2304
- */
2305
- steps?: number;
2306
- count?: number;
2307
- /**
2308
- * Video specific fields
2309
- */
2310
- resolution?: VideoResolution;
2311
- seconds?: number;
2312
- fps?: number;
2313
- /**
2314
- * Audio specific fields
2315
- */
2316
- sample_rate?: number;
2317
- /**
2318
- * App-specific key-value pairs for custom pricing factors
2319
- */
2320
- extra?: {
2321
- [key: string]: any;
2322
- };
2323
- }
2324
- /**
2325
- * OutputMeta contains structured metadata about task inputs and outputs for pricing calculation
2326
- */
2327
- export interface OutputMeta {
2328
- inputs: MetaItem[];
2329
- outputs: MetaItem[];
2330
- }
2331
2218
  export interface UsageEvent extends BaseModel, PermissionModel {
2332
2219
  usage_billing_record_id: string;
2333
2220
  reference_id: string;
@@ -2341,74 +2228,6 @@ export interface UsageEvent extends BaseModel, PermissionModel {
2341
2228
  quantity: number;
2342
2229
  unit: string;
2343
2230
  }
2344
- /**
2345
- * DiscountItem represents a single discount applied to a billing record
2346
- */
2347
- export interface DiscountItem {
2348
- reason: string;
2349
- amount: number;
2350
- }
2351
- export interface UsageBillingRecord extends BaseModel, PermissionModel {
2352
- /**
2353
- * Fee breakdown (all in microcents)
2354
- */
2355
- total: number;
2356
- discount: number;
2357
- /**
2358
- * User debit (total charged)
2359
- */
2360
- user_debit_transaction_id: string;
2361
- user_debit_transaction?: Transaction;
2362
- /**
2363
- * Resource owner credit (for providing compute)
2364
- */
2365
- resource_credit_transaction_id: string;
2366
- resource_credit_transaction?: Transaction;
2367
- /**
2368
- * Creator royalty credit (app creator earnings)
2369
- */
2370
- royalty_credit_transaction_id: string;
2371
- royalty_credit_transaction?: Transaction;
2372
- /**
2373
- * Inference fee credit (platform fee)
2374
- */
2375
- inference_credit_transaction_id: string;
2376
- inference_credit_transaction?: Transaction;
2377
- /**
2378
- * Partner fee credit (cloud API fee)
2379
- */
2380
- partner_credit_transaction_id: string;
2381
- partner_credit_transaction?: Transaction;
2382
- }
2383
- export interface UsageBillingRefund extends BaseModel, PermissionModel {
2384
- usage_billing_record_id: string;
2385
- usage_billing_record?: UsageBillingRecord;
2386
- /**
2387
- * User refund (total refunded)
2388
- */
2389
- user_debit_refund_transaction_id: string;
2390
- user_debit_refund_transaction?: Transaction;
2391
- /**
2392
- * Resource owner reversal
2393
- */
2394
- resource_credit_refund_transaction_id: string;
2395
- resource_credit_refund_transaction?: Transaction;
2396
- /**
2397
- * Creator royalty reversal
2398
- */
2399
- royalty_credit_refund_transaction_id: string;
2400
- royalty_credit_refund_transaction?: Transaction;
2401
- /**
2402
- * Inference fee reversal
2403
- */
2404
- inference_credit_refund_transaction_id: string;
2405
- inference_credit_refund_transaction?: Transaction;
2406
- /**
2407
- * Partner fee reversal
2408
- */
2409
- partner_credit_refund_transaction_id: string;
2410
- partner_credit_refund_transaction?: Transaction;
2411
- }
2412
2231
  /**
2413
2232
  * User-related types
2414
2233
  */
package/dist/types.js CHANGED
@@ -153,7 +153,7 @@ export const InstanceStatusDeleted = "deleted";
153
153
  export const TaskStatusUnknown = 0; // 0
154
154
  export const TaskStatusReceived = 1; // 1
155
155
  export const TaskStatusQueued = 2; // 2
156
- export const TaskStatusScheduled = 3; // 3
156
+ export const TaskStatusDispatched = 3; // 3 - Worker assigned, task sent to worker
157
157
  export const TaskStatusPreparing = 4; // 4
158
158
  export const TaskStatusServing = 5; // 5
159
159
  export const TaskStatusSettingUp = 6; // 6
@@ -184,26 +184,8 @@ export const ToolInvocationStatusAwaitingApproval = "awaiting_approval"; // Wait
184
184
  export const ToolInvocationStatusCompleted = "completed";
185
185
  export const ToolInvocationStatusFailed = "failed";
186
186
  export const ToolInvocationStatusCancelled = "cancelled";
187
- export const TransactionTypeCredit = "credit"; // Adding credits
188
- export const TransactionTypeDebit = "debit"; // Removing credits
189
- export const PaymentRecordStatusPending = 0;
190
- export const PaymentRecordStatusComplete = 1;
191
- export const PaymentRecordStatusFailed = 2;
192
- export const PaymentRecordStatusExpired = 3;
193
- export const PaymentRecordTypeCheckout = "checkout"; // Stripe Checkout session (manual top-up)
194
- export const PaymentRecordTypeAutoRecharge = "auto_recharge"; // Direct charge (auto-recharge)
195
187
  export const UsageEventResourceTierPrivate = "private";
196
188
  export const UsageEventResourceTierCloud = "cloud";
197
- export const MetaItemTypeText = "text";
198
- export const MetaItemTypeImage = "image";
199
- export const MetaItemTypeVideo = "video";
200
- export const MetaItemTypeAudio = "audio";
201
- export const MetaItemTypeRaw = "raw";
202
- export const VideoRes480P = "480p";
203
- export const VideoRes720P = "720p";
204
- export const VideoRes1080P = "1080p";
205
- export const VideoRes1440P = "1440p";
206
- export const VideoRes4K = "4k";
207
189
  export const RoleGuest = "guest";
208
190
  export const RoleUser = "user";
209
191
  export const RoleAdmin = "admin";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Status utilities for handling both int and string-based status values.
3
+ * Provides future compatibility when API migrates from int to string status.
4
+ */
5
+ import { TaskStatus } from './types';
6
+ /**
7
+ * Parse task status from int or string to TaskStatus number.
8
+ * Handles both current int-based API and future string-based API.
9
+ */
10
+ export declare function parseStatus(status: number | string | undefined | null): TaskStatus;
11
+ /**
12
+ * Check if a task status is terminal (completed, failed, or cancelled).
13
+ * Handles both int and string status values.
14
+ */
15
+ export declare function isTerminalStatus(status: number | string | undefined | null): boolean;
package/dist/utils.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Status utilities for handling both int and string-based status values.
3
+ * Provides future compatibility when API migrates from int to string status.
4
+ */
5
+ import { TaskStatusUnknown, TaskStatusReceived, TaskStatusQueued, TaskStatusDispatched, TaskStatusPreparing, TaskStatusServing, TaskStatusSettingUp, TaskStatusRunning, TaskStatusCancelling, TaskStatusUploading, TaskStatusCompleted, TaskStatusFailed, TaskStatusCancelled, } from './types';
6
+ /** Map string status names to TaskStatus values (for future string-based API) */
7
+ const STATUS_STRING_MAP = {
8
+ unknown: TaskStatusUnknown,
9
+ received: TaskStatusReceived,
10
+ queued: TaskStatusQueued,
11
+ dispatched: TaskStatusDispatched,
12
+ preparing: TaskStatusPreparing,
13
+ serving: TaskStatusServing,
14
+ setting_up: TaskStatusSettingUp,
15
+ running: TaskStatusRunning,
16
+ cancelling: TaskStatusCancelling,
17
+ uploading: TaskStatusUploading,
18
+ completed: TaskStatusCompleted,
19
+ failed: TaskStatusFailed,
20
+ cancelled: TaskStatusCancelled,
21
+ };
22
+ /**
23
+ * Parse task status from int or string to TaskStatus number.
24
+ * Handles both current int-based API and future string-based API.
25
+ */
26
+ export function parseStatus(status) {
27
+ if (status === undefined || status === null) {
28
+ return TaskStatusUnknown;
29
+ }
30
+ if (typeof status === 'number') {
31
+ return status;
32
+ }
33
+ if (typeof status === 'string') {
34
+ return STATUS_STRING_MAP[status.toLowerCase()] ?? TaskStatusUnknown;
35
+ }
36
+ return TaskStatusUnknown;
37
+ }
38
+ /**
39
+ * Check if a task status is terminal (completed, failed, or cancelled).
40
+ * Handles both int and string status values.
41
+ */
42
+ export function isTerminalStatus(status) {
43
+ const parsed = parseStatus(status);
44
+ return parsed === TaskStatusCompleted || parsed === TaskStatusFailed || parsed === TaskStatusCancelled;
45
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencesh/sdk",
3
- "version": "0.5.8",
3
+ "version": "0.5.10",
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",