@flovialabs/sdk 0.1.9 → 0.1.11

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,19 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.11
6
+
7
+ - SDK request-construction failures use `invalid_request` with `executed: no` before any request is sent; raw exception causes are not exposed.
8
+ - CLI stdin rejects malformed UTF-8 before sending, and key-file errors no longer expose the local file path.
9
+
10
+ ## 0.1.10
11
+
12
+ - `flovia tools` keeps a short second sentence of each description, so what a tool is for stays visible.
13
+ - `flovia tools <tool>` ends with a runnable `flovia call` example from the schema's required arguments and the stdin form; tools with `operation_id` repeat how to keep it for recovery.
14
+ - An unknown tool name in `tools <tool>` or `call` suggests the closest offered name. `call` reads the catalog only after Flovia reports the name as unknown.
15
+ - With `--json`, errors are also printed as one JSON object on stdout (`ok`, `code`, `meaning`, `next_step`, `executed`, `retry_after_seconds`, `operation_id`, plus the reply's fields). Exit codes are unchanged.
16
+ - New `flovia agents-md` prints a short note for `CLAUDE.md` or `AGENTS.md`. No key or network is used.
17
+
5
18
  ## 0.1.9
6
19
 
7
20
  - `flovia tools <tool>` shows just one offered tool's full description and input schema. With `--json` it returns that tool object; the existing full catalog array is unchanged. This only reads the catalog.
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.9
13
+ npm install --save-exact @flovialabs/sdk@0.1.11
14
14
  ```
15
15
 
16
16
  ## Your key
@@ -226,10 +226,11 @@ npx flovia call flovia_usage_today '{}'
226
226
  npx flovia generate --op sdk-example-0001 --max-output 1000 --reasoning-effort low "Explain a DEX aggregator."
227
227
  # Only to reopen that exact request within about 15 minutes (not a new generation):
228
228
  npx flovia generate --op sdk-example-0001 --max-output 1000 --reasoning-effort low --yes "Explain a DEX aggregator."
229
+ npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
229
230
  npx flovia help
230
231
  npx flovia --version
231
232
  ```
232
- These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.9 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.
233
+ These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.11 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.
233
234
 
234
235
  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.
235
236
 
@@ -239,7 +240,11 @@ For a data lookup, save its JSON object (including your chosen `operation_id`) i
239
240
  flovia call flovia_coingecko - < request.json
240
241
  ```
241
242
 
242
- This sends the saved request once. Reopening it uses the same file and operation ID; never create a new ID to recover a lost answer. The CLI does not invent or save an ID for `call`. Inspect the live `inputSchema` first, and follow any returned consent or recovery instructions. `tools <tool> --json` returns one tool object; `tools --json` keeps returning the full array. Neither executes a data lookup.
243
+ This sends the saved request once. Reopening it uses the same file and operation ID; never create a new ID to recover a lost answer. The CLI does not invent or save an ID for `call`. Inspect the live `inputSchema` first, and follow any returned consent or recovery instructions. `tools <tool> --json` returns one tool object; `tools --json` keeps returning the full array. Neither executes a data lookup. Without `--json`, `tools <tool>` ends with an example `call` line built from the schema's required arguments (placeholders to replace). An unknown tool name gets the closest offered name.
244
+
245
+ With `--json`, an error is also one JSON object on stdout: `ok: false`, `code`, `meaning`, and when present `next_step`, `executed`, `retry_after_seconds` and `operation_id`, next to the reply's own fields. Exit codes stay 0, 1 and 2.
246
+
247
+ For an AI agent, `flovia agents-md` prints a short note to paste into `CLAUDE.md` or `AGENTS.md`. It contains no key and makes no request.
243
248
 
244
249
  For multiline generation text, keep the original input in a private file:
245
250
 
package/dist/cli.d.ts CHANGED
@@ -15,6 +15,9 @@ export interface Io {
15
15
  /** TTY-only waiting feedback on stderr; returns a cleanup function. Never used with --json. */
16
16
  waiting?: () => () => void;
17
17
  }
18
+ export declare const AGENTS_MD = "## Flovia\n- Flovia is available through the `flovia` CLI. The key is in the FLOVIA_KEY environment variable; never paste, print or commit it.\n- Run `flovia status` first: it shows allowances, services and any consent the person must answer.\n- Find a tool with `flovia tools`, and its arguments with `flovia tools <tool> --json`.\n- Write the arguments to request.json, then run `flovia call <tool> - < request.json`.\n- Before a data lookup, save request.json with its operation_id. To recover a lost reply, send the same file with the same id; never a new id.\n- On an error, read `next_step` (and `retry_after_seconds`) and follow it. With `--json`, errors are one JSON object on stdout.\n";
19
+ /** Runnable call lines from the schema's required properties, the stdin form and, with operation_id, how to keep it. */
20
+ export declare function exampleCall(tool: string, schema: unknown): string;
18
21
  export declare function help(command?: string): string;
19
22
  export interface Parsed {
20
23
  command: string;
@@ -29,5 +32,5 @@ export declare function renderUsage(u: UsageTodayReply, today?: boolean, now?: n
29
32
  /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
30
33
  export declare function renderError(e: FloviaError): string;
31
34
  export declare function run(argv: string[], io: Io): Promise<number>;
32
- /** Decode UTF-8 across chunks, including a character split between reads. */
35
+ /** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
33
36
  export declare function readStdin(input: NodeJS.ReadableStream): Promise<string>;
package/dist/cli.js CHANGED
@@ -17,6 +17,7 @@ const COMMANDS = {
17
17
  tools: { usage: "tools [tool]", about: "list offered tools, or inspect one tool's description and arguments", flags: {} },
18
18
  call: { usage: "call <tool> ['<json args>' | -]", about: "call a tool; - reads a JSON object from stdin", flags: {} },
19
19
  generate: { usage: "generate (--op ID | --new-op) [--max-output N]\n [--reasoning-effort LEVEL] [--yes] <prompt | ->", about: "a text generation (uses your free allowance, then your purchased balance)", flags: { "--op": true, "--new-op": false, "--max-output": true, "--reasoning-effort": true, "--yes": false } },
20
+ "agents-md": { usage: "agents-md", about: "a short Flovia note to paste into CLAUDE.md or AGENTS.md (no network)", flags: {} },
20
21
  help: { usage: "help [command]", about: "this help", flags: {} },
21
22
  version: { usage: "version", about: "the installed CLI version", flags: {} },
22
23
  };
@@ -35,6 +36,50 @@ function distance(a, b) {
35
36
  }
36
37
  const near = (word, options) => options.find((k) => distance(k, word) <= 2 || k.startsWith(word));
37
38
  const didYouMean = (word, options, quote = "") => { const n = near(word, options); return n === undefined ? "" : `; did you mean ${quote}${n}${quote}?`; };
39
+ /** Agents often drop the flovia_ prefix ("coingecko"), which is too far for near() alone. */
40
+ const notOffered = (word, names) => {
41
+ const n = near(word, names) ?? near(`flovia_${word}`, names);
42
+ return `Tool is not offered to this key${n === undefined ? "." : `; did you mean "${n}"?`} Run: flovia tools`;
43
+ };
44
+ const SAVE_OP = ["Save the request and operation_id before sending a data lookup.",
45
+ "To recover a lost reply, keep the same request and operation_id.",
46
+ "Never create a new operation_id just to recover an answer."];
47
+ export const AGENTS_MD = `## Flovia
48
+ - Flovia is available through the \`flovia\` CLI. The key is in the FLOVIA_KEY environment variable; never paste, print or commit it.
49
+ - Run \`flovia status\` first: it shows allowances, services and any consent the person must answer.
50
+ - Find a tool with \`flovia tools\`, and its arguments with \`flovia tools <tool> --json\`.
51
+ - Write the arguments to request.json, then run \`flovia call <tool> - < request.json\`.
52
+ - Before a data lookup, save request.json with its operation_id. To recover a lost reply, send the same file with the same id; never a new id.
53
+ - On an error, read \`next_step\` (and \`retry_after_seconds\`) and follow it. With \`--json\`, errors are one JSON object on stdout.
54
+ `;
55
+ /** A placeholder for one schema property: its example, default or first enum value, else a value of its type. */
56
+ function placeholder(name, s) {
57
+ if (s.example !== undefined)
58
+ return s.example;
59
+ if (Array.isArray(s.examples) && s.examples.length)
60
+ return s.examples[0];
61
+ if (s.default !== undefined)
62
+ return s.default;
63
+ if (Array.isArray(s.enum) && s.enum.length)
64
+ return s.enum[0];
65
+ const type = Array.isArray(s.type) ? s.type[0] : s.type;
66
+ return type === "integer" || type === "number" ? 1 : type === "boolean" ? false : type === "array" ? [] : type === "object" ? {} : `<${name}>`;
67
+ }
68
+ /** Runnable call lines from the schema's required properties, the stdin form and, with operation_id, how to keep it. */
69
+ export function exampleCall(tool, schema) {
70
+ const s = obj(schema), props = obj(s["properties"]), required = Array.isArray(s["required"]) ? s["required"].map(String) : [];
71
+ const args = Object.fromEntries(required.map((k) => [k, placeholder(k, obj(props[k]))]));
72
+ const lines = ["", "Example (replace the placeholders):", ` flovia call ${tool} '${JSON.stringify(args).replaceAll("'", "'\\''")}'`,
73
+ "Or from a saved file:", ` flovia call ${tool} - < request.json`];
74
+ if (Object.hasOwn(props, "operation_id"))
75
+ lines.push(...SAVE_OP);
76
+ return lines.join("\n") + "\n";
77
+ }
78
+ /** The first sentence, plus the next when both fit in about 200 characters, so what the tool is for survives. */
79
+ const brief = (description) => {
80
+ const [first = "", second] = description.split(/(?<=\.)\s/);
81
+ return second !== undefined && first.length + second.length < 200 ? `${first} ${second}` : first;
82
+ };
38
83
  export function help(command) {
39
84
  const c = command === undefined || !Object.hasOwn(COMMANDS, command) ? undefined : COMMANDS[command];
40
85
  const lines = c === undefined ? ["Usage: flovia <command> [options]", "",
@@ -45,7 +90,7 @@ export function help(command) {
45
90
  if (command === "tools" || c === undefined)
46
91
  lines.push("", "Inspect one tool: flovia tools <tool> --json", "Inspect all tool arguments: flovia tools --json", "Read-only example: flovia call flovia_status '{}'");
47
92
  if (command === "call")
48
- lines.push("", "Read a saved request: flovia call <tool> - < request.json", "Save the request and operation_id before sending a data lookup.", "To recover a lost reply, keep the same request and operation_id.", "Never create a new operation_id just to recover an answer.");
93
+ lines.push("", "Read a saved request: flovia call <tool> - < request.json", ...SAVE_OP);
49
94
  lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 error from Flovia, 2 usage error.", "");
50
95
  return lines.join("\n");
51
96
  }
@@ -108,18 +153,19 @@ async function readKey(p, io) {
108
153
  const file = str(p.flags.get("--key-file"));
109
154
  if (file !== undefined) {
110
155
  let text;
156
+ // Never echo the path: a key pasted in its place would land in the output.
111
157
  try {
112
158
  text = await io.readFile(file);
113
159
  }
114
160
  catch {
115
- throw new Usage(`--key-file: cannot read ${file}`);
161
+ throw new Usage("--key-file: cannot read the key file");
116
162
  }
117
163
  const key = text.trim();
118
164
  if (key === "")
119
- throw new Usage(`--key-file: ${file} is empty`);
165
+ throw new Usage("--key-file: the key file is empty");
120
166
  const mode = await io.fileMode?.(file).catch(() => null);
121
167
  if (typeof mode === "number" && (mode & 0o077) !== 0)
122
- io.err(`warning: ${file} is readable by other users (mode ${(mode & 0o777).toString(8)}); run: chmod 600 ${file}\n`);
168
+ io.err(`warning: the key file is readable by other users (mode ${(mode & 0o777).toString(8)}); run chmod 600 on it\n`);
123
169
  return key;
124
170
  }
125
171
  const key = io.env["FLOVIA_KEY"]?.trim();
@@ -243,10 +289,16 @@ export async function run(argv, io) {
243
289
  out(`flovia ${VERSION}\n`);
244
290
  return 0;
245
291
  }
292
+ if (p.command === "agents-md") {
293
+ out(AGENTS_MD);
294
+ return 0;
295
+ }
246
296
  }
247
297
  catch (e) {
248
298
  if (e instanceof Usage) {
249
299
  err(`${e.message}\n`);
300
+ if (argv.includes("--json"))
301
+ out(JSON.stringify({ ok: false, code: "usage", meaning: e.message }, null, 2) + "\n");
250
302
  return 2;
251
303
  }
252
304
  throw e;
@@ -310,16 +362,16 @@ export async function run(argv, io) {
310
362
  if (name !== undefined) {
311
363
  const tool = tools.find((t) => t.name === name);
312
364
  if (tool === undefined)
313
- throw new Usage("Tool is not offered to this key. Run: flovia tools");
365
+ throw new Usage(notOffered(name, tools.map((t) => t.name)));
314
366
  if (json)
315
367
  print(tool);
316
368
  else
317
- out(`${tool.name}\n${tool.description ?? ""}\n\nArguments (JSON Schema):\n${JSON.stringify(tool.inputSchema, null, 2)}\n`);
369
+ out(`${tool.name}\n${tool.description ?? ""}\n\nArguments (JSON Schema):\n${JSON.stringify(tool.inputSchema, null, 2)}\n${exampleCall(tool.name, tool.inputSchema)}`);
318
370
  }
319
371
  else if (json)
320
372
  print(tools);
321
373
  else
322
- out(tools.map((t) => `${t.name}\n ${prose((t.description ?? "").split(/(?<=\.)\s/)[0] ?? "")}\n`).join("\n") + "\nArguments: flovia tools <tool> --json\nRead-only example: flovia call flovia_status '{}'\n");
374
+ out(tools.map((t) => `${t.name}\n ${prose(brief(t.description ?? ""))}\n`).join("\n") + "\nArguments: flovia tools <tool> --json\nRead-only example: flovia call flovia_status '{}'\n");
323
375
  return 0;
324
376
  }
325
377
  case "call": {
@@ -346,7 +398,16 @@ export async function run(argv, io) {
346
398
  if (args === null || typeof args !== "object" || Array.isArray(args))
347
399
  throw new Usage("call: the arguments must be a JSON object");
348
400
  const client = await connect();
349
- print(await waitFor(() => client.call(tool, args)));
401
+ try {
402
+ print(await waitFor(() => client.call(tool, args)));
403
+ }
404
+ catch (e) {
405
+ // The relay's MCP server refuses an unknown name with "Tool <name> not found" before running anything; only then read the catalog to suggest one.
406
+ if (!(e instanceof FloviaError && e.code === "mcp_error" && /\bTool \S+ (not found|disabled)/.test(e.message)))
407
+ throw e;
408
+ const names = await client.listTools().then((t) => t.map((x) => x.name), () => []);
409
+ throw new FloviaError({ code: "tool_not_offered", executed: "no", message: notOffered(tool, names), nextStep: "Run: flovia tools" });
410
+ }
350
411
  return 0;
351
412
  }
352
413
  case "generate": {
@@ -359,7 +420,14 @@ export async function run(argv, io) {
359
420
  const max = positiveInt("--max-output", str(p.flags.get("--max-output")));
360
421
  const effort = reasoningEffort(str(p.flags.get("--reasoning-effort")));
361
422
  const client = await connect();
362
- const input = text === "-" ? await io.readStdin() : text;
423
+ let input = text;
424
+ if (text === "-")
425
+ try {
426
+ input = await io.readStdin();
427
+ }
428
+ catch {
429
+ throw new Usage("generate: cannot read the prompt from stdin (it must be UTF-8 text)");
430
+ }
363
431
  if (input.trim() === "")
364
432
  throw new Usage("generate: the prompt is empty");
365
433
  recoveryLimit = max;
@@ -401,27 +469,33 @@ export async function run(argv, io) {
401
469
  catch (e) {
402
470
  if (e instanceof Usage) {
403
471
  err(`${e.message}\n`);
472
+ if (json)
473
+ print({ ok: false, code: "usage", meaning: e.message });
404
474
  return 2;
405
475
  }
406
476
  if (e instanceof FloviaError) {
407
- if (json && e.reply)
408
- print(e.reply);
477
+ // One JSON object on stdout: the reply's own fields, plus the cause and next step at the top level.
478
+ if (json)
479
+ print({ ...obj(e.reply), ok: false, code: e.code, meaning: e.message, ...(e.nextStep ? { next_step: e.nextStep } : {}), executed: e.executed,
480
+ ...(e.retryAfterSeconds !== null ? { retry_after_seconds: e.retryAfterSeconds } : {}), ...(e.operationId ? { operation_id: e.operationId } : {}) });
409
481
  err(renderError(e));
410
482
  if (p.command === "generate" && e.operationId && e.executed === "unknown")
411
483
  err(`To recover: rerun with --op ${e.operationId}, the same prompt or prompt file, ${recoveryLimit === undefined ? "no --max-output" : `--max-output ${recoveryLimit}`}, ${recoveryEffort === undefined ? "no --reasoning-effort" : `--reasoning-effort ${recoveryEffort}`},\nand the same --key-file and --base-url. Do not use --new-op or change the request; that can charge again.\n`);
412
484
  return e.code === "invalid_base_url" ? 2 : 1;
413
485
  }
414
- err(`error: ${e instanceof Error ? e.message : String(e)}\n`);
486
+ const message = e instanceof Error ? e.message : String(e);
487
+ err(`error: ${message}\n`);
488
+ if (json)
489
+ print({ ok: false, code: "error", meaning: message });
415
490
  return 1;
416
491
  }
417
492
  }
418
- /** Decode UTF-8 across chunks, including a character split between reads. */
493
+ /** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
419
494
  export async function readStdin(input) {
420
- input.setEncoding("utf8");
421
- let text = "";
495
+ const chunks = [];
422
496
  for await (const chunk of input)
423
- text += String(chunk);
424
- return text;
497
+ chunks.push(Buffer.from(chunk));
498
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
425
499
  }
426
500
  /** Run only as the program (also through npm's bin symlink), not when imported. Node and Bun alike. */
427
501
  const isMain = (() => { try {
package/dist/client.js CHANGED
@@ -78,12 +78,19 @@ export class FloviaClient {
78
78
  }
79
79
  /** One HTTP request. A network failure or timeout is executed "unknown": the relay may have received it. */
80
80
  async #send(path, body, headers = {}, operationId = null) {
81
- let r;
81
+ let request;
82
82
  try {
83
- const 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: "POST", redirect: "error", body: JSON.stringify(body), 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 } : {}) } });
87
+ }
88
+ catch {
89
+ // Built before any send (a multi-line key or header, a body JSON cannot hold): nothing reached Flovia. The cause may hold a header.
90
+ throw this.#error({ code: "invalid_request", executed: "no", operationId, message: "The request could not be built (check the key, ids and body); nothing was sent.", nextStep: null });
91
+ }
92
+ let r;
93
+ try {
87
94
  r = await this.#fetch(request);
88
95
  }
89
96
  catch (cause) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flovialabs/sdk",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
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",