@hoodcompute/sdk 0.2.0 → 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.
- package/dist/{chunk-72VFNNOI.js → chunk-EH6FBSJB.js} +86 -10
- package/dist/chunk-EH6FBSJB.js.map +1 -0
- package/dist/{client-CIPi_mUM.d.cts → client-PLfo5vhW.d.cts} +26 -1
- package/dist/{client-CIPi_mUM.d.ts → client-PLfo5vhW.d.ts} +26 -1
- package/dist/index.cjs +84 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -4
- package/dist/index.d.ts +6 -4
- package/dist/index.js +1 -1
- package/dist/react.cjs +111 -17
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +3 -1
- package/dist/react.d.ts +3 -1
- package/dist/react.js +28 -10
- package/dist/react.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-72VFNNOI.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/constants.ts","../src/http.ts","../src/streaming.ts","../src/resources/chat.ts","../src/resources/models.ts","../src/resources/jobs.ts","../src/resources/account.ts","../src/client.ts","../src/webhooks.ts"],"names":["response","normalize","crypto"],"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,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,OAAA;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EAAA,IAAI,YAAY,CAAA,EAAG;AACjB,IAAA,MAAM,GAAA,GAAM,QAAQ,GAAA,IAAO,IAAA,CAAK,MAAM,IAAA,CAAK,GAAA,KAAQ,GAAI,CAAA;AACvD,IAAA,IAAI,IAAA,CAAK,IAAI,GAAA,GAAM,MAAA,CAAO,SAAS,CAAC,CAAA,GAAI,WAAW,OAAO,KAAA;AAAA,EAC5D;AAEA,EAAA,MAAM,QAAA,GAAWC,uBAAA,CACd,UAAA,CAAW,QAAA,EAAU,MAAM,CAAA,CAC3B,MAAA,CAAO,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,OAAO,CAAA,CAAE,CAAA,CAChC,OAAO,KAAK,CAAA;AAEf,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAC9B,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAC9B,EAAA,IAAI,CAAA,CAAE,MAAA,KAAW,CAAA,CAAE,MAAA,EAAQ,OAAO,KAAA;AAClC,EAAA,OAAOA,uBAAA,CAAO,eAAA,CAAgB,CAAA,EAAG,CAAC,CAAA;AACpC;AAMO,SAAS,qBAAA,CACd,OAAA,EACA,SAAA,EACA,MAAA,EACA,OAAA,EACc;AACd,EAAA,IAAI,CAAC,sBAAA,CAAuB,OAAA,EAAS,SAAA,EAAW,MAAA,EAAQ,OAAO,CAAA,EAAG;AAChE,IAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,EAC1D;AACA,EAAA,OAAO,IAAA,CAAK,MAAM,OAAO,CAAA;AAC3B","file":"index.cjs","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 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. */\nexport const SDK_VERSION = \"0.1.0\"\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 * 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 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 userSignal?.addEventListener(\"abort\", onAbort, { once: true })\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 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 return Math.min(1000 * 2 ** attempt, 8000)\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\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.\n let boundary = buffer.indexOf(\"\\n\\n\")\n while (boundary !== -1) {\n const rawEvent = buffer.slice(0, boundary)\n buffer = buffer.slice(boundary + 2)\n\n const chunk = parseEvent(rawEvent)\n if (chunk === DONE) {\n return\n }\n if (chunk) {\n yield chunk\n }\n boundary = buffer.indexOf(\"\\n\\n\")\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 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 * 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 * 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 { NotFoundError } from \"../errors.js\"\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 * 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","/**\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","/**\n * Webhook signature verification.\n *\n * HoodCompute signs every webhook delivery with an HMAC-SHA256 over\n * `{timestamp}.{raw_body}` using your webhook secret. Always verify the\n * signature against the raw request body, before parsing JSON, to confirm the\n * delivery is authentic and untampered.\n */\n\nimport crypto from \"node:crypto\"\nimport type {\n WebhookEvent,\n JobCompletedEvent,\n CreditLowEvent,\n WorkerSlashedEvent,\n} from \"./webhook-types.js\"\n\nexport interface VerifyWebhookOptions {\n /**\n * Reject deliveries whose timestamp is older than this many seconds, to\n * guard against replay. Set to 0 to disable. Defaults to 300 (5 minutes).\n */\n toleranceSeconds?: number\n /** Current Unix time in seconds. Injectable for testing. */\n now?: number\n}\n\n/**\n * Verify a webhook signature against the raw request body.\n *\n * @param rawBody The exact bytes of the request body, as a string. Do not parse\n * or re-serialize it first.\n * @param signature Value of the `HoodCompute-Signature` header.\n * @param secret Your webhook signing secret.\n * @returns `true` when the signature is valid and within tolerance.\n *\n * @example\n * const ok = verifyWebhookSignature(rawBody, req.headers[\"hoodcompute-signature\"], secret)\n * if (!ok) return res.status(400).end()\n */\nexport function verifyWebhookSignature(\n rawBody: string,\n signature: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n): boolean {\n if (!signature) return false\n\n const match = /^t=(\\d+),v1=([0-9a-f]+)$/.exec(signature.trim())\n if (!match) return false\n const timestamp = match[1] as string\n const received = match[2] as string\n\n const tolerance = options.toleranceSeconds ?? 300\n if (tolerance > 0) {\n const now = options.now ?? Math.floor(Date.now() / 1000)\n if (Math.abs(now - Number(timestamp)) > tolerance) return false\n }\n\n const expected = crypto\n .createHmac(\"sha256\", secret)\n .update(`${timestamp}.${rawBody}`)\n .digest(\"hex\")\n\n const a = Buffer.from(expected)\n const b = Buffer.from(received)\n if (a.length !== b.length) return false\n return crypto.timingSafeEqual(a, b)\n}\n\n/**\n * Verify a webhook signature and, on success, parse the body into a typed\n * event. Throws if the signature is invalid.\n */\nexport function constructWebhookEvent(\n rawBody: string,\n signature: string | null | undefined,\n secret: string,\n options?: VerifyWebhookOptions,\n): WebhookEvent {\n if (!verifyWebhookSignature(rawBody, signature, secret, options)) {\n throw new Error(\"Invalid HoodCompute webhook signature.\")\n }\n return JSON.parse(rawBody) as WebhookEvent\n}\n\nexport type {\n WebhookEvent,\n JobCompletedEvent,\n CreditLowEvent,\n WorkerSlashedEvent,\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/constants.ts","../src/http.ts","../src/streaming.ts","../src/resources/chat.ts","../src/resources/models.ts","../src/resources/jobs.ts","../src/resources/account.ts","../src/client.ts","../src/webhooks.ts"],"names":["response","normalize","sleep","crypto"],"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,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,OAAA;AACpB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AAAA,EACxB;AACF;AAGO,IAAM,mBAAA,GAAN,cAAkC,gBAAA,CAAiB;AAAA,EACxD,eAAe,IAAA,EAAsD;AACnE,IAAA,KAAA,CAAM,GAAG,IAAI,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAGO,IAAM,wBAAA,GAAN,cAAuC,gBAAA,CAAiB;AAAA,EAC7D,eAAe,IAAA,EAAsD;AACnE,IAAA,KAAA,CAAM,GAAG,IAAI,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,0BAAA;AAAA,EACd;AACF;AAGO,IAAM,mBAAA,GAAN,cAAkC,gBAAA,CAAiB;AAAA,EACxD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AAM,SAAA,GAAY,MAAM,CAAC,CAAA;AACzB,EAAA,MAAM,QAAA,GAAW,MAAM,CAAC,CAAA;AAExB,EAAA,MAAM,SAAA,GAAY,QAAQ,gBAAA,IAAoB,GAAA;AAC9C,EAAA,IAAI,YAAY,CAAA,EAAG;AACjB,IAAA,MAAM,GAAA,GAAM,QAAQ,GAAA,IAAO,IAAA,CAAK,MAAM,IAAA,CAAK,GAAA,KAAQ,GAAI,CAAA;AACvD,IAAA,IAAI,IAAA,CAAK,IAAI,GAAA,GAAM,MAAA,CAAO,SAAS,CAAC,CAAA,GAAI,WAAW,OAAO,KAAA;AAAA,EAC5D;AAEA,EAAA,MAAM,QAAA,GAAWC,uBAAA,CACd,UAAA,CAAW,QAAA,EAAU,MAAM,CAAA,CAC3B,MAAA,CAAO,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,OAAO,CAAA,CAAE,CAAA,CAChC,OAAO,KAAK,CAAA;AAEf,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAC9B,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAC9B,EAAA,IAAI,CAAA,CAAE,MAAA,KAAW,CAAA,CAAE,MAAA,EAAQ,OAAO,KAAA;AAClC,EAAA,OAAOA,uBAAA,CAAO,eAAA,CAAgB,CAAA,EAAG,CAAC,CAAA;AACpC;AAMO,SAAS,qBAAA,CACd,OAAA,EACA,SAAA,EACA,MAAA,EACA,OAAA,EACc;AACd,EAAA,IAAI,CAAC,sBAAA,CAAuB,OAAA,EAAS,SAAA,EAAW,MAAA,EAAQ,OAAO,CAAA,EAAG;AAChE,IAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,EAC1D;AACA,EAAA,OAAO,IAAA,CAAK,MAAM,OAAO,CAAA;AAC3B","file":"index.cjs","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 * 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 * 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 * 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","/**\n * Webhook signature verification.\n *\n * HoodCompute signs every webhook delivery with an HMAC-SHA256 over\n * `{timestamp}.{raw_body}` using your webhook secret. Always verify the\n * signature against the raw request body, before parsing JSON, to confirm the\n * delivery is authentic and untampered.\n */\n\nimport crypto from \"node:crypto\"\nimport type {\n WebhookEvent,\n JobCompletedEvent,\n CreditLowEvent,\n WorkerSlashedEvent,\n} from \"./webhook-types.js\"\n\nexport interface VerifyWebhookOptions {\n /**\n * Reject deliveries whose timestamp is older than this many seconds, to\n * guard against replay. Set to 0 to disable. Defaults to 300 (5 minutes).\n */\n toleranceSeconds?: number\n /** Current Unix time in seconds. Injectable for testing. */\n now?: number\n}\n\n/**\n * Verify a webhook signature against the raw request body.\n *\n * @param rawBody The exact bytes of the request body, as a string. Do not parse\n * or re-serialize it first.\n * @param signature Value of the `HoodCompute-Signature` header.\n * @param secret Your webhook signing secret.\n * @returns `true` when the signature is valid and within tolerance.\n *\n * @example\n * const ok = verifyWebhookSignature(rawBody, req.headers[\"hoodcompute-signature\"], secret)\n * if (!ok) return res.status(400).end()\n */\nexport function verifyWebhookSignature(\n rawBody: string,\n signature: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n): boolean {\n if (!signature) return false\n\n const match = /^t=(\\d+),v1=([0-9a-f]+)$/.exec(signature.trim())\n if (!match) return false\n const timestamp = match[1] as string\n const received = match[2] as string\n\n const tolerance = options.toleranceSeconds ?? 300\n if (tolerance > 0) {\n const now = options.now ?? Math.floor(Date.now() / 1000)\n if (Math.abs(now - Number(timestamp)) > tolerance) return false\n }\n\n const expected = crypto\n .createHmac(\"sha256\", secret)\n .update(`${timestamp}.${rawBody}`)\n .digest(\"hex\")\n\n const a = Buffer.from(expected)\n const b = Buffer.from(received)\n if (a.length !== b.length) return false\n return crypto.timingSafeEqual(a, b)\n}\n\n/**\n * Verify a webhook signature and, on success, parse the body into a typed\n * event. Throws if the signature is invalid.\n */\nexport function constructWebhookEvent(\n rawBody: string,\n signature: string | null | undefined,\n secret: string,\n options?: VerifyWebhookOptions,\n): WebhookEvent {\n if (!verifyWebhookSignature(rawBody, signature, secret, options)) {\n throw new Error(\"Invalid HoodCompute webhook signature.\")\n }\n return JSON.parse(rawBody) as WebhookEvent\n}\n\nexport type {\n WebhookEvent,\n JobCompletedEvent,\n CreditLowEvent,\n WorkerSlashedEvent,\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { M as ModelTier } from './client-
|
|
2
|
-
export { A as Account, C as ChatCompletion, a as ChatCompletionChoice, b as ChatCompletionChunk, c as ChatCompletionChunkChoice, d as ChatCompletionCreateParams, e as ChatCompletionDelta, f as ChatCompletionStream, g as ChatMessage, h as ChatRole, e as Delta, D as DisputeResult, H as HoodComputeClient, i as HoodComputeClientOptions, J as Job, j as JobList, k as JobListParams, l as JobOnChain, m as JobReceipt, n as JobStatus, o as Model, p as ModelList, q as ModelMeta, S as StreamReceipt, U as Usage } from './client-
|
|
1
|
+
import { M as ModelTier } from './client-PLfo5vhW.cjs';
|
|
2
|
+
export { A as Account, C as ChatCompletion, a as ChatCompletionChoice, b as ChatCompletionChunk, c as ChatCompletionChunkChoice, d as ChatCompletionCreateParams, e as ChatCompletionDelta, f as ChatCompletionStream, g as ChatMessage, h as ChatRole, e as Delta, D as DisputeResult, H as HoodComputeClient, i as HoodComputeClientOptions, J as Job, j as JobList, k as JobListParams, l as JobOnChain, m as JobReceipt, n as JobStatus, o as Model, p as ModelList, q as ModelMeta, S as StreamReceipt, U as Usage, W as WaitForSettlementOptions } from './client-PLfo5vhW.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Webhook event types delivered to your endpoint.
|
|
@@ -96,8 +96,8 @@ declare const DEFAULT_BASE_URL = "https://api.hoodcompute.com/v1";
|
|
|
96
96
|
declare const ROBINHOOD_CHAIN_ID = 4663;
|
|
97
97
|
/** Base URL of the Robinhood Chain Blockscout explorer. */
|
|
98
98
|
declare const BLOCKSCOUT_BASE_URL = "https://robinhoodchain.blockscout.com";
|
|
99
|
-
/** SDK version, surfaced in the User-Agent header. */
|
|
100
|
-
declare const SDK_VERSION = "0.
|
|
99
|
+
/** SDK version, surfaced in the User-Agent header. Keep in sync with package.json. */
|
|
100
|
+
declare const SDK_VERSION = "0.2.2";
|
|
101
101
|
/**
|
|
102
102
|
* Build a Blockscout explorer link for a Robinhood Chain transaction hash.
|
|
103
103
|
*
|
|
@@ -152,6 +152,8 @@ declare class NotFoundError extends HoodComputeError {
|
|
|
152
152
|
}
|
|
153
153
|
/** 429. The request rate to the API is too high. Back off and retry. */
|
|
154
154
|
declare class RateLimitError extends HoodComputeError {
|
|
155
|
+
/** Suggested seconds to wait before retrying, when the API provides one. */
|
|
156
|
+
get retryAfter(): number | undefined;
|
|
155
157
|
constructor(...args: ConstructorParameters<typeof HoodComputeError>);
|
|
156
158
|
}
|
|
157
159
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { M as ModelTier } from './client-
|
|
2
|
-
export { A as Account, C as ChatCompletion, a as ChatCompletionChoice, b as ChatCompletionChunk, c as ChatCompletionChunkChoice, d as ChatCompletionCreateParams, e as ChatCompletionDelta, f as ChatCompletionStream, g as ChatMessage, h as ChatRole, e as Delta, D as DisputeResult, H as HoodComputeClient, i as HoodComputeClientOptions, J as Job, j as JobList, k as JobListParams, l as JobOnChain, m as JobReceipt, n as JobStatus, o as Model, p as ModelList, q as ModelMeta, S as StreamReceipt, U as Usage } from './client-
|
|
1
|
+
import { M as ModelTier } from './client-PLfo5vhW.js';
|
|
2
|
+
export { A as Account, C as ChatCompletion, a as ChatCompletionChoice, b as ChatCompletionChunk, c as ChatCompletionChunkChoice, d as ChatCompletionCreateParams, e as ChatCompletionDelta, f as ChatCompletionStream, g as ChatMessage, h as ChatRole, e as Delta, D as DisputeResult, H as HoodComputeClient, i as HoodComputeClientOptions, J as Job, j as JobList, k as JobListParams, l as JobOnChain, m as JobReceipt, n as JobStatus, o as Model, p as ModelList, q as ModelMeta, S as StreamReceipt, U as Usage, W as WaitForSettlementOptions } from './client-PLfo5vhW.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Webhook event types delivered to your endpoint.
|
|
@@ -96,8 +96,8 @@ declare const DEFAULT_BASE_URL = "https://api.hoodcompute.com/v1";
|
|
|
96
96
|
declare const ROBINHOOD_CHAIN_ID = 4663;
|
|
97
97
|
/** Base URL of the Robinhood Chain Blockscout explorer. */
|
|
98
98
|
declare const BLOCKSCOUT_BASE_URL = "https://robinhoodchain.blockscout.com";
|
|
99
|
-
/** SDK version, surfaced in the User-Agent header. */
|
|
100
|
-
declare const SDK_VERSION = "0.
|
|
99
|
+
/** SDK version, surfaced in the User-Agent header. Keep in sync with package.json. */
|
|
100
|
+
declare const SDK_VERSION = "0.2.2";
|
|
101
101
|
/**
|
|
102
102
|
* Build a Blockscout explorer link for a Robinhood Chain transaction hash.
|
|
103
103
|
*
|
|
@@ -152,6 +152,8 @@ declare class NotFoundError extends HoodComputeError {
|
|
|
152
152
|
}
|
|
153
153
|
/** 429. The request rate to the API is too high. Back off and retry. */
|
|
154
154
|
declare class RateLimitError extends HoodComputeError {
|
|
155
|
+
/** Suggested seconds to wait before retrying, when the API provides one. */
|
|
156
|
+
get retryAfter(): number | undefined;
|
|
155
157
|
constructor(...args: ConstructorParameters<typeof HoodComputeError>);
|
|
156
158
|
}
|
|
157
159
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
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 } from './chunk-
|
|
1
|
+
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 } from './chunk-EH6FBSJB.js';
|
|
2
2
|
import crypto from 'crypto';
|
|
3
3
|
|
|
4
4
|
function verifyWebhookSignature(rawBody, signature, secret, options = {}) {
|
package/dist/react.cjs
CHANGED
|
@@ -42,6 +42,11 @@ var NotFoundError = class extends HoodComputeError {
|
|
|
42
42
|
}
|
|
43
43
|
};
|
|
44
44
|
var RateLimitError = class extends HoodComputeError {
|
|
45
|
+
/** Suggested seconds to wait before retrying, when the API provides one. */
|
|
46
|
+
get retryAfter() {
|
|
47
|
+
const value = this.details?.retry_after;
|
|
48
|
+
return typeof value === "number" ? value : void 0;
|
|
49
|
+
}
|
|
45
50
|
constructor(...args) {
|
|
46
51
|
super(...args);
|
|
47
52
|
this.name = "RateLimitError";
|
|
@@ -126,7 +131,7 @@ function isRetryable(err) {
|
|
|
126
131
|
var DEFAULT_BASE_URL = "https://api.hoodcompute.com/v1";
|
|
127
132
|
var DEFAULT_TIMEOUT_MS = 12e4;
|
|
128
133
|
var DEFAULT_MAX_RETRIES = 2;
|
|
129
|
-
var SDK_VERSION = "0.
|
|
134
|
+
var SDK_VERSION = "0.2.2";
|
|
130
135
|
|
|
131
136
|
// src/http.ts
|
|
132
137
|
var HttpClient = class {
|
|
@@ -178,6 +183,7 @@ var HttpClient = class {
|
|
|
178
183
|
}
|
|
179
184
|
throw error;
|
|
180
185
|
} catch (err) {
|
|
186
|
+
if (options.signal?.aborted) throw err;
|
|
181
187
|
if (err instanceof ConnectionError && attempt < this.maxRetries) {
|
|
182
188
|
lastError = err;
|
|
183
189
|
await sleep(this.backoff(attempt));
|
|
@@ -192,7 +198,11 @@ var HttpClient = class {
|
|
|
192
198
|
const controller = new AbortController();
|
|
193
199
|
const timer = setTimeout(() => controller.abort(), this.timeout);
|
|
194
200
|
const onAbort = () => controller.abort();
|
|
195
|
-
userSignal?.
|
|
201
|
+
if (userSignal?.aborted) {
|
|
202
|
+
controller.abort();
|
|
203
|
+
} else {
|
|
204
|
+
userSignal?.addEventListener("abort", onAbort, { once: true });
|
|
205
|
+
}
|
|
196
206
|
try {
|
|
197
207
|
return await this.fetchImpl(url, { ...init, signal: controller.signal });
|
|
198
208
|
} catch (err) {
|
|
@@ -216,6 +226,13 @@ var HttpClient = class {
|
|
|
216
226
|
} catch {
|
|
217
227
|
body = void 0;
|
|
218
228
|
}
|
|
229
|
+
const retryAfterHeader = response.headers.get("retry-after");
|
|
230
|
+
if (retryAfterHeader !== null && typeof body?.details?.retry_after !== "number") {
|
|
231
|
+
const seconds = Number(retryAfterHeader);
|
|
232
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
233
|
+
body = { ...body, details: { ...body?.details, retry_after: seconds } };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
219
236
|
const requestId = response.headers.get("x-request-id") ?? void 0;
|
|
220
237
|
return errorFromResponse(response.status, body, requestId);
|
|
221
238
|
}
|
|
@@ -243,7 +260,7 @@ var HttpClient = class {
|
|
|
243
260
|
backoff(attempt, error) {
|
|
244
261
|
const retryAfter = error && typeof error === "object" && "details" in error && typeof error.details?.retry_after === "number" ? error.details.retry_after * 1e3 : void 0;
|
|
245
262
|
if (retryAfter !== void 0) return retryAfter;
|
|
246
|
-
return Math.min(1e3 * 2 ** attempt, 8e3);
|
|
263
|
+
return Math.min(1e3 * 2 ** attempt, 8e3) * (0.5 + Math.random() * 0.5);
|
|
247
264
|
}
|
|
248
265
|
};
|
|
249
266
|
function sleep(ms) {
|
|
@@ -270,10 +287,10 @@ var ChatCompletionStream = class {
|
|
|
270
287
|
const { done, value } = await reader.read();
|
|
271
288
|
if (done) break;
|
|
272
289
|
buffer += decoder.decode(value, { stream: true });
|
|
273
|
-
let boundary = buffer
|
|
274
|
-
while (boundary !==
|
|
275
|
-
const rawEvent = buffer.slice(0, boundary);
|
|
276
|
-
buffer = buffer.slice(boundary +
|
|
290
|
+
let boundary = findBoundary(buffer);
|
|
291
|
+
while (boundary !== null) {
|
|
292
|
+
const rawEvent = buffer.slice(0, boundary.index);
|
|
293
|
+
buffer = buffer.slice(boundary.index + boundary.length);
|
|
277
294
|
const chunk = parseEvent(rawEvent);
|
|
278
295
|
if (chunk === DONE) {
|
|
279
296
|
return;
|
|
@@ -281,7 +298,7 @@ var ChatCompletionStream = class {
|
|
|
281
298
|
if (chunk) {
|
|
282
299
|
yield chunk;
|
|
283
300
|
}
|
|
284
|
-
boundary = buffer
|
|
301
|
+
boundary = findBoundary(buffer);
|
|
285
302
|
}
|
|
286
303
|
}
|
|
287
304
|
const trailing = parseEvent(buffer);
|
|
@@ -289,6 +306,8 @@ var ChatCompletionStream = class {
|
|
|
289
306
|
yield trailing;
|
|
290
307
|
}
|
|
291
308
|
} finally {
|
|
309
|
+
await reader.cancel().catch(() => {
|
|
310
|
+
});
|
|
292
311
|
reader.releaseLock();
|
|
293
312
|
this.receipt = this.readReceipt();
|
|
294
313
|
}
|
|
@@ -314,6 +333,13 @@ var ChatCompletionStream = class {
|
|
|
314
333
|
}
|
|
315
334
|
};
|
|
316
335
|
var DONE = /* @__PURE__ */ Symbol("done");
|
|
336
|
+
function findBoundary(buffer) {
|
|
337
|
+
const lf = buffer.indexOf("\n\n");
|
|
338
|
+
const crlf = buffer.indexOf("\r\n\r\n");
|
|
339
|
+
if (lf === -1 && crlf === -1) return null;
|
|
340
|
+
if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
|
|
341
|
+
return { index: lf, length: 2 };
|
|
342
|
+
}
|
|
317
343
|
function parseEvent(raw) {
|
|
318
344
|
const dataLines = [];
|
|
319
345
|
for (const line of raw.split("\n")) {
|
|
@@ -412,6 +438,11 @@ var Models = class {
|
|
|
412
438
|
};
|
|
413
439
|
|
|
414
440
|
// src/resources/jobs.ts
|
|
441
|
+
var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
442
|
+
"settled",
|
|
443
|
+
"failed",
|
|
444
|
+
"refunded"
|
|
445
|
+
]);
|
|
415
446
|
function normalize2(raw) {
|
|
416
447
|
return {
|
|
417
448
|
id: raw.id,
|
|
@@ -466,6 +497,48 @@ var Jobs = class {
|
|
|
466
497
|
nextCursor: data.next_cursor
|
|
467
498
|
};
|
|
468
499
|
}
|
|
500
|
+
/**
|
|
501
|
+
* List every job matching the filters, transparently following cursor
|
|
502
|
+
* pagination. Stop iterating early to stop fetching pages.
|
|
503
|
+
*
|
|
504
|
+
* @example
|
|
505
|
+
* for await (const job of client.jobs.iterate({ status: "settled" })) {
|
|
506
|
+
* console.log(job.id, job.creditsCharged)
|
|
507
|
+
* }
|
|
508
|
+
*/
|
|
509
|
+
async *iterate(params = {}, options = {}) {
|
|
510
|
+
let cursor;
|
|
511
|
+
while (true) {
|
|
512
|
+
const page = await this.list({ ...params, before: cursor }, options);
|
|
513
|
+
yield* page.data;
|
|
514
|
+
if (!page.hasMore || page.nextCursor === null) return;
|
|
515
|
+
cursor = page.nextCursor;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Poll a job until it reaches a terminal status (`settled`, `failed`, or
|
|
520
|
+
* `refunded`) and return the final record. Throws {@link JobTimeoutError}
|
|
521
|
+
* when the deadline passes first.
|
|
522
|
+
*/
|
|
523
|
+
async waitForSettlement(jobId, options = {}) {
|
|
524
|
+
const pollIntervalMs = options.pollIntervalMs ?? 2e3;
|
|
525
|
+
const timeoutMs = options.timeoutMs ?? 12e4;
|
|
526
|
+
const deadline = Date.now() + timeoutMs;
|
|
527
|
+
while (true) {
|
|
528
|
+
const job = await this.get(jobId, { signal: options.signal });
|
|
529
|
+
if (TERMINAL_STATUSES.has(job.status)) return job;
|
|
530
|
+
if (Date.now() + pollIntervalMs > deadline) {
|
|
531
|
+
throw new JobTimeoutError(
|
|
532
|
+
`Job ${jobId} still has status "${job.status}" after ${timeoutMs}ms.`,
|
|
533
|
+
{ code: "settlement_wait_timeout" }
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
await sleep2(pollIntervalMs);
|
|
537
|
+
if (options.signal?.aborted) {
|
|
538
|
+
throw new ConnectionError("Request aborted by caller.");
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
469
542
|
/**
|
|
470
543
|
* Fetch the on-chain receipt for a settled job. Throws if the job exists but
|
|
471
544
|
* has not settled yet.
|
|
@@ -515,6 +588,9 @@ var Jobs = class {
|
|
|
515
588
|
};
|
|
516
589
|
}
|
|
517
590
|
};
|
|
591
|
+
function sleep2(ms) {
|
|
592
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
593
|
+
}
|
|
518
594
|
|
|
519
595
|
// src/resources/account.ts
|
|
520
596
|
var AccountResource = class {
|
|
@@ -582,20 +658,29 @@ function useHoodComputeChat(options) {
|
|
|
582
658
|
);
|
|
583
659
|
const callbacks = react.useRef({ onComplete, onError });
|
|
584
660
|
callbacks.current = { onComplete, onError };
|
|
661
|
+
const messagesRef = react.useRef(messages);
|
|
662
|
+
messagesRef.current = messages;
|
|
663
|
+
const abortRef = react.useRef(null);
|
|
664
|
+
const stop = react.useCallback(() => {
|
|
665
|
+
abortRef.current?.abort();
|
|
666
|
+
}, []);
|
|
585
667
|
const send = react.useCallback(
|
|
586
668
|
async (message) => {
|
|
669
|
+
abortRef.current?.abort();
|
|
670
|
+
const controller = new AbortController();
|
|
671
|
+
abortRef.current = controller;
|
|
587
672
|
setError(null);
|
|
588
673
|
setStatus("streaming");
|
|
589
674
|
const userMessage = { role: "user", content: message };
|
|
590
|
-
const history = [...
|
|
591
|
-
|
|
675
|
+
const history = [...messagesRef.current, userMessage];
|
|
676
|
+
messagesRef.current = [...history, { role: "assistant", content: "" }];
|
|
677
|
+
setMessages(messagesRef.current);
|
|
592
678
|
const outbound = systemPrompt ? [{ role: "system", content: systemPrompt }, ...history] : history;
|
|
593
679
|
try {
|
|
594
|
-
const stream = await client.chat.completions.create(
|
|
595
|
-
model,
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
});
|
|
680
|
+
const stream = await client.chat.completions.create(
|
|
681
|
+
{ model, messages: outbound, stream: true },
|
|
682
|
+
{ signal: controller.signal }
|
|
683
|
+
);
|
|
599
684
|
for await (const chunk of stream) {
|
|
600
685
|
const delta = chunk.choices[0]?.delta?.content;
|
|
601
686
|
if (!delta) continue;
|
|
@@ -620,21 +705,30 @@ function useHoodComputeChat(options) {
|
|
|
620
705
|
callbacks.current.onComplete?.(receipt);
|
|
621
706
|
setStatus("idle");
|
|
622
707
|
} catch (err) {
|
|
708
|
+
if (controller.signal.aborted) {
|
|
709
|
+
if (abortRef.current === controller) setStatus("idle");
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
623
712
|
const normalized = err instanceof Error ? err : new Error(String(err));
|
|
624
713
|
setError(normalized);
|
|
625
714
|
setStatus("error");
|
|
626
715
|
callbacks.current.onError?.(normalized);
|
|
716
|
+
} finally {
|
|
717
|
+
if (abortRef.current === controller) abortRef.current = null;
|
|
627
718
|
}
|
|
628
719
|
},
|
|
629
|
-
[client, model,
|
|
720
|
+
[client, model, systemPrompt]
|
|
630
721
|
);
|
|
631
722
|
const reset = react.useCallback(() => {
|
|
723
|
+
abortRef.current?.abort();
|
|
724
|
+
abortRef.current = null;
|
|
725
|
+
messagesRef.current = [];
|
|
632
726
|
setMessages([]);
|
|
633
727
|
setStatus("idle");
|
|
634
728
|
setError(null);
|
|
635
729
|
setLastReceipt(null);
|
|
636
730
|
}, []);
|
|
637
|
-
return { send, messages, status, balance, lastReceipt, error, reset };
|
|
731
|
+
return { send, stop, messages, status, balance, lastReceipt, error, reset };
|
|
638
732
|
}
|
|
639
733
|
|
|
640
734
|
exports.useHoodComputeChat = useHoodComputeChat;
|