@flovialabs/sdk 0.1.14 → 0.1.16

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
@@ -2,6 +2,31 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.16
6
+
7
+ - Expect contract `2026-10-07.167`: `call("flovia_runway", { action: "list" })` previews maximum reservations for an image or 2–5-second video, as allowance shares and USD if purchased balance pays. Listing never generates or reserves; the final charge can differ.
8
+ - Expect contract `2026-10-07.166`: free month window and expiring plan credit, combined with API key provider restrictions.
9
+ - Expect contract `2026-10-07.163`: `flovia_firecrawl` scrape takes an optional `country` (one of 26 ISO 3166-1 alpha-2 codes listed by `action: "list"`). Query strings are still refused.
10
+
11
+ - Expect contract `2026-10-07.162`: `flovia_x` adds read-only actions (`search_all`, `count_all`, `replies`, `posts`, `users`, `users_by_usernames`, `user_mentions`, `followers`, `following`, `reposted_by`, `list_lookup`, `list_posts`, `trends`); `action: "list"` shows each one's arguments.
12
+ - X is currently withdrawn from Flovia's public tools. SDK types do not enable it or guarantee its availability.
13
+ - `flovia status` prints one line when you have a saved reset (from `flovia_status`'s `banked_resets`), pointing to `flovia resets`. Nothing is shown when you have none or the relay does not report it; it never uses one.
14
+
15
+ - Breaking: contract `2026-10-07.161` requires `operation_id` on every `flovia_x` action, including `list`. X accepts usernames with `@`, fractional UTC timestamps or `+00:00`, and clamps times and result counts to its supported range. Keep the same operation ID when recovering a call.
16
+
17
+ - Contract `2026-10-07.160` adds public Firecrawl PDFs up to 10 pages (text, no OCR). Use `pdf: true` for PDF URLs without a `.pdf` path. HTML is unchanged.
18
+
19
+ - Banked resets: `bankedResets()` and `flovia resets` check saved resets and the CLI shows both free windows. `useBankedReset(id)` and `flovia resets use <id> --yes` use one right to restart the 5-hour and weekly free windows. They require the relay's account routes; they never resend automatically. After a lost, unreadable or 401 reply, check first; an unknown result does not mean nothing changed.
20
+
21
+ - Expect contract `2026-10-07.159`; `PUBLIC_CODES` includes `provider_not_allowed` for API key provider restrictions. Credentials are never switched automatically.
22
+ - Expect contract `2026-10-07.158`: use `call("flovia_fal", ...)` for asynchronous fal.ai image jobs; preserve the operation ID for status and recovery.
23
+
24
+ ## 0.1.15
25
+
26
+ - Expect contract `2026-10-07.153`.
27
+ - Runway: use `call("flovia_runway", ...)` for image/video creation and status after the person's separate consent. `downloadRunwayOutput()` and `flovia runway-output <generation_id> --out PATH` download a private output without regenerating; files are created exclusively with mode `0600`.
28
+ - Runway calls never auto-resend, including pre-execution refusals when `retryRateLimited` is enabled. Preserve the original operation ID for recovery; unknown is not proof of failure or zero cost.
29
+
5
30
  ## 0.1.14
6
31
 
7
32
  - Expect contract `2026-10-07.149`; `FloviaCode` and `PUBLIC_CODES` include `relay_internal_error`.
@@ -15,17 +40,14 @@
15
40
  ## 0.1.12
16
41
 
17
42
  - Expect contract `2026-10-07.146`: Flovia can look up public X posts (recent search and counts, one post and its quote posts, an account's recent posts); the tool is closed unless Flovia offers it.
18
-
19
43
  - Expect contract `2026-10-07.145`: reopened Nansen trade quotes replace transaction data with SHA-256 fingerprints. Fresh replies are unchanged; preparation uses only an owned, encrypted short-lived quote copy when enabled.
20
44
 
21
45
  - Expect contract `2026-10-07.144`: the Base unsigned-preparation tool takes an owned quote reference and index, with separately billed chain checks; it is available only when Flovia offers it. `cannot_summarize` returns nothing to sign; Flovia does not charge for the preparation. Flovia never signs or sends.
22
-
23
46
  - Contract `2026-10-07.143` adds nine read-only Nansen GET endpoints for swap quotes, bridge status, perp account data and token sectors.
24
47
 
25
48
  - `FloviaCode` and `PUBLIC_CODES` include the relay's Firecrawl codes `page_tls_invalid` and `page_unreachable`.
26
49
 
27
50
  - Expect contract `2026-10-07.138`: Exa accepts optional `text_max_characters` (1–12,000) for page text in the existing search. Missing text and possible truncation are marked; all results share the existing reply budget. Default excerpts, search count and charges are unchanged.
28
-
29
51
  - Expect contract `2026-10-07.137`: Exa supports optional publication-date bounds and category filters; default search and charges are unchanged.
30
52
 
31
53
  - The CLI reads the key from `~/.config/flovia/key` when neither `--key-file` nor `FLOVIA_KEY` is given.
package/README.md CHANGED
@@ -10,13 +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 --save-exact @flovialabs/sdk@0.1.14
13
+ npm install --save-exact @flovialabs/sdk@0.1.16
14
14
  ```
15
15
 
16
16
  ## Your key
17
17
 
18
18
  1. Register at https://console.flovia.dev/auth/register with email verification and a Passkey.
19
- 2. In [Flovia Console](https://console.flovia.dev/groupbuy/), press Create API key. Console shows it once; save it somewhere private.
19
+ 2. In [Flovia Console](https://console.flovia.dev/groupbuy/), press Create API key. Give it an app name such as CLI or Cursor. Console shows it once; save it somewhere private.
20
20
  3. Set the key (`flv_...`) in the environment, then check it:
21
21
 
22
22
  ```sh
@@ -26,11 +26,11 @@ npx flovia status
26
26
 
27
27
  Without `FLOVIA_KEY` or `--key-file`, the CLI reads `~/.config/flovia/key`, the file Console's Claude Code setup saves.
28
28
 
29
- Claude Code pluginの既定の保存先は別ファイル `~/.config/flovia/relay-key` です。Consoleでキーを更新したら、CLIのキーファイル(または `FLOVIA_KEY`)とpluginの両方を更新し、pluginはClaude Codeで `/flovia:setup` を再実行してください(基点 `28e5cbeee1d7bca5c68c18d765e576445e452997`、2026-10-25確認)。
29
+ Claude Code pluginの既定の保存先は別ファイル `~/.config/flovia/relay-key` です。CLIとpluginには別々のキーを使えます。キーを交換したときは、そのキーを使っていた保存先だけを更新してください。pluginのキーを交換した場合は、Claude Codeで `/flovia:setup` を再実行してください(保存先の基点 `28e5cbeee1d7bca5c68c18d765e576445e452997`、2026-10-25確認)。
30
30
 
31
31
  `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.
32
32
 
33
- Keys from the test period no longer work. The [Quickstart](https://docs.flovia.dev/get-started/quickstart/) has the full steps, and [Free and paid use](https://docs.flovia.dev/usage/) explains the limits. If you lose your key or think it leaked, regenerate it on the API Key tab in [Flovia Console](https://console.flovia.dev/groupbuy/); the old key stops working at once. Installing this package does not create an account or start a free allowance.
33
+ Keys from the test period no longer work. The [Quickstart](https://docs.flovia.dev/get-started/quickstart/) has the full steps, and [Free and paid use](https://docs.flovia.dev/usage/) explains the limits. You can keep up to five active API keys on one account; all share its allowance, balance and limits. If a key is lost or exposed, select Revoke for that key on the API Key tab in [Flovia Console](https://console.flovia.dev/groupbuy/), then Create API key and update the apps that used it. Other keys and OAuth connections keep working. See [Manage API keys](https://docs.flovia.dev/connect/check/#manage-api-keys). Installing this package does not create an account or start a free allowance.
34
34
 
35
35
  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.
36
36
 
@@ -81,6 +81,41 @@ const price = await flovia.call("flovia_coingecko", priceRequest);
81
81
 
82
82
  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.
83
83
 
84
+ ### Runway images and videos
85
+
86
+ When `listTools()` offers `flovia_runway`, use the same `call()` method and your Flovia key. Runway needs the person's separate consent: show the returned notice and ask only when `next_step` requests it. Never supply a yes for the person. Runway may train on inputs and outputs; do not send private information or credentials.
87
+
88
+ ```ts
89
+ const catalog = await flovia.call("flovia_runway", { action: "list" });
90
+ // After the person's actual consent has been recorded, save this request before sending.
91
+ const imageRequest = {
92
+ action: "image", prompt: "A blue paper circle on a white background",
93
+ operation_id: newOperationId(),
94
+ };
95
+ const accepted = await flovia.call("flovia_runway", imageRequest);
96
+ // Accepted is not completed. Later, explicitly read the same job's status:
97
+ const result = await flovia.call("flovia_runway", {
98
+ action: "status", operation_id: imageRequest.operation_id,
99
+ });
100
+ // Only when output.state is ready, using the generation_id returned by Flovia:
101
+ const output = await flovia.downloadRunwayOutput(String(result["generation_id"]));
102
+ // output.data is Uint8Array; output.contentType is the checked media type.
103
+ ```
104
+
105
+ Images are one 720p `gen4_image` result. Videos use `action: "video"` with `duration: 2` through `5`, and return MP4. Runway jobs never resend automatically, even with `retryRateLimited: true`. Keep the original operation ID after a disconnect or unknown result; never generate a replacement to recover it. A failed/moderated generation may still be charged. Status distinguishes the billing state from output delivery.
106
+
107
+ Flovia keeps output privately for 24 hours, with authenticated downloads; Runway's own retention is separate. The SDK download is a bounded (32 MiB), one-request GET to Flovia, never a provider URL. A download does not generate or charge again. OAuth-only MCP users can use the returned `console_download_url` while signed in to their own Console.
108
+
109
+ ```bash
110
+ flovia call flovia_runway '{"action":"list"}'
111
+ # Create through call only after actual consent; save your JSON request first.
112
+ flovia call flovia_runway - < image-request.json
113
+ flovia call flovia_runway '{"action":"status","operation_id":"<saved-operation-id>"}'
114
+ flovia runway-output <generation_id> --out image.png
115
+ ```
116
+
117
+ `runway-output` creates a new file with mode `0600`; it never overwrites. A failed write may leave a private partial file, so inspect it before choosing another output path. Show **Powered by Runway** with a link to [Runway](https://runwayml.com) when displaying generated media; SDK consumers must carry that attribution into their own interface.
118
+
84
119
  ### Run one result, display it, then reopen it
85
120
 
86
121
  Save this complete example as `first-price.mjs` beside your `node_modules`. Keep it server-side or on your own machine.
@@ -189,13 +224,13 @@ A refusal (`ok: false`) or a failed request throws `FloviaError`:
189
224
 
190
225
  HTTP 401 with `code: "formal_registration_required"` means test access ended: register at https://console.flovia.dev/auth/register with email verification and a Passkey (or use the link in your invitation email if you have one); if you have already registered, sign in to Console, press Create API key, then reconnect with the new key. 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.
191
226
 
192
- ### `notice_first` and `data_consent_needed`: a human must answer
227
+ ### Notices and consent
193
228
 
194
- These two codes are thrown on purpose. They need the person's own answer, and the SDK never answers for them.
229
+ These two codes stop the call on purpose. Show the notice in full and follow `nextStep`; a separate explicit opt-in may be required. The SDK never consents for the person.
195
230
 
196
- 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.
197
- 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.
198
- 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`.
231
+ 1. Show the full `error.reply.user_notice` unchanged (`error.reply.notice` for case reports), and `error.reply.consent.question` when present. For `data_consent_needed`, use `consent.line` when there is no question; the short question does not replace the notice.
232
+ 2. For `data_consent_needed`, get the person's own answer through your normal flow. Follow `nextStep` for the consent tool: lookup consent uses `flovia_data_consent`; Runway uses `flovia_runway` with `action: "consent"`. Pass `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. Case-report `notice_first` uses its own explicit opt-in and returned `consent_version`, not `flovia_data_consent`.
233
+ 3. For `data_consent_needed`, repeat the unchanged call only after their `y` is accepted; with `n`, stop. For `notice_first`, show the notice and follow `nextStep`; add `notice_shown: true` only when requested. Never opt in to a report automatically.
199
234
 
200
235
  Do not answer these automatically from code or from an agent.
201
236
 
@@ -230,11 +265,13 @@ npx flovia call flovia_usage_today '{}'
230
265
  npx flovia generate --op sdk-example-0001 --max-output 1000 --reasoning-effort low "Explain a DEX aggregator."
231
266
  # Only to reopen that exact request within about 15 minutes (not a new generation):
232
267
  npx flovia generate --op sdk-example-0001 --max-output 1000 --reasoning-effort low --yes "Explain a DEX aggregator."
268
+ npx flovia resets # saved resets and both free windows (read-only)
269
+ npx flovia resets use 42 --yes # use saved reset 42 (cannot be undone)
233
270
  npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
234
271
  npx flovia help
235
272
  npx flovia --version
236
273
  ```
237
- These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.14 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.
274
+ These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.16 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.
238
275
 
239
276
  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.
240
277
 
@@ -265,6 +302,7 @@ Keep the same `--key-file` and `--base-url` too. For a prompt starting with a hy
265
302
  - Every command takes `--json` (the raw reply), `--base-url URL`, `--timeout SECONDS` and `--key-file PATH`.
266
303
  - `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.
267
304
  - `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.
305
+ - `resets` only reads: the number of saved resets, the next to expire, and the 5-hour and weekly windows. `resets use <id> --yes` uses one; both free windows (5-hour and week) start again from 0%. Without `--yes` nothing is sent, even on a terminal. It is never resent automatically: after a lost reply, run `flovia resets` before trying again. `Not used; nothing changed.` exits 1. In code: `client.bankedResets()` and `client.useBankedReset(id)`.
268
306
  - Exit codes: 0 ok, 1 an error from Flovia, 2 a usage error.
269
307
 
270
308
  ### Safety
@@ -272,7 +310,7 @@ Keep the same `--key-file` and `--base-url` too. For a prompt starting with a hy
272
310
  - 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.
273
311
  - A key file readable by other users gets a warning; use `chmod 600`.
274
312
  - `--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]`.
275
- - 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.
313
+ - The CLI shows the full notice, `next_step` and any returned `consent.question`, then stops. On `data_consent_needed`, `consent.line` (as Runway returns) supplies the question when `consent.question` is absent. Questions appear under `Your choice:`. Notice text, links and questions stay unchanged; only headings and help text are shortened. The person answers themselves; `--yes` confirms spending, not data consent or report opt-in.
276
314
 
277
315
  ## License
278
316
 
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { FloviaError, type StatusReply, type UsageTodayReply } from "./index.js";
2
+ import { FloviaError, type BankedResets, type StatusReply, type UsageTodayReply } from "./index.js";
3
+ /** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
4
+ export declare function writePrivateOutput(path: string, data: Uint8Array): Promise<void>;
3
5
  export interface Io {
4
6
  env: Record<string, string | undefined>;
5
7
  out: (s: string) => void;
@@ -8,6 +10,7 @@ export interface Io {
8
10
  /** The file's permission bits, to warn when a key file is readable by others. */
9
11
  fileMode?: (path: string) => Promise<number>;
10
12
  readStdin: () => Promise<string>;
13
+ writeOutput?: (path: string, data: Uint8Array) => Promise<void>;
11
14
  /** A yes/no question on a terminal; null when there is none (piped or CI). */
12
15
  confirm: ((question: string) => boolean | Promise<boolean>) | null;
13
16
  fetch?: (request: Request) => Promise<Response>;
@@ -29,6 +32,7 @@ export declare function parse(argv: string[]): Parsed;
29
32
  export declare function when(v: unknown, now?: number): string;
30
33
  export declare function renderStatus(s: StatusReply, expected: string | null, now?: number): string;
31
34
  export declare function renderUsage(u: UsageTodayReply, today?: boolean, now?: number): string;
35
+ export declare function renderResets(r: BankedResets, s: StatusReply, now?: number): string;
32
36
  /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
33
37
  export declare function renderError(e: FloviaError): string;
34
38
  export declare function run(argv: string[], io: Io): Promise<number>;
package/dist/cli.js CHANGED
@@ -3,11 +3,22 @@
3
3
  * flovia: a small CLI over the SDK's public client, for people to check their status and usage and try calls with their own key.
4
4
  * The key comes from FLOVIA_KEY, --key-file or ~/.config/flovia/key only (never argv, which ps shows), and is never printed. Exit 2: usage error; 1: a relay error.
5
5
  */
6
- import { readFile, stat } from "node:fs/promises";
6
+ import { open, readFile, stat } from "node:fs/promises";
7
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
+ /** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
12
+ export async function writePrivateOutput(path, data) {
13
+ const file = await open(path, "wx", 0o600);
14
+ try {
15
+ await file.writeFile(data);
16
+ await file.sync();
17
+ }
18
+ finally {
19
+ await file.close();
20
+ }
21
+ }
11
22
  const GLOBAL = "[--json] [--base-url URL] [--timeout SECONDS] [--key-file PATH]";
12
23
  const CONSOLE = "https://console.flovia.dev/groupbuy/";
13
24
  const VERSION = String(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
@@ -16,7 +27,9 @@ const COMMANDS = {
16
27
  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
28
  tools: { usage: "tools [tool]", about: "list offered tools, or inspect one tool's description and arguments", flags: {} },
18
29
  call: { usage: "call <tool> ['<json args>' | -]", about: "call a tool; - reads a JSON object from stdin", flags: {} },
30
+ "runway-output": { usage: "runway-output <generation_id> --out PATH", about: "download an existing private output; never regenerates or overwrites", flags: { "--out": true } },
19
31
  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 } },
32
+ resets: { usage: "resets [use <id> --yes]", about: "check saved resets (read-only), or use one to restart both free windows", flags: { "--yes": false } },
20
33
  "agents-md": { usage: "agents-md", about: "a short Flovia note to paste into CLAUDE.md or AGENTS.md (no network)", flags: {} },
21
34
  help: { usage: "help [command]", about: "this help", flags: {} },
22
35
  version: { usage: "version", about: "the installed CLI version", flags: {} },
@@ -91,6 +104,8 @@ export function help(command) {
91
104
  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.");
92
105
  if (command === "tools" || c === undefined)
93
106
  lines.push("", "Inspect one tool: flovia tools <tool> --json", "Inspect all tool arguments: flovia tools --json", "Read-only example: flovia call flovia_status '{}'");
107
+ if (command === "resets")
108
+ lines.push("", "flovia resets only reads; it never uses one.", "Using one starts both free windows (5-hour and week) again; it cannot be undone.", " flovia resets use <id> --yes", "It is never resent automatically; after a lost reply, run flovia resets first.");
94
109
  if (command === "call")
95
110
  lines.push("", "Read a saved request: flovia call <tool> - < request.json", ...SAVE_OP);
96
111
  lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 error from Flovia, 2 usage error.", "");
@@ -219,6 +234,10 @@ export function renderStatus(s, expected, now = Date.now()) {
219
234
  for (const [name, w] of [["free 5-hour", s.five_hour], ["free week", s.week]])
220
235
  lines.push(`${label(name)}${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : name === "free 5-hour" ? ", not started" : ""}`);
221
236
  lines.push(`${label("purchased balance")}${String(s["purchased_balance_display"] ?? "-")}`);
237
+ // An older relay omits banked_resets; nothing is shown then.
238
+ const banked = obj(s["banked_resets"]), n = banked["available"];
239
+ if (typeof n === "number" && n > 0)
240
+ lines.push(`You have ${n} saved reset${n === 1 ? "" : "s"} (until ${String(banked["next_expires_at"]).slice(0, 10)}). Run: flovia resets`);
222
241
  const pending = obj(s["free_pending"]);
223
242
  if (pending["next_step"])
224
243
  lines.push(`free allowance not started: ${String(pending["next_step"])}`);
@@ -254,6 +273,16 @@ export function renderUsage(u, today = false, now = Date.now()) {
254
273
  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)}`);
255
274
  return lines.join("\n") + "\n";
256
275
  }
276
+ export function renderResets(r, s, now = Date.now()) {
277
+ const lines = [`${label("saved resets")}${r.available}`];
278
+ if (r.next)
279
+ lines.push(`${label("next to expire")}id ${r.next.id}, expires ${when(r.next.expires_at, now)}`);
280
+ for (const [name, w] of [["free 5-hour", s.five_hour], ["free week", s.week]])
281
+ lines.push(`${label(name)}${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : ""}`);
282
+ if (r.next)
283
+ lines.push("Using one starts both free windows (5-hour and week) again from 0%. It cannot be undone.", `To use it: flovia resets use ${r.next.id} --yes`);
284
+ return lines.join("\n") + "\n";
285
+ }
257
286
  /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
258
287
  export function renderError(e) {
259
288
  const lines = [`error: ${e.code}: ${e.message}`];
@@ -268,12 +297,17 @@ export function renderError(e) {
268
297
  lines.push(`operation_id: ${e.operationId}${e.executed === "unknown" ? " (keep this id; never send the request again under a new one)" : ""}`);
269
298
  const reply = obj(e.reply);
270
299
  if (e.code === "notice_first" || e.code === "data_consent_needed") {
271
- if (reply["user_notice"])
272
- lines.push("", "Notice for the person:", String(reply["user_notice"]));
273
- const question = obj(reply["consent"])["question"];
300
+ const notice = reply["user_notice"] || reply["notice"];
301
+ if (notice)
302
+ lines.push("", "Notice:", String(notice));
303
+ const consent = obj(reply["consent"]), question = consent["question"] || (e.code === "data_consent_needed" ? consent["line"] : undefined);
274
304
  if (question)
275
- lines.push("", `Question for the person: ${String(question)}`);
276
- lines.push("", "The person must answer this themselves through the normal flow (their agent and Flovia). This CLI does not answer it.");
305
+ lines.push("", `Your choice: ${String(question)}`);
306
+ if (e.code === "data_consent_needed") {
307
+ lines.push("", "Only the user can consent; the CLI does not answer for them.");
308
+ }
309
+ else
310
+ lines.push("", "Follow next_step. The CLI does not opt in for the user.");
277
311
  }
278
312
  return lines.join("\n") + "\n";
279
313
  }
@@ -335,6 +369,26 @@ export async function run(argv, io) {
335
369
  fetch: (r) => { r.headers.set("X-Flovia-Client", "flovia-cli"); return (io.fetch ?? fetch)(r); }, onContractMismatch: (expected) => { mismatch = expected; } });
336
370
  };
337
371
  switch (p.command) {
372
+ case "runway-output": {
373
+ const [id, extra] = p.positional, path = str(p.flags.get("--out"));
374
+ if (!id || extra !== undefined || !path || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id))
375
+ throw new Usage("Usage: flovia runway-output <generation_id> --out PATH");
376
+ if (!io.writeOutput)
377
+ throw new Usage("A private output-file writer is required.");
378
+ const client = await connect(), output = await waitFor(() => client.downloadRunwayOutput(id));
379
+ try {
380
+ await io.writeOutput(path, output.data);
381
+ }
382
+ catch {
383
+ throw new Usage("Could not save the output; check for a partial file. Existing files are never overwritten.");
384
+ }
385
+ const saved = { saved: true, generation_id: id, bytes: output.data.byteLength, content_type: output.contentType, attribution: "Powered by Runway", attribution_url: "https://runwayml.com" };
386
+ if (json)
387
+ print(saved);
388
+ else
389
+ out("Output saved privately. Powered by Runway (https://runwayml.com).\n");
390
+ return 0;
391
+ }
338
392
  case "status": {
339
393
  const client = await connect(), s = await waitFor(() => client.status());
340
394
  if (json)
@@ -345,6 +399,31 @@ export async function run(argv, io) {
345
399
  err(`warning: contract ${s.contract_version} differs from this CLI's ${String(mismatch)}\n`);
346
400
  return 0;
347
401
  }
402
+ case "resets": {
403
+ const [action, id, extra] = p.positional;
404
+ if (action === undefined) {
405
+ if (p.flags.has("--yes"))
406
+ throw new Usage("Usage: flovia resets use <id> --yes");
407
+ const client = await connect(), r = await waitFor(() => client.bankedResets()), s = await waitFor(() => client.status());
408
+ if (json)
409
+ print({ ...r, five_hour: s.five_hour, week: s.week });
410
+ else
411
+ out(renderResets(r, s, (io.now ?? Date.now)()));
412
+ return 0;
413
+ }
414
+ const grant = action === "use" && extra === undefined && id !== undefined && /^[1-9][0-9]{0,15}$/.test(id) ? Number(id) : NaN;
415
+ if (!Number.isSafeInteger(grant))
416
+ throw new Usage("Usage: flovia resets use <id> --yes (the id from flovia resets)");
417
+ if (!p.flags.has("--yes"))
418
+ throw new Usage("resets use: add --yes to use it; it cannot be undone. Check first: flovia resets");
419
+ const client = await connect(), u = await waitFor(() => client.useBankedReset(grant));
420
+ if (json)
421
+ print(u);
422
+ else
423
+ out(u.outcome === "used" ? `Used. Both free windows (5-hour and week) start again from 0%.\n${label("saved resets")}${u.available}\n`
424
+ : `Not used; nothing changed.\n${label("saved resets")}${u.available}\nCheck: flovia resets\n`);
425
+ return u.outcome === "used" ? 0 : 1;
426
+ }
348
427
  case "usage": {
349
428
  const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")), 7), cursor = str(p.flags.get("--cursor"));
350
429
  if (since !== undefined && days !== undefined)
@@ -525,6 +604,7 @@ if (isMain) {
525
604
  };
526
605
  process.exitCode = await run(process.argv.slice(2), {
527
606
  env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
607
+ writeOutput: writePrivateOutput,
528
608
  readFile: (path) => readFile(path, "utf8"), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
529
609
  confirm: tty ? confirm : null,
530
610
  ...(process.stderr.isTTY ? { waiting: () => {
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Generation, type GenerationRequest, type StatusReply, type ToolReply, type UsageTodayArgs, type UsageTodayReply } from "./types.js";
1
+ import { type Generation, type GenerationRequest, type StatusReply, type ToolReply, type UsageTodayArgs, type UsageTodayReply, type BankedResets, type BankedResetUse } from "./types.js";
2
2
  export interface FloviaClientOptions {
3
3
  /** A Flovia key (flv_...). Defaults to the FLOVIA_KEY environment variable. Never logged. */
4
4
  apiKey?: string;
@@ -27,6 +27,18 @@ export declare const newOperationId: () => string;
27
27
  export declare class FloviaClient {
28
28
  #private;
29
29
  constructor(options?: FloviaClientOptions);
30
+ /** Download an existing Runway output before its 24h expiry. This GET never creates, regenerates or retries a task. */
31
+ downloadRunwayOutput(generationId: string): Promise<{
32
+ data: Uint8Array;
33
+ contentType: string;
34
+ }>;
35
+ /** The account's saved resets: count and the first to expire. Read-only; nothing is used. */
36
+ bankedResets(): Promise<BankedResets>;
37
+ /**
38
+ * Use one saved reset (its id from bankedResets()): both free windows, 5-hour and week, start again. Never resent automatically;
39
+ * "not_used" means nothing changed. After a lost, refused (401) or unreadable reply, check bankedResets() before deciding to try again.
40
+ */
41
+ useBankedReset(grantId: number): Promise<BankedResetUse>;
30
42
  /** tools/list: the tools this key is offered, with their input schemas. */
31
43
  listTools(): Promise<ToolInfo[]>;
32
44
  /** tools/call for any tool. A reply with ok: false throws FloviaError (handshakes such as notice_first too; see error.reply). */
package/dist/client.js CHANGED
@@ -77,10 +77,10 @@ export class FloviaClient {
77
77
  return new FloviaError(safe);
78
78
  }
79
79
  /** One HTTP request. A network failure or timeout is executed "unknown": the relay may have received it. */
80
- async #send(path, body, headers = {}, operationId = null) {
80
+ async #send(path, body, headers = {}, operationId = null, method = "POST") {
81
81
  let request;
82
82
  try {
83
- request = new Request(this.#base + path, { method: "POST", redirect: "error", body: JSON.stringify(body), signal: AbortSignal.timeout(this.#timeoutMs),
83
+ request = new Request(this.#base + path, { method, redirect: "error", body: method === "POST" ? JSON.stringify(body) : null, signal: AbortSignal.timeout(this.#timeoutMs),
84
84
  // The family only, so the relay can count SDK calls apart from other clients; never a version or an id.
85
85
  headers: { Authorization: `Bearer ${this.#key}`, "Content-Type": "application/json", "X-Flovia-Client": "flovia-sdk", ...headers,
86
86
  ...(this.#accessToken ? { "Cf-Access-Token": this.#accessToken } : {}) } });
@@ -119,6 +119,94 @@ export class FloviaClient {
119
119
  message: String(message.error?.message ?? "No result."), nextStep: operationId ? SAME_OPERATION : null });
120
120
  return message.result;
121
121
  }
122
+ /** Download an existing Runway output before its 24h expiry. This GET never creates, regenerates or retries a task. */
123
+ async downloadRunwayOutput(generationId) {
124
+ const unavailable = () => this.#error({ code: "output_unavailable", executed: "no", message: "The private output could not be downloaded.", nextStep: "Check the original generation's status and expiry; never regenerate it automatically." });
125
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(generationId))
126
+ throw this.#error({ code: "invalid_request", executed: "no", message: "Use the generation_id returned by Flovia, never a URL or upstream task ID." });
127
+ let reader;
128
+ try {
129
+ const response = await this.#send("/mcp?runway_output=" + generationId, null, { Accept: "image/png, image/jpeg, image/webp, video/mp4" }, null, "GET");
130
+ const contentType = response.headers.get("Content-Type"), declared = response.headers.get("Content-Length"), length = declared === null ? null : Number(declared), limit = 32 * 1024 * 1024;
131
+ if (response.status !== 200 || !response.body || contentType === null || !["image/png", "image/jpeg", "image/webp", "video/mp4"].includes(contentType ?? "") ||
132
+ length !== null && (!Number.isSafeInteger(length) || length < 1 || length > limit))
133
+ throw unavailable();
134
+ reader = response.body.getReader();
135
+ const chunks = [];
136
+ let size = 0;
137
+ while (true) {
138
+ const { value, done } = await reader.read();
139
+ if (done)
140
+ break;
141
+ size += value.byteLength;
142
+ if (size > limit)
143
+ throw unavailable();
144
+ chunks.push(value);
145
+ }
146
+ if (size === 0 || length !== null && size !== length)
147
+ throw unavailable();
148
+ const data = new Uint8Array(size);
149
+ let offset = 0;
150
+ for (const chunk of chunks) {
151
+ data.set(chunk, offset);
152
+ offset += chunk.byteLength;
153
+ }
154
+ return { data, contentType };
155
+ }
156
+ catch (error) {
157
+ await reader?.cancel().catch(() => { });
158
+ if (error instanceof FloviaError && ["unauthorized", "formal_registration_required"].includes(error.code))
159
+ throw error;
160
+ throw unavailable();
161
+ }
162
+ finally {
163
+ reader?.releaseLock();
164
+ }
165
+ }
166
+ /** The account's saved resets: count and the first to expire. Read-only; nothing is used. */
167
+ async bankedResets() {
168
+ const r = await this.#send("/account/banked-resets", null, {}, null, "GET");
169
+ const body = await this.#account(r, null);
170
+ if (!isResets(body))
171
+ throw this.#error({ code: "invalid_reply", status: r.status, executed: "no", message: "The saved-reset reply was not in the expected form.", nextStep: null });
172
+ return { available: body.available, next: body.next };
173
+ }
174
+ /**
175
+ * Use one saved reset (its id from bankedResets()): both free windows, 5-hour and week, start again. Never resent automatically;
176
+ * "not_used" means nothing changed. After a lost, refused (401) or unreadable reply, check bankedResets() before deciding to try again.
177
+ */
178
+ async useBankedReset(grantId) {
179
+ if (!Number.isSafeInteger(grantId) || grantId <= 0)
180
+ throw new FloviaError({ code: "invalid_request", executed: "no", message: "grantId must be a positive whole number from bankedResets()." });
181
+ const check = "It may have been used. Run bankedResets() (flovia resets) to see whether it was used before trying again.";
182
+ const unknown = (e) => this.#error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
183
+ nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check });
184
+ let r;
185
+ try {
186
+ r = await this.#send("/account/banked-resets/use", { grant_id: grantId });
187
+ }
188
+ // The relay rechecks the key after the use, so a 401 does not prove that nothing changed.
189
+ catch (e) {
190
+ throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? unknown(e) : e;
191
+ }
192
+ const body = await this.#account(r, check);
193
+ if (!isResets(body) || (body["outcome"] !== "used" && body["outcome"] !== "not_used"))
194
+ throw this.#error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The saved-reset reply was not in the expected form.", nextStep: check });
195
+ return { outcome: body["outcome"], available: body.available, next: body.next };
196
+ }
197
+ async #account(r, unknownStep) {
198
+ let body;
199
+ try {
200
+ body = await readReply(r, null, init => this.#error(init));
201
+ }
202
+ catch (e) {
203
+ throw e instanceof FloviaError && unknownStep !== null ? this.#error({ code: e.code, status: r.status, executed: "unknown", message: e.message, nextStep: unknownStep }) : e;
204
+ }
205
+ if (r.status === 200)
206
+ return body;
207
+ throw this.#error({ code: typeof body["error"] === "string" ? body["error"] : `http_${r.status}`, status: r.status, executed: r.status >= 500 && unknownStep !== null ? "unknown" : "no",
208
+ message: typeof body["message"] === "string" ? body["message"] : `HTTP ${r.status}`, nextStep: r.status >= 500 ? unknownStep : null });
209
+ }
122
210
  /** tools/list: the tools this key is offered, with their input schemas. */
123
211
  async listTools() {
124
212
  return (await this.#rpc("tools/list")).tools;
@@ -151,7 +239,7 @@ export class FloviaClient {
151
239
  return reply;
152
240
  const wait = seconds(reply.retry_after_seconds);
153
241
  // Only a refusal that surely did not run; at least 1 s apart, so a missing or 0 wait never resends at once.
154
- if (this.#resend && attempt === 0 && e.executed === "no" && RESEND_CODES.has(e.code) && (wait ?? 0) <= MAX_RESEND_WAIT_S) {
242
+ if (tool !== "flovia_runway" && this.#resend && attempt === 0 && e.executed === "no" && RESEND_CODES.has(e.code) && (wait ?? 0) <= MAX_RESEND_WAIT_S) {
155
243
  await sleep(Math.max(1, wait ?? 0) * 1000);
156
244
  continue;
157
245
  }
@@ -197,6 +285,13 @@ export class FloviaClient {
197
285
  retryAfterSeconds: seconds(r.headers.get("Retry-After")) ?? seconds(body["retry_after_seconds"]) });
198
286
  }
199
287
  }
288
+ const count = (v, min) => typeof v === "number" && Number.isSafeInteger(v) && v >= min;
289
+ /** The saved-reset summary's exact public form. */
290
+ function isResets(b) {
291
+ const next = b["next"];
292
+ return count(b["available"], 0) && (next === null || (typeof next === "object" && !Array.isArray(next) && count(next["id"], 1)
293
+ && typeof next["expires_at"] === "string" && !Number.isNaN(Date.parse(next["expires_at"])))) && (next === null) === (b["available"] === 0);
294
+ }
200
295
  /** Whether a refused generation ran, from its public code (the same reading flovia_openai gives over MCP). */
201
296
  function generationExecuted(code) {
202
297
  if (["answer_unavailable", "answer_expired", "answer_delivery_denied"].includes(code))
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.149";
2
+ export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.167";
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 ["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", "free_not_granted", "global_cap", "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed", "operation_conflict", "operation_pending", "relay_internal_error", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "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", "provider_not_allowed", "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_month", "window_week", "over_week", "free_limited", "free_needs_email", "free_not_granted", "global_cap", "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed", "operation_conflict", "operation_pending", "relay_internal_error", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "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";
@@ -80,3 +80,15 @@ export interface Generation {
80
80
  receivedAt: string | null;
81
81
  conversationId: string | null;
82
82
  }
83
+ /** GET /account/banked-resets: saved resets that can still be used, and the first to expire. */
84
+ export interface BankedResets {
85
+ available: number;
86
+ next: {
87
+ id: number;
88
+ expires_at: string;
89
+ } | null;
90
+ }
91
+ /** "used": both free windows (5-hour and week) start again. "not_used": nothing changed (already used, expired, a lookup still settling, or nothing to reset). */
92
+ export interface BankedResetUse extends BankedResets {
93
+ outcome: "used" | "not_used";
94
+ }
package/dist/types.js CHANGED
@@ -1,11 +1,11 @@
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.149";
2
+ export const EXPECTED_CONTRACT_VERSION = "2026-10-07.167";
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
  "approval_pending", "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first",
6
- "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large",
6
+ "provider_not_allowed", "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", "window_5h", "window_week", "over_week", "free_limited", "free_needs_email", "free_not_granted", "global_cap",
8
+ "over_max_credits", "window_5h", "window_month", "window_week", "over_week", "free_limited", "free_needs_email", "free_not_granted", "global_cap",
9
9
  "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed",
10
10
  "operation_conflict", "operation_pending", "relay_internal_error", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "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",
package/package.json CHANGED
@@ -1,10 +1,15 @@
1
1
  {
2
2
  "name": "@flovialabs/sdk",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
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",
7
7
  "homepage": "https://api.flovia.dev",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/flovia/groupbuy.git",
11
+ "directory": "packages/flovia-sdk"
12
+ },
8
13
  "keywords": [
9
14
  "flovia",
10
15
  "mcp",