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/CHANGELOG.md ADDED
@@ -0,0 +1,69 @@
1
+ # Changelog — `frutebox` (npm)
2
+
3
+ The JavaScript/TypeScript client for the Frutebox network, and the `frutebox` command. It is
4
+ released in lockstep with the PyPI packages of the same name: one SDK, one version.
5
+
6
+ Publishing is an owner action.
7
+
8
+ ## [Unreleased]
9
+
10
+ Nothing yet.
11
+
12
+ ## [0.2.0] — 2026-11-18
13
+
14
+ ### Added
15
+
16
+ - Native answers carry a request **`id`** (also in the `x-frutebox-request-id` header from the first
17
+ byte) and **`usage.tokenCost`, always 0**: tokens are never charged; `cost` is electricity plus internet.
18
+
19
+ ### Changed
20
+
21
+ - **No call takes a `model` any more.** Frutebox's orchestrator determines the model for every
22
+ prompt; a caller never chooses one. `chat.completions.create` and `audio.transcriptions.create`
23
+ lost their `model` argument, and passing one raises with that explanation. Responses still
24
+ report, in `model`, what the orchestrator chose.
25
+
26
+ ## [0.1.1] — 2026-11-17
27
+
28
+ ### Fixed
29
+
30
+ - **A failure that arrives late now throws.** The API keeps a slow request alive: after about 20
31
+ seconds it commits `200` and sends a keepalive byte every 15 seconds, so long jobs (large prompts,
32
+ a busy or reconnecting node) are no longer cut off. If such a job then fails, the failure arrives
33
+ as a body with `error` and `deferred_status`. 0.1.0 returned that body as a result; 0.1.1 throws
34
+ the same error class the status would have raised (`NoCapacityError` for 503, and so on), for
35
+ `chat()`, every other JSON call, and streams.
36
+
37
+ ## [0.1.0] — 2026-10-15
38
+
39
+ First release under the unscoped `frutebox` name.
40
+
41
+ ### The client
42
+
43
+ - `new Frutebox({ apiKey })` covers **all 16 published operations**, checked against
44
+ `sdk/spec/openapi.json` rather than against itself.
45
+ - Subpath exports: `frutebox/errors`, `frutebox/spec`, `frutebox/account`. Each is asserted to
46
+ resolve from an installed tarball, not merely from the source directory.
47
+ - `FruteboxAccount` (`frutebox/account`) carries the session-authed first-party surface,
48
+ including the nine Standby Agents operations.
49
+ - Typed errors mirroring the Python client, and `.d.ts` for both entry points.
50
+ - **0.0.1 compatibility is kept**: `fb.models()` stays callable.
51
+
52
+ ### The CLI
53
+
54
+ - `frutebox login|logout|share|node|agents`, matching the PyPI CLI command for command. A test
55
+ reads both sources and fails if the two disagree on which actions exist — they were written on
56
+ different days and nothing else compared them.
57
+ - `frutebox agents results <id>` and `show <id>` added, so every wired endpoint is reachable.
58
+ - The step-up code is read from `FRUTEBOX_TOTP` or stdin, **never a flag**; the session token is
59
+ read from stdin. `ps` shows argv to every user on the machine.
60
+
61
+ ### Release
62
+
63
+ - `npm publish --provenance`, which signs the tarball against the workflow run that built it.
64
+ - The release job does not trust "publish returned success": it installs the published version
65
+ from the registry and asserts the client files are actually in it. A previous publish returned
66
+ `+ frutebox@0.0.1` while the registry served a stub with no client in it.
67
+
68
+ [Unreleased]: https://github.com/frutebox/frutebox/compare/sdk-v0.1.0...HEAD
69
+ [0.1.0]: https://github.com/frutebox/frutebox/releases/tag/sdk-v0.1.0
package/README.md CHANGED
@@ -1,54 +1,205 @@
1
1
  # frutebox
2
2
 
3
3
  The official [Frutebox](https://frutebox.com) SDK for JavaScript and TypeScript — call the Frutebox
4
- network with no third-party AI library. Zero dependencies.
4
+ network with no third-party AI library. Every answer comes from the real Frutebox network: no other
5
+ provider is called, paid or depended on.
5
6
 
6
7
  ```bash
7
8
  npm install frutebox
8
9
  ```
9
10
 
11
+ Zero dependencies (`fetch` is built into Node 18+), no build step, and types are included.
12
+
13
+ ## Two surfaces, and which one to use
14
+
15
+ The API publishes two chat shapes and the website documents both, so this client covers both.
16
+
17
+ **Use the native one.** It is the long-term surface, and it returns something the other cannot:
18
+ the request's **real measured cost**, electricity and internet, per serving node.
19
+
10
20
  ```js
11
21
  import { Frutebox } from "frutebox";
12
22
 
13
- const frutebox = new Frutebox({ apiKey: process.env.FRUTEBOX_API_KEY });
23
+ const fb = new Frutebox(); // reads FRUTEBOX_API_KEY
14
24
 
15
- const res = await frutebox.chat({ message: "Say hello in five words." });
16
- console.log(res.reply);
17
- console.log(res.usage); // tokens, compute time, and what it cost
25
+ const res = await fb.chat({ message: "Draft a friendly reminder email.", region: "eu-west" });
26
+ console.log(res.reply, res.model, res.region);
27
+ console.log(res.usage.cost, res.usage.currency);
28
+ for (const node of res.usage.nodes ?? []) console.log(node.name, node.computeMs, node.watts);
18
29
  ```
19
30
 
20
- TypeScript types ship with the package. HTTPS is enforced, so your key is never sent in plaintext.
31
+ **The drop-in shape still works and is deprecated.** It exists so an app written against the common
32
+ AI SDKs moves to Frutebox by changing a base URL and a key. Nothing is refused, re-routed or
33
+ re-priced for using it — it just warns once, because the published spec marks the operation
34
+ `deprecated: true` and a `choices` array has nowhere to put a measured cost.
21
35
 
22
- - Get an API key: <https://frutebox.com/app/keys>
23
- - Documentation: <https://frutebox.com/docs>
36
+ ```js
37
+ const res = await fb.chat.completions.create({ messages: [{ role: "user", content: "Hello" }] });
38
+ console.log(res.choices[0].message.content);
39
+
40
+ // Streaming returns an async iterable of chat.completion.chunk objects.
41
+ const stream = await fb.chat.completions.create({ messages: [...], stream: true });
42
+ for await (const chunk of stream) process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
43
+ ```
44
+
45
+ ## Long prompts, waiting, and the request id
46
+
47
+ A request is never dropped for lack of capacity: it waits in the network until a node can run it (up
48
+ to 30 minutes), and Frutebox's orchestrator determines the model; you never pass one. While you wait,
49
+ the server keeps the connection alive with a space every 15 seconds, so a long prompt is not a
50
+ silent connection. This client reads straight through that. A failure that happens after the wait
51
+ has started arrives inside the 200 and is **raised** like any other error.
52
+
53
+ ```js
54
+ const res = await fb.chat({ message: longPrompt });
55
+ console.log(res.id); // the request id: quote it when you report a request
56
+ console.log(res.usage.tokenCost); // always 0: tokens are never charged
57
+ ```
58
+
59
+ Set your own overall deadline generously: about 300 s for short prompts, 600 s for long ones and
60
+ 1200 s for long prompts that must return JSON. If you abandon a request, it stops on Frutebox's
61
+ side and is not charged.
62
+
63
+ ## Embeddings
64
+
65
+ Native: vectors come back directly as `embeddings`, in request order. You do **not** pick the
66
+ embedder — Frutebox chooses from its licence-cleared roster — and `model` reports what actually ran.
67
+
68
+ ```js
69
+ const { embeddings, dimensions, model } = await fb.embeddings.create({ input: ["first", "second"] });
70
+ ```
71
+
72
+ ## Media is always asynchronous
73
+
74
+ Every image, video and audio call returns a **job**, never a file. Poll it, or let the client poll:
75
+
76
+ ```js
77
+ // One call, polled for you. Throws JobFailed / JobTimeout rather than returning a half-answer.
78
+ const done = await fb.images.generateAndWait({ prompt: "a pear, watercolour", size: "1024x1024" });
79
+ console.log(done.image_url);
80
+
81
+ // Or drive it yourself.
82
+ let job = await fb.images.generate({ prompt: "a pear, watercolour", n: 2 });
83
+ while (job.status === "queued" || job.status === "running") job = await fb.images.retrieve(job.id);
84
+ ```
85
+
86
+ `status` is the signal, not the presence of a url: the url field appears **only** once status is
87
+ `done`.
88
+
89
+ ```js
90
+ await fb.videos.generateAndWait({ prompt: "a pear rolling downhill" }); // POST /videos
91
+ await fb.videos.generations.create({ prompt: "…" }); // the drop-in spelling
92
+ await fb.audio.generations.createAndWait({ prompt: "a jingle", kind: "music", duration_s: 30 });
93
+ await fb.audio.speech({ input: "Hello there" }); // ArrayBuffer
94
+ await fb.audio.transcriptions.create({ file: new Blob([bytes]), filename: "clip.mp3" });
95
+ await fb.moderations.create({ input: "some text" });
96
+ const { data } = await fb.models.list();
97
+ await fb.models.retrieve(data[0].id); // never a pinned literal
98
+ await fb.skills.list();
99
+ ```
24
100
 
25
- `FRUTEBOX_API_KEY` is read from the environment when no `apiKey` is passed. The older
26
- `STEVAI_API_KEY` is still accepted so existing environments keep working.
101
+ **The model id is not yours to pin, and it is being renamed.** Frutebox serves one model and sizes
102
+ it to the task, so you never pick one — `chat` and `embeddings` take no `model` argument at all.
103
+ The published id is whatever `models.list()` reports; an older integration that still sends the
104
+ previous id keeps working, because the server accepts it as an undocumented alias. Reading the id
105
+ rather than pinning it makes the rename a non-event for your code — which is why the examples above
106
+ do exactly that.
27
107
 
28
108
  ## Errors
29
109
 
30
- Every failure throws a `FruteboxError` carrying the HTTP `status` and, where the API supplies one,
31
- a `code`.
110
+ One class per published status, and both published error bodies are parsed — the native flat
111
+ `{error, code, retryAfterSeconds}` and the drop-in nested `{error: {message, type, code}}`.
32
112
 
33
113
  ```js
34
- import { Frutebox, FruteboxError } from "frutebox";
114
+ import { RateLimitError, BudgetError, NotImplementedByNetwork } from "frutebox/errors";
35
115
 
36
116
  try {
37
- await frutebox.chat({ message: "..." });
117
+ await fb.chat({ message: "…" });
38
118
  } catch (err) {
39
- if (err instanceof FruteboxError) console.error(err.status, err.code, err.message);
119
+ if (err instanceof RateLimitError) await sleep((err.retryAfterSeconds ?? 5) * 1000);
120
+ else if (err instanceof BudgetError) { /* 402 — over the account's budget */ }
121
+ else if (err instanceof NotImplementedByNetwork) { /* 501 — never a fabricated result */ }
122
+ else throw err;
40
123
  }
41
124
  ```
42
125
 
43
- ## Status
126
+ `JobFailed` and `JobTimeout` carry the job. A timeout does **not** cancel it — the job is still
127
+ running on the network, so the id is there to keep polling with.
128
+
129
+ ## Your own account — a different client, and a different credential
130
+
131
+ Some things are not on the public API at all: they authenticate your **account**, not a key. They get
132
+ their own client, because an `sk_live_…` key would return 401 for every one of them.
133
+
134
+ ```js
135
+ import { FruteboxAccount } from "frutebox/account";
136
+
137
+ const me = new FruteboxAccount(); // reads FRUTEBOX_SESSION_TOKEN
138
+ await me.conversations.rename("conv_123", "Q3 planning");
139
+
140
+ await me.featureRequests.create({ title: "Export to CSV", description: "A button on the usage page." });
141
+ await me.featureRequests.list({ limit: 20 }); // ADMINS ONLY — 403 otherwise
142
+ ```
143
+
144
+ The session token is the one `frutebox login` stores, so the CLI and this client share a credential.
145
+ Passing an API key throws immediately rather than letting the server answer an unexplained 401.
146
+
147
+ | | `Frutebox` | `FruteboxAccount` |
148
+ |---|---|---|
149
+ | credential | `sk_live_…` API key | session token |
150
+ | surface | `/api/v1/*`, 16 operations | first-party endpoints outside `/api/v1` |
151
+ | published in the OpenAPI document | yes | **no** |
152
+
153
+ > **These two endpoints are not deployed yet.** They were written on `lane2/backend` (`46a7a38d`,
154
+ > `a403cb55`) and reach production through MAIN's merge. Until then they return 404. The shapes here
155
+ > come from those routes' own validation schemas, and the test suite starts comparing against the
156
+ > real source the moment they land.
157
+
158
+ **Not here on purpose:** org, groups, rules and user import. They are session-authed today, but they
159
+ are being changed to accept an API key with an org-admin scope — at which point they belong on
160
+ `Frutebox`, with a scope entry and a spec entry. Putting them here now would mean moving them later.
161
+
162
+ ## The CLI
163
+
164
+ Installing the package installs a `frutebox` command for sharing this machine's hardware with the
165
+ network, through the same endpoints the desktop app uses.
166
+
167
+ ```bash
168
+ pbpaste | frutebox login # a SESSION token, read from stdin — never a flag
169
+ frutebox share --join --region eu-west
170
+ frutebox share --status # node state and earnings
171
+ frutebox share --limits # when this machine will and will not take work
172
+ frutebox share --leave
173
+ ```
174
+
175
+ It shares its config directory with the Python package's identical CLI, so the two are one tool
176
+ with two front doors. The node **agent** itself is Python, so `node contribute` here registers the
177
+ machine and prints the command to start it; `pip install frutebox` starts it for you.
178
+
179
+ `frutebox agents` is **not implemented**: Standby Agents has no endpoints yet, and the command says
180
+ so rather than guessing at shapes nobody has published.
181
+
182
+ ## Keys and configuration
183
+
184
+ ```js
185
+ new Frutebox({ apiKey, baseUrl, timeoutMs, fetch });
186
+ ```
187
+
188
+ `FRUTEBOX_API_KEY` is read when no `apiKey` is passed; the older `STEVAI_API_KEY` is still accepted
189
+ so existing environments keep working. HTTPS is enforced, so your key is never sent in plaintext
190
+ (`localhost` is exempt for development). `fetch` is injectable for tests.
44
191
 
45
- **0.0.1 is an early release.** It covers `chat` and `models` against the native Frutebox endpoint,
46
- and requires Node 18 or newer (it uses the built-in `fetch`). A fully typed client generated from
47
- the published API specification is planned, and the surface may change before 1.0.
192
+ The key is kept out of `JSON.stringify`, `util.inspect` and every error this client throws,
193
+ including transport failures — a fetch failure can carry the request, and the request carries the
194
+ auth header.
48
195
 
49
- This package talks to the native endpoint. The OpenAI-shaped compatibility surface is a separate
50
- migration path that is being phased out — see the documentation if you are moving an existing app.
196
+ ## The contract
51
197
 
52
- ## Licence
198
+ This client is generated against the published OpenAPI document and checked against it in CI:
53
199
 
54
- MIT — see [LICENSE](LICENSE).
200
+ - `GET https://frutebox.com/api/v1/openapi.json`
201
+ - `import { OPERATIONS } from "frutebox/spec"` maps every published operation to the method that
202
+ calls it. CI fails if a published operation has no method, or a method has no published operation.
203
+
204
+ - Get an API key: <https://frutebox.com/app/keys>
205
+ - Documentation: <https://frutebox.com/docs>
package/account.d.ts ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Type declarations for the session-authenticated, first-party surface.
3
+ *
4
+ * This is NOT the public developer API. `Frutebox` (from `frutebox`) is key-authed and published in
5
+ * the OpenAPI document; this client is session-authed and covers endpoints outside `/api/v1` that
6
+ * the spec does not describe. An API key will not work here and the constructor throws rather than
7
+ * letting the server answer 401.
8
+ */
9
+ import type { FruteboxError } from "./index.js";
10
+
11
+ export declare const DEFAULT_BASE_URL: string;
12
+ /** The `/api` server the spec gives these paths — the developer API is `/api/v1`. */
13
+ export declare const ACCOUNT_PREFIX: "/api";
14
+ export declare const DEFAULT_TIMEOUT_MS: number;
15
+
16
+ /** `MAX_USER_TITLE` in the rename route. */
17
+ export declare const MAX_CONVERSATION_TITLE: 120;
18
+ /** `MAX_FR_TITLE` / `MAX_FR_BODY` in the feature-requests route. */
19
+ export declare const MAX_FEATURE_REQUEST_TITLE: 160;
20
+ export declare const MAX_FEATURE_REQUEST_DESCRIPTION: 4000;
21
+
22
+ /** Session-authed operations, mapped to the method that calls them. Not the spec's operations. */
23
+ export declare const SESSION_OPERATIONS: Readonly<Record<string, string>>;
24
+
25
+ /** `PATCH /api/conversations/{id}` — the stored values, read back. */
26
+ export interface RenameResult {
27
+ ok?: boolean;
28
+ /** What is STORED, decrypted — not the string you sent. */
29
+ title?: string;
30
+ lengthMode?: string;
31
+ reasoningMode?: string;
32
+ }
33
+
34
+ /** `POST /api/feature-requests` — 201. */
35
+ export interface FeatureRequestCreated {
36
+ id: string;
37
+ status: string;
38
+ /** ISO 8601. */
39
+ createdAt: string;
40
+ }
41
+
42
+ export interface FeatureRequest {
43
+ id: string;
44
+ /** The submitter, by id only — an admin reading the queue is not handed decrypted identities. */
45
+ userId: string;
46
+ title: string;
47
+ /** "" when the submitter filed a one-liner. */
48
+ description: string;
49
+ status: string;
50
+ createdAt: string;
51
+ }
52
+
53
+ export interface FeatureRequestList {
54
+ requests: FeatureRequest[];
55
+ }
56
+
57
+ /** `PATCH /org/{id}/groups/{groupId}` — every field optional; omitted is not the same as `[]`. */
58
+ export interface GroupRules {
59
+ name?: string;
60
+ requiredRegion?: string;
61
+ teeOnly?: boolean;
62
+ allowedTalents?: string[];
63
+ requiredTemplates?: string[];
64
+ branding?: Record<string, unknown>;
65
+ addMembers?: string[];
66
+ removeMembers?: string[];
67
+ }
68
+
69
+ /** `GET /me/policy` — the resolved union of every layer that governs you. */
70
+ export interface EffectivePolicy {
71
+ version: number;
72
+ /** True when `since` matched: the body is omitted and nothing changed. */
73
+ unchanged?: boolean;
74
+ blocked?: string[];
75
+ blockedOrigins?: string[];
76
+ store?: Record<string, unknown>;
77
+ requiredTemplates?: string[];
78
+ branding?: Record<string, unknown>;
79
+ allowedTalents?: string[];
80
+ requiredRegion?: string;
81
+ teeOnly?: boolean;
82
+ }
83
+
84
+ export interface FruteboxAccountOptions {
85
+ /** Falls back to `FRUTEBOX_SESSION_TOKEN`. An `sk_live_…` key is refused. */
86
+ sessionToken?: string;
87
+ baseUrl?: string;
88
+ timeoutMs?: number;
89
+ /** Injectable for tests. Defaults to the global `fetch`. */
90
+ fetch?: typeof fetch;
91
+ }
92
+
93
+ export declare class FruteboxAccount {
94
+ constructor(options?: FruteboxAccountOptions);
95
+ readonly baseUrl: string;
96
+
97
+ conversations: {
98
+ /** Trimmed; 1..120 characters after trimming. Blank is refused — clearing is not a rename. */
99
+ rename(conversationId: string, title: string): Promise<RenameResult>;
100
+ };
101
+
102
+ featureRequests: {
103
+ create(params: { title: string; description?: string }): Promise<FeatureRequestCreated>;
104
+ /** **Admins only** — a non-admin gets 403, thrown as `PolicyError`. */
105
+ list(params?: { limit?: number }): Promise<FeatureRequestList>;
106
+ };
107
+
108
+ org: {
109
+ groups: {
110
+ /**
111
+ * Set a group's rules. **Admins only.** A group can only ever RESTRICT — layers union at
112
+ * resolve time. Only the fields passed are written; an undeclared field is refused rather
113
+ * than dropped.
114
+ */
115
+ setRules(orgId: string, groupId: string, fields: GroupRules): Promise<Record<string, unknown>>;
116
+ };
117
+ };
118
+
119
+ me: {
120
+ /** The one poll every client uses. `since` makes an unchanged poll nearly free. */
121
+ policy(params?: { since?: number | string }): Promise<EffectivePolicy>;
122
+ };
123
+ }
124
+
125
+ export default FruteboxAccount;