@hoodcompute/sdk 0.2.1 → 0.2.2

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.
@@ -36,6 +36,11 @@ var NotFoundError = class extends HoodComputeError {
36
36
  }
37
37
  };
38
38
  var RateLimitError = class extends HoodComputeError {
39
+ /** Suggested seconds to wait before retrying, when the API provides one. */
40
+ get retryAfter() {
41
+ const value = this.details?.retry_after;
42
+ return typeof value === "number" ? value : void 0;
43
+ }
39
44
  constructor(...args) {
40
45
  super(...args);
41
46
  this.name = "RateLimitError";
@@ -122,7 +127,7 @@ var ROBINHOOD_CHAIN_ID = 4663;
122
127
  var BLOCKSCOUT_BASE_URL = "https://robinhoodchain.blockscout.com";
123
128
  var DEFAULT_TIMEOUT_MS = 12e4;
124
129
  var DEFAULT_MAX_RETRIES = 2;
125
- var SDK_VERSION = "0.1.0";
130
+ var SDK_VERSION = "0.2.2";
126
131
  function explorerTxUrl(txHash) {
127
132
  return `${BLOCKSCOUT_BASE_URL}/tx/${txHash}`;
128
133
  }
@@ -150,10 +155,10 @@ var ChatCompletionStream = class {
150
155
  const { done, value } = await reader.read();
151
156
  if (done) break;
152
157
  buffer += decoder.decode(value, { stream: true });
153
- let boundary = buffer.indexOf("\n\n");
154
- while (boundary !== -1) {
155
- const rawEvent = buffer.slice(0, boundary);
156
- buffer = buffer.slice(boundary + 2);
158
+ let boundary = findBoundary(buffer);
159
+ while (boundary !== null) {
160
+ const rawEvent = buffer.slice(0, boundary.index);
161
+ buffer = buffer.slice(boundary.index + boundary.length);
157
162
  const chunk = parseEvent(rawEvent);
158
163
  if (chunk === DONE) {
159
164
  return;
@@ -161,7 +166,7 @@ var ChatCompletionStream = class {
161
166
  if (chunk) {
162
167
  yield chunk;
163
168
  }
164
- boundary = buffer.indexOf("\n\n");
169
+ boundary = findBoundary(buffer);
165
170
  }
166
171
  }
167
172
  const trailing = parseEvent(buffer);
@@ -169,6 +174,8 @@ var ChatCompletionStream = class {
169
174
  yield trailing;
170
175
  }
171
176
  } finally {
177
+ await reader.cancel().catch(() => {
178
+ });
172
179
  reader.releaseLock();
173
180
  this.receipt = this.readReceipt();
174
181
  }
@@ -194,6 +201,13 @@ var ChatCompletionStream = class {
194
201
  }
195
202
  };
196
203
  var DONE = /* @__PURE__ */ Symbol("done");
204
+ function findBoundary(buffer) {
205
+ const lf = buffer.indexOf("\n\n");
206
+ const crlf = buffer.indexOf("\r\n\r\n");
207
+ if (lf === -1 && crlf === -1) return null;
208
+ if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
209
+ return { index: lf, length: 2 };
210
+ }
197
211
  function parseEvent(raw) {
198
212
  const dataLines = [];
199
213
  for (const line of raw.split("\n")) {
@@ -263,6 +277,7 @@ var HttpClient = class {
263
277
  }
264
278
  throw error;
265
279
  } catch (err) {
280
+ if (options.signal?.aborted) throw err;
266
281
  if (err instanceof ConnectionError && attempt < this.maxRetries) {
267
282
  lastError = err;
268
283
  await sleep(this.backoff(attempt));
@@ -277,7 +292,11 @@ var HttpClient = class {
277
292
  const controller = new AbortController();
278
293
  const timer = setTimeout(() => controller.abort(), this.timeout);
279
294
  const onAbort = () => controller.abort();
280
- userSignal?.addEventListener("abort", onAbort, { once: true });
295
+ if (userSignal?.aborted) {
296
+ controller.abort();
297
+ } else {
298
+ userSignal?.addEventListener("abort", onAbort, { once: true });
299
+ }
281
300
  try {
282
301
  return await this.fetchImpl(url, { ...init, signal: controller.signal });
283
302
  } catch (err) {
@@ -301,6 +320,13 @@ var HttpClient = class {
301
320
  } catch {
302
321
  body = void 0;
303
322
  }
323
+ const retryAfterHeader = response.headers.get("retry-after");
324
+ if (retryAfterHeader !== null && typeof body?.details?.retry_after !== "number") {
325
+ const seconds = Number(retryAfterHeader);
326
+ if (Number.isFinite(seconds) && seconds >= 0) {
327
+ body = { ...body, details: { ...body?.details, retry_after: seconds } };
328
+ }
329
+ }
304
330
  const requestId = response.headers.get("x-request-id") ?? void 0;
305
331
  return errorFromResponse(response.status, body, requestId);
306
332
  }
@@ -328,7 +354,7 @@ var HttpClient = class {
328
354
  backoff(attempt, error) {
329
355
  const retryAfter = error && typeof error === "object" && "details" in error && typeof error.details?.retry_after === "number" ? error.details.retry_after * 1e3 : void 0;
330
356
  if (retryAfter !== void 0) return retryAfter;
331
- return Math.min(1e3 * 2 ** attempt, 8e3);
357
+ return Math.min(1e3 * 2 ** attempt, 8e3) * (0.5 + Math.random() * 0.5);
332
358
  }
333
359
  };
334
360
  function sleep(ms) {
@@ -414,6 +440,11 @@ var Models = class {
414
440
  };
415
441
 
416
442
  // src/resources/jobs.ts
443
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
444
+ "settled",
445
+ "failed",
446
+ "refunded"
447
+ ]);
417
448
  function normalize2(raw) {
418
449
  return {
419
450
  id: raw.id,
@@ -468,6 +499,48 @@ var Jobs = class {
468
499
  nextCursor: data.next_cursor
469
500
  };
470
501
  }
502
+ /**
503
+ * List every job matching the filters, transparently following cursor
504
+ * pagination. Stop iterating early to stop fetching pages.
505
+ *
506
+ * @example
507
+ * for await (const job of client.jobs.iterate({ status: "settled" })) {
508
+ * console.log(job.id, job.creditsCharged)
509
+ * }
510
+ */
511
+ async *iterate(params = {}, options = {}) {
512
+ let cursor;
513
+ while (true) {
514
+ const page = await this.list({ ...params, before: cursor }, options);
515
+ yield* page.data;
516
+ if (!page.hasMore || page.nextCursor === null) return;
517
+ cursor = page.nextCursor;
518
+ }
519
+ }
520
+ /**
521
+ * Poll a job until it reaches a terminal status (`settled`, `failed`, or
522
+ * `refunded`) and return the final record. Throws {@link JobTimeoutError}
523
+ * when the deadline passes first.
524
+ */
525
+ async waitForSettlement(jobId, options = {}) {
526
+ const pollIntervalMs = options.pollIntervalMs ?? 2e3;
527
+ const timeoutMs = options.timeoutMs ?? 12e4;
528
+ const deadline = Date.now() + timeoutMs;
529
+ while (true) {
530
+ const job = await this.get(jobId, { signal: options.signal });
531
+ if (TERMINAL_STATUSES.has(job.status)) return job;
532
+ if (Date.now() + pollIntervalMs > deadline) {
533
+ throw new JobTimeoutError(
534
+ `Job ${jobId} still has status "${job.status}" after ${timeoutMs}ms.`,
535
+ { code: "settlement_wait_timeout" }
536
+ );
537
+ }
538
+ await sleep2(pollIntervalMs);
539
+ if (options.signal?.aborted) {
540
+ throw new ConnectionError("Request aborted by caller.");
541
+ }
542
+ }
543
+ }
471
544
  /**
472
545
  * Fetch the on-chain receipt for a settled job. Throws if the job exists but
473
546
  * has not settled yet.
@@ -517,6 +590,9 @@ var Jobs = class {
517
590
  };
518
591
  }
519
592
  };
593
+ function sleep2(ms) {
594
+ return new Promise((resolve) => setTimeout(resolve, ms));
595
+ }
520
596
 
521
597
  // src/resources/account.ts
522
598
  var AccountResource = class {
@@ -571,5 +647,5 @@ function readEnv(name) {
571
647
  }
572
648
 
573
649
  export { AuthenticationError, BLOCKSCOUT_BASE_URL, ChatCompletionStream, ConnectionError, DEFAULT_BASE_URL, HoodComputeClient, HoodComputeError, InsufficientCreditsError, InvalidRequestError, JobTimeoutError, NoWorkersAvailableError, NotFoundError, ROBINHOOD_CHAIN_ID, RateLimitError, SDK_VERSION, ServerError, explorerAddressUrl, explorerTxUrl };
574
- //# sourceMappingURL=chunk-72VFNNOI.js.map
575
- //# sourceMappingURL=chunk-72VFNNOI.js.map
650
+ //# sourceMappingURL=chunk-EH6FBSJB.js.map
651
+ //# sourceMappingURL=chunk-EH6FBSJB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/constants.ts","../src/streaming.ts","../src/http.ts","../src/resources/chat.ts","../src/resources/models.ts","../src/resources/jobs.ts","../src/resources/account.ts","../src/client.ts"],"names":["response","normalize","sleep"],"mappings":";AAmBO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAc1C,WAAA,CACE,OAAA,EACA,IAAA,GAOI,EAAC,EACL;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK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,CAAA;AAED,IAAA,IAAA,CAAK,IAAA,GAAO,IAAI,IAAA,CAAK,IAAI,CAAA;AACzB,IAAA,IAAA,CAAK,MAAA,GAAS,IAAI,MAAA,CAAO,IAAI,CAAA;AAC7B,IAAA,IAAA,CAAK,IAAA,GAAO,IAAI,IAAA,CAAK,IAAI,CAAA;AACzB,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,eAAA,CAAgB,IAAI,CAAA;AAAA,EACzC;AACF;AAEA,SAAS,QAAQ,IAAA,EAAkC;AACjD,EAAA,IAAI,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,GAAA,EAAK;AACjD,IAAA,OAAO,OAAA,CAAQ,IAAI,IAAI,CAAA;AAAA,EACzB;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-EH6FBSJB.js","sourcesContent":["/**\n * Error types raised by the HoodCompute SDK.\n *\n * Every failed API request is surfaced as a `HoodComputeError` (or a subclass).\n * The machine-readable `code` maps to the codes documented at\n * https://docs.hoodcompute.com/api-reference/errors.\n */\n\n/** Shape of the error body returned by the API. */\nexport interface ApiErrorBody {\n code?: string\n message?: string\n type?: string\n param?: string | null\n docs?: string\n details?: Record<string, unknown>\n}\n\n/** Base class for all errors raised by the SDK. */\nexport class HoodComputeError extends Error {\n /** HTTP status code, when the error came from an API response. */\n readonly status?: number\n /** Machine-readable error code, for example `insufficient_credits`. */\n readonly code?: string\n /** Error category reported by the API. */\n readonly type?: string\n /** Request parameter that caused the error, when applicable. */\n readonly param?: string | null\n /** Additional structured detail from the API. */\n readonly details?: Record<string, unknown>\n /** Value of the `x-request-id` response header, useful for support. */\n readonly requestId?: string\n\n constructor(\n message: string,\n opts: {\n status?: number\n code?: string\n type?: string\n param?: string | null\n details?: Record<string, unknown>\n requestId?: string\n } = {},\n ) {\n super(message)\n this.name = \"HoodComputeError\"\n this.status = opts.status\n this.code = opts.code\n this.type = opts.type\n this.param = opts.param\n this.details = opts.details\n this.requestId = opts.requestId\n }\n}\n\n/** 401 / 403. The API key is missing, invalid, revoked, or suspended. */\nexport class AuthenticationError extends HoodComputeError {\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"AuthenticationError\"\n }\n}\n\n/** 402. The credit balance is too low for the requested tier. */\nexport class InsufficientCreditsError extends HoodComputeError {\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"InsufficientCreditsError\"\n }\n}\n\n/** 400. The request body is malformed or a required field is missing. */\nexport class InvalidRequestError extends HoodComputeError {\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"InvalidRequestError\"\n }\n}\n\n/** 404. The requested resource does not exist. */\nexport class NotFoundError extends HoodComputeError {\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"NotFoundError\"\n }\n}\n\n/** 429. The request rate to the API is too high. Back off and retry. */\nexport class RateLimitError extends HoodComputeError {\n /** Suggested seconds to wait before retrying, when the API provides one. */\n get retryAfter(): number | undefined {\n const value = this.details?.retry_after\n return typeof value === \"number\" ? value : undefined\n }\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"RateLimitError\"\n }\n}\n\n/**\n * 503. No workers are currently hosting the requested model. This is a\n * transient condition. Check `retryAfter` and try again.\n */\nexport class NoWorkersAvailableError extends HoodComputeError {\n /** Suggested seconds to wait before retrying. */\n get retryAfter(): number | undefined {\n const value = this.details?.retry_after\n return typeof value === \"number\" ? value : undefined\n }\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"NoWorkersAvailableError\"\n }\n}\n\n/** 504. No worker completed the job within the timeout. Credits were refunded. */\nexport class JobTimeoutError extends HoodComputeError {\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"JobTimeoutError\"\n }\n}\n\n/** 5xx. An internal server error. Usually safe to retry. */\nexport class ServerError extends HoodComputeError {\n constructor(...args: ConstructorParameters<typeof HoodComputeError>) {\n super(...args)\n this.name = \"ServerError\"\n }\n}\n\n/** The request failed to reach the API, or timed out, or was aborted. */\nexport class ConnectionError extends HoodComputeError {\n constructor(message: string, opts: { cause?: unknown } = {}) {\n super(message)\n this.name = \"ConnectionError\"\n if (opts.cause !== undefined) this.cause = opts.cause\n }\n}\n\n/**\n * Construct the appropriate error subclass from an API response.\n * @internal\n */\nexport function errorFromResponse(\n status: number,\n body: ApiErrorBody | undefined,\n requestId?: string,\n): HoodComputeError {\n const code = body?.code\n const message = body?.message ?? `HoodCompute API request failed with status ${status}`\n const opts = {\n status,\n code,\n type: body?.type,\n param: body?.param ?? null,\n details: body?.details,\n requestId,\n }\n\n if (code === \"no_workers_available\") return new NoWorkersAvailableError(message, opts)\n if (code === \"job_timeout\") return new JobTimeoutError(message, opts)\n if (code === \"insufficient_credits\") return new InsufficientCreditsError(message, opts)\n\n switch (status) {\n case 400:\n case 422:\n return new InvalidRequestError(message, opts)\n case 401:\n case 403:\n return new AuthenticationError(message, opts)\n case 402:\n return new InsufficientCreditsError(message, opts)\n case 404:\n return new NotFoundError(message, opts)\n case 429:\n return new RateLimitError(message, opts)\n case 503:\n return new NoWorkersAvailableError(message, opts)\n case 504:\n return new JobTimeoutError(message, opts)\n default:\n if (status >= 500) return new ServerError(message, opts)\n return new HoodComputeError(message, opts)\n }\n}\n\n/** Whether an error is worth retrying with the same payload. @internal */\nexport function isRetryable(err: unknown): boolean {\n if (err instanceof ConnectionError) return true\n if (err instanceof HoodComputeError) {\n if (err.status === undefined) return false\n return err.status >= 500 || err.status === 429\n }\n return false\n}\n","/**\n * Network and client defaults for HoodCompute.\n */\n\n/** Default HoodCompute API base URL. */\nexport const DEFAULT_BASE_URL = \"https://api.hoodcompute.com/v1\"\n\n/** Robinhood Chain mainnet chain ID. */\nexport const ROBINHOOD_CHAIN_ID = 4663\n\n/** Base URL of the Robinhood Chain Blockscout explorer. */\nexport const BLOCKSCOUT_BASE_URL = \"https://robinhoodchain.blockscout.com\"\n\n/** Default request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 120_000\n\n/** Default number of automatic retries on transient failures. */\nexport const DEFAULT_MAX_RETRIES = 2\n\n/** SDK version, surfaced in the User-Agent header. Keep in sync with package.json. */\nexport const SDK_VERSION = \"0.2.2\"\n\n/**\n * Build a Blockscout explorer link for a Robinhood Chain transaction hash.\n *\n * @example\n * explorerTxUrl(receipt.settlementTx)\n * // \"https://robinhoodchain.blockscout.com/tx/0x...\"\n */\nexport function explorerTxUrl(txHash: string): string {\n return `${BLOCKSCOUT_BASE_URL}/tx/${txHash}`\n}\n\n/**\n * Build a Blockscout explorer link for a Robinhood Chain address.\n */\nexport function explorerAddressUrl(address: string): string {\n return `${BLOCKSCOUT_BASE_URL}/address/${address}`\n}\n","/**\n * Server-Sent Events parsing and the streaming chat completion object.\n */\n\nimport type { ChatCompletionChunk } from \"./types.js\"\nimport { ConnectionError } from \"./errors.js\"\n\n/**\n * Lightweight settlement metadata surfaced from a streaming response once it\n * closes. Values are read from response headers as the network makes them\n * available. For the full on-chain receipt, call `client.jobs.getReceipt(jobId)`.\n */\nexport interface StreamReceipt {\n jobId: string | null\n settlementTx: string | null\n escrowTx: string | null\n workerAddress: string | null\n creditsRemaining: number | null\n}\n\n/**\n * An async-iterable stream of chat completion chunks.\n *\n * Iterate it with `for await` to consume tokens as they arrive. Once iteration\n * finishes, `jobId` and `receipt` are populated from the response.\n *\n * @example\n * const stream = await client.chat.completions.create({ ..., stream: true })\n * for await (const chunk of stream) {\n * process.stdout.write(chunk.choices[0]?.delta?.content ?? \"\")\n * }\n * console.log(stream.receipt.settlementTx)\n */\nexport class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk> {\n /** HoodCompute job ID for this completion, from the response header. */\n jobId: string | null\n /** Settlement metadata, populated once the stream finishes. */\n receipt: StreamReceipt\n\n private readonly response: Response\n\n constructor(response: Response) {\n this.response = response\n this.jobId = response.headers.get(\"x-hoodcompute-job-id\")\n this.receipt = this.readReceipt()\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n const body = this.response.body\n if (!body) {\n throw new ConnectionError(\"The streaming response contained no body.\")\n }\n\n const decoder = new TextDecoder()\n const reader = body.getReader()\n let buffer = \"\"\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n\n // SSE events are separated by a blank line, with either LF or CRLF\n // line endings.\n let boundary = findBoundary(buffer)\n while (boundary !== null) {\n const rawEvent = buffer.slice(0, boundary.index)\n buffer = buffer.slice(boundary.index + boundary.length)\n\n const chunk = parseEvent(rawEvent)\n if (chunk === DONE) {\n return\n }\n if (chunk) {\n yield chunk\n }\n boundary = findBoundary(buffer)\n }\n }\n\n // Flush a trailing event with no terminating blank line.\n const trailing = parseEvent(buffer)\n if (trailing && trailing !== DONE) {\n yield trailing\n }\n } finally {\n // Cancel before releasing so an early exit from iteration closes the\n // underlying connection instead of leaving it open.\n await reader.cancel().catch(() => {})\n reader.releaseLock()\n // Refresh the receipt in case trailer headers landed after the stream.\n this.receipt = this.readReceipt()\n }\n }\n\n /** Convenience: collect the full concatenated text of the stream. */\n async text(): Promise<string> {\n let out = \"\"\n for await (const chunk of this) {\n out += chunk.choices[0]?.delta?.content ?? \"\"\n }\n return out\n }\n\n private readReceipt(): StreamReceipt {\n const h = this.response.headers\n const creditsRemaining = h.get(\"x-hoodcompute-credits-remaining\")\n return {\n jobId: h.get(\"x-hoodcompute-job-id\"),\n settlementTx: h.get(\"x-hoodcompute-settlement-tx\"),\n escrowTx: h.get(\"x-hoodcompute-tx-hash\"),\n workerAddress: h.get(\"x-hoodcompute-worker\"),\n creditsRemaining: creditsRemaining !== null ? Number(creditsRemaining) : null,\n }\n }\n}\n\n/** Sentinel marking the `[DONE]` terminator. */\nconst DONE = Symbol(\"done\")\n\n/**\n * Locate the earliest blank-line event boundary in the buffer, whether the\n * server uses LF or CRLF line endings.\n */\nfunction findBoundary(buffer: string): { index: number; length: number } | null {\n const lf = buffer.indexOf(\"\\n\\n\")\n const crlf = buffer.indexOf(\"\\r\\n\\r\\n\")\n if (lf === -1 && crlf === -1) return null\n if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 }\n return { index: lf, length: 2 }\n}\n\n/**\n * Parse one raw SSE event block into a chunk. Returns `DONE` on the terminator,\n * `null` for events without usable data (comments, empty blocks).\n */\nfunction parseEvent(raw: string): ChatCompletionChunk | typeof DONE | null {\n const dataLines: string[] = []\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trimEnd()\n if (trimmed.startsWith(\":\") || trimmed === \"\") continue\n if (trimmed.startsWith(\"data:\")) {\n dataLines.push(trimmed.slice(5).trimStart())\n }\n }\n if (dataLines.length === 0) return null\n\n const data = dataLines.join(\"\\n\")\n if (data === \"[DONE]\") return DONE\n\n try {\n return JSON.parse(data) as ChatCompletionChunk\n } catch {\n return null\n }\n}\n","/**\n * Internal HTTP transport. Handles authentication headers, timeouts, automatic\n * retries with exponential backoff, and error normalization. Not part of the\n * public API surface.\n * @internal\n */\n\nimport {\n ConnectionError,\n errorFromResponse,\n isRetryable,\n type ApiErrorBody,\n} from \"./errors.js\"\nimport { SDK_VERSION } from \"./constants.js\"\n\nexport interface HttpClientOptions {\n apiKey: string\n baseURL: string\n timeout: number\n maxRetries: number\n defaultHeaders?: Record<string, string>\n fetch?: typeof fetch\n}\n\nexport interface RequestOptions {\n method?: string\n path: string\n query?: Record<string, string | number | undefined>\n body?: unknown\n /** When true, the raw Response is returned without reading the body. */\n stream?: boolean\n signal?: AbortSignal\n}\n\nexport class HttpClient {\n private readonly apiKey: string\n private readonly baseURL: string\n private readonly timeout: number\n private readonly maxRetries: number\n private readonly defaultHeaders: Record<string, string>\n private readonly fetchImpl: typeof fetch\n\n constructor(options: HttpClientOptions) {\n this.apiKey = options.apiKey\n this.baseURL = options.baseURL.replace(/\\/$/, \"\")\n this.timeout = options.timeout\n this.maxRetries = options.maxRetries\n this.defaultHeaders = options.defaultHeaders ?? {}\n\n const impl = options.fetch ?? globalThis.fetch\n if (!impl) {\n throw new ConnectionError(\n \"No global fetch implementation found. Use Node 18+ or pass a `fetch` option.\",\n )\n }\n this.fetchImpl = impl\n }\n\n /** Perform a request and return the parsed JSON body plus response headers. */\n async request<T>(options: RequestOptions): Promise<{ data: T; response: Response }> {\n const response = await this.raw(options)\n const text = await response.text()\n const data = text ? (JSON.parse(text) as T) : (undefined as T)\n return { data, response }\n }\n\n /**\n * Perform a request and return the raw Response. Used by the streaming path,\n * which reads `response.body` directly. Errors are still parsed and thrown.\n */\n async raw(options: RequestOptions): Promise<Response> {\n const url = this.buildUrl(options.path, options.query)\n const headers = this.buildHeaders(options)\n const init: RequestInit = {\n method: options.method ?? \"GET\",\n headers,\n }\n if (options.body !== undefined) {\n init.body = JSON.stringify(options.body)\n }\n\n let lastError: unknown\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n try {\n const response = await this.fetchWithTimeout(url, init, options.signal)\n if (response.ok) return response\n\n const error = await this.toError(response)\n if (isRetryable(error) && attempt < this.maxRetries) {\n lastError = error\n await sleep(this.backoff(attempt, error))\n continue\n }\n throw error\n } catch (err) {\n // An abort from the caller is a deliberate cancellation, never retried.\n if (options.signal?.aborted) throw err\n if (err instanceof ConnectionError && attempt < this.maxRetries) {\n lastError = err\n await sleep(this.backoff(attempt))\n continue\n }\n throw err\n }\n }\n\n // Loop only exits via return/throw except when the last attempt was a\n // retryable failure that exhausted the budget.\n throw lastError instanceof Error\n ? lastError\n : new ConnectionError(\"Request failed after exhausting retries.\")\n }\n\n private async fetchWithTimeout(\n url: string,\n init: RequestInit,\n userSignal?: AbortSignal,\n ): Promise<Response> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeout)\n const onAbort = () => controller.abort()\n // A signal that is already aborted never fires its \"abort\" event again.\n if (userSignal?.aborted) {\n controller.abort()\n } else {\n userSignal?.addEventListener(\"abort\", onAbort, { once: true })\n }\n\n try {\n return await this.fetchImpl(url, { ...init, signal: controller.signal })\n } catch (err) {\n if (userSignal?.aborted) {\n throw new ConnectionError(\"Request aborted by caller.\", { cause: err })\n }\n if (controller.signal.aborted) {\n throw new ConnectionError(`Request timed out after ${this.timeout}ms.`, { cause: err })\n }\n throw new ConnectionError(\"Failed to reach the HoodCompute API.\", { cause: err })\n } finally {\n clearTimeout(timer)\n userSignal?.removeEventListener(\"abort\", onAbort)\n }\n }\n\n private async toError(response: Response) {\n let body: ApiErrorBody | undefined\n try {\n const parsed = (await response.json()) as { error?: ApiErrorBody } | ApiErrorBody\n body = \"error\" in parsed && parsed.error ? parsed.error : (parsed as ApiErrorBody)\n } catch {\n body = undefined\n }\n\n // Surface a standard Retry-After header through `details.retry_after` when\n // the body itself does not carry one, so the retry loop and callers see a\n // single source of truth.\n const retryAfterHeader = response.headers.get(\"retry-after\")\n if (retryAfterHeader !== null && typeof body?.details?.retry_after !== \"number\") {\n const seconds = Number(retryAfterHeader)\n if (Number.isFinite(seconds) && seconds >= 0) {\n body = { ...body, details: { ...body?.details, retry_after: seconds } }\n }\n }\n\n const requestId = response.headers.get(\"x-request-id\") ?? undefined\n return errorFromResponse(response.status, body, requestId)\n }\n\n private buildUrl(path: string, query?: RequestOptions[\"query\"]): string {\n const url = new URL(`${this.baseURL}${path}`)\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n }\n return url.toString()\n }\n\n private buildHeaders(options: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n Accept: options.stream ? \"text/event-stream\" : \"application/json\",\n \"User-Agent\": `hoodcompute-sdk-js/${SDK_VERSION}`,\n ...this.defaultHeaders,\n }\n if (options.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\"\n }\n return headers\n }\n\n private backoff(attempt: number, error?: unknown): number {\n // Honor a server-suggested retry_after when present (in seconds).\n const retryAfter =\n error &&\n typeof error === \"object\" &&\n \"details\" in error &&\n typeof (error as { details?: Record<string, unknown> }).details?.retry_after === \"number\"\n ? ((error as { details: Record<string, unknown> }).details.retry_after as number) * 1000\n : undefined\n if (retryAfter !== undefined) return retryAfter\n // Full jitter keeps simultaneous clients from retrying in lockstep.\n return Math.min(1000 * 2 ** attempt, 8000) * (0.5 + Math.random() * 0.5)\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","/**\n * Chat completions. OpenAI-compatible in request and response shape, with the\n * job ID and on-chain settlement attached to every result.\n */\n\nimport type { HttpClient } from \"../http.js\"\nimport type {\n ChatCompletion,\n ChatCompletionCreateParams,\n} from \"../types.js\"\nimport { ChatCompletionStream } from \"../streaming.js\"\n\n/** Raw response body from the completions endpoint, before SDK normalization. */\ninterface RawChatCompletion {\n id: string\n object: \"chat.completion\"\n created: number\n model: string\n choices: ChatCompletion[\"choices\"]\n usage: ChatCompletion[\"usage\"]\n}\n\nexport class Completions {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a chat completion.\n *\n * Pass `stream: true` to receive a {@link ChatCompletionStream}. Otherwise a\n * fully resolved {@link ChatCompletion} is returned.\n */\n create(\n params: ChatCompletionCreateParams & { stream: true },\n options?: { signal?: AbortSignal },\n ): Promise<ChatCompletionStream>\n create(\n params: ChatCompletionCreateParams & { stream?: false },\n options?: { signal?: AbortSignal },\n ): Promise<ChatCompletion>\n create(\n params: ChatCompletionCreateParams,\n options?: { signal?: AbortSignal },\n ): Promise<ChatCompletion | ChatCompletionStream>\n async create(\n params: ChatCompletionCreateParams,\n options: { signal?: AbortSignal } = {},\n ): Promise<ChatCompletion | ChatCompletionStream> {\n if (params.stream) {\n const response = await this.http.raw({\n method: \"POST\",\n path: \"/chat/completions\",\n body: params,\n stream: true,\n signal: options.signal,\n })\n return new ChatCompletionStream(response)\n }\n\n const { data, response } = await this.http.request<RawChatCompletion>({\n method: \"POST\",\n path: \"/chat/completions\",\n body: params,\n signal: options.signal,\n })\n\n const creditsRemaining = response.headers.get(\"x-hoodcompute-credits-remaining\")\n return {\n ...data,\n jobId: response.headers.get(\"x-hoodcompute-job-id\") ?? data.id,\n settlementTx: response.headers.get(\"x-hoodcompute-settlement-tx\"),\n creditsCharged: null,\n creditsRemaining: creditsRemaining !== null ? Number(creditsRemaining) : null,\n }\n }\n}\n\nexport class Chat {\n readonly completions: Completions\n constructor(http: HttpClient) {\n this.completions = new Completions(http)\n }\n}\n","/**\n * Models. Reflects the live worker pool: a model is listed only while at least\n * one worker is hosting it.\n */\n\nimport type { HttpClient } from \"../http.js\"\nimport type { Model, ModelList, ModelTier } from \"../types.js\"\n\ninterface RawModel {\n id: string\n object: \"model\"\n created: number\n owned_by: string\n hoodcompute: {\n tier: ModelTier\n credits_per_request: number\n credits_per_1k_tokens: number\n active_workers: number\n median_latency_ms: number\n parameters: string\n context_window: number\n }\n}\n\nfunction normalize(raw: RawModel): Model {\n return {\n id: raw.id,\n object: raw.object,\n created: raw.created,\n ownedBy: raw.owned_by,\n hoodcompute: {\n tier: raw.hoodcompute.tier,\n creditsPerRequest: raw.hoodcompute.credits_per_request,\n creditsPer1kTokens: raw.hoodcompute.credits_per_1k_tokens,\n activeWorkers: raw.hoodcompute.active_workers,\n medianLatencyMs: raw.hoodcompute.median_latency_ms,\n parameters: raw.hoodcompute.parameters,\n contextWindow: raw.hoodcompute.context_window,\n },\n }\n}\n\nexport class Models {\n constructor(private readonly http: HttpClient) {}\n\n /** List every model currently available on the network. */\n async list(options: { signal?: AbortSignal } = {}): Promise<ModelList> {\n const { data } = await this.http.request<{ object: \"list\"; data: RawModel[] }>({\n path: \"/models\",\n signal: options.signal,\n })\n return { object: \"list\", data: data.data.map(normalize) }\n }\n\n /** Retrieve a single model by ID, including its live worker count. */\n async retrieve(modelId: string, options: { signal?: AbortSignal } = {}): Promise<Model> {\n const { data } = await this.http.request<RawModel>({\n path: `/models/${encodeURIComponent(modelId)}`,\n signal: options.signal,\n })\n return normalize(data)\n }\n}\n","/**\n * Jobs. Retrieve job status, fetch on-chain receipts, and open disputes.\n */\n\nimport type { HttpClient } from \"../http.js\"\nimport type {\n DisputeResult,\n Job,\n JobList,\n JobListParams,\n JobReceipt,\n JobStatus,\n ModelTier,\n Usage,\n} from \"../types.js\"\nimport { ConnectionError, JobTimeoutError, NotFoundError } from \"../errors.js\"\n\n/** Statuses after which a job will no longer change. */\nconst TERMINAL_STATUSES: ReadonlySet<JobStatus> = new Set([\n \"settled\",\n \"failed\",\n \"refunded\",\n])\n\nexport interface WaitForSettlementOptions {\n /** Milliseconds between polls. Defaults to 2000. */\n pollIntervalMs?: number\n /** Give up after this many milliseconds. Defaults to 120000. */\n timeoutMs?: number\n signal?: AbortSignal\n}\n\ninterface RawJob {\n id: string\n object: \"job\"\n status: JobStatus\n model: string\n tier: ModelTier\n credits_charged: number\n usdg_value: number\n worker_address: string\n created_at: string\n completed_at: string | null\n on_chain: {\n escrow_tx: string\n settlement_tx: string\n escrow_address: string\n block_number: number\n proof_hash: string\n } | null\n usage: Usage | null\n}\n\nfunction normalize(raw: RawJob): Job {\n return {\n id: raw.id,\n object: raw.object,\n status: raw.status,\n model: raw.model,\n tier: raw.tier,\n creditsCharged: raw.credits_charged,\n usdgValue: raw.usdg_value,\n workerAddress: raw.worker_address,\n createdAt: raw.created_at,\n completedAt: raw.completed_at,\n onChain: raw.on_chain\n ? {\n escrowTx: raw.on_chain.escrow_tx,\n settlementTx: raw.on_chain.settlement_tx,\n escrowAddress: raw.on_chain.escrow_address,\n blockNumber: raw.on_chain.block_number,\n proofHash: raw.on_chain.proof_hash,\n }\n : null,\n usage: raw.usage,\n }\n}\n\nexport class Jobs {\n constructor(private readonly http: HttpClient) {}\n\n /** Retrieve a job by ID, including its on-chain settlement detail. */\n async get(jobId: string, options: { signal?: AbortSignal } = {}): Promise<Job> {\n const { data } = await this.http.request<RawJob>({\n path: `/jobs/${encodeURIComponent(jobId)}`,\n signal: options.signal,\n })\n return normalize(data)\n }\n\n /** List jobs for the authenticated key, most recent first. */\n async list(params: JobListParams = {}, options: { signal?: AbortSignal } = {}): Promise<JobList> {\n const { data } = await this.http.request<{\n object: \"list\"\n data: RawJob[]\n has_more: boolean\n next_cursor: string | null\n }>({\n path: \"/jobs\",\n query: {\n limit: params.limit,\n before: params.before,\n after: params.after,\n status: params.status,\n model: params.model,\n },\n signal: options.signal,\n })\n return {\n object: \"list\",\n data: data.data.map(normalize),\n hasMore: data.has_more,\n nextCursor: data.next_cursor,\n }\n }\n\n /**\n * List every job matching the filters, transparently following cursor\n * pagination. Stop iterating early to stop fetching pages.\n *\n * @example\n * for await (const job of client.jobs.iterate({ status: \"settled\" })) {\n * console.log(job.id, job.creditsCharged)\n * }\n */\n async *iterate(\n params: Omit<JobListParams, \"before\" | \"after\"> = {},\n options: { signal?: AbortSignal } = {},\n ): AsyncGenerator<Job, void, undefined> {\n let cursor: string | undefined\n while (true) {\n const page = await this.list({ ...params, before: cursor }, options)\n yield* page.data\n if (!page.hasMore || page.nextCursor === null) return\n cursor = page.nextCursor\n }\n }\n\n /**\n * Poll a job until it reaches a terminal status (`settled`, `failed`, or\n * `refunded`) and return the final record. Throws {@link JobTimeoutError}\n * when the deadline passes first.\n */\n async waitForSettlement(\n jobId: string,\n options: WaitForSettlementOptions = {},\n ): Promise<Job> {\n const pollIntervalMs = options.pollIntervalMs ?? 2_000\n const timeoutMs = options.timeoutMs ?? 120_000\n const deadline = Date.now() + timeoutMs\n\n while (true) {\n const job = await this.get(jobId, { signal: options.signal })\n if (TERMINAL_STATUSES.has(job.status)) return job\n\n if (Date.now() + pollIntervalMs > deadline) {\n throw new JobTimeoutError(\n `Job ${jobId} still has status \"${job.status}\" after ${timeoutMs}ms.`,\n { code: \"settlement_wait_timeout\" },\n )\n }\n await sleep(pollIntervalMs)\n if (options.signal?.aborted) {\n throw new ConnectionError(\"Request aborted by caller.\")\n }\n }\n }\n\n /**\n * Fetch the on-chain receipt for a settled job. Throws if the job exists but\n * has not settled yet.\n */\n async getReceipt(jobId: string, options: { signal?: AbortSignal } = {}): Promise<JobReceipt> {\n const job = await this.get(jobId, options)\n if (!job.onChain) {\n throw new NotFoundError(\n `Job ${jobId} has status \"${job.status}\" and no on-chain receipt yet.`,\n { code: \"receipt_not_ready\" },\n )\n }\n return {\n jobId: job.id,\n model: job.model,\n tier: job.tier,\n creditsCharged: job.creditsCharged,\n usdgValue: job.usdgValue,\n workerAddress: job.workerAddress,\n escrowTx: job.onChain.escrowTx,\n settlementTx: job.onChain.settlementTx,\n blockNumber: job.onChain.blockNumber,\n proofHash: job.onChain.proofHash,\n }\n }\n\n /**\n * Open a dispute on a completed job. Must be called within 60 seconds of\n * receiving the final output token.\n *\n * @param receivedOutputHash SHA-256 of the full response text you received,\n * formatted as `sha256:<hex>`.\n */\n async dispute(\n jobId: string,\n receivedOutputHash: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<DisputeResult> {\n const { data } = await this.http.request<{\n job_id: string\n dispute_opened: boolean\n your_hash: string\n worker_hash: string\n dispute_tx?: string | null\n arbitration_window_hours?: number | null\n }>({\n method: \"POST\",\n path: `/jobs/${encodeURIComponent(jobId)}/dispute`,\n body: { received_output_hash: receivedOutputHash },\n signal: options.signal,\n })\n return {\n jobId: data.job_id,\n disputeOpened: data.dispute_opened,\n yourHash: data.your_hash,\n workerHash: data.worker_hash,\n disputeTx: data.dispute_tx ?? null,\n arbitrationWindowHours: data.arbitration_window_hours ?? null,\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","/**\n * Account. The wallet and credit balance tied to the authenticated API key.\n */\n\nimport type { HttpClient } from \"../http.js\"\nimport type { Account } from \"../types.js\"\n\ninterface RawAccount {\n wallet: string\n credits_remaining: number\n usdg_value: number\n last_topup_at: string | null\n api_key_created_at: string | null\n}\n\nexport class AccountResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Retrieve the current account, including the live credit balance. */\n async get(options: { signal?: AbortSignal } = {}): Promise<Account> {\n const { data } = await this.http.request<RawAccount>({\n path: \"/account\",\n signal: options.signal,\n })\n return {\n wallet: data.wallet,\n creditsRemaining: data.credits_remaining,\n usdgValue: data.usdg_value,\n lastTopupAt: data.last_topup_at ?? null,\n apiKeyCreatedAt: data.api_key_created_at ?? null,\n }\n }\n}\n","/**\n * The HoodCompute client. Entry point for chat completions, models, jobs, and\n * account access against the decentralized inference network.\n */\n\nimport { HttpClient } from \"./http.js\"\nimport { HoodComputeError } from \"./errors.js\"\nimport {\n DEFAULT_BASE_URL,\n DEFAULT_MAX_RETRIES,\n DEFAULT_TIMEOUT_MS,\n} from \"./constants.js\"\nimport { Chat } from \"./resources/chat.js\"\nimport { Models } from \"./resources/models.js\"\nimport { Jobs } from \"./resources/jobs.js\"\nimport { AccountResource } from \"./resources/account.js\"\n\nexport interface HoodComputeClientOptions {\n /**\n * API key, formatted `hoodc_live_...`. Falls back to the\n * `HOODCOMPUTE_API_KEY` environment variable when omitted.\n */\n apiKey?: string\n /** API base URL. Defaults to `https://api.hoodcompute.com/v1`. */\n baseURL?: string\n /** Per-request timeout in milliseconds. Defaults to 120000. */\n timeout?: number\n /** Automatic retries on 5xx, 429, and connection failures. Defaults to 2. */\n maxRetries?: number\n /** Headers added to every request. */\n defaultHeaders?: Record<string, string>\n /** Custom fetch implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch\n}\n\nexport class HoodComputeClient {\n readonly chat: Chat\n readonly models: Models\n readonly jobs: Jobs\n readonly account: AccountResource\n\n constructor(options: HoodComputeClientOptions = {}) {\n const apiKey = options.apiKey ?? readEnv(\"HOODCOMPUTE_API_KEY\")\n if (!apiKey) {\n throw new HoodComputeError(\n \"Missing API key. Pass `apiKey` to the client or set the HOODCOMPUTE_API_KEY environment variable.\",\n { code: \"missing_api_key\" },\n )\n }\n\n const http = new HttpClient({\n apiKey,\n baseURL: options.baseURL ?? DEFAULT_BASE_URL,\n timeout: options.timeout ?? DEFAULT_TIMEOUT_MS,\n maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,\n defaultHeaders: options.defaultHeaders,\n fetch: options.fetch,\n })\n\n this.chat = new Chat(http)\n this.models = new Models(http)\n this.jobs = new Jobs(http)\n this.account = new AccountResource(http)\n }\n}\n\nfunction readEnv(name: string): string | undefined {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[name]\n }\n return undefined\n}\n"]}
@@ -342,6 +342,13 @@ declare class Models {
342
342
  * Jobs. Retrieve job status, fetch on-chain receipts, and open disputes.
343
343
  */
344
344
 
345
+ interface WaitForSettlementOptions {
346
+ /** Milliseconds between polls. Defaults to 2000. */
347
+ pollIntervalMs?: number;
348
+ /** Give up after this many milliseconds. Defaults to 120000. */
349
+ timeoutMs?: number;
350
+ signal?: AbortSignal;
351
+ }
345
352
  declare class Jobs {
346
353
  private readonly http;
347
354
  constructor(http: HttpClient);
@@ -353,6 +360,24 @@ declare class Jobs {
353
360
  list(params?: JobListParams, options?: {
354
361
  signal?: AbortSignal;
355
362
  }): Promise<JobList>;
363
+ /**
364
+ * List every job matching the filters, transparently following cursor
365
+ * pagination. Stop iterating early to stop fetching pages.
366
+ *
367
+ * @example
368
+ * for await (const job of client.jobs.iterate({ status: "settled" })) {
369
+ * console.log(job.id, job.creditsCharged)
370
+ * }
371
+ */
372
+ iterate(params?: Omit<JobListParams, "before" | "after">, options?: {
373
+ signal?: AbortSignal;
374
+ }): AsyncGenerator<Job, void, undefined>;
375
+ /**
376
+ * Poll a job until it reaches a terminal status (`settled`, `failed`, or
377
+ * `refunded`) and return the final record. Throws {@link JobTimeoutError}
378
+ * when the deadline passes first.
379
+ */
380
+ waitForSettlement(jobId: string, options?: WaitForSettlementOptions): Promise<Job>;
356
381
  /**
357
382
  * Fetch the on-chain receipt for a settled job. Throws if the job exists but
358
383
  * has not settled yet.
@@ -415,4 +440,4 @@ declare class HoodComputeClient {
415
440
  constructor(options?: HoodComputeClientOptions);
416
441
  }
417
442
 
418
- export { type Account as A, type ChatCompletion as C, type DisputeResult as D, HoodComputeClient as H, type Job as J, type ModelTier as M, type StreamReceipt as S, type Usage as U, type ChatCompletionChoice as a, type ChatCompletionChunk as b, type ChatCompletionChunkChoice as c, type ChatCompletionCreateParams as d, type ChatCompletionDelta as e, ChatCompletionStream as f, type ChatMessage as g, type ChatRole as h, type HoodComputeClientOptions as i, type JobList as j, type JobListParams as k, type JobOnChain as l, type JobReceipt as m, type JobStatus as n, type Model as o, type ModelList as p, type ModelMeta as q };
443
+ export { type Account as A, type ChatCompletion as C, type DisputeResult as D, HoodComputeClient as H, type Job as J, type ModelTier as M, type StreamReceipt as S, type Usage as U, type WaitForSettlementOptions as W, type ChatCompletionChoice as a, type ChatCompletionChunk as b, type ChatCompletionChunkChoice as c, type ChatCompletionCreateParams as d, type ChatCompletionDelta as e, ChatCompletionStream as f, type ChatMessage as g, type ChatRole as h, type HoodComputeClientOptions as i, type JobList as j, type JobListParams as k, type JobOnChain as l, type JobReceipt as m, type JobStatus as n, type Model as o, type ModelList as p, type ModelMeta as q };
@@ -342,6 +342,13 @@ declare class Models {
342
342
  * Jobs. Retrieve job status, fetch on-chain receipts, and open disputes.
343
343
  */
344
344
 
345
+ interface WaitForSettlementOptions {
346
+ /** Milliseconds between polls. Defaults to 2000. */
347
+ pollIntervalMs?: number;
348
+ /** Give up after this many milliseconds. Defaults to 120000. */
349
+ timeoutMs?: number;
350
+ signal?: AbortSignal;
351
+ }
345
352
  declare class Jobs {
346
353
  private readonly http;
347
354
  constructor(http: HttpClient);
@@ -353,6 +360,24 @@ declare class Jobs {
353
360
  list(params?: JobListParams, options?: {
354
361
  signal?: AbortSignal;
355
362
  }): Promise<JobList>;
363
+ /**
364
+ * List every job matching the filters, transparently following cursor
365
+ * pagination. Stop iterating early to stop fetching pages.
366
+ *
367
+ * @example
368
+ * for await (const job of client.jobs.iterate({ status: "settled" })) {
369
+ * console.log(job.id, job.creditsCharged)
370
+ * }
371
+ */
372
+ iterate(params?: Omit<JobListParams, "before" | "after">, options?: {
373
+ signal?: AbortSignal;
374
+ }): AsyncGenerator<Job, void, undefined>;
375
+ /**
376
+ * Poll a job until it reaches a terminal status (`settled`, `failed`, or
377
+ * `refunded`) and return the final record. Throws {@link JobTimeoutError}
378
+ * when the deadline passes first.
379
+ */
380
+ waitForSettlement(jobId: string, options?: WaitForSettlementOptions): Promise<Job>;
356
381
  /**
357
382
  * Fetch the on-chain receipt for a settled job. Throws if the job exists but
358
383
  * has not settled yet.
@@ -415,4 +440,4 @@ declare class HoodComputeClient {
415
440
  constructor(options?: HoodComputeClientOptions);
416
441
  }
417
442
 
418
- export { type Account as A, type ChatCompletion as C, type DisputeResult as D, HoodComputeClient as H, type Job as J, type ModelTier as M, type StreamReceipt as S, type Usage as U, type ChatCompletionChoice as a, type ChatCompletionChunk as b, type ChatCompletionChunkChoice as c, type ChatCompletionCreateParams as d, type ChatCompletionDelta as e, ChatCompletionStream as f, type ChatMessage as g, type ChatRole as h, type HoodComputeClientOptions as i, type JobList as j, type JobListParams as k, type JobOnChain as l, type JobReceipt as m, type JobStatus as n, type Model as o, type ModelList as p, type ModelMeta as q };
443
+ export { type Account as A, type ChatCompletion as C, type DisputeResult as D, HoodComputeClient as H, type Job as J, type ModelTier as M, type StreamReceipt as S, type Usage as U, type WaitForSettlementOptions as W, type ChatCompletionChoice as a, type ChatCompletionChunk as b, type ChatCompletionChunkChoice as c, type ChatCompletionCreateParams as d, type ChatCompletionDelta as e, ChatCompletionStream as f, type ChatMessage as g, type ChatRole as h, type HoodComputeClientOptions as i, type JobList as j, type JobListParams as k, type JobOnChain as l, type JobReceipt as m, type JobStatus as n, type Model as o, type ModelList as p, type ModelMeta as q };
package/dist/index.cjs CHANGED
@@ -44,6 +44,11 @@ var NotFoundError = class extends HoodComputeError {
44
44
  }
45
45
  };
46
46
  var RateLimitError = class extends HoodComputeError {
47
+ /** Suggested seconds to wait before retrying, when the API provides one. */
48
+ get retryAfter() {
49
+ const value = this.details?.retry_after;
50
+ return typeof value === "number" ? value : void 0;
51
+ }
47
52
  constructor(...args) {
48
53
  super(...args);
49
54
  this.name = "RateLimitError";
@@ -130,7 +135,7 @@ var ROBINHOOD_CHAIN_ID = 4663;
130
135
  var BLOCKSCOUT_BASE_URL = "https://robinhoodchain.blockscout.com";
131
136
  var DEFAULT_TIMEOUT_MS = 12e4;
132
137
  var DEFAULT_MAX_RETRIES = 2;
133
- var SDK_VERSION = "0.1.0";
138
+ var SDK_VERSION = "0.2.2";
134
139
  function explorerTxUrl(txHash) {
135
140
  return `${BLOCKSCOUT_BASE_URL}/tx/${txHash}`;
136
141
  }
@@ -188,6 +193,7 @@ var HttpClient = class {
188
193
  }
189
194
  throw error;
190
195
  } catch (err) {
196
+ if (options.signal?.aborted) throw err;
191
197
  if (err instanceof ConnectionError && attempt < this.maxRetries) {
192
198
  lastError = err;
193
199
  await sleep(this.backoff(attempt));
@@ -202,7 +208,11 @@ var HttpClient = class {
202
208
  const controller = new AbortController();
203
209
  const timer = setTimeout(() => controller.abort(), this.timeout);
204
210
  const onAbort = () => controller.abort();
205
- userSignal?.addEventListener("abort", onAbort, { once: true });
211
+ if (userSignal?.aborted) {
212
+ controller.abort();
213
+ } else {
214
+ userSignal?.addEventListener("abort", onAbort, { once: true });
215
+ }
206
216
  try {
207
217
  return await this.fetchImpl(url, { ...init, signal: controller.signal });
208
218
  } catch (err) {
@@ -226,6 +236,13 @@ var HttpClient = class {
226
236
  } catch {
227
237
  body = void 0;
228
238
  }
239
+ const retryAfterHeader = response.headers.get("retry-after");
240
+ if (retryAfterHeader !== null && typeof body?.details?.retry_after !== "number") {
241
+ const seconds = Number(retryAfterHeader);
242
+ if (Number.isFinite(seconds) && seconds >= 0) {
243
+ body = { ...body, details: { ...body?.details, retry_after: seconds } };
244
+ }
245
+ }
229
246
  const requestId = response.headers.get("x-request-id") ?? void 0;
230
247
  return errorFromResponse(response.status, body, requestId);
231
248
  }
@@ -253,7 +270,7 @@ var HttpClient = class {
253
270
  backoff(attempt, error) {
254
271
  const retryAfter = error && typeof error === "object" && "details" in error && typeof error.details?.retry_after === "number" ? error.details.retry_after * 1e3 : void 0;
255
272
  if (retryAfter !== void 0) return retryAfter;
256
- return Math.min(1e3 * 2 ** attempt, 8e3);
273
+ return Math.min(1e3 * 2 ** attempt, 8e3) * (0.5 + Math.random() * 0.5);
257
274
  }
258
275
  };
259
276
  function sleep(ms) {
@@ -280,10 +297,10 @@ var ChatCompletionStream = class {
280
297
  const { done, value } = await reader.read();
281
298
  if (done) break;
282
299
  buffer += decoder.decode(value, { stream: true });
283
- let boundary = buffer.indexOf("\n\n");
284
- while (boundary !== -1) {
285
- const rawEvent = buffer.slice(0, boundary);
286
- buffer = buffer.slice(boundary + 2);
300
+ let boundary = findBoundary(buffer);
301
+ while (boundary !== null) {
302
+ const rawEvent = buffer.slice(0, boundary.index);
303
+ buffer = buffer.slice(boundary.index + boundary.length);
287
304
  const chunk = parseEvent(rawEvent);
288
305
  if (chunk === DONE) {
289
306
  return;
@@ -291,7 +308,7 @@ var ChatCompletionStream = class {
291
308
  if (chunk) {
292
309
  yield chunk;
293
310
  }
294
- boundary = buffer.indexOf("\n\n");
311
+ boundary = findBoundary(buffer);
295
312
  }
296
313
  }
297
314
  const trailing = parseEvent(buffer);
@@ -299,6 +316,8 @@ var ChatCompletionStream = class {
299
316
  yield trailing;
300
317
  }
301
318
  } finally {
319
+ await reader.cancel().catch(() => {
320
+ });
302
321
  reader.releaseLock();
303
322
  this.receipt = this.readReceipt();
304
323
  }
@@ -324,6 +343,13 @@ var ChatCompletionStream = class {
324
343
  }
325
344
  };
326
345
  var DONE = /* @__PURE__ */ Symbol("done");
346
+ function findBoundary(buffer) {
347
+ const lf = buffer.indexOf("\n\n");
348
+ const crlf = buffer.indexOf("\r\n\r\n");
349
+ if (lf === -1 && crlf === -1) return null;
350
+ if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
351
+ return { index: lf, length: 2 };
352
+ }
327
353
  function parseEvent(raw) {
328
354
  const dataLines = [];
329
355
  for (const line of raw.split("\n")) {
@@ -422,6 +448,11 @@ var Models = class {
422
448
  };
423
449
 
424
450
  // src/resources/jobs.ts
451
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
452
+ "settled",
453
+ "failed",
454
+ "refunded"
455
+ ]);
425
456
  function normalize2(raw) {
426
457
  return {
427
458
  id: raw.id,
@@ -476,6 +507,48 @@ var Jobs = class {
476
507
  nextCursor: data.next_cursor
477
508
  };
478
509
  }
510
+ /**
511
+ * List every job matching the filters, transparently following cursor
512
+ * pagination. Stop iterating early to stop fetching pages.
513
+ *
514
+ * @example
515
+ * for await (const job of client.jobs.iterate({ status: "settled" })) {
516
+ * console.log(job.id, job.creditsCharged)
517
+ * }
518
+ */
519
+ async *iterate(params = {}, options = {}) {
520
+ let cursor;
521
+ while (true) {
522
+ const page = await this.list({ ...params, before: cursor }, options);
523
+ yield* page.data;
524
+ if (!page.hasMore || page.nextCursor === null) return;
525
+ cursor = page.nextCursor;
526
+ }
527
+ }
528
+ /**
529
+ * Poll a job until it reaches a terminal status (`settled`, `failed`, or
530
+ * `refunded`) and return the final record. Throws {@link JobTimeoutError}
531
+ * when the deadline passes first.
532
+ */
533
+ async waitForSettlement(jobId, options = {}) {
534
+ const pollIntervalMs = options.pollIntervalMs ?? 2e3;
535
+ const timeoutMs = options.timeoutMs ?? 12e4;
536
+ const deadline = Date.now() + timeoutMs;
537
+ while (true) {
538
+ const job = await this.get(jobId, { signal: options.signal });
539
+ if (TERMINAL_STATUSES.has(job.status)) return job;
540
+ if (Date.now() + pollIntervalMs > deadline) {
541
+ throw new JobTimeoutError(
542
+ `Job ${jobId} still has status "${job.status}" after ${timeoutMs}ms.`,
543
+ { code: "settlement_wait_timeout" }
544
+ );
545
+ }
546
+ await sleep2(pollIntervalMs);
547
+ if (options.signal?.aborted) {
548
+ throw new ConnectionError("Request aborted by caller.");
549
+ }
550
+ }
551
+ }
479
552
  /**
480
553
  * Fetch the on-chain receipt for a settled job. Throws if the job exists but
481
554
  * has not settled yet.
@@ -525,6 +598,9 @@ var Jobs = class {
525
598
  };
526
599
  }
527
600
  };
601
+ function sleep2(ms) {
602
+ return new Promise((resolve) => setTimeout(resolve, ms));
603
+ }
528
604
 
529
605
  // src/resources/account.ts
530
606
  var AccountResource = class {