frutebox 0.0.1 → 0.2.0

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/index.mjs CHANGED
@@ -1,116 +1,514 @@
1
1
  /**
2
2
  * Official Frutebox SDK for JavaScript and TypeScript.
3
3
  *
4
- * Built against the NATIVE endpoint (`POST /api/v1/chat`) rather than the OpenAI-shaped
5
- * compatibility surface at `/api/v1/chat/completions`. The compatibility surface is being phased
6
- * out, so a new client should not be born on it.
4
+ * TWO SURFACES, because the website documents two and tells developers to choose:
7
5
  *
8
- * Zero dependencies: `fetch` is built into Node 18+.
6
+ * NATIVE await fb.chat({ message, region }) POST /chat
7
+ * The long-term surface. `usage` carries the request's REAL measured cost
8
+ * (electricity and internet per serving node), which a `choices` array cannot hold.
9
+ * DROP-IN await fb.chat.completions.create({ messages }) POST /chat/completions
10
+ * The shape the common AI SDKs use, so an existing app moves over by changing a base
11
+ * URL and a key. DEPRECATED in the published spec and still live: nothing is refused,
12
+ * re-routed or re-priced for using it.
13
+ *
14
+ * Zero dependencies — `fetch` is built into Node 18+ — and no build step, so the bytes shipped are
15
+ * the bytes written. Types are hand-written in `index.d.ts` rather than generated, for the same
16
+ * reason.
17
+ *
18
+ * BACKWARDS COMPATIBILITY WITH 0.0.1 IS LOAD-BEARING. That release exposed `fb.chat({...})` and
19
+ * `fb.models()` as callables and it is on npm, so both remain callable here while also carrying
20
+ * the namespaces (`fb.chat.completions`, `fb.models.retrieve`). A published client does not get to
21
+ * rename its own entry points.
22
+ *
23
+ * The full contract is at GET https://frutebox.com/api/v1/openapi.json, snapshotted in the repo at
24
+ * sdk/spec/openapi.json. `OPERATIONS` maps every published operation to the method that calls it,
25
+ * and CI fails if the two drift.
9
26
  */
27
+ import { API_PREFIX, OPERATIONS } from "./spec.mjs";
28
+ import {
29
+ AuthenticationError, BudgetError, FruteboxError, InvalidRequestError, JobFailed, JobTimeout,
30
+ NoCapacityError, NotFoundError, NotImplementedByNetwork, PolicyError, RateLimitError,
31
+ errorFromBody,
32
+ } from "./errors.mjs";
10
33
 
11
- export class FruteboxError extends Error {
12
- constructor(message, status = 0, code = undefined) {
13
- super(message);
14
- this.name = "FruteboxError";
15
- this.status = status;
16
- this.code = code;
17
- }
34
+ export {
35
+ API_PREFIX, OPERATIONS,
36
+ FruteboxError, InvalidRequestError, AuthenticationError, BudgetError, PolicyError,
37
+ NotFoundError, RateLimitError, NotImplementedByNetwork, NoCapacityError, JobFailed, JobTimeout,
38
+ };
39
+
40
+ export const DEFAULT_BASE_URL = "https://frutebox.com";
41
+
42
+ /** THE ORCHESTRATOR DETERMINES THE MODEL (owner, 2026-11-18). No call in this SDK takes one. */
43
+ const NO_MODEL = "Frutebox's orchestrator determines the model for each prompt; a caller never "
44
+ + "chooses one. Remove the `model` argument.";
45
+ export const DEFAULT_TIMEOUT_MS = 60_000;
46
+
47
+ /** Terminal job states, from the spec's status enum: queued|running|done|failed|disabled. */
48
+ const TERMINAL = new Set(["done", "failed", "disabled"]);
49
+ const PENDING = new Set(["queued", "running"]);
50
+
51
+ /** Drop undefined/null, so a body never carries `{"region": null}` for an unmentioned region. */
52
+ function compact(obj) {
53
+ const out = {};
54
+ for (const [k, v] of Object.entries(obj)) if (v !== undefined && v !== null) out[k] = v;
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * Warn that a kept-for-compatibility argument is NOT sent.
60
+ *
61
+ * These were accepted by earlier versions and the server never read them — confirmed at the route,
62
+ * not inferred: /images/generations parses prompt/n/size, /videos/generations parses prompt.
63
+ * Sending them was the silent kind of wrong, where the call succeeds and the caller believes they
64
+ * asked for something. Dropping them without a word would be the same mistake.
65
+ */
66
+ function deadField(name, specPath) {
67
+ // eslint-disable-next-line no-console
68
+ console.warn(
69
+ `[frutebox] \`${name}\` is not part of the published request schema for POST ${specPath} and `
70
+ + `is NOT being sent. The server has never read it. Remove it from your call.`,
71
+ );
18
72
  }
19
73
 
74
+ let warnedDropIn = false;
75
+
20
76
  export class Frutebox {
21
- constructor({ apiKey, baseUrl = "https://frutebox.com", timeoutMs = 60000 } = {}) {
22
- // Accept the environment as a fallback, new spelling first. STEVAI_API_KEY is still read so
23
- // existing environments keep working.
77
+ #apiKey;
78
+ #timeoutMs;
79
+ #fetch;
80
+
81
+ constructor({ apiKey, baseUrl = DEFAULT_BASE_URL, timeoutMs = DEFAULT_TIMEOUT_MS, fetch: fetchImpl, localRunner } = {}) {
82
+ // The environment is a fallback, new spelling first. STEVAI_API_KEY is still read because this
83
+ // is a PUBLISHED contract and that name is in users' environments and CI.
24
84
  const key = apiKey
25
85
  || (typeof process !== "undefined" && process.env
26
86
  ? (process.env.FRUTEBOX_API_KEY || process.env.STEVAI_API_KEY)
27
87
  : undefined);
28
88
  if (!key) {
29
- throw new FruteboxError("A Frutebox API key is required.", 0, "missing_api_key");
89
+ throw new FruteboxError(
90
+ "A Frutebox API key is required. Pass { apiKey } or set FRUTEBOX_API_KEY.",
91
+ { code: "missing_api_key" },
92
+ );
30
93
  }
31
94
 
32
- const base = String(baseUrl).replace(/\/+$/, "");
33
- // Enforce HTTPS so the key is never sent in plaintext; localhost is exempt for development.
95
+ let base = String(baseUrl).replace(/\/+$/, "");
96
+ // Accept either the origin or the spec's full server URL, so copying
97
+ // `https://frutebox.com/api/v1` out of the spec does not produce `/api/v1/api/v1/chat`.
98
+ if (base.endsWith(API_PREFIX)) base = base.slice(0, -API_PREFIX.length);
99
+
100
+ // Refuse to put the key on the wire in plaintext; localhost is exempt for development.
34
101
  const isLocal = base.startsWith("http://localhost") || base.startsWith("http://127.0.0.1");
35
102
  if (!base.startsWith("https://") && !isLocal) {
36
103
  throw new FruteboxError(
37
104
  "baseUrl must use https:// (refusing to send your key in plaintext).",
38
- 0,
39
- "insecure_base_url",
105
+ { code: "insecure_base_url" },
40
106
  );
41
107
  }
42
108
 
43
109
  this.baseUrl = base;
44
110
  this.#apiKey = key;
45
111
  this.#timeoutMs = timeoutMs;
112
+ this.#fetch = fetchImpl ?? ((...a) => fetch(...a));
113
+
114
+ /** 28-F.1: the on-device model. Injected — the SDK bundles no weights. */
115
+ this._localRunner = localRunner ?? null;
116
+ this.chat = makeChat(this);
117
+ this.embeddings = { create: (p = {}) => this.#embeddings(p) };
118
+ this.models = makeModels(this);
119
+ this.images = makeImages(this);
120
+ this.videos = makeVideos(this);
121
+ this.audio = makeAudio(this);
122
+ this.moderations = { create: ({ input } = {}) => this.#json("POST", "/moderations", { input }) };
123
+ this.skills = { list: () => this.#json("GET", "/skills") };
46
124
  }
47
125
 
48
- #apiKey;
49
- #timeoutMs;
126
+ /** Never the key: a default inspection would print the private field in some runtimes. */
127
+ toJSON() { return { baseUrl: this.baseUrl }; }
128
+ [Symbol.for("nodejs.util.inspect.custom")]() { return `Frutebox { baseUrl: '${this.baseUrl}' }`; }
50
129
 
51
- /**
52
- * Send one message to the Frutebox network and get the reply.
53
- * Returns { reply, model, region, usage }.
54
- */
55
- async chat({ message, region } = {}) {
56
- if (typeof message !== "string" || message.length === 0) {
57
- throw new FruteboxError("`message` must be a non-empty string.", 0, "invalid_request");
130
+ // --- transport ---------------------------------------------------------------------------
131
+ #url(specPath, pathParams) {
132
+ let path = specPath;
133
+ if (pathParams) {
134
+ for (const [k, v] of Object.entries(pathParams)) {
135
+ path = path.replace(`{${k}}`, encodeURIComponent(String(v)));
136
+ }
58
137
  }
138
+ return `${this.baseUrl}${API_PREFIX}${path}`;
139
+ }
59
140
 
60
- const body = { message };
61
- if (region) body.region = region;
141
+ async #request(method, specPath, { body, pathParams, formData, stream = false } = {}) {
142
+ const url = this.#url(specPath, pathParams);
143
+ const headers = { authorization: `Bearer ${this.#apiKey}` };
144
+ let payload;
145
+ if (formData !== undefined) {
146
+ // Content-Type is set by the runtime, with the multipart boundary. Setting it by hand
147
+ // produces a body the server cannot parse.
148
+ payload = formData;
149
+ } else if (body !== undefined) {
150
+ headers["content-type"] = "application/json";
151
+ payload = JSON.stringify(body);
152
+ }
153
+ if (!stream) headers.accept = "application/json";
62
154
 
63
155
  const controller = new AbortController();
64
156
  const timer = setTimeout(() => controller.abort(), this.#timeoutMs);
65
157
  let res;
66
158
  try {
67
- res = await fetch(`${this.baseUrl}/api/v1/chat`, {
68
- method: "POST",
69
- headers: {
70
- "content-type": "application/json",
71
- authorization: `Bearer ${this.#apiKey}`,
72
- },
73
- body: JSON.stringify(body),
74
- signal: controller.signal,
75
- });
159
+ res = await this.#fetch(url, { method, headers, body: payload, signal: controller.signal });
76
160
  } catch (err) {
77
161
  if (err && err.name === "AbortError") {
78
- throw new FruteboxError(`Frutebox request timed out after ${this.#timeoutMs}ms.`, 0, "timeout");
162
+ throw new FruteboxError(`Frutebox request timed out after ${this.#timeoutMs}ms.`, { code: "timeout" });
79
163
  }
80
- throw new FruteboxError(`Frutebox request failed: ${err && err.message ? err.message : err}`, 0, "network");
164
+ // Only the error's NAME is reported. A fetch failure can carry the request, and the request
165
+ // carries the Authorization header.
166
+ throw new FruteboxError(
167
+ `Frutebox request failed: ${err && err.name ? err.name : "network error"}.`,
168
+ { code: "network" },
169
+ );
81
170
  } finally {
82
171
  clearTimeout(timer);
83
172
  }
84
173
 
85
- if (!res.ok) throw await toError(res);
86
- return res.json();
174
+ if (!res.ok) {
175
+ let parsed;
176
+ try { parsed = await res.json(); } catch { parsed = undefined; }
177
+ throw errorFromBody(res.status, parsed, res.headers?.get?.("retry-after"));
178
+ }
179
+ return res;
87
180
  }
88
181
 
89
- /** List the models available to your key. */
90
- async models() {
91
- const res = await fetch(`${this.baseUrl}/api/v1/models`, {
92
- headers: { authorization: `Bearer ${this.#apiKey}` },
93
- });
94
- if (!res.ok) throw await toError(res);
95
- return res.json();
182
+ async #json(method, specPath, body, opts = {}) {
183
+ const res = await this.#request(method, specPath, { body: body && compact(body), ...opts });
184
+ return raiseIfDeferred(await res.json());
185
+ }
186
+
187
+ async #embeddings({ input, region } = {}) {
188
+ if (Array.isArray(input) && input.length === 0) {
189
+ throw new FruteboxError("`input` must not be empty.", { code: "invalid_request" });
190
+ }
191
+ return this.#json("POST", "/embeddings", { input, region });
96
192
  }
193
+
194
+ /**
195
+ * Poll a media job to a terminal state.
196
+ *
197
+ * The spec says the url field is "Present only once `status` is `done`", so STATUS is what is
198
+ * checked — not the presence of a url, which would read a still-running job as a finished one
199
+ * with a missing file.
200
+ */
201
+ async _wait(retrieve, job, { timeoutMs, pollIntervalMs }) {
202
+ const id = job?.id;
203
+ if (!id) throw new FruteboxError("The job response carried no id, so it cannot be polled.", { code: "no_job_id" });
204
+
205
+ const deadline = Date.now() + timeoutMs;
206
+ let current = job;
207
+ for (;;) {
208
+ const status = current?.status;
209
+ if (TERMINAL.has(status)) {
210
+ if (status === "done") return current;
211
+ throw new JobFailed(current.error || `Job ${id} ended as '${status}'.`, current);
212
+ }
213
+ if (!PENDING.has(status)) {
214
+ // The spec's enum is closed, so an unknown status means the server grew a state this
215
+ // client does not know. Not assumed to be success OR failure.
216
+ throw new FruteboxError(
217
+ `Job ${id} reported unknown status '${status}'; refusing to guess.`,
218
+ { code: "unknown_job_status" },
219
+ );
220
+ }
221
+ if (Date.now() >= deadline) {
222
+ throw new JobTimeout(
223
+ `Job ${id} was still '${status}' after ${timeoutMs}ms. It is still running on the network `
224
+ + `— poll it again with the id on this error.`,
225
+ current,
226
+ );
227
+ }
228
+ await new Promise((r) => setTimeout(r, Math.max(0, Math.min(pollIntervalMs, deadline - Date.now()))));
229
+ current = await retrieve(id);
230
+ }
231
+ }
232
+
233
+ /** @internal — the namespace factories below are the only callers. */
234
+ _json(...a) { return this.#json(...a); }
235
+ /** @internal */ _request(...a) { return this.#request(...a); }
97
236
  }
98
237
 
99
- async function toError(res) {
100
- let message = `Frutebox request failed (${res.status}).`;
101
- let code;
102
- try {
103
- const body = await res.json();
104
- if (typeof body?.error === "string") message = body.error;
105
- else if (body?.error?.message) {
106
- message = body.error.message;
107
- code = body.error.code;
238
+ // =============================================================================================
239
+ // namespaces
240
+ // =============================================================================================
241
+ /**
242
+ * Read a `text/event-stream` as native `{type,…}` events, stopping at `[DONE]`.
243
+ *
244
+ * Separate from `streamCompletion`, which yields the drop-in's OpenAI-shaped chunks. One reader
245
+ * serving both would have to pretend the two payloads are the same shape, and they are not.
246
+ */
247
+ /**
248
+ * A LATE failure throws exactly like an early one (2026-11-17). The API keeps a slow job's connection
249
+ * alive by committing `200` and sending a byte every 15 s; a job that then fails has no status left to
250
+ * send, so the failure arrives as a body with `error` and `deferred_status` — the status it would have
251
+ * had. Returned as-is, a 55-minute "no machine" failure looked like a successful result. Thrown here
252
+ * through the same `errorFromBody`, so callers catch the same error class either way.
253
+ */
254
+ function raiseIfDeferred(parsed) {
255
+ if (parsed && typeof parsed === "object" && "error" in parsed
256
+ && Number.isInteger(parsed.deferred_status)) {
257
+ throw errorFromBody(parsed.deferred_status, parsed, undefined);
258
+ }
259
+ return parsed;
260
+ }
261
+
262
+ async function* sseEvents(res) {
263
+ const reader = res.body.getReader();
264
+ const decoder = new TextDecoder();
265
+ let buffer = "";
266
+ for (;;) {
267
+ const { done, value } = await reader.read();
268
+ if (done) return;
269
+ buffer += decoder.decode(value, { stream: true });
270
+ const lines = buffer.split("\n");
271
+ buffer = lines.pop() ?? "";
272
+ for (const line of lines) {
273
+ const t = line.trim();
274
+ if (!t.startsWith("data:")) continue;
275
+ const data = t.slice(5).trim();
276
+ if (data === "[DONE]") return;
277
+ // Not JSON means a keep-alive, not the end of the answer.
278
+ let event;
279
+ try { event = JSON.parse(data); } catch { continue; /* keep-alive */ }
280
+ yield raiseIfDeferred(event);
281
+ }
282
+ }
283
+ }
284
+
285
+ /** 28-F.1 spells it exactly this way; the route's zod enum is [...regionIds, "local"]. */
286
+ const LOCAL_REGION = "local";
287
+
288
+ /**
289
+ * 28-F.1's on-device half: run HERE, or check the balance before falling back.
290
+ *
291
+ * §F.4's rule is that a call is charged only when Frutebox's infrastructure does work. A local
292
+ * run that posted the prompt anyway would give the privacy away and keep only the discount, so
293
+ * when the device can serve, NO REQUEST IS MADE.
294
+ *
295
+ * Without a runner (or when it returns null — "this device cannot serve it"), F.1's order is
296
+ * followed exactly: ask the local directive, which answers `fallback.allowed` after a BALANCE
297
+ * CHECK, and only then use the network. A refusal throws rather than charging silently.
298
+ */
299
+ async function runLocal(c, message, priority) {
300
+ if (c._localRunner) {
301
+ const reply = await c._localRunner(message);
302
+ if (reply !== null && reply !== undefined) {
303
+ return { reply, run: "local", charged: false, region: LOCAL_REGION };
304
+ }
305
+ }
306
+ const directive = await c._json("POST", "/chat", { message, region: LOCAL_REGION, priority });
307
+ const fallback = directive?.fallback ?? {};
308
+ if (!fallback.allowed) {
309
+ // Fail CLOSED: a missing fallback block is not an invitation to spend the user's balance.
310
+ const code = fallback.error ?? "insufficient_balance";
311
+ throw new FruteboxError(
312
+ `the on-device model cannot serve this and the network fallback was refused: ${code}`,
313
+ { code, status: code === "insufficient_balance" ? 402 : 503 });
314
+ }
315
+ return c._json("POST", "/chat", { message, priority });
316
+ }
317
+
318
+ function makeChat(c) {
319
+ /** NATIVE POST /chat. Callable, because 0.0.1 published it that way. */
320
+ const chat = async ({ message, region, priority } = {}) => {
321
+ if (typeof message !== "string" || message.length === 0) {
322
+ throw new FruteboxError("`message` must be a non-empty string.", { code: "invalid_request" });
323
+ }
324
+ if (region === LOCAL_REGION) return runLocal(c, message, priority);
325
+ return c._json("POST", "/chat", { message, region, priority });
326
+ };
327
+
328
+ /**
329
+ * NATIVE streaming — `POST /chat/stream`, Server-Sent Events. The non-deprecated door.
330
+ *
331
+ * Yields `{type,…}` events: `start`, then `delta` with `text`, then `done` with `usage`.
332
+ * An unknown `type` is SKIPPABLE by design, so a new event kind is not fatal to an old client.
333
+ *
334
+ * INCREMENTAL DELIVERY, NOT INCREMENTAL GENERATION: the network returns a complete answer
335
+ * today, so this chunks a finished reply rather than racing it.
336
+ */
337
+ chat.stream = async function* ({ message, region, priority } = {}) {
338
+ if (typeof message !== "string" || !message) {
339
+ throw new FruteboxError("`message` must be a non-empty string.", 0, "invalid_request");
340
+ }
341
+ const res = await c._request("POST", "/chat/stream", {
342
+ body: { message, ...compact({ region, priority }) },
343
+ stream: true,
344
+ });
345
+ yield* sseEvents(res);
346
+ };
347
+
348
+ chat.completions = {
349
+ /**
350
+ * DROP-IN POST /chat/completions. **Deprecated** — use `fb.chat({ message })`.
351
+ *
352
+ * Warned once per process because the published spec marks the operation `deprecated: true`;
353
+ * the spec's comment says that flag exists so a generated SDK warns on the method rather than
354
+ * in prose nobody reads. Warned ONCE, not per call, so a loop does not bury the log.
355
+ */
356
+ create: async ({ messages, stream = false, region, stream_options, ...extra } = {}) => {
357
+ if ("model" in extra) throw new FruteboxError(NO_MODEL, { code: "model_not_chosen_by_caller" });
358
+ if (!warnedDropIn) {
359
+ warnedDropIn = true;
360
+ // eslint-disable-next-line no-console
361
+ console.warn(
362
+ "[frutebox] POST /chat/completions is deprecated (see the Deprecation/Sunset headers on "
363
+ + "every response). Use fb.chat({ message }), the native surface, which also returns the "
364
+ + "request's measured cost. The drop-in surface remains live.",
365
+ );
366
+ }
367
+ const body = { messages, stream: Boolean(stream), ...extra, ...compact({ region, stream_options }) };
368
+ const res = await c._request("POST", "/chat/completions", { body, stream: Boolean(stream) });
369
+ return stream ? streamCompletion(res) : raiseIfDeferred(await res.json());
370
+ },
371
+ };
372
+ return chat;
373
+ }
374
+
375
+ /**
376
+ * Yield `chat.completion.chunk` objects from the SSE stream, stopping at `data: [DONE]`.
377
+ *
378
+ * A malformed frame is skipped rather than ending the stream: the next frame may be fine, and a
379
+ * truncated answer is worse than a missing chunk.
380
+ */
381
+ async function* streamCompletion(res) {
382
+ const reader = res.body.getReader();
383
+ const decoder = new TextDecoder();
384
+ let buffer = "";
385
+ for (;;) {
386
+ const { done, value } = await reader.read();
387
+ if (done) break;
388
+ buffer += decoder.decode(value, { stream: true });
389
+ // SSE frames are newline-delimited; the last fragment may be incomplete, so it stays buffered.
390
+ const lines = buffer.split("\n");
391
+ buffer = lines.pop() ?? "";
392
+ for (const line of lines) {
393
+ const trimmed = line.trim();
394
+ if (!trimmed.startsWith("data:")) continue;
395
+ const data = trimmed.slice(5).trim();
396
+ if (data === "[DONE]") return;
397
+ let event;
398
+ try { event = JSON.parse(data); } catch { continue; /* skip a malformed frame */ }
399
+ yield raiseIfDeferred(event);
108
400
  }
109
- if (!code && typeof body?.code === "string") code = body.code;
110
- } catch {
111
- // A non-JSON error body leaves the status-derived message in place.
112
401
  }
113
- return new FruteboxError(message, res.status, code);
402
+ }
403
+
404
+ function makeModels(c) {
405
+ /** GET /models. Callable, because 0.0.1 published `fb.models()`. */
406
+ const models = () => c._json("GET", "/models");
407
+ models.list = () => c._json("GET", "/models");
408
+ /**
409
+ * GET /models/{id}. Frutebox serves ONE model and sizes it to the task, so any known id resolves
410
+ * to it and anything else is a clear 404 rather than a silent default.
411
+ */
412
+ models.retrieve = (id) => c._json("GET", "/models/{id}", undefined, { pathParams: { id } });
413
+ return models;
414
+ }
415
+
416
+ function makeImages(c) {
417
+ const ns = {
418
+ /**
419
+ * POST /images/generations — ASYNC. Returns a queued job (202); no image is ever returned
420
+ * here. `n` is clamped to 1..4 by the server. `region` is accepted for backwards compatibility
421
+ * only and is not sent.
422
+ */
423
+ generate: ({ prompt, n, size, region } = {}) => {
424
+ if (region !== undefined && region !== null) deadField("region", "/images/generations");
425
+ return c._json("POST", "/images/generations", { prompt, n, size });
426
+ },
427
+ /** GET /images/generations/{id} — poll. `image_url` appears once status is `done`. */
428
+ retrieve: (id) => c._json("GET", "/images/generations/{id}", undefined, { pathParams: { id } }),
429
+ };
430
+ ns.generateAndWait = async ({ prompt, n, size, timeoutMs = 300_000, pollIntervalMs = 2_000 } = {}) => {
431
+ const job = await ns.generate({ prompt, n, size });
432
+ return c._wait(ns.retrieve, job, { timeoutMs, pollIntervalMs });
433
+ };
434
+ return ns;
435
+ }
436
+
437
+ function makeVideos(c) {
438
+ /**
439
+ * TWO PATHS, ONE OPERATION, and both are published because both are live: POST /videos is the
440
+ * Frutebox-native spelling and POST /videos/generations the drop-in one. Covering only one would
441
+ * leave a live endpoint this SDK cannot reach, which the spec explicitly says not to do.
442
+ */
443
+ const ns = {
444
+ generate: ({ prompt, seconds, region } = {}) => {
445
+ if (seconds !== undefined && seconds !== null) deadField("seconds", "/videos");
446
+ if (region !== undefined && region !== null) deadField("region", "/videos");
447
+ return c._json("POST", "/videos", { prompt });
448
+ },
449
+ retrieve: (id) => c._json("GET", "/videos/{id}", undefined, { pathParams: { id } }),
450
+ generations: {
451
+ /** POST /videos/generations (drop-in spelling) — the same operation as POST /videos. */
452
+ create: ({ prompt, seconds } = {}) => {
453
+ if (seconds !== undefined && seconds !== null) deadField("seconds", "/videos/generations");
454
+ return c._json("POST", "/videos/generations", { prompt });
455
+ },
456
+ },
457
+ };
458
+ ns.generateAndWait = async ({ prompt, timeoutMs = 900_000, pollIntervalMs = 5_000 } = {}) => {
459
+ const job = await ns.generate({ prompt });
460
+ return c._wait(ns.retrieve, job, { timeoutMs, pollIntervalMs });
461
+ };
462
+ return ns;
463
+ }
464
+
465
+ function makeAudio(c) {
466
+ const generations = {
467
+ /** POST /audio/generations — music or sound, ASYNC. `kind` is music|song|sfx. */
468
+ create: ({ prompt, kind, duration_s, lyrics, format } = {}) =>
469
+ c._json("POST", "/audio/generations", { prompt, kind, duration_s, lyrics, format }),
470
+ /** GET /audio/generations/{id} — poll. `audio_url` appears once status is `done`. */
471
+ retrieve: (id) => c._json("GET", "/audio/generations/{id}", undefined, { pathParams: { id } }),
472
+ };
473
+ generations.createAndWait = async ({ prompt, kind, duration_s, lyrics, format, timeoutMs = 600_000, pollIntervalMs = 3_000 } = {}) => {
474
+ const job = await generations.create({ prompt, kind, duration_s, lyrics, format });
475
+ return c._wait(generations.retrieve, job, { timeoutMs, pollIntervalMs });
476
+ };
477
+
478
+ return {
479
+ generations,
480
+ /**
481
+ * POST /audio/speech — text to speech. ASYNC, and this CHANGED under us.
482
+ *
483
+ * It used to answer 200 with raw audio. On main it answers 202 with a queued job
484
+ * (`object: "audio.speech.job"`) and `GET /audio/speech/{id}` polls it. The old client called
485
+ * `res.arrayBuffer()`, so it handed back the JSON job body as bytes — a caller would have
486
+ * written that into a .mp3 and heard nothing.
487
+ *
488
+ * Still callable as `audio.speech({ input })` so existing call sites resolve; what comes back
489
+ * had to change, because the server's answer changed.
490
+ */
491
+ speech: Object.assign(
492
+ async ({ input, voice, format } = {}) => c._json("POST", "/audio/speech", { input, voice, format }),
493
+ {
494
+ create: async ({ input, voice, format } = {}) =>
495
+ c._json("POST", "/audio/speech", { input, voice, format }),
496
+ /** GET /audio/speech/{id} — poll. The audio appears once `status` is `done`. */
497
+ retrieve: (id) => c._json("GET", "/audio/speech/{id}", undefined, { pathParams: { id } }),
498
+ },
499
+ ),
500
+ transcriptions: {
501
+ /** POST /audio/transcriptions — speech to text, multipart/form-data. */
502
+ create: async ({ file, filename = "audio", language, ...extra } = {}) => {
503
+ if ("model" in extra) throw new FruteboxError(NO_MODEL, { code: "model_not_chosen_by_caller" });
504
+ const form = new FormData();
505
+ form.append("file", file, filename);
506
+ if (language) form.append("language", language);
507
+ const res = await c._request("POST", "/audio/transcriptions", { formData: form });
508
+ return raiseIfDeferred(await res.json());
509
+ },
510
+ },
511
+ };
114
512
  }
115
513
 
116
514
  export default Frutebox;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "frutebox",
3
- "version": "0.0.1",
4
- "description": "Official Frutebox SDK — call the Frutebox network from JavaScript and TypeScript. No third-party AI SDK required.",
3
+ "version": "0.2.0",
4
+ "description": "Official Frutebox SDK \u2014 call the Frutebox network from JavaScript and TypeScript. No third-party AI SDK required.",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "module": "./index.mjs",
@@ -10,11 +10,27 @@
10
10
  ".": {
11
11
  "types": "./index.d.ts",
12
12
  "import": "./index.mjs"
13
+ },
14
+ "./errors": {
15
+ "import": "./errors.mjs"
16
+ },
17
+ "./spec": {
18
+ "import": "./spec.mjs"
19
+ },
20
+ "./account": {
21
+ "types": "./account.d.ts",
22
+ "import": "./account.mjs"
13
23
  }
14
24
  },
15
25
  "files": [
26
+ "bin",
16
27
  "index.mjs",
17
28
  "index.d.ts",
29
+ "errors.mjs",
30
+ "spec.mjs",
31
+ "account.d.ts",
32
+ "account.mjs",
33
+ "CHANGELOG.md",
18
34
  "README.md",
19
35
  "LICENSE"
20
36
  ],
@@ -30,5 +46,15 @@
30
46
  "author": "Frutebox",
31
47
  "engines": {
32
48
  "node": ">=18"
49
+ },
50
+ "scripts": {
51
+ "test": "node --test"
52
+ },
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+https://github.com/frutebox/frutebox.git"
56
+ },
57
+ "bin": {
58
+ "frutebox": "./bin/frutebox.mjs"
33
59
  }
34
60
  }
package/spec.mjs ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * THE OPERATION REGISTRY — every published operation, mapped to the client method that calls it.
3
+ *
4
+ * The TypeScript twin of `frutebox._spec.OPERATIONS` in the Python package, and it exists for the
5
+ * same reason: the drift check is mechanical rather than a promise in a README. `test/spec-
6
+ * conformance.test.mjs` asserts this table against `sdk/spec/openapi.json` in both directions, and
7
+ * resolves every dotted path against a real client instance, so a typo here fails too.
8
+ *
9
+ * Shipped with the package (it is in `files`) because it is also the honest answer to "what does
10
+ * this client cover?" — importable rather than prose.
11
+ */
12
+
13
+ /** Everything is published under the spec's single server, `https://frutebox.com/api/v1`. */
14
+ export const API_PREFIX = "/api/v1";
15
+
16
+ /** `"METHOD specPath"` -> dotted attribute path on a `Frutebox` instance. */
17
+ export const OPERATIONS = Object.freeze({
18
+ // chat: BOTH surfaces, deliberately. Native is the long-term path; the drop-in is what
19
+ // /docs/quickstart and /docs/sdk open with, and it is deprecated, not dead.
20
+ "POST /chat": "chat",
21
+ "POST /chat/stream": "chat.stream",
22
+ "POST /chat/completions": "chat.completions.create",
23
+ // native embeddings
24
+ "POST /embeddings": "embeddings.create",
25
+ // models
26
+ "GET /models": "models.list",
27
+ "GET /models/{id}": "models.retrieve",
28
+ // media: async create + poll, every one of them
29
+ "POST /images/generations": "images.generate",
30
+ "GET /images/generations/{id}": "images.retrieve",
31
+ "POST /videos": "videos.generate",
32
+ "POST /videos/generations": "videos.generations.create",
33
+ "GET /videos/{id}": "videos.retrieve",
34
+ "POST /audio/generations": "audio.generations.create",
35
+ "GET /audio/generations/{id}": "audio.generations.retrieve",
36
+ "POST /audio/speech": "audio.speech.create",
37
+ "GET /audio/speech/{id}": "audio.speech.retrieve",
38
+ "POST /audio/transcriptions": "audio.transcriptions.create",
39
+ // the rest
40
+ "POST /moderations": "moderations.create",
41
+ "GET /skills": "skills.list",
42
+ });