@flovialabs/sdk 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ - CLI status distinguishes a successful connection from declined sharing, withdrawal, stopped keys and consent that needs an answer.
6
+ - Unknown commands and options never echo the untrusted input. Prompts starting with a hyphen are accepted after `--`.
7
+ - Added `--version`, safe setup and authentication recovery steps, stdin examples and shorter help and tool listings.
8
+ - Interactive generation shows elapsed waiting time on stderr. Recovery keeps the same operation id, input and output limit; there are no automatic retries.
9
+ - Partial answers have a plain delivery explanation. Replay remains free; when a reply has no exact Flovia cost, the CLI says so and points to period usage rather than estimating it.
10
+
11
+ ## 0.1.1
12
+
13
+ - CLI generation output shows the response status and incomplete reason. A delivered partial answer still exits 0; no continuation is generated automatically.
14
+ - CLI status shows bought balance; usage shows server-provided bought totals and the generation subtotal without adding them twice. Free usage stays in percentages.
15
+ - Corrected consent, replay lifetime, onboarding and copyable usage examples in the README.
16
+
3
17
  ## 0.1.0
4
18
 
5
19
  First release. Flovia is in alpha; APIs may change.
package/README.md CHANGED
@@ -10,11 +10,13 @@ TypeScript client and command-line tool for [Flovia](https://api.flovia.dev). It
10
10
  ## Install
11
11
 
12
12
  ```sh
13
- npm install @flovialabs/sdk
13
+ npm install --save-exact @flovialabs/sdk@0.1.2
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
+
18
20
  Set your Flovia key (`flv_...`) in the environment:
19
21
 
20
22
  ```sh
@@ -28,7 +30,7 @@ Or pass it as `new FloviaClient({ apiKey })`. The client keeps the key private:
28
30
  ## Quick start
29
31
 
30
32
  ```ts
31
- import { FloviaClient, FloviaError, newOperationId } from "@flovialabs/sdk";
33
+ import { FloviaClient, newOperationId } from "@flovialabs/sdk";
32
34
 
33
35
  const flovia = new FloviaClient(); // reads FLOVIA_KEY; base URL https://api.flovia.dev
34
36
 
@@ -37,7 +39,7 @@ const status = await flovia.status();
37
39
  console.log(status.five_hour.used_pct, status.week.used_pct);
38
40
 
39
41
  // Your lookups today (or since a time within the last 7 days)
40
- const usage = await flovia.usageToday({ since: "2026-10-10T00:00:00Z" });
42
+ const usage = await flovia.usageToday(); // today, UTC
41
43
 
42
44
  // Any tool: list them, then call one
43
45
  const tools = await flovia.listTools();
@@ -45,15 +47,36 @@ const reply = await flovia.call("flovia_status");
45
47
 
46
48
  // A text generation (uses credits). Save the operation id before sending.
47
49
  const op = newOperationId();
48
- const g = await flovia.generate({ model: "gpt-6-luna", input: "Summarize this." }, { operationId: op });
49
- console.log(g.outputText);
50
+ const request = { model: "gpt-6-luna" as const, input: "Explain a DEX aggregator in one sentence." };
51
+ // Persist { op, request } in your application's private storage before the next line.
52
+ const g = await flovia.generate(request, { operationId: op });
53
+ console.log(g.response.status, g.response.incomplete_details, g.outputText);
50
54
  ```
51
55
 
56
+ ### First data lookup
57
+
58
+ `listTools()` returns the tools offered to your account and their `inputSchema`. A catalog call sends nothing to the data provider. For example, list CoinGecko paths, then make one price lookup:
59
+
60
+ ```ts
61
+ await flovia.call("flovia_coingecko", {
62
+ path: "list", request_text: "Which prices can I read?", purpose: "choose a supported path",
63
+ });
64
+ const priceRequest = {
65
+ path: "/simple/price", query: { ids: "bitcoin", vs_currencies: "usd", include_last_updated_at: true },
66
+ request_text: "What is Bitcoin's USD price?", purpose: "check a price with its update time",
67
+ conversation_id: "sdk-price-example", operation_id: newOperationId(),
68
+ };
69
+ // Save priceRequest before sending; this lookup uses the shared allowance.
70
+ const price = await flovia.call("flovia_coingecko", priceRequest);
71
+ ```
72
+
73
+ 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
+
52
75
  ### Operation ids and replay
53
76
 
54
77
  `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.
55
78
 
56
- If the reply is lost (timeout, network error, `executed: "unknown"`), send the same request again with the **same** id. Flovia returns the saved answer with `replayed: true` and does not charge again. Never resend under a new id: that may run and charge twice.
79
+ 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.
57
80
 
58
81
  ## Errors
59
82
 
@@ -74,9 +97,9 @@ A refusal (`ok: false`) or a failed request throws `FloviaError`:
74
97
 
75
98
  These two codes are thrown on purpose. They need the person's own answer, and the SDK never answers for them.
76
99
 
77
- 1. Show `error.reply.user_notice` (or, for consent, `error.reply.consent.question`) to the person, unchanged.
78
- 2. Get the person's answer through your normal flow. For consent, send their own words to the `flovia_data_consent` tool.
79
- 3. Repeat the same call with the same arguments. After `notice_first`, add `notice_shown: true`.
100
+ 1. Show the full `error.reply.user_notice` unchanged. For `data_consent_needed`, also show `error.reply.consent.question`; the short question does not replace the notice.
101
+ 2. For `data_consent_needed`, get the person's own answer through your normal flow. Call `flovia_data_consent` with `answer` (`"y"` or `"n"` from that answer), `consent_version` from `error.reply.consent.version`, and `user_words` containing their actual words. Do not substitute the current SDK version or a generated answer. `notice_first` alone does not ask for a consent answer or supply a consent version.
102
+ 3. For `data_consent_needed`, repeat the unchanged call only after their `y` is accepted; with `n`, stop. For `notice_first`, repeat the same call after showing the notice, adding `notice_shown: true`.
80
103
 
81
104
  Do not answer these automatically from code or from an agent.
82
105
 
@@ -105,17 +128,33 @@ export FLOVIA_KEY=flv_... # or: --key-file ~/.config/flovia/key
105
128
  npx flovia status
106
129
  npx flovia usage --days 3
107
130
  npx flovia tools
108
- npx flovia call flovia_usage_today '{"since":"2026-10-11T00:00:00Z"}'
109
- npx flovia generate --new-op "Summarize this." # prints the operation id, then asks before sending
110
- npx flovia generate --op op_... --yes "Summarize this." # same id: the saved answer, not charged again
131
+ npx flovia tools --json # includes each tool's inputSchema
132
+ npx flovia call flovia_usage_today '{}'
133
+ npx flovia generate --op sdk-example-0001 --max-output 300 "Explain a DEX aggregator."
134
+ # Only to reopen that exact request within about 15 minutes (not a new generation):
135
+ npx flovia generate --op sdk-example-0001 --max-output 300 --yes "Explain a DEX aggregator."
111
136
  npx flovia help
137
+ npx flovia --version
112
138
  ```
113
- These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.0 flovia --help`.
139
+ These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.2 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.
140
+
141
+ 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.
142
+
143
+ For multiline text, keep the original input in a private file:
144
+
145
+ ```sh
146
+ flovia generate --new-op --max-output 300 --yes - < prompt.txt
147
+ # To recover this request, use its printed id, the SAME file and options:
148
+ flovia generate --op <saved-id> --max-output 300 --yes - < prompt.txt
149
+ ```
150
+
151
+ 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.
114
152
 
115
- `usage` shows lookup counts by source and the server-provided totals. 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`.
153
+ `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`.
116
154
 
117
155
  - Every command takes `--json` (the raw reply), `--base-url URL`, `--timeout SECONDS` and `--key-file PATH`.
118
156
  - `generate` uses credits. It needs `--op ID` or `--new-op`, and asks for confirmation on a terminal; add `--yes` in scripts.
157
+ - `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.
119
158
  - Exit codes: 0 ok, 1 an error from Flovia, 2 a usage error.
120
159
 
121
160
  ### Safety
@@ -123,7 +162,7 @@ These commands run after installing `@flovialabs/sdk` in the current project. Wi
123
162
  - The key is read only from `FLOVIA_KEY` or a key file, never from a command-line argument (other users can see arguments in `ps`). It is never printed.
124
163
  - A key file readable by other users gets a warning; use `chmod 600`.
125
164
  - `--base-url` must be `https`, so the key is never sent unencrypted. Plain `http` is allowed only for `localhost`, `127.0.0.1` and `[::1]`.
126
- - On `notice_first` or `data_consent_needed` the CLI shows the notice or question and stops. The person answers it themselves.
165
+ - On `notice_first` or `data_consent_needed` the CLI shows the full notice and, when present, the question, then stops. The person answers it themselves; `--yes` confirms spending, not data consent.
127
166
 
128
167
  ## License
129
168
 
package/dist/cli.d.ts CHANGED
@@ -12,6 +12,8 @@ export interface Io {
12
12
  confirm: ((question: string) => boolean | Promise<boolean>) | null;
13
13
  fetch?: (request: Request) => Promise<Response>;
14
14
  now?: () => number;
15
+ /** TTY-only waiting feedback on stderr; returns a cleanup function. Never used with --json. */
16
+ waiting?: () => () => void;
15
17
  }
16
18
  export declare function help(command?: string): string;
17
19
  export interface Parsed {
package/dist/cli.js CHANGED
@@ -4,18 +4,21 @@
4
4
  * The key comes from FLOVIA_KEY or --key-file only (never argv, which ps shows), and is never printed. Exit 2: usage error; 1: a relay error.
5
5
  */
6
6
  import { readFile, stat } from "node:fs/promises";
7
- import { realpathSync } from "node:fs";
7
+ import { readFileSync, realpathSync } from "node:fs";
8
8
  import { createInterface } from "node:readline/promises";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { FloviaClient, FloviaError, newOperationId } from "./index.js";
11
11
  const GLOBAL = "[--json] [--base-url URL] [--timeout SECONDS] [--key-file PATH]";
12
+ const CONSOLE = "https://console.flovia.dev/groupbuy/";
13
+ const VERSION = String(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
12
14
  const COMMANDS = {
13
- status: { usage: "status", about: "free windows, services, contract version and recent updates", flags: {} },
15
+ status: { usage: "status", about: "usage windows, services, contract version and recent updates", flags: {} },
14
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 } },
15
17
  tools: { usage: "tools", about: "the tools this key is offered", flags: {} },
16
18
  call: { usage: "call <tool> ['<json args>']", about: "call any tool and print its reply", flags: {} },
17
19
  generate: { usage: "generate (--op ID | --new-op) [--max-output N] [--yes] <prompt | ->", about: "a text generation (uses credits)", flags: { "--op": true, "--new-op": false, "--max-output": true, "--yes": false } },
18
20
  help: { usage: "help [command]", about: "this help", flags: {} },
21
+ version: { usage: "version", about: "the installed CLI version", flags: {} },
19
22
  };
20
23
  const GLOBAL_FLAGS = { "--json": false, "--base-url": true, "--timeout": true, "--key-file": true, "--help": false, "-h": false };
21
24
  class Usage extends Error {
@@ -33,31 +36,40 @@ function distance(a, b) {
33
36
  const near = (word, options) => options.find((k) => distance(k, word) <= 2 || k.startsWith(word));
34
37
  const didYouMean = (word, options, quote = "") => { const n = near(word, options); return n === undefined ? "" : `; did you mean ${quote}${n}${quote}?`; };
35
38
  export function help(command) {
36
- const c = command === undefined ? undefined : COMMANDS[command];
37
- if (c !== undefined)
38
- return `Usage: flovia ${c.usage} ${GLOBAL}\n ${c.about}\n`;
39
- return ["Usage: flovia <command> " + GLOBAL, "",
40
- ...Object.values(COMMANDS).map((x) => ` ${x.usage.padEnd(68)} ${x.about}`), "",
41
- "The key is read from FLOVIA_KEY, or from the file given with --key-file. It is never accepted as an argument.",
42
- "Default base URL: https://api.flovia.dev. Exit codes: 0 ok, 1 relay error, 2 usage error.", ""].join("\n");
39
+ const c = command === undefined || !Object.hasOwn(COMMANDS, command) ? undefined : COMMANDS[command];
40
+ const lines = c === undefined ? ["Usage: flovia <command> [options]", "",
41
+ ...Object.values(COMMANDS).flatMap((x) => [` ${x.usage}`, ` ${x.about}`])] : [`Usage: flovia ${c.usage}`, ` ${c.about}`];
42
+ lines.push("", "Options: " + GLOBAL, "", `Get or manage your key: ${CONSOLE}`, "Save the key privately, then: flovia status --key-file <saved-key-file>", "Or set FLOVIA_KEY. Never paste the key into a command argument.");
43
+ if (command === "generate")
44
+ lines.push("", "Default output limit: 1000 tokens; maximum: 4000.", "Long answers can take minutes. Save the id, same input and output limit.", " flovia generate --new-op --max-output 300 --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
+ if (command === "tools" || c === undefined)
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.", "");
48
+ return lines.join("\n");
43
49
  }
44
50
  export function parse(argv) {
45
51
  const [command, ...rest] = argv;
46
52
  if (command === undefined || command === "--help" || command === "-h")
47
53
  return { command: "help", flags: new Map(), positional: [] };
48
- const spec = COMMANDS[command];
54
+ if (command === "--version")
55
+ return { command: "version", flags: new Map(), positional: [] };
56
+ const spec = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : undefined;
49
57
  if (spec === undefined)
50
- throw new Usage(`unknown command "${command}"${didYouMean(command, Object.keys(COMMANDS), '"')} Run: flovia help`);
58
+ throw new Usage(`unknown command${didYouMean(command, Object.keys(COMMANDS), '"')} Run: flovia help`);
51
59
  const known = { ...GLOBAL_FLAGS, ...spec.flags }, flags = new Map(), positional = [];
52
60
  for (let i = 0; i < rest.length; i++) {
53
61
  const a = rest[i] ?? "";
62
+ if (a === "--") {
63
+ positional.push(...rest.slice(i + 1));
64
+ break;
65
+ }
54
66
  if (a === "-" || !a.startsWith("-")) {
55
67
  positional.push(a);
56
68
  continue;
57
69
  }
58
70
  const eq = a.indexOf("="), name = eq > 0 ? a.slice(0, eq) : a;
59
71
  if (!(name in known))
60
- throw new Usage(`${command}: unknown option ${name}${didYouMean(name, Object.keys(known))} Usage: flovia ${spec.usage}`);
72
+ throw new Usage(`${command}: unknown option${didYouMean(name, Object.keys(known))} Run: flovia help ${command}`);
61
73
  if (!known[name]) {
62
74
  if (eq > 0)
63
75
  throw new Usage(`${command}: ${name} takes no value`);
@@ -71,6 +83,8 @@ export function parse(argv) {
71
83
  }
72
84
  if (flags.has("--help") || flags.has("-h"))
73
85
  return { command: "help", flags: new Map(), positional: [command] };
86
+ if (command === "help" && positional[0] !== undefined && !Object.hasOwn(COMMANDS, positional[0]))
87
+ throw new Usage("unknown help topic. Run: flovia help");
74
88
  return { command, flags, positional };
75
89
  }
76
90
  const str = (v) => typeof v === "string" ? v : undefined;
@@ -103,7 +117,7 @@ async function readKey(p, io) {
103
117
  }
104
118
  const key = io.env["FLOVIA_KEY"]?.trim();
105
119
  if (!key)
106
- throw new Usage("No key: set FLOVIA_KEY or pass --key-file PATH (the key is never accepted as an argument).");
120
+ throw new Usage(`No key: set FLOVIA_KEY or pass --key-file PATH. Never paste a key as an argument.\nGet or manage your key: ${CONSOLE}\nThen: flovia status --key-file <saved-key-file>`);
107
121
  return key;
108
122
  }
109
123
  const pct = (v) => typeof v === "number" ? `${v}%` : "-";
@@ -120,26 +134,38 @@ export function when(v, now = Date.now()) {
120
134
  return `${mon} ${day}${d.getUTCFullYear() === new Date(now).getUTCFullYear() ? "" : ` ${year}`} ${hm?.slice(0, 5)} UTC`;
121
135
  }
122
136
  const obj = (v) => v !== null && typeof v === "object" ? v : {};
137
+ /** Wrap prose only, never prompts, answers, consent notices, JSON or copyable commands. */
138
+ const prose = (text) => (text.match(/.{1,76}(?:\s|$)|\S+/g) ?? []).map((line) => line.trim()).join("\n ");
123
139
  export function renderStatus(s, expected, now = Date.now()) {
124
- const lines = [`Flovia ${s.stage}, contract ${s.contract_version}${expected === null ? "" : ` (warning: this CLI expects ${expected})`}`];
140
+ const lines = ["Connection: OK", `Flovia ${s.stage}, contract ${s.contract_version}`];
141
+ if (expected !== null)
142
+ lines.push(`warning: this CLI expects ${expected}`, "Connection succeeded; check recent updates before making calls.");
143
+ const stopped = obj(s["stopped"]), consent = obj(s["data_consent"]);
144
+ if (stopped["message"])
145
+ lines.push(`key stopped: ${String(stopped["message"])}`);
146
+ if (obj(s["consent"])["sharing"] === "withdrawn")
147
+ lines.push("New usage: stopped (sharing withdrawn).");
148
+ else if (consent["needed"] === true)
149
+ lines.push("New usage: waits for your own y/n to the current data consent.");
150
+ else if (consent["answer"] === "n")
151
+ lines.push("New usage: stopped (sharing declined). Your choice is saved.");
152
+ else if (consent["answer"] === "y")
153
+ lines.push("Data consent: accepted. Service and allowance limits still apply.");
154
+ else
155
+ lines.push("Data consent: not reported (see --json).");
125
156
  for (const [label, w] of [["5-hour window", s.five_hour], ["week", s.week]])
126
157
  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" : ""}`);
158
+ lines.push(`bought balance ${String(s["purchased_balance_display"] ?? "-")}`);
127
159
  const pending = obj(s["free_pending"]);
128
160
  if (pending["next_step"])
129
- lines.push(`free use not started: ${String(pending["next_step"])}`);
130
- const stopped = obj(s["stopped"]);
131
- if (stopped["message"])
132
- lines.push(`key stopped: ${String(stopped["message"])}`);
161
+ lines.push(`usage allowance not started: ${String(pending["next_step"])}`);
133
162
  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)}` : ""}`; });
134
- lines.push(`services ${services.length ? services.join(", ") : "-"}`);
163
+ lines.push("services (provider state)", ...services.map((v) => ` ${v}`));
135
164
  lines.push(`turned off ${s.services_off.length ? s.services_off.join(", ") : "none"}`);
136
- const consent = obj(s["data_consent"]);
137
- if (consent["needed"] === true)
138
- lines.push("data consent needed: lookups wait for the person's own y/n (answer through the normal flow, not this CLI)");
139
165
  const updates = Array.isArray(s["recent_updates"]) ? s["recent_updates"] : [];
140
166
  for (const u of updates.slice(0, 2)) {
141
167
  const x = obj(u), first = Array.isArray(x["lines"]) ? String(x["lines"][0] ?? "") : "";
142
- lines.push(`update ${String(x["version"])} (${String(x["date"])}): ${first}`);
168
+ lines.push(prose(`update ${String(x["version"])} (${String(x["date"])}): ${first}`));
143
169
  }
144
170
  if (updates.length > 2)
145
171
  lines.push(`+${updates.length - 2} more (--json)`);
@@ -148,8 +174,9 @@ export function renderStatus(s, expected, now = Date.now()) {
148
174
  export function renderUsage(u, today = false, now = Date.now()) {
149
175
  const lines = [`since ${when(u["since"], now)} until ${when(u["until"], now)}${today ? " (today, UTC; use --days 7 for the week)" : ""}`];
150
176
  const week = obj(u["free_week"]);
151
- lines.push(`free week: ${pct(week["used_pct"])} used${week["resets_at"] ? `, resets ${when(week["resets_at"], now)}` : ""}`);
152
- lines.push(`total in this period: ${String(obj(u["total"])["free_display"] ?? "-")} of the free week, ${String(u["count"] ?? 0)} lookups`);
177
+ lines.push(`week allocation: ${pct(week["used_pct"])} used${week["resets_at"] ? `, resets ${when(week["resets_at"], now)}` : ""}`);
178
+ lines.push(`total in this period: ${String(obj(u["total"])["free_display"] ?? "-")} of the weekly allocation, ${String(u["count"] ?? 0)} lookups`);
179
+ lines.push(`bought credits used: ${String(obj(u["total"])["bought_display"] ?? "-")} total (includes generations)`);
153
180
  // Endpoint percentages are rounded (0 can mean <1%); only counts can be summed by source.
154
181
  const bySource = new Map();
155
182
  for (const e of Array.isArray(u["by_endpoint"]) ? u["by_endpoint"] : []) {
@@ -159,7 +186,7 @@ export function renderUsage(u, today = false, now = Date.now()) {
159
186
  if (bySource.size)
160
187
  lines.push("", table([["source", "lookups"], ...[...bySource].map(([n, count]) => [n, String(count)])]).trimEnd());
161
188
  const g = obj(u["generations"]);
162
- 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 free week`);
189
+ 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)`);
163
190
  if (u.has_more)
164
191
  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)}`);
165
192
  return lines.join("\n") + "\n";
@@ -167,6 +194,8 @@ export function renderUsage(u, today = false, now = Date.now()) {
167
194
  /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
168
195
  export function renderError(e) {
169
196
  const lines = [`error: ${e.code}: ${e.message}`];
197
+ if (e.code === "unauthorized")
198
+ 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.");
170
199
  if (e.nextStep)
171
200
  lines.push(`next_step: ${e.nextStep}`);
172
201
  lines.push(`executed: ${e.executed}`);
@@ -197,6 +226,10 @@ export async function run(argv, io) {
197
226
  out(help(p.positional[0]));
198
227
  return 0;
199
228
  }
229
+ if (p.command === "version") {
230
+ out(`flovia ${VERSION}\n`);
231
+ return 0;
232
+ }
200
233
  key = await readKey(p, io);
201
234
  }
202
235
  catch (e) {
@@ -208,6 +241,7 @@ export async function run(argv, io) {
208
241
  }
209
242
  const json = p.flags.has("--json"), print = (v) => out(JSON.stringify(v, null, 2) + "\n");
210
243
  let mismatch = null;
244
+ let recoveryLimit;
211
245
  try {
212
246
  const timeout = positiveInt("--timeout", str(p.flags.get("--timeout")));
213
247
  const baseUrl = str(p.flags.get("--base-url"));
@@ -246,7 +280,7 @@ export async function run(argv, io) {
246
280
  if (json)
247
281
  print(tools);
248
282
  else
249
- out(table(tools.map((t) => [t.name, (t.description ?? "").split(/(?<=\.)\s/)[0] ?? ""])));
283
+ out(tools.map((t) => `${t.name}\n ${prose((t.description ?? "").split(/(?<=\.)\s/)[0] ?? "")}\n`).join("\n") + "\nArguments: flovia tools --json\nRead-only example: flovia call flovia_status '{}'\n");
250
284
  return 0;
251
285
  }
252
286
  case "call": {
@@ -277,11 +311,12 @@ export async function run(argv, io) {
277
311
  if (input.trim() === "")
278
312
  throw new Usage("generate: the prompt is empty");
279
313
  const max = positiveInt("--max-output", str(p.flags.get("--max-output")));
314
+ recoveryLimit = max;
280
315
  const id = op ?? newOperationId();
281
316
  // The id is shown before anything is sent, so a lost reply can be reopened with it (never resent under a new one).
282
317
  if (fresh)
283
318
  err(`operation_id: ${id}\nSave it. To resend or reopen this request, use: --op ${id}\n`);
284
- err("This generation uses Flovia credits (free windows first, then bought credits). Resending the same --op returns the saved answer at no charge.\n");
319
+ err("This generation uses Flovia credits (usage allowance first, then bought credits).\nSame --op, same input and output limit: saved answers are free for about 15 minutes.\nPending, unknown or expired answers: never replace them with a new id.\n");
285
320
  if (!p.flags.has("--yes")) {
286
321
  if (io.confirm === null || text === "-")
287
322
  throw new Usage("generate: add --yes to send (no terminal to confirm on)");
@@ -290,11 +325,29 @@ export async function run(argv, io) {
290
325
  return 2;
291
326
  }
292
327
  }
293
- const g = await client.generate({ model: "gpt-6-luna", input, ...(max ? { max_output_tokens: max } : {}) }, { operationId: id });
328
+ const stopWaiting = json ? undefined : io.waiting?.();
329
+ let g;
330
+ try {
331
+ g = await client.generate({ model: "gpt-6-luna", input, ...(max ? { max_output_tokens: max } : {}) }, { operationId: id });
332
+ }
333
+ finally {
334
+ stopWaiting?.();
335
+ }
336
+ const reason = obj(g.response["incomplete_details"])["reason"];
294
337
  if (json)
295
338
  print(g);
296
- else
297
- out(`${g.outputText}\n\n[operation_id ${id}${g.replayed ? ", replayed: the saved answer, not charged again" : ""}${g.generationId ? `, generation ${g.generationId}` : ""}]\n`);
339
+ else {
340
+ out(`${g.outputText}\n\nstatus: ${String(g.response["status"] ?? "unknown")}${reason ? `, reason: ${String(reason)}` : ""}\noperation_id: ${id}\n${g.generationId ? `generation: ${g.generationId}\n` : ""}`);
341
+ if (g.response["status"] === "incomplete")
342
+ out(`${reason === "max_output_tokens" ? "Partial answer: the output limit was reached" : "Partial answer"}; delivered and settled. No continuation was generated.\n`);
343
+ else if (g.response["status"] === "completed")
344
+ out("Answer delivered and settled.\n");
345
+ if (g.replayed)
346
+ out("replayed: the saved answer, not charged again.\n");
347
+ else
348
+ out("Exact Flovia cost is not included in this reply.\n");
349
+ out("Period usage: flovia usage (keep the same --key-file and --base-url options).\n");
350
+ }
298
351
  return 0;
299
352
  }
300
353
  }
@@ -309,6 +362,8 @@ export async function run(argv, io) {
309
362
  if (json && e.reply)
310
363
  print(e.reply);
311
364
  err(renderError(e));
365
+ if (p.command === "generate" && e.operationId && e.executed === "unknown")
366
+ err(`Recovery: keep the same input and ${recoveryLimit === undefined ? "omit --max-output as before" : `--max-output ${recoveryLimit}`} 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`);
312
367
  return e.code === "invalid_base_url" ? 2 : 1;
313
368
  }
314
369
  err(`error: ${e instanceof Error ? e.message : String(e)}\n`);
@@ -345,5 +400,12 @@ if (isMain) {
345
400
  env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
346
401
  readFile: (path) => readFile(path, "utf8"), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
347
402
  confirm: tty ? confirm : null,
403
+ ...(process.stderr.isTTY ? { waiting: () => {
404
+ const start = Date.now();
405
+ process.stderr.write("Waiting for Flovia; long answers can take minutes.\n");
406
+ const timer = setInterval(() => process.stderr.write(`Waiting for Flovia (${Math.floor((Date.now() - start) / 1000)}s elapsed).\n`), 5000);
407
+ timer.unref();
408
+ return () => clearInterval(timer);
409
+ } } : {}),
348
410
  });
349
411
  }
package/dist/client.d.ts CHANGED
@@ -35,7 +35,8 @@ export declare class FloviaClient {
35
35
  usageToday(args?: UsageTodayArgs): Promise<UsageTodayReply>;
36
36
  /**
37
37
  * POST /openai/v1/responses. operationId is required: save it with the request before calling. Sending the same request with the same id
38
- * again returns the saved answer (replayed: true) at no charge. Never resent automatically, and never under a new id.
38
+ * again can return the saved answer (replayed: true) for about 15 minutes at no charge. Pending, unknown and expired answers
39
+ * are not proof that nothing ran. Never resent automatically, and never under a new id to recover an answer.
39
40
  */
40
41
  generate(request: GenerationRequest, options: {
41
42
  operationId: string;
package/dist/client.js CHANGED
@@ -64,10 +64,10 @@ export class FloviaClient {
64
64
  }
65
65
  /** One HTTP request. A network failure or timeout is executed "unknown": the relay may have received it. */
66
66
  async #send(path, body, headers = {}, operationId = null) {
67
- const request = new Request(this.#base + path, { method: "POST", body: JSON.stringify(body), signal: AbortSignal.timeout(this.#timeoutMs),
68
- headers: { Authorization: `Bearer ${this.#key}`, "Content-Type": "application/json", ...headers } });
69
67
  let r;
70
68
  try {
69
+ const request = new Request(this.#base + path, { method: "POST", body: JSON.stringify(body), signal: AbortSignal.timeout(this.#timeoutMs),
70
+ headers: { Authorization: `Bearer ${this.#key}`, "Content-Type": "application/json", ...headers } });
71
71
  r = await this.#fetch(request);
72
72
  }
73
73
  catch (cause) {
@@ -143,7 +143,8 @@ export class FloviaClient {
143
143
  }
144
144
  /**
145
145
  * POST /openai/v1/responses. operationId is required: save it with the request before calling. Sending the same request with the same id
146
- * again returns the saved answer (replayed: true) at no charge. Never resent automatically, and never under a new id.
146
+ * again can return the saved answer (replayed: true) for about 15 minutes at no charge. Pending, unknown and expired answers
147
+ * are not proof that nothing ran. Never resent automatically, and never under a new id to recover an answer.
147
148
  */
148
149
  async generate(request, options) {
149
150
  const op = options.operationId;
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
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.116";
2
+ export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.118";
3
3
  /** Every public explanation.code (the relay's contract). A provider's own HTTP error is `http_<status>`. */
4
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"];
5
5
  export type FloviaCode = (typeof PUBLIC_CODES)[number] | `http_${number}`;
package/dist/types.js CHANGED
@@ -1,5 +1,5 @@
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.116";
2
+ export const EXPECTED_CONTRACT_VERSION = "2026-10-07.118";
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
5
  "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flovialabs/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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",