@flovialabs/sdk 0.1.4 → 0.1.6

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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.1.6
6
+
7
+ - Interactive `status`, `usage`, `tools` and `call` show elapsed waiting time on stderr, as `generate` already does. JSON output stays quiet.
8
+ - CLI and README use the same two terms for paying: "free allowance" and "purchased balance".
9
+ - Clearer recovery advice after a lost generation reply: rerun with the same `--op`, prompt and options; a new id can charge again. The id line no longer tells you to resend when the next step says not to.
10
+ - A rejected key shows one Console link and one next step. Timeouts are shown in seconds. A network error or timeout without an operation id now says to check usage before sending again.
11
+ - Shorter help; exit code 1 is described as "an error from Flovia".
12
+ - CLI argument mistakes (a missing tool, `--op` or a bad option value) show the usage line before the key is read, so they no longer show "No key".
13
+ - `status` labels its windows "free 5-hour" and "free week" and lines up its values in one column. `usage` says "1 lookup".
14
+ - `PUBLIC_CODES` includes `approval_pending`.
15
+ - README: shorter key setup, current docs links, the generation codes `generation_pending` and `generation_unknown`, and the 0.1.5 `npx` example.
16
+
17
+ ## 0.1.5
18
+
19
+ - Keep `formal_registration_required` and a direct registration recovery step on HTTP 401; preserve the operation id and never retry authentication failures.
20
+ - Include a complete one-price Node example with private request persistence, same-operation replay and an explicitly saved, offline display.
21
+
3
22
  ## 0.1.4
4
23
 
5
24
  - Luna generation accepts `reasoning.effort` values `none`, `low`, `medium`, `high`, `xhigh` and `max`. The default remains `none`.
package/README.md CHANGED
@@ -10,20 +10,25 @@ TypeScript client and command-line tool for [Flovia](https://api.flovia.dev). It
10
10
  ## Install
11
11
 
12
12
  ```sh
13
- npm install --save-exact @flovialabs/sdk@0.1.4
13
+ npm install --save-exact @flovialabs/sdk@0.1.6
14
14
  ```
15
15
 
16
16
  ## Your key
17
17
 
18
- You need an invitation to [register and receive a Flovia key](https://api.flovia.dev/join). Keep the key private; it is shown once. Follow the [connection guide](https://api.flovia.dev/) to confirm your email and start the free allowance. Contact [Flovia support](https://flovia.dev/contact) if you need access or lose your key. Installing this package does not create an account or start an allowance.
19
-
20
- Set your Flovia key (`flv_...`) in the environment:
18
+ 1. Open the link in your invitation email and register.
19
+ 2. In [Flovia Console](https://console.flovia.dev/groupbuy/), create an API key. Console shows it once; save it somewhere private.
20
+ 3. Set the key (`flv_...`) in the environment, then check it:
21
21
 
22
22
  ```sh
23
23
  export FLOVIA_KEY=flv_...
24
+ npx flovia status
24
25
  ```
25
26
 
26
- Or pass it as `new FloviaClient({ apiKey })`. The client keeps the key private: it does not appear in logs, error messages or `console.log(client)`. The SDK sends no telemetry.
27
+ `status` shows how much of your free allowance you have used, and your purchased balance. A $0 purchased balance is fine while free allowance remains.
28
+
29
+ Keys from the test period no longer work. The [Quickstart](https://flovia.dev/docs/quickstart) has the full steps, and [Free and paid use](https://flovia.dev/docs/usage) explains the limits. If the invitation is missing or you lose your key, [contact Flovia](https://flovia.dev/contact). Installing this package does not create an account or start a free allowance.
30
+
31
+ In code, the client reads `FLOVIA_KEY`, or you can pass it as `new FloviaClient({ apiKey })`. The client keeps the key private: it does not appear in logs, error messages or `console.log(client)`. The SDK sends no telemetry.
27
32
 
28
33
  `baseUrl` requires HTTPS. Plain HTTP is allowed only for loopback development (`localhost`, `127.0.0.1`, `[::1]`). Raw transport diagnostics are not attached to errors because they may contain request headers.
29
34
 
@@ -34,7 +39,7 @@ import { FloviaClient, newOperationId } from "@flovialabs/sdk";
34
39
 
35
40
  const flovia = new FloviaClient(); // reads FLOVIA_KEY; base URL https://api.flovia.dev
36
41
 
37
- // Your free windows, services and the contract version
42
+ // Your free allowance windows, services and the contract version
38
43
  const status = await flovia.status();
39
44
  console.log(status.five_hour.used_pct, status.week.used_pct);
40
45
 
@@ -45,7 +50,7 @@ const usage = await flovia.usageToday(); // today, UTC
45
50
  const tools = await flovia.listTools();
46
51
  const reply = await flovia.call("flovia_status");
47
52
 
48
- // A text generation (uses credits). Save the operation id before sending.
53
+ // A text generation (uses your free allowance first, then your purchased balance). Save the operation id before sending.
49
54
  const op = newOperationId();
50
55
  const request = { model: "gpt-6-luna" as const, input: "Explain a DEX aggregator in one sentence.", reasoning: { effort: "low" as const } };
51
56
  // Persist { op, request } in your application's private storage before the next line.
@@ -66,12 +71,93 @@ const priceRequest = {
66
71
  request_text: "What is Bitcoin's USD price?", purpose: "check a price with its update time",
67
72
  conversation_id: "sdk-price-example", operation_id: newOperationId(),
68
73
  };
69
- // Save priceRequest before sending; this lookup uses the shared allowance.
74
+ // Save priceRequest before sending; this lookup uses your free allowance or purchased balance.
70
75
  const price = await flovia.call("flovia_coingecko", priceRequest);
71
76
  ```
72
77
 
73
78
  If either call asks for a notice or consent, stop and follow the human-answer flow below. Read the returned source time, coverage and missing-value notes; a successful lookup is not a guarantee that it answers your question. Flovia exposes selected read-only paths, methods and public HTML hosts, not every feature of the upstream plans. Use the live catalog for the supported subset. OpenAI supports text generation with `gpt-6-luna`; it does not fetch other providers or offer image/audio generation.
74
79
 
80
+ ### Run one result, display it, then reopen it
81
+
82
+ Save this complete example as `first-price.mjs` beside your `node_modules`. Keep it server-side or on your own machine.
83
+
84
+ ```js
85
+ // Run on your own machine. Never bundle this file, FLOVIA_KEY or private usage into a browser app.
86
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
87
+ import { pathToFileURL } from "node:url";
88
+ import { FloviaClient, FloviaError, newOperationId } from "@flovialabs/sdk";
89
+
90
+ const mode = process.argv[2];
91
+ if (!["--new", "--replay", "--saved"].includes(mode)) {
92
+ console.error("Use --new once, --replay with the saved request, or --saved (no network).");
93
+ process.exit(1);
94
+ }
95
+ const directory = new URL("./.flovia-price/", pathToFileURL(process.cwd() + "/"));
96
+ const requestFile = new URL("request.json", directory);
97
+ const answerFile = new URL("answer.json", directory);
98
+
99
+ try {
100
+ let reply;
101
+ if (mode === "--saved") {
102
+ reply = JSON.parse(await readFile(answerFile, "utf8"));
103
+ } else {
104
+ const client = new FloviaClient();
105
+ if (mode === "--new") {
106
+ await mkdir(directory, { mode: 0o700 });
107
+ const request = {
108
+ path: "/simple/price",
109
+ query: { ids: "bitcoin", vs_currencies: "usd", include_last_updated_at: true },
110
+ request_text: "What is Bitcoin's USD price?",
111
+ purpose: "display one price with its source update time",
112
+ conversation_id: "sdk-first-price",
113
+ operation_id: newOperationId(),
114
+ };
115
+ // Exclusive creation: rerunning --new cannot silently replace the operation that might have run.
116
+ await writeFile(requestFile, JSON.stringify(request), { mode: 0o600, flag: "wx" });
117
+ await client.status(); // Account/allowance read only; stop on authentication errors.
118
+ }
119
+ const request = JSON.parse(await readFile(requestFile, "utf8"));
120
+ reply = await client.call("flovia_coingecko", request);
121
+ await writeFile(answerFile, JSON.stringify(reply), { mode: 0o600 });
122
+ }
123
+ const price = JSON.parse(reply.response).bitcoin;
124
+ const updated = price?.last_updated_at;
125
+ console.log(JSON.stringify({
126
+ display: mode === "--saved" ? "Saved locally; not a live update" : reply.stored_answer ? "Earlier answer; not a live update" : "Fetched once; not auto-updating",
127
+ btc_usd: price?.usd ?? null,
128
+ provider_updated_at: Number.isFinite(updated) ? new Date(updated * 1000).toISOString() : null,
129
+ flovia_received_at: reply.created_at ?? null,
130
+ lookup_id: reply.lookup_id ?? null,
131
+ charge_guidance: mode === "--saved" ? "Nothing: this display is offline; see the original lookup in private usage"
132
+ : reply.for_user?.charged_to_you ?? "Unavailable; do not assume zero",
133
+ attribution: "Data provided by CoinGecko",
134
+ }, null, 2));
135
+ } catch (error) {
136
+ if (error instanceof FloviaError) {
137
+ console.error(JSON.stringify({ code: error.code, executed: error.executed, operation_id: error.operationId, next_step: error.nextStep }));
138
+ } else {
139
+ console.error("Could not read, save or display the example. Keep .flovia-price unchanged; do not start a new operation to recover it.");
140
+ }
141
+ // No automatic resend, consent answer or replacement operation, including on pending/unknown or an expired saved answer.
142
+ process.exitCode = 1;
143
+ }
144
+ ```
145
+
146
+ After installing this SDK and setting `FLOVIA_KEY` privately, run:
147
+
148
+ ```sh
149
+ # One new CoinGecko lookup; uses your free allowance or purchased balance.
150
+ node first-price.mjs --new
151
+ # Same request and operation id; reopen promptly, while the saved answer is available.
152
+ node first-price.mjs --replay
153
+ # Display the local answer without any API request.
154
+ node first-price.mjs --saved
155
+ ```
156
+
157
+ The example saves the request and operation id **before** sending, in `.flovia-price/request.json` (0600 inside a 0700 directory), and the returned answer in `answer.json` (0600). Keep this directory private and out of Git. Repeating `--new` refuses to overwrite it. Do not delete it or change the id to recover a lost answer. `--replay` sends the saved arguments unchanged; if the saved text is unavailable or the outcome is pending/unknown, follow the error's `next_step` instead of making a new request. A notice or consent refusal needs the person's answer; this script never supplies one.
158
+
159
+ The displayed result separates the USD price, CoinGecko's update time, Flovia's original receipt time, lookup id and the server's charge guidance. Unknown values stay `null`; missing cost is not zero. A replay or local saved display is labelled as such and never presented as a live update. For period usage, run `npx flovia usage` separately; it is your private account data, not the cost of this one result. A browser demo may display the public price and attribution from your server, but must not expose the Flovia key, private reply files or account usage, or offer an unauthenticated refresh endpoint that spends your allowance. The example does not auto-refresh. Follow the provider's attribution and redistribution terms.
160
+
75
161
  ### Thinking effort
76
162
 
77
163
  For Luna, set `reasoning.effort` to `none`, `low`, `medium`, `high`, `xhigh` or `max`; omitting it keeps Flovia's `none` default. Higher effort can take longer and use more reasoning tokens. Those tokens share `max_output_tokens` with the visible answer, so an answer may be shorter or `incomplete`. The default output limit remains 1,000, with an explicit maximum of 4,000. Effort does not raise Flovia's per-request spending cap or guarantee a better answer. Save the effort with the rest of the request; changing it under the same operation id is a different request and is refused.
@@ -80,7 +166,7 @@ For Luna, set `reasoning.effort` to `none`, `low`, `medium`, `high`, `xhigh` or
80
166
 
81
167
  `generate()` requires an operation id (8-128 characters of `A-Z a-z 0-9 _ . : -`). Create one with `newOperationId()` and store it with the request **before** sending.
82
168
 
83
- If the reply is lost (timeout, network error, `executed: "unknown"`), keep the request and **same** id. A completed or incomplete answer can normally be reopened for about **15 minutes** with the unchanged request, `replayed: true` and no additional charge. Follow `nextStep` for `operation_pending` or `upstream_unknown`; the answer may not yet be available. After `answer_expired` or `operation_retired`, Flovia cannot return the saved text. Never start a new id to recover a lost answer: that may run and charge twice. A genuinely new generation requires the person's decision to spend again.
169
+ If the reply is lost (timeout, network error, `executed: "unknown"`), keep the request and **same** id. A completed or incomplete answer can normally be reopened for about **15 minutes** with the unchanged request, `replayed: true` and no additional charge. Follow `nextStep` for `generation_pending` or `generation_unknown`; the answer may not be available yet. After `answer_expired` or `operation_retired`, Flovia cannot return the saved text. Never start a new id to recover a lost answer: that may run and charge twice. A genuinely new generation requires the person's decision to spend again.
84
170
 
85
171
  ## Errors
86
172
 
@@ -97,6 +183,8 @@ A refusal (`ok: false`) or a failed request throws `FloviaError`:
97
183
  | `operationId` | the operation id of the request |
98
184
  | `reply` | the full reply body |
99
185
 
186
+ HTTP 401 with `code: "formal_registration_required"` means test access ended: complete formal registration from the invitation email, then reconnect through Console. A generic `unauthorized` means the key was not accepted; check your account and current key in Console. Both are unsent (`executed: "no"`) and are never retried automatically. The SDK does not expose arbitrary authentication response bodies.
187
+
100
188
  ### `notice_first` and `data_consent_needed`: a human must answer
101
189
 
102
190
  These two codes are thrown on purpose. They need the person's own answer, and the SDK never answers for them.
@@ -140,7 +228,7 @@ npx flovia generate --op sdk-example-0001 --max-output 1000 --reasoning-effort l
140
228
  npx flovia help
141
229
  npx flovia --version
142
230
  ```
143
- These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.4 flovia --help`. Use a unique operation id for each new request; `sdk-example-0001` is only an example. Save the id, prompt and options before sending, and keep them unchanged for replay.
231
+ These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.6 flovia --help`. Use a unique operation id for each new request; `sdk-example-0001` is only an example. Save the id, prompt and options before sending, and keep them unchanged for replay.
144
232
 
145
233
  Get or manage your key in [Console](https://console.flovia.dev/groupbuy/), save it privately, then run `flovia status --key-file <saved-key-file>`. A connected key can still have sharing declined, withdrawn or stopped; `status` shows those separately from provider availability. It never answers consent for you.
146
234
 
@@ -154,10 +242,10 @@ flovia generate --op <saved-id> --max-output 1000 --reasoning-effort high --yes
154
242
 
155
243
  Keep the same `--key-file` and `--base-url` too. For a prompt starting with a hyphen, use `--` before the prompt. Long answers can take minutes; an interactive terminal shows elapsed time on stderr. Piped and JSON output stays unchanged. A timeout does not prove that nothing ran: never recover by repeating `--new-op`. Partial answers are delivered and settled, but the CLI never generates a continuation automatically. The HTTP reply does not include exact Flovia cost; use `flovia usage` for period totals, which are not the price of this one answer. A replay adds no charge.
156
244
 
157
- `status` shows bought balance. `usage` shows lookup counts, free percentages and server-provided bought totals; its generation subtotal is already included in the period total. Missing amounts show `-`, not zero. It does not add rounded endpoint percentages. To continue a listing, copy the printed command with its exact `--since` and `--cursor`; do not combine `--days` with `--cursor`.
245
+ `status` shows your purchased balance. `usage` shows lookup counts, free allowance percentages and the purchased-balance totals from the server; its generation subtotal is already included in the period total. Missing amounts show `-`, not zero. It does not add rounded endpoint percentages. To continue a listing, copy the printed command with its exact `--since` and `--cursor`; do not combine `--days` with `--cursor`.
158
246
 
159
247
  - Every command takes `--json` (the raw reply), `--base-url URL`, `--timeout SECONDS` and `--key-file PATH`.
160
- - `generate` uses credits. It needs `--op ID` or `--new-op`, and asks for confirmation on a terminal; add `--yes` in scripts.
248
+ - `generate` uses your free allowance first, then your purchased balance. It needs `--op ID` or `--new-op`, and asks for confirmation on a terminal; add `--yes` in scripts.
161
249
  - `generate` prints the response status and incomplete reason. `incomplete` / `max_output_tokens` means the delivered text stopped at the output limit, not that a continuation ran. Exit 0 means the response was delivered, not that the text is complete or correct. `--json` retains the full public response.
162
250
  - Exit codes: 0 ok, 1 an error from Flovia, 2 a usage error.
163
251
 
package/dist/cli.js CHANGED
@@ -16,7 +16,7 @@ const COMMANDS = {
16
16
  usage: { usage: "usage [--since ISO | --days N] [--cursor C]", about: "lookups and generations (today, or since a time within 7 days)", flags: { "--since": true, "--days": true, "--cursor": true } },
17
17
  tools: { usage: "tools", about: "the tools this key is offered", flags: {} },
18
18
  call: { usage: "call <tool> ['<json args>']", about: "call any tool and print its reply", flags: {} },
19
- generate: { usage: "generate (--op ID | --new-op) [--max-output N]\n [--reasoning-effort LEVEL] [--yes] <prompt | ->", about: "a text generation (uses credits)", flags: { "--op": true, "--new-op": false, "--max-output": true, "--reasoning-effort": true, "--yes": false } },
19
+ generate: { usage: "generate (--op ID | --new-op) [--max-output N]\n [--reasoning-effort LEVEL] [--yes] <prompt | ->", about: "a text generation (uses your free allowance, then your purchased balance)", flags: { "--op": true, "--new-op": false, "--max-output": true, "--reasoning-effort": true, "--yes": false } },
20
20
  help: { usage: "help [command]", about: "this help", flags: {} },
21
21
  version: { usage: "version", about: "the installed CLI version", flags: {} },
22
22
  };
@@ -44,7 +44,7 @@ export function help(command) {
44
44
  lines.push("", "Default output limit: 1000 tokens; maximum: 4000.", "--reasoning-effort: none (default), low, medium, high, xhigh, max.", "Reasoning shares the output token limit; higher effort can leave less visible text.", "Long answers can take minutes. Save the id, same input, output limit and effort.", " flovia generate --new-op --reasoning-effort high --yes - < prompt.txt", "Replay only: replace --new-op with --op <saved-id>; keep everything else.", "Use -- before a prompt that starts with a hyphen.");
45
45
  if (command === "tools" || c === undefined)
46
46
  lines.push("", "Inspect tool arguments: flovia tools --json", "Read-only example: flovia call flovia_status '{}'");
47
- lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 relay error, 2 usage error.", "");
47
+ lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 error from Flovia, 2 usage error.", "");
48
48
  return lines.join("\n");
49
49
  }
50
50
  export function parse(argv) {
@@ -141,6 +141,8 @@ export function when(v, now = Date.now()) {
141
141
  const obj = (v) => v !== null && typeof v === "object" ? v : {};
142
142
  /** Wrap prose only, never prompts, answers, consent notices, JSON or copyable commands. */
143
143
  const prose = (text) => (text.match(/.{1,76}(?:\s|$)|\S+/g) ?? []).map((line) => line.trim()).join("\n ");
144
+ /** Status labels share one column; the longest is "purchased balance". */
145
+ const label = (name) => name.padEnd(19);
144
146
  export function renderStatus(s, expected, now = Date.now()) {
145
147
  const lines = ["Connection: OK", `Flovia ${s.stage}, contract ${s.contract_version}`];
146
148
  if (expected !== null)
@@ -158,15 +160,15 @@ export function renderStatus(s, expected, now = Date.now()) {
158
160
  lines.push("Data consent: accepted. Service and allowance limits still apply.");
159
161
  else
160
162
  lines.push("Data consent: not reported (see --json).");
161
- for (const [label, w] of [["5-hour window", s.five_hour], ["week", s.week]])
162
- lines.push(`${label.padEnd(14)} ${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : label === "5-hour window" ? ", not started" : ""}`);
163
- lines.push(`bought balance ${String(s["purchased_balance_display"] ?? "-")}`);
163
+ for (const [name, w] of [["free 5-hour", s.five_hour], ["free week", s.week]])
164
+ lines.push(`${label(name)}${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : name === "free 5-hour" ? ", not started" : ""}`);
165
+ lines.push(`${label("purchased balance")}${String(s["purchased_balance_display"] ?? "-")}`);
164
166
  const pending = obj(s["free_pending"]);
165
167
  if (pending["next_step"])
166
- lines.push(`usage allowance not started: ${String(pending["next_step"])}`);
168
+ lines.push(`free allowance not started: ${String(pending["next_step"])}`);
167
169
  const services = Object.entries(obj(s["services"])).map(([name, v]) => { const x = obj(v); return `${name} ${String(x["state"] ?? "?")}${x["until"] ? ` until ${when(x["until"], now)}` : ""}`; });
168
- lines.push("services (provider state)", ...services.map((v) => ` ${v}`));
169
- lines.push(`turned off ${s.services_off.length ? s.services_off.join(", ") : "none"}`);
170
+ lines.push(`${label("services")}(provider state)`, ...services.map((v) => ` ${v}`));
171
+ lines.push(`${label("turned off")}${s.services_off.length ? s.services_off.join(", ") : "none"}`);
170
172
  const updates = Array.isArray(s["recent_updates"]) ? s["recent_updates"] : [];
171
173
  for (const u of updates.slice(0, 2)) {
172
174
  const x = obj(u), first = Array.isArray(x["lines"]) ? String(x["lines"][0] ?? "") : "";
@@ -179,9 +181,9 @@ export function renderStatus(s, expected, now = Date.now()) {
179
181
  export function renderUsage(u, today = false, now = Date.now()) {
180
182
  const lines = [`since ${when(u["since"], now)} until ${when(u["until"], now)}${today ? " (today, UTC; use --days 7 for the week)" : ""}`];
181
183
  const week = obj(u["free_week"]);
182
- lines.push(`week allocation: ${pct(week["used_pct"])} used${week["resets_at"] ? `, resets ${when(week["resets_at"], now)}` : ""}`);
183
- lines.push(`total in this period: ${String(obj(u["total"])["free_display"] ?? "-")} of the weekly allocation, ${String(u["count"] ?? 0)} lookups`);
184
- lines.push(`bought credits used: ${String(obj(u["total"])["bought_display"] ?? "-")} total (includes generations)`);
184
+ lines.push(`free allowance this week: ${pct(week["used_pct"])} used${week["resets_at"] ? `, resets ${when(week["resets_at"], now)}` : ""}`);
185
+ lines.push(`total in this period: ${String(obj(u["total"])["free_display"] ?? "-")} of the weekly free allowance, ${String(u["count"] ?? 0)} ${u["count"] === 1 ? "lookup" : "lookups"}`);
186
+ lines.push(`purchased balance used: ${String(obj(u["total"])["bought_display"] ?? "-")} total (includes generations)`);
185
187
  // Endpoint percentages are rounded (0 can mean <1%); only counts can be summed by source.
186
188
  const bySource = new Map();
187
189
  for (const e of Array.isArray(u["by_endpoint"]) ? u["by_endpoint"] : []) {
@@ -191,7 +193,7 @@ export function renderUsage(u, today = false, now = Date.now()) {
191
193
  if (bySource.size)
192
194
  lines.push("", table([["source", "lookups"], ...[...bySource].map(([n, count]) => [n, String(count)])]).trimEnd());
193
195
  const g = obj(u["generations"]);
194
- lines.push("", `generations: ${String(g["operations"] ?? 0)} (completed ${String(g["completed"] ?? 0)}, incomplete ${String(g["incomplete"] ?? 0)}, unknown ${String(g["unknown"] ?? 0)}), ${String(g["free_display"] ?? "-")} of the weekly allocation, bought ${String(g["bought_display"] ?? "-")} (included in total)`);
196
+ lines.push("", `generations: ${String(g["operations"] ?? 0)} (completed ${String(g["completed"] ?? 0)}, incomplete ${String(g["incomplete"] ?? 0)}, unknown ${String(g["unknown"] ?? 0)}), ${String(g["free_display"] ?? "-")} of the weekly free allowance, purchased ${String(g["bought_display"] ?? "-")} (included in total)`);
195
197
  if (u.has_more)
196
198
  lines.push("", `more lookups: rerun flovia usage with the same --key-file and --base-url options, adding --since ${String(u["since"])} --cursor ${String(u.next_cursor)}`);
197
199
  return lines.join("\n") + "\n";
@@ -199,15 +201,15 @@ export function renderUsage(u, today = false, now = Date.now()) {
199
201
  /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
200
202
  export function renderError(e) {
201
203
  const lines = [`error: ${e.code}: ${e.message}`];
202
- if (e.code === "unauthorized")
203
- lines.push(`Check your key in ${CONSOLE}`, "Then: flovia status --key-file <saved-key-file>", "Keep the same --base-url if you selected another relay.");
204
204
  if (e.nextStep)
205
205
  lines.push(`next_step: ${e.nextStep}`);
206
+ if (e.code === "unauthorized")
207
+ lines.push("After you save a current key, check it: flovia status --key-file <saved-key-file>");
206
208
  lines.push(`executed: ${e.executed}`);
207
209
  if (e.retryAfterSeconds !== null)
208
210
  lines.push(`retry_after_seconds: ${e.retryAfterSeconds}`);
209
211
  if (e.operationId)
210
- lines.push(`operation_id: ${e.operationId}${e.executed === "unknown" ? " (resend with this same id; never a new one)" : ""}`);
212
+ lines.push(`operation_id: ${e.operationId}${e.executed === "unknown" ? " (keep this id; never send the request again under a new one)" : ""}`);
211
213
  const reply = obj(e.reply);
212
214
  if (e.code === "notice_first" || e.code === "data_consent_needed") {
213
215
  if (reply["user_notice"])
@@ -222,7 +224,11 @@ export function renderError(e) {
222
224
  export async function run(argv, io) {
223
225
  let key = null;
224
226
  // Belt and braces: whatever is printed passes through here, so the key cannot appear even if a reply or error echoed it.
225
- const scrub = (s) => key === null ? s : s.replaceAll(key, "[key]");
227
+ const accessToken = io.env["FLOVIA_ACCESS_TOKEN"]?.trim();
228
+ const scrub = (s) => {
229
+ const masked = key === null ? s : s.replaceAll(key, "[key]");
230
+ return accessToken ? masked.replaceAll(accessToken, "[access-token]") : masked;
231
+ };
226
232
  const out = (s) => io.out(scrub(s)), err = (s) => io.err(scrub(s));
227
233
  let p;
228
234
  try {
@@ -235,7 +241,6 @@ export async function run(argv, io) {
235
241
  out(`flovia ${VERSION}\n`);
236
242
  return 0;
237
243
  }
238
- key = await readKey(p, io);
239
244
  }
240
245
  catch (e) {
241
246
  if (e instanceof Usage) {
@@ -245,17 +250,31 @@ export async function run(argv, io) {
245
250
  throw e;
246
251
  }
247
252
  const json = p.flags.has("--json"), print = (v) => out(JSON.stringify(v, null, 2) + "\n");
253
+ const waitFor = async (request) => {
254
+ const stop = json ? undefined : io.waiting?.();
255
+ try {
256
+ return await request();
257
+ }
258
+ finally {
259
+ stop?.();
260
+ }
261
+ };
248
262
  let mismatch = null;
249
263
  let recoveryLimit;
250
264
  let recoveryEffort;
251
265
  try {
252
266
  const timeout = positiveInt("--timeout", str(p.flags.get("--timeout")));
253
267
  const baseUrl = str(p.flags.get("--base-url"));
254
- const client = new FloviaClient({ apiKey: key, ...(baseUrl !== undefined ? { baseUrl } : {}), ...(timeout ? { timeoutMs: timeout * 1000 } : {}),
255
- ...(io.fetch ? { fetch: io.fetch } : {}), onContractMismatch: (expected) => { mismatch = expected; } });
268
+ // The key is read only after the command's own arguments are checked, so a usage mistake shows the usage line first.
269
+ const connect = async () => {
270
+ key = await readKey(p, io);
271
+ return new FloviaClient({ apiKey: key, ...(baseUrl !== undefined ? { baseUrl } : {}), ...(timeout ? { timeoutMs: timeout * 1000 } : {}),
272
+ ...(accessToken ? { accessToken } : {}),
273
+ ...(io.fetch ? { fetch: io.fetch } : {}), onContractMismatch: (expected) => { mismatch = expected; } });
274
+ };
256
275
  switch (p.command) {
257
276
  case "status": {
258
- const s = await client.status();
277
+ const client = await connect(), s = await waitFor(() => client.status());
259
278
  if (json)
260
279
  print(s);
261
280
  else
@@ -274,7 +293,7 @@ export async function run(argv, io) {
274
293
  throw new Usage("--since must be an ISO 8601 time");
275
294
  // A minute's margin so --days 7 stays inside the relay's 7 days by the time it arrives.
276
295
  const from = days === undefined ? since : new Date((io.now ?? Date.now)() - days * 86_400_000 + 60_000).toISOString();
277
- const u = await client.usageToday({ ...(from ? { since: from } : {}), ...(cursor ? { cursor } : {}) });
296
+ const client = await connect(), u = await waitFor(() => client.usageToday({ ...(from ? { since: from } : {}), ...(cursor ? { cursor } : {}) }));
278
297
  if (json)
279
298
  print(u);
280
299
  else
@@ -282,7 +301,7 @@ export async function run(argv, io) {
282
301
  return 0;
283
302
  }
284
303
  case "tools": {
285
- const tools = await client.listTools();
304
+ const client = await connect(), tools = await waitFor(() => client.listTools());
286
305
  if (json)
287
306
  print(tools);
288
307
  else
@@ -303,7 +322,8 @@ export async function run(argv, io) {
303
322
  }
304
323
  if (args === null || typeof args !== "object" || Array.isArray(args))
305
324
  throw new Usage("call: the arguments must be a JSON object");
306
- print(await client.call(tool, args));
325
+ const client = await connect();
326
+ print(await waitFor(() => client.call(tool, args)));
307
327
  return 0;
308
328
  }
309
329
  case "generate": {
@@ -313,18 +333,19 @@ export async function run(argv, io) {
313
333
  const [text, extra] = p.positional;
314
334
  if (text === undefined || extra !== undefined)
315
335
  throw new Usage(`Usage: flovia ${COMMANDS["generate"]?.usage}`);
336
+ const max = positiveInt("--max-output", str(p.flags.get("--max-output")));
337
+ const effort = reasoningEffort(str(p.flags.get("--reasoning-effort")));
338
+ const client = await connect();
316
339
  const input = text === "-" ? await io.readStdin() : text;
317
340
  if (input.trim() === "")
318
341
  throw new Usage("generate: the prompt is empty");
319
- const max = positiveInt("--max-output", str(p.flags.get("--max-output")));
320
- const effort = reasoningEffort(str(p.flags.get("--reasoning-effort")));
321
342
  recoveryLimit = max;
322
343
  recoveryEffort = effort;
323
344
  const id = op ?? newOperationId();
324
345
  // The id is shown before anything is sent, so a lost reply can be reopened with it (never resent under a new one).
325
346
  if (fresh)
326
347
  err(`operation_id: ${id}\nSave it. To resend or reopen this request, use: --op ${id}\n`);
327
- err("This generation uses Flovia credits (usage allowance first, then bought credits).\nSame --op, same input, output limit and effort: saved answers are free for about 15 minutes.\nPending, unknown or expired answers: never replace them with a new id.\n");
348
+ err("This generation uses your free allowance first, then your purchased balance.\nIf the reply is lost, rerun with the same --op, prompt, output limit and effort.\nA saved answer comes back free for about 15 minutes. Never use a new id to recover an answer.\n");
328
349
  if (!p.flags.has("--yes")) {
329
350
  if (io.confirm === null || text === "-")
330
351
  throw new Usage("generate: add --yes to send (no terminal to confirm on)");
@@ -333,14 +354,7 @@ export async function run(argv, io) {
333
354
  return 2;
334
355
  }
335
356
  }
336
- const stopWaiting = json ? undefined : io.waiting?.();
337
- let g;
338
- try {
339
- g = await client.generate({ model: "gpt-6-luna", input, ...(max ? { max_output_tokens: max } : {}), ...(effort ? { reasoning: { effort } } : {}) }, { operationId: id });
340
- }
341
- finally {
342
- stopWaiting?.();
343
- }
357
+ const g = await waitFor(() => client.generate({ model: "gpt-6-luna", input, ...(max ? { max_output_tokens: max } : {}), ...(effort ? { reasoning: { effort } } : {}) }, { operationId: id }));
344
358
  const reason = obj(g.response["incomplete_details"])["reason"];
345
359
  if (json)
346
360
  print(g);
@@ -371,7 +385,7 @@ export async function run(argv, io) {
371
385
  print(e.reply);
372
386
  err(renderError(e));
373
387
  if (p.command === "generate" && e.operationId && e.executed === "unknown")
374
- err(`Recovery: keep the same input, ${recoveryLimit === undefined ? "omit --max-output as before" : `--max-output ${recoveryLimit}`} and ${recoveryEffort === undefined ? "omit --reasoning-effort as before" : `--reasoning-effort ${recoveryEffort}`} with --op ${e.operationId}.\nUse the original prompt file and the same --key-file / --base-url.\nDo not rerun --new-op or create a different request to recover this answer.\n`);
388
+ err(`To recover: rerun with --op ${e.operationId}, the same prompt or prompt file, ${recoveryLimit === undefined ? "no --max-output" : `--max-output ${recoveryLimit}`}, ${recoveryEffort === undefined ? "no --reasoning-effort" : `--reasoning-effort ${recoveryEffort}`},\nand the same --key-file and --base-url. Do not use --new-op or change the request; that can charge again.\n`);
375
389
  return e.code === "invalid_base_url" ? 2 : 1;
376
390
  }
377
391
  err(`error: ${e instanceof Error ? e.message : String(e)}\n`);
@@ -410,7 +424,7 @@ if (isMain) {
410
424
  confirm: tty ? confirm : null,
411
425
  ...(process.stderr.isTTY ? { waiting: () => {
412
426
  const start = Date.now();
413
- process.stderr.write("Waiting for Flovia; long answers can take minutes.\n");
427
+ process.stderr.write("Waiting for Flovia.\n");
414
428
  const timer = setInterval(() => process.stderr.write(`Waiting for Flovia (${Math.floor((Date.now() - start) / 1000)}s elapsed).\n`), 5000);
415
429
  timer.unref();
416
430
  return () => clearInterval(timer);
package/dist/client.d.ts CHANGED
@@ -4,6 +4,8 @@ export interface FloviaClientOptions {
4
4
  apiKey?: string;
5
5
  /** Defaults to https://api.flovia.dev. */
6
6
  baseUrl?: string;
7
+ /** Cloudflare Access JWT for the private dev relay. Never sent to other origins. */
8
+ accessToken?: string;
7
9
  /** Per request, in milliseconds. Defaults to 300 s: a long generation takes minutes. */
8
10
  timeoutMs?: number;
9
11
  fetch?: (request: Request) => Promise<Response>;
package/dist/client.js CHANGED
@@ -33,6 +33,7 @@ async function readReply(r, operationId, makeError, sse = false) {
33
33
  export class FloviaClient {
34
34
  #key;
35
35
  #base;
36
+ #accessToken;
36
37
  #timeoutMs;
37
38
  #fetch;
38
39
  #resend;
@@ -56,6 +57,9 @@ export class FloviaClient {
56
57
  if (url.protocol !== "https:" && !(url.protocol === "http:" && local))
57
58
  throw new FloviaError({ code: "invalid_base_url", executed: "no", message: "baseUrl / --base-url must be https (plain http only for localhost, 127.0.0.1 or [::1])." });
58
59
  this.#base = base.replace(/\/+$/, "");
60
+ if (options.accessToken && (url.origin !== "https://dev.api.flovia.dev" || url.username || url.password))
61
+ throw new FloviaError({ code: "invalid_base_url", executed: "no", message: "accessToken requires https://dev.api.flovia.dev." });
62
+ this.#accessToken = options.accessToken;
59
63
  this.#timeoutMs = options.timeoutMs ?? 300_000;
60
64
  this.#fetch = options.fetch ?? ((r) => fetch(r));
61
65
  this.#resend = options.retryRateLimited ?? false;
@@ -64,7 +68,10 @@ export class FloviaClient {
64
68
  }
65
69
  /** Mask only this client's exact key in diagnostic strings and reply field names; keep Error field names intact. */
66
70
  #error(init) {
67
- const scrub = (text) => text.replaceAll(this.#key, "[key]");
71
+ const scrub = (text) => {
72
+ const masked = text.replaceAll(this.#key, "[key]");
73
+ return this.#accessToken ? masked.replaceAll(this.#accessToken, "[access-token]") : masked;
74
+ };
68
75
  const safe = JSON.parse(JSON.stringify(init, (_name, value) => typeof value === "string" ? scrub(value) : value !== init && value !== null && typeof value === "object" && !Array.isArray(value)
69
76
  ? Object.fromEntries(Object.entries(value).map(([name, field]) => [scrub(name), field])) : value));
70
77
  return new FloviaError(safe);
@@ -73,19 +80,27 @@ export class FloviaClient {
73
80
  async #send(path, body, headers = {}, operationId = null) {
74
81
  let r;
75
82
  try {
76
- const request = new Request(this.#base + path, { method: "POST", body: JSON.stringify(body), signal: AbortSignal.timeout(this.#timeoutMs),
77
- headers: { Authorization: `Bearer ${this.#key}`, "Content-Type": "application/json", ...headers } });
83
+ const request = new Request(this.#base + path, { method: "POST", redirect: "error", body: JSON.stringify(body), signal: AbortSignal.timeout(this.#timeoutMs),
84
+ headers: { Authorization: `Bearer ${this.#key}`, "Content-Type": "application/json", ...headers,
85
+ ...(this.#accessToken ? { "Cf-Access-Token": this.#accessToken } : {}) } });
78
86
  r = await this.#fetch(request);
79
87
  }
80
88
  catch (cause) {
81
89
  const timeout = cause instanceof Error && cause.name === "TimeoutError";
82
90
  // Transport diagnostics may contain request headers, so never attach their raw cause.
83
91
  throw this.#error({ code: timeout ? "timeout" : "network_error", executed: "unknown", operationId,
84
- message: timeout ? `No reply within ${this.#timeoutMs} ms.` : "The request did not complete.",
85
- nextStep: operationId ? SAME_OPERATION : null });
92
+ message: timeout ? `No reply within ${this.#timeoutMs / 1000} seconds.` : "The request did not complete.",
93
+ nextStep: operationId ? SAME_OPERATION : "The request may have reached Flovia. Check your usage before you send it again." });
94
+ }
95
+ if (r.status === 401) {
96
+ // Recognize only the public auth code; never attach an arbitrary proxy body, diagnostic or reflected credential.
97
+ const auth = await r.json().catch(() => null);
98
+ const formal = auth !== null && typeof auth === "object" && "error" in auth && auth.error === "formal_registration_required";
99
+ throw this.#error({ code: formal ? "formal_registration_required" : "unauthorized", status: 401, executed: "no", operationId,
100
+ message: formal ? "Test access has ended. API keys issued during the test no longer work." : "The Flovia key was not accepted.",
101
+ nextStep: formal ? "Complete formal registration from your invitation email, then open https://console.flovia.dev/auth/ to connect your app again."
102
+ : "Open https://console.flovia.dev/groupbuy/ to check your account and get a current key. Do not resend with the same key." });
86
103
  }
87
- if (r.status === 401)
88
- throw new FloviaError({ code: "unauthorized", status: 401, executed: "no", message: "The Flovia key was not accepted." });
89
104
  return r;
90
105
  }
91
106
  async #rpc(method, params, operationId = null) {
@@ -140,7 +155,8 @@ export class FloviaClient {
140
155
  const s = await this.call("flovia_status");
141
156
  if (!this.#warned && s.contract_version !== EXPECTED_CONTRACT_VERSION) {
142
157
  this.#warned = true;
143
- this.#onMismatch(EXPECTED_CONTRACT_VERSION, String(s.contract_version).replaceAll(this.#key, "[key]"));
158
+ const version = String(s.contract_version).replaceAll(this.#key, "[key]");
159
+ this.#onMismatch(EXPECTED_CONTRACT_VERSION, this.#accessToken ? version.replaceAll(this.#accessToken, "[access-token]") : version);
144
160
  }
145
161
  return s;
146
162
  }
package/dist/types.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** The relay's tool contract this SDK was written against (flovia_status.contract_version). */
2
- export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.120";
2
+ export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.134";
3
3
  /** Every public explanation.code (the relay's contract). A provider's own HTTP error is `http_<status>`. */
4
- export declare const PUBLIC_CODES: readonly ["key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first", "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large", "answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long", "over_max_credits", "cost_confirmation_needed", "window_5h", "window_week", "over_week", "free_limited", "free_needs_email", "global_cap", "flovia_paused", "free_paused", "rate_limited", "too_many_in_parallel", "reservation_changed", "operation_conflict", "operation_pending", "upstream_unknown", "upstream_unavailable", "replay_response_unavailable", "rpc_error", "unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off"];
4
+ export declare const PUBLIC_CODES: readonly ["approval_pending", "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first", "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large", "answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long", "over_max_credits", "window_5h", "window_week", "over_week", "free_limited", "free_needs_email", "global_cap", "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed", "operation_conflict", "operation_pending", "upstream_unknown", "upstream_unavailable", "replay_response_unavailable", "rpc_error", "unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off"];
5
5
  export type FloviaCode = (typeof PUBLIC_CODES)[number] | `http_${number}`;
6
6
  /** Whether the request ran upstream: "unknown" means keep the same operation_id and never send a replacement. */
7
7
  export type Executed = "yes" | "no" | "unknown";
@@ -26,7 +26,9 @@ export interface Window {
26
26
  used_pct: number;
27
27
  resets_at: string | null;
28
28
  }
29
- export type StatusArgs = Record<string, never>;
29
+ export type StatusArgs = {
30
+ about_sharing?: true;
31
+ };
30
32
  export interface StatusReply extends ToolReply {
31
33
  contract_version: string;
32
34
  stage: string;
package/dist/types.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /** The relay's tool contract this SDK was written against (flovia_status.contract_version). */
2
- export const EXPECTED_CONTRACT_VERSION = "2026-10-07.120";
2
+ export const EXPECTED_CONTRACT_VERSION = "2026-10-07.134";
3
3
  /** Every public explanation.code (the relay's contract). A provider's own HTTP error is `http_<status>`. */
4
4
  export const PUBLIC_CODES = [
5
- "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first",
5
+ "approval_pending", "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first",
6
6
  "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large",
7
7
  "answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long",
8
- "over_max_credits", "cost_confirmation_needed", "window_5h", "window_week", "over_week", "free_limited", "free_needs_email", "global_cap",
9
- "flovia_paused", "free_paused", "rate_limited", "too_many_in_parallel", "reservation_changed",
8
+ "over_max_credits", "window_5h", "window_week", "over_week", "free_limited", "free_needs_email", "global_cap",
9
+ "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed",
10
10
  "operation_conflict", "operation_pending", "upstream_unknown", "upstream_unavailable", "replay_response_unavailable", "rpc_error",
11
11
  "unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off",
12
12
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flovialabs/sdk",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "description": "TypeScript client and CLI for Flovia: MCP tools over HTTP and OpenAI-compatible generation. Zero dependencies.",
6
6
  "license": "MIT",