@flovialabs/sdk 0.1.1 → 0.1.3
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 +12 -0
- package/README.md +15 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +90 -31
- package/dist/client.js +20 -13
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/types.d.ts +3 -1
- package/dist/types.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
- Redact the configured API key when it is echoed in SDK errors, recovery metadata, diagnostic reply fields or contract warnings.
|
|
6
|
+
|
|
7
|
+
## 0.1.2
|
|
8
|
+
|
|
9
|
+
- CLI status distinguishes a successful connection from declined sharing, withdrawal, stopped keys and consent that needs an answer.
|
|
10
|
+
- Unknown commands and options never echo the untrusted input. Prompts starting with a hyphen are accepted after `--`.
|
|
11
|
+
- Added `--version`, safe setup and authentication recovery steps, stdin examples and shorter help and tool listings.
|
|
12
|
+
- Interactive generation shows elapsed waiting time on stderr. Recovery keeps the same operation id, input and output limit; there are no automatic retries.
|
|
13
|
+
- 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.
|
|
14
|
+
|
|
3
15
|
## 0.1.1
|
|
4
16
|
|
|
5
17
|
- CLI generation output shows the response status and incomplete reason. A delivered partial answer still exits 0; no continuation is generated automatically.
|
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ 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.
|
|
13
|
+
npm install --save-exact @flovialabs/sdk@0.1.3
|
|
14
14
|
```
|
|
15
15
|
|
|
16
16
|
## Your key
|
|
@@ -134,8 +134,21 @@ npx flovia generate --op sdk-example-0001 --max-output 300 "Explain a DEX aggreg
|
|
|
134
134
|
# Only to reopen that exact request within about 15 minutes (not a new generation):
|
|
135
135
|
npx flovia generate --op sdk-example-0001 --max-output 300 --yes "Explain a DEX aggregator."
|
|
136
136
|
npx flovia help
|
|
137
|
+
npx flovia --version
|
|
137
138
|
```
|
|
138
|
-
These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.
|
|
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.3 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.
|
|
139
152
|
|
|
140
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`.
|
|
141
154
|
|
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: "
|
|
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
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"
|
|
42
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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(
|
|
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,27 +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}
|
|
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" : ""}`);
|
|
127
158
|
lines.push(`bought balance ${String(s["purchased_balance_display"] ?? "-")}`);
|
|
128
159
|
const pending = obj(s["free_pending"]);
|
|
129
160
|
if (pending["next_step"])
|
|
130
|
-
lines.push(`
|
|
131
|
-
const stopped = obj(s["stopped"]);
|
|
132
|
-
if (stopped["message"])
|
|
133
|
-
lines.push(`key stopped: ${String(stopped["message"])}`);
|
|
161
|
+
lines.push(`usage allowance not started: ${String(pending["next_step"])}`);
|
|
134
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)}` : ""}`; });
|
|
135
|
-
lines.push(
|
|
163
|
+
lines.push("services (provider state)", ...services.map((v) => ` ${v}`));
|
|
136
164
|
lines.push(`turned off ${s.services_off.length ? s.services_off.join(", ") : "none"}`);
|
|
137
|
-
const consent = obj(s["data_consent"]);
|
|
138
|
-
if (consent["needed"] === true)
|
|
139
|
-
lines.push("data consent needed: lookups wait for the person's own y/n (answer through the normal flow, not this CLI)");
|
|
140
165
|
const updates = Array.isArray(s["recent_updates"]) ? s["recent_updates"] : [];
|
|
141
166
|
for (const u of updates.slice(0, 2)) {
|
|
142
167
|
const x = obj(u), first = Array.isArray(x["lines"]) ? String(x["lines"][0] ?? "") : "";
|
|
143
|
-
lines.push(`update ${String(x["version"])} (${String(x["date"])}): ${first}`);
|
|
168
|
+
lines.push(prose(`update ${String(x["version"])} (${String(x["date"])}): ${first}`));
|
|
144
169
|
}
|
|
145
170
|
if (updates.length > 2)
|
|
146
171
|
lines.push(`+${updates.length - 2} more (--json)`);
|
|
@@ -149,8 +174,8 @@ export function renderStatus(s, expected, now = Date.now()) {
|
|
|
149
174
|
export function renderUsage(u, today = false, now = Date.now()) {
|
|
150
175
|
const lines = [`since ${when(u["since"], now)} until ${when(u["until"], now)}${today ? " (today, UTC; use --days 7 for the week)" : ""}`];
|
|
151
176
|
const week = obj(u["free_week"]);
|
|
152
|
-
lines.push(`
|
|
153
|
-
lines.push(`total in this period: ${String(obj(u["total"])["free_display"] ?? "-")} of the
|
|
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`);
|
|
154
179
|
lines.push(`bought credits used: ${String(obj(u["total"])["bought_display"] ?? "-")} total (includes generations)`);
|
|
155
180
|
// Endpoint percentages are rounded (0 can mean <1%); only counts can be summed by source.
|
|
156
181
|
const bySource = new Map();
|
|
@@ -161,7 +186,7 @@ export function renderUsage(u, today = false, now = Date.now()) {
|
|
|
161
186
|
if (bySource.size)
|
|
162
187
|
lines.push("", table([["source", "lookups"], ...[...bySource].map(([n, count]) => [n, String(count)])]).trimEnd());
|
|
163
188
|
const g = obj(u["generations"]);
|
|
164
|
-
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
|
|
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)`);
|
|
165
190
|
if (u.has_more)
|
|
166
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)}`);
|
|
167
192
|
return lines.join("\n") + "\n";
|
|
@@ -169,6 +194,8 @@ export function renderUsage(u, today = false, now = Date.now()) {
|
|
|
169
194
|
/** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
|
|
170
195
|
export function renderError(e) {
|
|
171
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.");
|
|
172
199
|
if (e.nextStep)
|
|
173
200
|
lines.push(`next_step: ${e.nextStep}`);
|
|
174
201
|
lines.push(`executed: ${e.executed}`);
|
|
@@ -199,6 +226,10 @@ export async function run(argv, io) {
|
|
|
199
226
|
out(help(p.positional[0]));
|
|
200
227
|
return 0;
|
|
201
228
|
}
|
|
229
|
+
if (p.command === "version") {
|
|
230
|
+
out(`flovia ${VERSION}\n`);
|
|
231
|
+
return 0;
|
|
232
|
+
}
|
|
202
233
|
key = await readKey(p, io);
|
|
203
234
|
}
|
|
204
235
|
catch (e) {
|
|
@@ -210,6 +241,7 @@ export async function run(argv, io) {
|
|
|
210
241
|
}
|
|
211
242
|
const json = p.flags.has("--json"), print = (v) => out(JSON.stringify(v, null, 2) + "\n");
|
|
212
243
|
let mismatch = null;
|
|
244
|
+
let recoveryLimit;
|
|
213
245
|
try {
|
|
214
246
|
const timeout = positiveInt("--timeout", str(p.flags.get("--timeout")));
|
|
215
247
|
const baseUrl = str(p.flags.get("--base-url"));
|
|
@@ -248,7 +280,7 @@ export async function run(argv, io) {
|
|
|
248
280
|
if (json)
|
|
249
281
|
print(tools);
|
|
250
282
|
else
|
|
251
|
-
out(
|
|
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");
|
|
252
284
|
return 0;
|
|
253
285
|
}
|
|
254
286
|
case "call": {
|
|
@@ -279,11 +311,12 @@ export async function run(argv, io) {
|
|
|
279
311
|
if (input.trim() === "")
|
|
280
312
|
throw new Usage("generate: the prompt is empty");
|
|
281
313
|
const max = positiveInt("--max-output", str(p.flags.get("--max-output")));
|
|
314
|
+
recoveryLimit = max;
|
|
282
315
|
const id = op ?? newOperationId();
|
|
283
316
|
// The id is shown before anything is sent, so a lost reply can be reopened with it (never resent under a new one).
|
|
284
317
|
if (fresh)
|
|
285
318
|
err(`operation_id: ${id}\nSave it. To resend or reopen this request, use: --op ${id}\n`);
|
|
286
|
-
err("This generation uses Flovia credits (
|
|
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");
|
|
287
320
|
if (!p.flags.has("--yes")) {
|
|
288
321
|
if (io.confirm === null || text === "-")
|
|
289
322
|
throw new Usage("generate: add --yes to send (no terminal to confirm on)");
|
|
@@ -292,12 +325,29 @@ export async function run(argv, io) {
|
|
|
292
325
|
return 2;
|
|
293
326
|
}
|
|
294
327
|
}
|
|
295
|
-
const
|
|
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
|
+
}
|
|
296
336
|
const reason = obj(g.response["incomplete_details"])["reason"];
|
|
297
337
|
if (json)
|
|
298
338
|
print(g);
|
|
299
|
-
else
|
|
300
|
-
out(`${g.outputText}\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
|
+
}
|
|
301
351
|
return 0;
|
|
302
352
|
}
|
|
303
353
|
}
|
|
@@ -312,6 +362,8 @@ export async function run(argv, io) {
|
|
|
312
362
|
if (json && e.reply)
|
|
313
363
|
print(e.reply);
|
|
314
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`);
|
|
315
367
|
return e.code === "invalid_base_url" ? 2 : 1;
|
|
316
368
|
}
|
|
317
369
|
err(`error: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
@@ -348,5 +400,12 @@ if (isMain) {
|
|
|
348
400
|
env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
|
|
349
401
|
readFile: (path) => readFile(path, "utf8"), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
|
|
350
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
|
+
} } : {}),
|
|
351
410
|
});
|
|
352
411
|
}
|
package/dist/client.js
CHANGED
|
@@ -14,7 +14,7 @@ const seconds = (v) => {
|
|
|
14
14
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
15
|
const SAME_OPERATION = "Resend with the same operation_id; do not use a new one.";
|
|
16
16
|
/** A lost or unreadable reply cannot prove that the operation did not run. */
|
|
17
|
-
async function readReply(r, operationId, sse = false) {
|
|
17
|
+
async function readReply(r, operationId, makeError, sse = false) {
|
|
18
18
|
try {
|
|
19
19
|
const text = (await r.text()).trimStart();
|
|
20
20
|
const payload = sse && !text.startsWith("{") ? text.split(/\r?\n/).filter((l) => l.startsWith("data:"))
|
|
@@ -26,7 +26,7 @@ async function readReply(r, operationId, sse = false) {
|
|
|
26
26
|
}
|
|
27
27
|
catch (cause) {
|
|
28
28
|
const timeout = cause instanceof Error && cause.name === "TimeoutError";
|
|
29
|
-
throw
|
|
29
|
+
throw makeError({ code: timeout ? "timeout" : `http_${r.status}`, status: r.status, executed: "unknown", operationId,
|
|
30
30
|
message: timeout ? "Timed out while reading the reply." : `Unexpected reply (HTTP ${r.status}).`, nextStep: operationId ? SAME_OPERATION : null });
|
|
31
31
|
}
|
|
32
32
|
}
|
|
@@ -62,18 +62,25 @@ export class FloviaClient {
|
|
|
62
62
|
// eslint-disable-next-line no-console -- versions only, never the key
|
|
63
63
|
this.#onMismatch = options.onContractMismatch ?? ((expected, actual) => console.warn(`Flovia contract ${actual} differs from the SDK's ${expected}; check flovia_status recent_updates.`));
|
|
64
64
|
}
|
|
65
|
+
/** Mask only this client's exact key in diagnostic strings and reply field names; keep Error field names intact. */
|
|
66
|
+
#error(init) {
|
|
67
|
+
const scrub = (text) => text.replaceAll(this.#key, "[key]");
|
|
68
|
+
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
|
+
? Object.fromEntries(Object.entries(value).map(([name, field]) => [scrub(name), field])) : value));
|
|
70
|
+
return new FloviaError(safe);
|
|
71
|
+
}
|
|
65
72
|
/** One HTTP request. A network failure or timeout is executed "unknown": the relay may have received it. */
|
|
66
73
|
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
74
|
let r;
|
|
70
75
|
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 } });
|
|
71
78
|
r = await this.#fetch(request);
|
|
72
79
|
}
|
|
73
80
|
catch (cause) {
|
|
74
81
|
const timeout = cause instanceof Error && cause.name === "TimeoutError";
|
|
75
82
|
// Transport diagnostics may contain request headers, so never attach their raw cause.
|
|
76
|
-
throw
|
|
83
|
+
throw this.#error({ code: timeout ? "timeout" : "network_error", executed: "unknown", operationId,
|
|
77
84
|
message: timeout ? `No reply within ${this.#timeoutMs} ms.` : "The request did not complete.",
|
|
78
85
|
nextStep: operationId ? SAME_OPERATION : null });
|
|
79
86
|
}
|
|
@@ -83,9 +90,9 @@ export class FloviaClient {
|
|
|
83
90
|
}
|
|
84
91
|
async #rpc(method, params, operationId = null) {
|
|
85
92
|
const r = await this.#send("/mcp", { jsonrpc: "2.0", id: ++this.#id, method, ...(params ? { params } : {}) }, { Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18" }, operationId);
|
|
86
|
-
const message = await readReply(r, operationId, true);
|
|
93
|
+
const message = await readReply(r, operationId, init => this.#error(init), true);
|
|
87
94
|
if (message.error !== undefined || message.result === null || typeof message.result !== "object" || Array.isArray(message.result))
|
|
88
|
-
throw
|
|
95
|
+
throw this.#error({ code: "mcp_error", status: r.status, executed: "unknown", operationId,
|
|
89
96
|
message: String(message.error?.message ?? "No result."), nextStep: operationId ? SAME_OPERATION : null });
|
|
90
97
|
return message.result;
|
|
91
98
|
}
|
|
@@ -113,7 +120,7 @@ export class FloviaClient {
|
|
|
113
120
|
}
|
|
114
121
|
}
|
|
115
122
|
catch {
|
|
116
|
-
throw
|
|
123
|
+
throw this.#error({ code: "tool_error", executed: "unknown", operationId, nextStep: operationId ? SAME_OPERATION : null,
|
|
117
124
|
message: result.isError ? "The tool failed." : "The tool reply is not JSON." });
|
|
118
125
|
}
|
|
119
126
|
const e = reply.explanation;
|
|
@@ -125,7 +132,7 @@ export class FloviaClient {
|
|
|
125
132
|
await sleep(Math.max(1, wait ?? 0) * 1000);
|
|
126
133
|
continue;
|
|
127
134
|
}
|
|
128
|
-
throw
|
|
135
|
+
throw this.#error({ code: e.code, message: e.meaning, nextStep: e.next_step, executed: e.executed, retryAfterSeconds: wait, operationId, reply });
|
|
129
136
|
}
|
|
130
137
|
}
|
|
131
138
|
/** flovia_status. Warns once when the relay's contract_version is not the one this SDK expects. */
|
|
@@ -133,7 +140,7 @@ export class FloviaClient {
|
|
|
133
140
|
const s = await this.call("flovia_status");
|
|
134
141
|
if (!this.#warned && s.contract_version !== EXPECTED_CONTRACT_VERSION) {
|
|
135
142
|
this.#warned = true;
|
|
136
|
-
this.#onMismatch(EXPECTED_CONTRACT_VERSION, s.contract_version);
|
|
143
|
+
this.#onMismatch(EXPECTED_CONTRACT_VERSION, String(s.contract_version).replaceAll(this.#key, "[key]"));
|
|
137
144
|
}
|
|
138
145
|
return s;
|
|
139
146
|
}
|
|
@@ -151,9 +158,9 @@ export class FloviaClient {
|
|
|
151
158
|
if (!OPERATION_ID.test(op))
|
|
152
159
|
throw new FloviaError({ code: "invalid_operation_id", executed: "no", message: "operationId must be 8-128 of A-Z a-z 0-9 _ . : -" });
|
|
153
160
|
const r = await this.#send("/openai/v1/responses", request, { "Flovia-Operation-Id": op, ...(options.conversationId ? { "Flovia-Conversation-Id": options.conversationId } : {}) }, op);
|
|
154
|
-
const body = await readReply(r, op);
|
|
161
|
+
const body = await readReply(r, op, init => this.#error(init));
|
|
155
162
|
if (r.status === 200 && !Array.isArray(body["output"]))
|
|
156
|
-
throw
|
|
163
|
+
throw this.#error({ code: "http_200", status: 200, executed: "unknown", operationId: op, message: "Unexpected generation reply (HTTP 200).", nextStep: SAME_OPERATION });
|
|
157
164
|
if (r.status === 200)
|
|
158
165
|
return { response: body, outputText: outputText(body), generationId: r.headers.get("Flovia-Generation-Id"),
|
|
159
166
|
replayed: r.headers.get("Flovia-Replayed") === "1", receivedAt: r.headers.get("Flovia-Received-At"), conversationId: r.headers.get("Flovia-Conversation-Id") };
|
|
@@ -161,7 +168,7 @@ export class FloviaClient {
|
|
|
161
168
|
const code = typeof err === "string" ? err : String(err?.code ?? `http_${r.status}`);
|
|
162
169
|
const message = String(err?.message ?? body["message"] ?? `HTTP ${r.status}`);
|
|
163
170
|
const executed = explanation?.executed ?? generationExecuted(code);
|
|
164
|
-
throw
|
|
171
|
+
throw this.#error({ code, message, status: r.status, operationId: op, reply: body,
|
|
165
172
|
executed, nextStep: explanation?.next_step ?? (executed === "unknown" ? SAME_OPERATION : null),
|
|
166
173
|
retryAfterSeconds: seconds(r.headers.get("Retry-After")) ?? seconds(body["retry_after_seconds"]) });
|
|
167
174
|
}
|
package/dist/errors.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export declare class FloviaError extends Error {
|
|
|
11
11
|
readonly status: number | null;
|
|
12
12
|
readonly retryAfterSeconds: number | null;
|
|
13
13
|
readonly operationId: string | null;
|
|
14
|
-
/** The
|
|
14
|
+
/** The reply body with configured-key echoes redacted, including fields such as user_notice or consent.question. */
|
|
15
15
|
readonly reply: ToolReply | null;
|
|
16
16
|
constructor(init: {
|
|
17
17
|
code: string;
|
package/dist/errors.js
CHANGED
|
@@ -10,7 +10,7 @@ export class FloviaError extends Error {
|
|
|
10
10
|
status;
|
|
11
11
|
retryAfterSeconds;
|
|
12
12
|
operationId;
|
|
13
|
-
/** The
|
|
13
|
+
/** The reply body with configured-key echoes redacted, including fields such as user_notice or consent.question. */
|
|
14
14
|
reply;
|
|
15
15
|
constructor(init) {
|
|
16
16
|
super(init.message, init.cause === undefined ? undefined : { cause: init.cause });
|
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.
|
|
2
|
+
export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.119";
|
|
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}`;
|
|
@@ -39,6 +39,8 @@ export interface UsageTodayArgs {
|
|
|
39
39
|
since?: string;
|
|
40
40
|
/** The previous next_cursor, unchanged, with the same since and conversation. */
|
|
41
41
|
cursor?: string;
|
|
42
|
+
/** The previous generations.next_cursor, with the same since and conversation. */
|
|
43
|
+
generation_cursor?: string;
|
|
42
44
|
/** Only this conversation's lookups. */
|
|
43
45
|
conversation?: string;
|
|
44
46
|
}
|
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.
|
|
2
|
+
export const EXPECTED_CONTRACT_VERSION = "2026-10-07.119";
|
|
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