@flovialabs/sdk 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.19
4
+
5
+ - Expect contract `2026-10-07.182`. context.dev input refusals include a fixed `refusal_detail` or `url_problem` and a matching correction hint. URL privacy restrictions remain unchanged.
6
+ - Contract `2026-10-07.181`: MiniMax generation replies include `lookup_id: "minimax:<generation_id>"`. An `operation_conflict` names the original `generation_id` and explains how to reopen it for free; do not generate again with a new operation ID without the user's decision.
7
+
8
+ - 次版の想定契約を`2026-10-07.180`に更新。`flovia_status`の`fal`欄に、今日のジョブ数・状態別件数と購入残高から精算した額を追加する。plan credit・無料枠・未精算の予約は購入分に含めない。
9
+ - 次版の想定契約を`2026-10-07.179`に更新。`flovia_endpoints`の返答に、Nansenの終了chainの日付・対象・状態を示す`chain_retirements`欄を追加した契約に合わせる。
10
+ - `timeoutMs` must be more than 0 and at most 2147483647 ms, and `--timeout` at most 2147483 seconds (about 24.8 days). Longer values used to overflow Node's timer, so every request timed out after about 1 ms and was reported as `timeout` with `executed: "unknown"`. They are now refused before anything is sent (`invalid_timeout`, or a usage error in the CLI).
11
+
12
+ ## 0.1.18
13
+
14
+ - `flovia doctor [--client <name>] [--network]` checks, read-only, the Flovia entry in each client's personal settings: its URL, sign-in or key mode, and whether the key file is readable or the environment variable is set. It never writes, runs a client/helper or prints a key. Only the exact installer helper for the selected key path is checked; unknown helpers and unsafe environment references require manual inspection without key reads or network calls for that entry. A sign-in entry gets that client's command to sign in again after a revoked or expired sign-in. `--network` checks `/mcp` and accepts only Flovia-format keys for `flovia_status`; fetch and reply reading share the existing timeout. The exit code is 1 when a check fails. TOML/YAML inspection covers limited line-based forms, not a full parser.
15
+ - `flovia usage --days N` は1〜30日を受け、開始時刻はRelayの時計で決める。#2641より前のRelayは `days` を受けないため、7日以内の `--since` を使う。`--days` は `--since` や `--cursor` と併用できない。
16
+ - 想定する契約を `2026-10-07.178` に更新。提供時のZerionの入力schemaと、精算情報の現行応答を記録する。SDKは `for_user`・`charge` が存在する場合の `ForUser`・`ReplyCharge` 型を公開し、その他の `for_user` 項目は `unknown` のまま残す。項目の欠如から支払額ゼロとは判断しない。
17
+ - `flovia_usage_today`の履歴の行に、記録済みの支払元・精算状態・正確な支払USDを示す`charge`を加えた。Gemini・MiniMaxの個別のMCP応答も、`for_user.charge`が存在する場合に同じ情報を返す。精算済みの無料分と、保存済みの応答の再表示の追加費用は`0.00`。未確定・取得不能の額は`null`で、項目が無い場合もゼロとは扱わない。履歴の生成プレビューはページをまたいで再掲されるため、同じ`lookup_id`は一度だけ数える。期間の合計は`total`を使い、replay・job snapshotを新しい課金として加えない。
18
+ - `for_user.charge` reports funding source, settlement status, and `call`, `replay`, or `job_snapshot` basis. Settled paid calls expose exact decimal USD; unresolved or unavailable amounts are `null`. Replay adds no charge, and a job snapshot describes the original job rather than another charge. Sum only settled call amounts; preparation totals with separately metered verification can remain unavailable.
19
+ - Expect contract `2026-10-07.174`. `flovia_status.services` includes Runway's state (`normal`, `paused`, or `off`) when `flovia_runway` is offered. Public provider guides match the offered tool names; this does not enable a provider or change pricing, caps, consent, or retrieval periods.
20
+ - Expect contract `2026-10-07.173`. OpenAI-compatible HTTP validation errors use `invalid_json`, `body_too_large`, `invalid_field`, or `secret_in_input` instead of the generic `invalid_request`. Safe error details name declared parameters or secret kinds without echoing inputs. The text input limit remains 64 KiB.
21
+ - `flovia install --client <claude-code|codex|cursor|claude-desktop|hermes>` adds Flovia's MCP server to that client's personal settings. The default `--auth oauth` uses the client's sign-in and no key. `--auth key` makes Claude Code read the key file on each connect, and Codex and Cursor read an environment variable; the key is never written to a config, an argument or the output. `--dry-run` shows the plan without running or writing anything. Other entries in Cursor's file are kept, and a different `flovia` entry is replaced only with `--force` (Cursor). Hermes settings are created only when missing or empty; other existing Hermes YAML needs a manual merge and is left untouched. Claude desktop gets the custom-connector link instead of a local change.
22
+
3
23
  ## 0.1.17
4
24
 
5
25
  - Introduce the consent API and CLI described below; these are not in the published 0.1.16 package. Expect contract `2026-10-07.172`. When the current notice is `relay-consent-19`, `flovia consent` describes notice 19's December 3/new-record retrieval rules. Earlier yes answers keep working; a new answer is not required to keep looking up.
package/README.md CHANGED
@@ -10,9 +10,17 @@ 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.17
13
+ npm install --save-exact @flovialabs/sdk@0.1.19
14
14
  ```
15
15
 
16
+ ## 0.1.19 release notes
17
+
18
+ This release expects contract `2026-10-07.182`, whose Relay replies include context.dev input-refusal details, MiniMax lookup IDs and conflict-recovery guidance, Nansen chain-retirement notices, and fal job counts with settled purchased-balance spend. The SDK also refuses timeout values that would overflow Node's timer before sending a request. Provider availability follows the Relay's current configuration.
19
+
20
+ ## 0.1.18 release notes
21
+
22
+ This release expects contract `2026-10-07.178`. It adds `flovia install --client` and the read-only `flovia doctor` command, lists up to 30 days of your usage history, and exports optional `ForUser` / `ReplyCharge` types for replies that include charge information. A missing charge is not zero. Replay and job snapshots must not be added as new calls. Earlier releases remain unchanged.
23
+
16
24
  ## 0.1.17 release notes
17
25
 
18
26
  This release introduces `client.consent()`, `client.acceptConsent(version)` and the `flovia consent` commands, which are not in the published 0.1.16 package. It expects contract `2026-10-07.172`. When the current notice is `relay-consent-19`, the CLI shows its December 3/new-record rule. Your earlier yes keeps working, and the CLI never answers for you.
@@ -53,7 +61,7 @@ const flovia = new FloviaClient(); // reads FLOVIA_KEY; base URL https://api.flo
53
61
  const status = await flovia.status();
54
62
  console.log(status.five_hour.used_pct, status.week.used_pct);
55
63
 
56
- // Your lookups today (or since a time within the last 7 days)
64
+ // Your lookups today (or the last N days, up to 30)
57
65
  const usage = await flovia.usageToday(); // today, UTC
58
66
 
59
67
  // Any tool: list them, then call one
@@ -248,7 +256,7 @@ Do not answer these automatically from code or from an agent.
248
256
 
249
257
  ## Timeouts
250
258
 
251
- Each request times out after 300 seconds by default (a long generation can take minutes). Change it with `timeoutMs`. A timeout throws `FloviaError` with code `timeout` and `executed: "unknown"`.
259
+ Each request times out after 300 seconds by default (a long generation can take minutes). Change it with `timeoutMs` (more than 0, at most 2147483647 ms; `--timeout` at most 2147483 seconds). A timeout throws `FloviaError` with code `timeout` and `executed: "unknown"`.
252
260
 
253
261
  A lost or unreadable reply is also `executed: "unknown"`, even after HTTP 200. Keep the saved operation ID and request; do not start another operation to recover the answer. A retired operation is never treated as proof that nothing ran.
254
262
 
@@ -263,7 +271,7 @@ The package installs a `flovia` command.
263
271
  ```sh
264
272
  export FLOVIA_KEY=flv_... # or: --key-file ~/.config/flovia/key
265
273
  npx flovia status
266
- npx flovia usage --days 3
274
+ npx flovia usage --days 30
267
275
  npx flovia tools
268
276
  npx flovia tools --json # includes each tool's inputSchema
269
277
  npx flovia tools flovia_coingecko --json # only this tool's description and inputSchema
@@ -279,7 +287,7 @@ npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
279
287
  npx flovia help
280
288
  npx flovia --version
281
289
  ```
282
- These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.17 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.
290
+ These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.19 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.
283
291
 
284
292
  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.
285
293
 
@@ -293,6 +301,28 @@ This sends the saved request once. Reopening it uses the same file and operation
293
301
 
294
302
  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.
295
303
 
304
+ To connect one AI client to Flovia's MCP server in one command (since 0.1.18; not included in 0.1.17):
305
+
306
+ ```sh
307
+ npx flovia install --client claude-code # or codex, cursor, claude-desktop, hermes
308
+ npx flovia install --client cursor --auth key --dry-run
309
+ ```
310
+
311
+ The default `--auth oauth` adds the server and lets the client sign in; no key is used. `--auth key` points Claude Code at the key file (`--key-file`, default `~/.config/flovia/key`) and Codex and Cursor at `FLOVIA_KEY` and `FLOVIA_API_KEY`; the key is never written into the client's settings, a command argument or the output. Claude Code and Codex are changed through their own `claude mcp add` and `codex mcp add`. Cursor's `~/.cursor/mcp.json` keeps its other entries. Hermes Agent gets a new `~/.hermes/config.yaml` only when it is missing or empty; an identical generated entry is left unchanged. Other existing Hermes settings are left untouched: merge Flovia by hand using Console's Quick Install. Claude desktop gets the custom-connector link. `--dry-run` shows the commands and files without changing anything.
312
+
313
+ Hermes Agent uses its Client ID Metadata Document by default. If sign-in reports `invalid_client` or times out, follow the manual [DCR fallback in the Hermes guide](https://docs.flovia.dev/connect/hermes/#if-sign-in-fails). The installer keeps existing Hermes settings unchanged.
314
+
315
+ To check what `install` set up (since 0.1.18; not included in 0.1.17):
316
+
317
+ ```sh
318
+ npx flovia doctor # every client
319
+ npx flovia doctor --client codex --network
320
+ ```
321
+
322
+ `doctor` only reads each client's personal settings (`~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.hermes/config.yaml`). It reports whether the `flovia` entry points at `https://api.flovia.dev/mcp`, whether it signs in or uses a key, and whether that key file is readable or that environment variable is set. It never writes, never runs the client or a helper, and never prints a key, a header value or a URL's query. A sign-in entry gets the client's command to sign in again: after a revoked or expired sign-in, clients keep retrying until a person signs in anew. Claude desktop is checked in Claude's Settings > Connectors. `--network` also asks Flovia: `/mcp` must answer with its sign-in challenge, and a Flovia-format key the recognised entry uses must be accepted by `flovia_status`. Fetching and reading the reply share the `--timeout` deadline, which defaults to 300 seconds. Without `--client`, clients that are not set up are listed but do not fail; the exit code is 1 when a check fails.
323
+
324
+ For Claude Code, doctor checks the key file only when `headersHelper` exactly matches the helper `install` generates for the default path or the supplied `--key-file` path. Other helpers and unsafe or credential-like environment-variable names produce an authentication warning and require manual inspection; doctor neither reads another key nor sends a request for that entry. URL warnings show the expected endpoint without echoing the configured URL's host or path. It does not parse full TOML or YAML: inline tables and flow mappings may be reported as an absent entry and need manual inspection.
325
+
296
326
  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.
297
327
 
298
328
  For multiline generation text, keep the original input in a private file:
package/dist/cli.d.ts CHANGED
@@ -17,6 +17,10 @@ export interface Io {
17
17
  now?: () => number;
18
18
  /** TTY-only waiting feedback on stderr; returns a cleanup function. Never used with --json. */
19
19
  waiting?: () => () => void;
20
+ /** Runs a client's own CLI (install); resolves its exit code, rejects with code ENOENT when it is not installed. */
21
+ exec?: (command: string, args: string[]) => Promise<number>;
22
+ /** Writes a client's settings file (install), creating its directory. */
23
+ writeFile?: (path: string, text: string) => Promise<void>;
20
24
  }
21
25
  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";
22
26
  /** Required properties plus Exa/Firecrawl's default-operation inputs, which are conditional in the schema. */
package/dist/cli.js CHANGED
@@ -3,11 +3,15 @@
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 { open, readFile, stat } from "node:fs/promises";
6
+ import { mkdir, open, readFile, stat, writeFile } from "node:fs/promises";
7
7
  import { readFileSync, realpathSync } from "node:fs";
8
+ import { spawn } from "node:child_process";
9
+ import { dirname } from "node:path";
8
10
  import { createInterface } from "node:readline/promises";
9
11
  import { fileURLToPath } from "node:url";
10
12
  import { FloviaClient, FloviaError, newOperationId } from "./index.js";
13
+ import { INSTALL_AUTH, INSTALL_CLIENTS, InstallRefusal, mergeJson, mergeYaml, planInstall } from "./install.js";
14
+ import { inspect, renderDoctor, settingsPath, settle } from "./doctor.js";
11
15
  /** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
12
16
  export async function writePrivateOutput(path, data) {
13
17
  const file = await open(path, "wx", 0o600);
@@ -24,13 +28,15 @@ const CONSOLE = "https://console.flovia.dev/groupbuy/";
24
28
  const VERSION = String(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
25
29
  const COMMANDS = {
26
30
  status: { usage: "status", about: "usage windows, services, contract version and recent updates", flags: {} },
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 } },
31
+ usage: { usage: "usage [--since ISO | --days N] [--cursor C]", about: "lookups and generations (today, or since a time within 30 days)", flags: { "--since": true, "--days": true, "--cursor": true } },
28
32
  tools: { usage: "tools [tool]", about: "list offered tools, or inspect one tool's description and arguments", flags: {} },
29
33
  call: { usage: "call <tool> ['<json args>' | -]", about: "call a tool; - reads a JSON object from stdin", flags: {} },
30
34
  "runway-output": { usage: "runway-output <generation_id> --out PATH", about: "download an existing private output; never regenerates or overwrites", flags: { "--out": true } },
31
35
  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
36
  resets: { usage: "resets [use <id> --yes]", about: "check saved resets (read-only), or use one to restart both free windows", flags: { "--yes": false } },
33
37
  consent: { usage: "consent [accept <version> --yes]", about: "read Flovia's current notice and your answer, or record your own yes to it", flags: { "--yes": false } },
38
+ install: { usage: "install --client NAME [--auth oauth|key] [--dry-run] [--force]", about: "add Flovia to one client's settings; never writes the key", flags: { "--client": true, "--auth": true, "--dry-run": false, "--force": false } },
39
+ doctor: { usage: "doctor [--client NAME] [--network]", about: "check clients' Flovia settings (read-only; never prints the key)", flags: { "--client": true, "--network": false } },
34
40
  "agents-md": { usage: "agents-md", about: "a short Flovia note to paste into CLAUDE.md or AGENTS.md (no network)", flags: {} },
35
41
  help: { usage: "help [command]", about: "this help", flags: {} },
36
42
  version: { usage: "version", about: "the installed CLI version", flags: {} },
@@ -109,6 +115,10 @@ export function help(command) {
109
115
  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.");
110
116
  if (command === "consent")
111
117
  lines.push("", "flovia consent only reads; it never answers.", "Only the account owner may answer, for themselves, after reading the notice:", " flovia consent accept <version> --yes", "Without --yes nothing is sent. The same answer can be given in Console.");
118
+ if (command === "install")
119
+ lines.push("", `--client: ${INSTALL_CLIENTS.join(", ")}`, "--auth oauth (default): sign in from the client; no key is used.", "--auth key: Claude Code reads the key file on each connect", " (--key-file, default ~/.config/flovia/key); Codex reads FLOVIA_KEY and", " Cursor FLOVIA_API_KEY from the environment. No config gets the key.", "--dry-run shows the commands and files without running or writing anything.", " flovia install --client claude-code", " flovia install --client cursor --auth key --dry-run");
120
+ if (command === "doctor")
121
+ lines.push("", `--client: ${INSTALL_CLIENTS.join(", ")} (default: every client)`, "Reads each client's personal settings only; nothing is written or run.", "--network also asks Flovia: /mcp must answer, and a key the entry uses must be accepted.", " flovia doctor", " flovia doctor --client codex --network");
112
122
  if (command === "call")
113
123
  lines.push("", "Read a saved request: flovia call <tool> - < request.json", ...SAVE_OP);
114
124
  lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 error from Flovia, 2 usage error.", "");
@@ -326,10 +336,13 @@ export function renderError(e) {
326
336
  }
327
337
  export async function run(argv, io) {
328
338
  let key = null;
339
+ const seen = [];
329
340
  // Belt and braces: whatever is printed passes through here, so the key cannot appear even if a reply or error echoed it.
330
341
  const accessToken = io.env["FLOVIA_ACCESS_TOKEN"]?.trim();
331
342
  const scrub = (s) => {
332
- const masked = key === null ? s : s.replaceAll(key, "[key]");
343
+ let masked = key === null ? s : s.replaceAll(key, "[key]");
344
+ for (const k of seen)
345
+ masked = masked.replaceAll(k, "[key]");
333
346
  return accessToken ? masked.replaceAll(accessToken, "[access-token]") : masked;
334
347
  };
335
348
  const out = (s) => io.out(scrub(s)), err = (s) => io.err(scrub(s));
@@ -372,7 +385,8 @@ export async function run(argv, io) {
372
385
  let recoveryLimit;
373
386
  let recoveryEffort;
374
387
  try {
375
- const timeout = positiveInt("--timeout", str(p.flags.get("--timeout")));
388
+ // Seconds; the SDK's longest timer is 2^31 - 1 ms, so the CLI stops at 2147483 s.
389
+ const timeout = positiveInt("--timeout", str(p.flags.get("--timeout")), 2_147_483);
376
390
  const baseUrl = str(p.flags.get("--base-url"));
377
391
  // The key is read only after the command's own arguments are checked, so a usage mistake shows the usage line first.
378
392
  const connect = async () => {
@@ -381,6 +395,10 @@ export async function run(argv, io) {
381
395
  ...(accessToken ? { accessToken } : {}),
382
396
  fetch: (r) => { r.headers.set("X-Flovia-Client", "flovia-cli"); return (io.fetch ?? fetch)(r); }, onContractMismatch: (expected) => { mismatch = expected; } });
383
397
  };
398
+ if (p.command === "install")
399
+ return await install(p, io, out, err, json);
400
+ if (p.command === "doctor")
401
+ return await doctor(p, io, out, json, (k) => { seen.push(k); }, { baseUrl, timeout });
384
402
  switch (p.command) {
385
403
  case "runway-output": {
386
404
  const [id, extra] = p.positional, path = str(p.flags.get("--out"));
@@ -467,20 +485,18 @@ export async function run(argv, io) {
467
485
  return 0;
468
486
  }
469
487
  case "usage": {
470
- const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")), 7), cursor = str(p.flags.get("--cursor"));
488
+ const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")), 30), cursor = str(p.flags.get("--cursor"));
471
489
  if (since !== undefined && days !== undefined)
472
490
  throw new Usage("usage: pass --since or --days, not both");
473
491
  if (cursor !== undefined && days !== undefined)
474
492
  throw new Usage("usage: with --cursor, use the previous reply's exact --since, not --days");
475
493
  if (since !== undefined && Number.isNaN(Date.parse(since)))
476
494
  throw new Usage("--since must be an ISO 8601 time");
477
- // A minute's margin so --days 7 stays inside the relay's 7 days by the time it arrives.
478
- const from = days === undefined ? since : new Date((io.now ?? Date.now)() - days * 86_400_000 + 60_000).toISOString();
479
- const client = await connect(), u = await waitFor(() => client.usageToday({ ...(from ? { since: from } : {}), ...(cursor ? { cursor } : {}) }));
495
+ const client = await connect(), u = await waitFor(() => client.usageToday({ ...(since ? { since } : {}), ...(days === undefined ? {} : { days }), ...(cursor ? { cursor } : {}) }));
480
496
  if (json)
481
497
  print(u);
482
498
  else
483
- out(renderUsage(u, from === undefined && cursor === undefined, (io.now ?? Date.now)()));
499
+ out(renderUsage(u, since === undefined && days === undefined && cursor === undefined, (io.now ?? Date.now)()));
484
500
  return 0;
485
501
  }
486
502
  case "tools": {
@@ -619,6 +635,234 @@ export async function run(argv, io) {
619
635
  return 1;
620
636
  }
621
637
  }
638
+ const quoteArg = (a) => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replaceAll("'", "'\\''")}'`;
639
+ const describeStep = (s) => s.kind === "exec" ? `run: ${[s.command, ...s.args.map(quoteArg)].join(" ")}`
640
+ : `update: ${s.path} (add flovia to ${s.kind === "json" ? "mcpServers" : "mcp_servers"}, keeping other entries)`;
641
+ /** No network and no key text: for Claude Code's key mode only the key file's readability is checked. */
642
+ async function install(p, io, out, err, json) {
643
+ const client = str(p.flags.get("--client")), auth = str(p.flags.get("--auth")) ?? "oauth";
644
+ if (p.positional.length)
645
+ throw new Usage(`Usage: flovia ${COMMANDS["install"]?.usage}`);
646
+ if (client === undefined || !INSTALL_CLIENTS.includes(client))
647
+ throw new Usage(`install: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${client === undefined ? "" : didYouMean(client, [...INSTALL_CLIENTS])}`);
648
+ if (!INSTALL_AUTH.includes(auth))
649
+ throw new Usage("install: --auth must be oauth or key");
650
+ const home = io.env["HOME"];
651
+ if (!home)
652
+ throw new Usage("install: HOME is not set");
653
+ let base;
654
+ try {
655
+ base = new URL(str(p.flags.get("--base-url")) ?? "https://api.flovia.dev");
656
+ }
657
+ catch {
658
+ throw new Usage("install: --base-url must be an https URL");
659
+ }
660
+ if (base.protocol !== "https:" || base.username || base.password)
661
+ throw new Usage("install: --base-url must be an https URL without credentials");
662
+ const resource = `${base.origin}/mcp`, keyFile = str(p.flags.get("--key-file"));
663
+ let plan;
664
+ try {
665
+ plan = planInstall({ client: client, auth: auth, resource, home, ...(keyFile ? { keyPath: keyFile } : {}) });
666
+ }
667
+ catch (e) {
668
+ if (e instanceof InstallRefusal)
669
+ throw new Usage(e.message);
670
+ throw e;
671
+ }
672
+ const dry = p.flags.has("--dry-run"), force = p.flags.has("--force"), done = [];
673
+ if (plan.client === "claude-code" && plan.auth === "key") {
674
+ const path = keyFile ?? "~/.config/flovia/key";
675
+ await fromFile(path.startsWith("~/") ? `${home}/${path.slice(2)}` : path, io, keyFile === undefined ? "~/.config/flovia/key" : "--key-file");
676
+ }
677
+ if (plan.client === "codex" && plan.auth === "key" && !io.env["FLOVIA_KEY"]?.trim())
678
+ err("warning: FLOVIA_KEY is not set in this shell; Codex needs it where it starts\n");
679
+ if (plan.client === "cursor" && plan.auth === "key" && !io.env["FLOVIA_API_KEY"]?.trim())
680
+ err("warning: FLOVIA_API_KEY is not set in this shell; Cursor needs it where it starts\n");
681
+ for (const step of plan.steps) {
682
+ if (dry) {
683
+ done.push(`would ${describeStep(step)}`);
684
+ continue;
685
+ }
686
+ if (step.kind === "exec") {
687
+ if (!io.exec)
688
+ throw new Usage("install: cannot run commands here; use --dry-run and run them yourself");
689
+ let code;
690
+ try {
691
+ code = await io.exec(step.command, step.args);
692
+ }
693
+ catch (e) {
694
+ if (e.code === "ENOENT")
695
+ throw new Usage(`install: ${step.command} was not found. Install it first, or use --dry-run and run the command yourself`);
696
+ throw new Usage(`install: ${step.command} could not complete; not retried. Check its settings before running install again`);
697
+ }
698
+ if (code !== 0)
699
+ throw new Usage(`install: ${step.command} exited with ${code}; not retried. Check its settings before running install again`);
700
+ done.push(describeStep(step));
701
+ continue;
702
+ }
703
+ if (!io.writeFile)
704
+ throw new Usage("install: cannot write files here; use --dry-run");
705
+ let existing;
706
+ try {
707
+ existing = await io.readFile(step.path);
708
+ }
709
+ catch (e) {
710
+ if (e.code === "ENOENT")
711
+ existing = null;
712
+ else
713
+ throw new Usage("install: cannot read the existing settings file; nothing was changed");
714
+ }
715
+ let next;
716
+ try {
717
+ const merged = step.kind === "json" ? mergeJson(existing, step.entry, force) : mergeYaml(existing, step.entry);
718
+ if (merged === "unchanged") {
719
+ done.push(`unchanged: ${step.path} already has this flovia entry`);
720
+ continue;
721
+ }
722
+ next = merged;
723
+ }
724
+ catch (e) {
725
+ if (e instanceof InstallRefusal)
726
+ throw new Usage(e.message);
727
+ throw e;
728
+ }
729
+ await io.writeFile(step.path, next);
730
+ done.push(describeStep(step));
731
+ }
732
+ if (json)
733
+ out(JSON.stringify({ ok: true, client: plan.client, auth: plan.auth, resource, dry_run: dry, done, next_steps: plan.next }, null, 2) + "\n");
734
+ else
735
+ out([`Flovia for ${plan.client} (${plan.auth === "oauth" ? "sign-in" : "key"})${dry ? ", dry run: nothing was changed" : ""}`, ...done.map((d) => ` ${d}`), "Next:", ...plan.next.map((n) => ` ${n}`)].join("\n") + "\n");
736
+ return 0;
737
+ }
738
+ /** Read-only: settings files, the key's readability, and with --network one unauthenticated /mcp request plus flovia_status with that key. */
739
+ async function doctor(p, io, out, json, remember, o) {
740
+ const client = str(p.flags.get("--client"));
741
+ if (p.positional.length)
742
+ throw new Usage(`Usage: flovia ${COMMANDS["doctor"]?.usage}`);
743
+ if (client !== undefined && !INSTALL_CLIENTS.includes(client))
744
+ throw new Usage(`doctor: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${didYouMean(client, [...INSTALL_CLIENTS])}`);
745
+ const home = io.env["HOME"];
746
+ if (!home)
747
+ throw new Usage("doctor: HOME is not set");
748
+ let base;
749
+ try {
750
+ base = new URL(o.baseUrl ?? "https://api.flovia.dev");
751
+ }
752
+ catch {
753
+ throw new Usage("doctor: --base-url must be an https URL");
754
+ }
755
+ if (base.protocol !== "https:" || base.username || base.password)
756
+ throw new Usage("doctor: --base-url must be an https URL without credentials");
757
+ const resource = `${base.origin}/mcp`, network = p.flags.has("--network"), keyFlag = str(p.flags.get("--key-file"));
758
+ const clients = client === undefined ? [...INSTALL_CLIENTS] : [client];
759
+ const doFetch = io.fetch ?? fetch;
760
+ /** One deadline includes fetch and body consumption/cancellation, even for injected transports. */
761
+ const timed = async (request) => {
762
+ const signal = AbortSignal.timeout((o.timeout ?? 300) * 1000);
763
+ let abort = () => { };
764
+ try {
765
+ const deadline = new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); });
766
+ return await Promise.race([request(signal), deadline]);
767
+ }
768
+ finally {
769
+ signal.removeEventListener("abort", abort);
770
+ }
771
+ };
772
+ let reachable;
773
+ const reach = async () => {
774
+ if (reachable)
775
+ return reachable;
776
+ try {
777
+ const r = await timed(async (signal) => {
778
+ const response = await doFetch(new Request(resource, { method: "GET", redirect: "error", signal, headers: { "X-Flovia-Client": "flovia-cli" } }));
779
+ await response.body?.cancel().catch(() => undefined);
780
+ return response;
781
+ });
782
+ reachable = r.status === 401 && /bearer/i.test(r.headers.get("www-authenticate") ?? "")
783
+ ? { result: "ok", detail: `${resource} answers and asks for sign-in or a key` }
784
+ : { result: "warn", detail: `${resource} answered HTTP ${r.status}, not the expected 401 with a sign-in challenge` };
785
+ }
786
+ catch {
787
+ reachable = { result: "fail", detail: `${resource} could not be reached from this machine` };
788
+ }
789
+ return reachable;
790
+ };
791
+ /** A key is read only to check it; it goes into the scrub list first, so no line can show it. */
792
+ const tryKey = async (k, r) => {
793
+ remember(k);
794
+ if (!network)
795
+ return;
796
+ // Same format as the Relay's issued-key schema; never send another service's credential to Flovia.
797
+ if (!/^flv_[A-Za-z0-9_-]{43}$/.test(k)) {
798
+ r.checks.push({ name: "key accepted", result: "warn", detail: "The configured value is not a Flovia key; it was not sent." });
799
+ return;
800
+ }
801
+ try {
802
+ await timed(async (signal) => {
803
+ const c = new FloviaClient({ apiKey: k, baseUrl: base.origin, ...(o.timeout ? { timeoutMs: o.timeout * 1000 } : {}),
804
+ fetch: (req) => { req.headers.set("X-Flovia-Client", "flovia-cli"); return doFetch(new Request(req, { signal })); }, onContractMismatch: () => undefined });
805
+ await c.status();
806
+ });
807
+ r.checks.push({ name: "key accepted", result: "ok", detail: "flovia_status answered with this key" });
808
+ }
809
+ catch (e) {
810
+ if (e instanceof FloviaError && (e.code === "unauthorized" || e.code === "key_disabled" || e.code === "key_stopped")) {
811
+ r.checks.push({ name: "key accepted", result: "fail", detail: `Flovia refused this key (${e.code})` });
812
+ r.next.push(`Issue or re-enable a key in Console (${CONSOLE}), save it, then restart ${r.client}.`);
813
+ }
814
+ else
815
+ r.checks.push({ name: "key accepted", result: "warn", detail: e instanceof FloviaError ? `flovia_status answered ${e.code}` : "flovia_status could not be reached" });
816
+ }
817
+ };
818
+ const reports = [];
819
+ for (const name of clients) {
820
+ const path = settingsPath(name, home);
821
+ let text = null;
822
+ if (path !== null) {
823
+ try {
824
+ text = await io.readFile(path);
825
+ }
826
+ catch (e) {
827
+ if (e.code !== "ENOENT") {
828
+ reports.push({ client: name, state: "fail", settings: path, auth: null, checks: [{ name: "settings", result: "fail", detail: `${path} could not be read` }], next: ["Check the file's permissions."] });
829
+ continue;
830
+ }
831
+ }
832
+ }
833
+ const r = inspect(name, text, resource, home, io.env, client !== undefined, keyFlag);
834
+ if (r.state === "ok" && r.auth === "key-file") {
835
+ const shown = keyFlag === undefined ? `~/${DEFAULT_KEY_FILE}` : "--key-file";
836
+ try {
837
+ const keyPath = keyFlag ?? `~/${DEFAULT_KEY_FILE}`;
838
+ const k = await fromFile(keyPath.startsWith("~/") ? `${home}/${keyPath.slice(2)}` : keyPath, io, shown);
839
+ r.checks.push({ name: "key", result: "ok", detail: `the key file (${shown}) is readable` });
840
+ await tryKey(k, r);
841
+ }
842
+ catch (e) {
843
+ if (!(e instanceof Usage))
844
+ throw e;
845
+ r.checks.push({ name: "key", result: "fail", detail: e.message });
846
+ r.next.push(`Save your key to ~/${DEFAULT_KEY_FILE} with chmod 600 (or pass the file Claude Code's headersHelper reads with --key-file).`);
847
+ }
848
+ }
849
+ if (r.state === "ok" && r.auth === "key-env" && r.keyEnv !== undefined) {
850
+ const k = io.env[r.keyEnv]?.trim();
851
+ if (k)
852
+ await tryKey(k, r);
853
+ }
854
+ if (network && r.auth !== "unknown" && (r.state === "ok" || r.state === "manual")) {
855
+ const n = await reach();
856
+ r.checks.push({ name: "network", ...n });
857
+ }
858
+ reports.push(settle(r));
859
+ }
860
+ if (json)
861
+ out(JSON.stringify({ ok: !reports.some((r) => r.state === "fail"), resource, network, clients: reports }, null, 2) + "\n");
862
+ else
863
+ out(renderDoctor(reports));
864
+ return reports.some((r) => r.state === "fail") ? 1 : 0;
865
+ }
622
866
  /** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
623
867
  export async function readStdin(input) {
624
868
  const chunks = [];
@@ -647,6 +891,16 @@ if (isMain) {
647
891
  process.exitCode = await run(process.argv.slice(2), {
648
892
  env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
649
893
  writeOutput: writePrivateOutput,
894
+ exec: (command, args) => new Promise((resolve, reject) => {
895
+ // Adding settings needs no credential values or interactive sign-in. Child diagnostics may contain secrets.
896
+ const env = { ...process.env };
897
+ for (const name of ["FLOVIA_KEY", "FLOVIA_API_KEY", "FLOVIA_ACCESS_TOKEN"])
898
+ delete env[name];
899
+ const child = spawn(command, args, { stdio: "ignore", env });
900
+ child.once("error", reject);
901
+ child.once("exit", (code) => resolve(code ?? 1));
902
+ }),
903
+ writeFile: async (path, text) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, text, "utf8"); },
650
904
  readFile: (path) => readFile(path, "utf8"), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
651
905
  confirm: tty ? confirm : null,
652
906
  ...(process.stderr.isTTY ? { waiting: () => {
package/dist/client.d.ts CHANGED
@@ -52,7 +52,7 @@ export declare class FloviaClient {
52
52
  call<R extends ToolReply = ToolReply>(tool: string, args?: Record<string, unknown>): Promise<R>;
53
53
  /** flovia_status. Warns once when the relay's contract_version is not the one this SDK expects. */
54
54
  status(): Promise<StatusReply>;
55
- /** flovia_usage_today: the user's lookups (today, or since a time within 7 days). */
55
+ /** flovia_usage_today: the user's lookups (today, the last N days up to 30, or since a time within 30 days). */
56
56
  usageToday(args?: UsageTodayArgs): Promise<UsageTodayReply>;
57
57
  /**
58
58
  * POST /openai/v1/responses. operationId is required: save it with the request before calling. Sending the same request with the same id
package/dist/client.js CHANGED
@@ -4,6 +4,8 @@ import { EXPECTED_CONTRACT_VERSION } from "./types.js";
4
4
  const OPERATION_ID = /^[A-Za-z0-9_.:-]{8,128}$/;
5
5
  const RESEND_CODES = new Set(["rate_limited", "too_many_in_parallel", "reservation_changed"]);
6
6
  const MAX_RESEND_WAIT_S = 60;
7
+ /** The longest timer delay Node accepts (2^31 - 1 ms). */
8
+ const MAX_TIMEOUT_MS = 2_147_483_647;
7
9
  /** A new operation_id. Save it with the request before sending, so a lost reply can be reopened with the same id. */
8
10
  export const newOperationId = () => `op_${crypto.randomUUID()}`;
9
11
  const envKey = () => globalThis.process?.env?.["FLOVIA_KEY"];
@@ -60,7 +62,11 @@ export class FloviaClient {
60
62
  if (options.accessToken && (url.origin !== "https://dev.api.flovia.dev" || url.username || url.password))
61
63
  throw new FloviaError({ code: "invalid_base_url", executed: "no", message: "accessToken requires https://dev.api.flovia.dev." });
62
64
  this.#accessToken = options.accessToken;
63
- this.#timeoutMs = options.timeoutMs ?? 300_000;
65
+ const timeoutMs = options.timeoutMs ?? 300_000;
66
+ // Node's timers hold a signed 32-bit delay; a longer AbortSignal.timeout fires after 1 ms and would abort every request at once.
67
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS)
68
+ throw new FloviaError({ code: "invalid_timeout", executed: "no", message: `timeoutMs must be a whole number from 1 to ${MAX_TIMEOUT_MS} ms (about 24.8 days).` });
69
+ this.#timeoutMs = timeoutMs;
64
70
  this.#fetch = options.fetch ?? ((r) => fetch(r));
65
71
  this.#resend = options.retryRateLimited ?? false;
66
72
  // eslint-disable-next-line no-console -- versions only, never the key
@@ -287,7 +293,7 @@ export class FloviaClient {
287
293
  }
288
294
  return s;
289
295
  }
290
- /** flovia_usage_today: the user's lookups (today, or since a time within 7 days). */
296
+ /** flovia_usage_today: the user's lookups (today, the last N days up to 30, or since a time within 30 days). */
291
297
  usageToday(args = {}) {
292
298
  return this.call("flovia_usage_today", { ...args });
293
299
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `flovia doctor [--client <name>]`: a read-only check of the Flovia entry `flovia install` writes. It reads each client's personal
3
+ * settings, reports whether the entry points at Flovia's /mcp and how it signs in, and whether the key it needs is readable. It never
4
+ * writes, never runs the client, and never prints a key, header value or configured URL.
5
+ * Parsing here is pure; cli.ts supplies the files and the optional network check.
6
+ */
7
+ import { type InstallClient } from "./install.js";
8
+ export type CheckResult = "ok" | "warn" | "fail";
9
+ export interface Check {
10
+ name: string;
11
+ result: CheckResult;
12
+ detail: string;
13
+ }
14
+ /** How the entry authenticates. key-env: an environment variable's name; key-file: Claude Code's headersHelper; key-in-settings: a literal key. */
15
+ export type DoctorAuth = "oauth" | "key-env" | "key-file" | "key-in-settings" | "unknown";
16
+ export interface ClientReport {
17
+ client: InstallClient;
18
+ /** not_set_up: no settings file or no flovia entry (only a failure when that client was asked for). manual: cannot be checked locally. */
19
+ state: "ok" | "warn" | "fail" | "not_set_up" | "manual";
20
+ settings: string | null;
21
+ auth: DoctorAuth | null;
22
+ /** The environment variable the entry reads its key from, when it says so. Never its value. */
23
+ keyEnv?: string;
24
+ checks: Check[];
25
+ next: string[];
26
+ }
27
+ /** Where `flovia install` puts each client's personal settings (user scope). */
28
+ export declare function settingsPath(client: InstallClient, home: string): string | null;
29
+ /** How to sign in again: after a revoked or expired sign-in the client keeps retrying the old token until a person signs in anew (#2615). */
30
+ export declare const SIGN_IN_AGAIN: Record<InstallClient, string>;
31
+ export interface Entry {
32
+ url: string | null;
33
+ auth: DoctorAuth;
34
+ keyEnv?: string;
35
+ }
36
+ /** The mcpServers.flovia entry of a Claude Code or Cursor JSON file; null when there is none; throws on invalid JSON. */
37
+ export declare function jsonEntry(text: string, keyPath?: string | null): Entry | null;
38
+ /** [mcp_servers.flovia] in Codex's config.toml: url and bearer_token_env_var (or a literal http_headers bearer). Line-based on purpose. */
39
+ export declare function tomlEntry(text: string): Entry | null;
40
+ /** mcp_servers > flovia > url/auth in Hermes's config.yaml, as `flovia install` writes it. Line-based on purpose. */
41
+ export declare function yamlEntry(text: string): Entry | null;
42
+ export declare function urlCheck(url: string | null, resource: string): Check;
43
+ /** Everything but the key file and the network: those need I/O, so cli.ts adds them. */
44
+ export declare function inspect(client: InstallClient, text: string | null, resource: string, home: string, env: Record<string, string | undefined>, asked: boolean, keyPath?: string): ClientReport;
45
+ /** The overall state from the checks: any fail, else any warn, else ok. */
46
+ export declare function settle(r: ClientReport): ClientReport;
47
+ export declare function renderDoctor(reports: ClientReport[]): string;
package/dist/doctor.js ADDED
@@ -0,0 +1,191 @@
1
+ /**
2
+ * `flovia doctor [--client <name>]`: a read-only check of the Flovia entry `flovia install` writes. It reads each client's personal
3
+ * settings, reports whether the entry points at Flovia's /mcp and how it signs in, and whether the key it needs is readable. It never
4
+ * writes, never runs the client, and never prints a key, header value or configured URL.
5
+ * Parsing here is pure; cli.ts supplies the files and the optional network check.
6
+ */
7
+ import { DEFAULT_KEY_PATH, headersHelper, INSTALL_CLIENTS } from "./install.js";
8
+ /** Where `flovia install` puts each client's personal settings (user scope). */
9
+ export function settingsPath(client, home) {
10
+ switch (client) {
11
+ case "claude-code": return `${home}/.claude.json`;
12
+ case "codex": return `${home}/.codex/config.toml`;
13
+ case "cursor": return `${home}/.cursor/mcp.json`;
14
+ case "hermes": return `${home}/.hermes/config.yaml`;
15
+ case "claude-desktop": return null;
16
+ }
17
+ }
18
+ /** How to sign in again: after a revoked or expired sign-in the client keeps retrying the old token until a person signs in anew (#2615). */
19
+ export const SIGN_IN_AGAIN = {
20
+ "claude-code": "In Claude Code run /mcp, choose flovia, and authenticate again.",
21
+ codex: "Run: codex mcp login flovia",
22
+ cursor: "In Cursor's MCP settings, turn Flovia off and on, then sign in when asked.",
23
+ hermes: "Run: hermes mcp login flovia",
24
+ "claude-desktop": "In Claude's Settings > Connectors, disconnect Flovia and connect it again.",
25
+ };
26
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
27
+ const ENV_REF = /^Bearer \$\{env:([^}]+)\}$/;
28
+ const envEntry = (url, keyEnv) => /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(keyEnv) && !/^(?:flv_|sk-|sk_(?:live|test)_|ghp_|phc_|github_pat_|xox[baprs]-)/i.test(keyEnv)
29
+ ? { url, auth: "key-env", keyEnv } : { url, auth: "unknown" };
30
+ /** The mcpServers.flovia entry of a Claude Code or Cursor JSON file; null when there is none; throws on invalid JSON. */
31
+ export function jsonEntry(text, keyPath = DEFAULT_KEY_PATH) {
32
+ const doc = JSON.parse(text);
33
+ if (!isObject(doc) || !isObject(doc["mcpServers"]) || !isObject(doc["mcpServers"]["flovia"]))
34
+ return null;
35
+ const e = doc["mcpServers"]["flovia"], url = typeof e["url"] === "string" ? e["url"] : null;
36
+ if (Object.hasOwn(e, "headersHelper"))
37
+ return { url, auth: keyPath !== null && !keyPath.includes("'") && (keyPath.startsWith("/") || keyPath.startsWith("~/")) && e["headersHelper"] === headersHelper(keyPath) ? "key-file" : "unknown" };
38
+ const headers = isObject(e["headers"]) ? e["headers"] : {};
39
+ const authHeader = Object.entries(headers).find(([k]) => k.toLowerCase() === "authorization")?.[1];
40
+ if (authHeader === undefined)
41
+ return { url, auth: "oauth" };
42
+ const ref = typeof authHeader === "string" ? ENV_REF.exec(authHeader) : null;
43
+ return ref ? envEntry(url, ref[1]) : { url, auth: typeof authHeader === "string" && authHeader.includes("${env:") ? "unknown" : "key-in-settings" };
44
+ }
45
+ const unquote = (v) => v.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
46
+ /** [mcp_servers.flovia] in Codex's config.toml: url and bearer_token_env_var (or a literal http_headers bearer). Line-based on purpose. */
47
+ export function tomlEntry(text) {
48
+ let inside = false, found = false, url = null, keyEnv, literal = false;
49
+ for (const raw of text.split(/\r?\n/)) {
50
+ const line = raw.replace(/\s+#.*$/, "").trim();
51
+ if (line.startsWith("[")) {
52
+ inside = /^\[\s*mcp_servers\.(?:flovia|"flovia")\s*\]$/.test(line);
53
+ found ||= inside;
54
+ continue;
55
+ }
56
+ if (!inside)
57
+ continue;
58
+ const m = /^([A-Za-z_]+)\s*=\s*(.+)$/.exec(line);
59
+ if (!m)
60
+ continue;
61
+ if (m[1] === "url")
62
+ url = unquote(m[2]);
63
+ else if (m[1] === "bearer_token_env_var")
64
+ keyEnv = unquote(m[2]);
65
+ else if (m[1] === "http_headers" && /authorization/i.test(m[2]))
66
+ literal = true;
67
+ }
68
+ if (!found)
69
+ return null;
70
+ return keyEnv !== undefined ? envEntry(url, keyEnv) : { url, auth: literal ? "key-in-settings" : "oauth" };
71
+ }
72
+ /** mcp_servers > flovia > url/auth in Hermes's config.yaml, as `flovia install` writes it. Line-based on purpose. */
73
+ export function yamlEntry(text) {
74
+ let section = false, inside = false, indent = -1, found = false, url = null, auth = null, headers = false;
75
+ for (const raw of text.split(/\r?\n/)) {
76
+ if (raw.trim() === "" || raw.trim().startsWith("#"))
77
+ continue;
78
+ const depth = raw.length - raw.trimStart().length, line = raw.trim();
79
+ if (depth === 0) {
80
+ section = line === "mcp_servers:";
81
+ inside = false;
82
+ continue;
83
+ }
84
+ if (!section)
85
+ continue;
86
+ if (/^["']?flovia["']?:\s*$/.test(line)) {
87
+ inside = true;
88
+ found = true;
89
+ indent = depth;
90
+ continue;
91
+ }
92
+ if (depth <= indent) {
93
+ inside = false;
94
+ continue;
95
+ }
96
+ if (!inside)
97
+ continue;
98
+ const m = /^([A-Za-z_]+):\s*(.*)$/.exec(line);
99
+ if (m?.[1] === "url")
100
+ url = unquote(m[2]);
101
+ else if (m?.[1] === "auth")
102
+ auth = unquote(m[2]);
103
+ else if (m?.[1] === "headers" || /^authorization:/i.test(line))
104
+ headers = true;
105
+ }
106
+ if (!found)
107
+ return null;
108
+ return { url, auth: auth === "oauth" ? "oauth" : headers ? "key-in-settings" : "unknown" };
109
+ }
110
+ export function urlCheck(url, resource) {
111
+ if (url === null)
112
+ return { name: "url", result: "fail", detail: "the flovia entry has no url" };
113
+ let u;
114
+ try {
115
+ u = new URL(url);
116
+ }
117
+ catch {
118
+ return { name: "url", result: "fail", detail: "the flovia entry's url is not a URL" };
119
+ }
120
+ if (u.username || u.password || u.search)
121
+ return { name: "url", result: "fail", detail: `the flovia entry's url carries credentials or a query; use ${resource}` };
122
+ if (`${u.origin}${u.pathname.replace(/\/$/, "")}` === resource)
123
+ return { name: "url", result: "ok", detail: resource };
124
+ if (u.protocol !== "https:")
125
+ return { name: "url", result: "fail", detail: `the flovia entry's url is not https; use ${resource}` };
126
+ return { name: "url", result: "warn", detail: `the flovia entry's url does not point to ${resource}` };
127
+ }
128
+ const AUTH_TEXT = {
129
+ oauth: "sign-in (OAuth); no key is stored",
130
+ "key-env": "key from an environment variable",
131
+ "key-file": "key read from a key file on each connect (headersHelper)",
132
+ "key-in-settings": "a key written in the settings file",
133
+ unknown: "not recognised",
134
+ };
135
+ /** Everything but the key file and the network: those need I/O, so cli.ts adds them. */
136
+ export function inspect(client, text, resource, home, env, asked, keyPath = DEFAULT_KEY_PATH) {
137
+ const settings = settingsPath(client, home);
138
+ if (client === "claude-desktop")
139
+ return { client, state: "manual", settings: null, auth: "oauth", checks: [{ name: "settings", result: "warn", detail: "Claude desktop keeps remote connectors in your Claude account, not in a local file" }],
140
+ next: ["Check Settings > Connectors in Claude: Flovia should be listed and connected.", `If tools fail with a sign-in error: ${SIGN_IN_AGAIN[client]}`] };
141
+ const install = `flovia install --client ${client}`;
142
+ const notSetUp = (detail) => ({ client, state: asked ? "fail" : "not_set_up", settings, auth: null,
143
+ checks: [{ name: "settings", result: asked ? "fail" : "warn", detail }], next: [`To add Flovia: ${install}`] });
144
+ if (text === null)
145
+ return notSetUp(`${settings} was not found`);
146
+ let entry;
147
+ try {
148
+ entry = client === "codex" ? tomlEntry(text) : client === "hermes" ? yamlEntry(text) : jsonEntry(text, client === "claude-code" ? keyPath : null);
149
+ }
150
+ catch {
151
+ return { client, state: "fail", settings, auth: null, checks: [{ name: "settings", result: "fail", detail: `${settings} is not valid JSON; the client cannot read it either` }], next: ["Fix the file's syntax, then run flovia doctor again."] };
152
+ }
153
+ if (entry === null)
154
+ return notSetUp(`${settings} has no flovia entry`);
155
+ const checks = [{ name: "settings", result: "ok", detail: `${settings} has a flovia entry` }, urlCheck(entry.url, resource)];
156
+ const next = [];
157
+ if (entry.auth === "unknown")
158
+ next.push("Check the client's authentication settings manually; doctor did not read a key or run a helper.");
159
+ checks.push({ name: "auth", result: entry.auth === "key-in-settings" || entry.auth === "unknown" ? "warn" : "ok", detail: AUTH_TEXT[entry.auth] });
160
+ if (entry.auth === "key-in-settings")
161
+ next.push(`Move the key out of ${settings}: rerun ${install} --auth key (it reads the key at connect time), then issue a new key in Console if this file was ever shared.`);
162
+ if (entry.auth === "key-env" && entry.keyEnv !== undefined) {
163
+ const set = Boolean(env[entry.keyEnv]?.trim());
164
+ checks.push({ name: "key", result: set ? "ok" : "warn", detail: `${entry.keyEnv} is ${set ? "set" : "not set"} in this shell` });
165
+ if (!set)
166
+ next.push(`Set ${entry.keyEnv} in your shell profile and start ${client === "cursor" ? "Cursor" : "Codex"} from a new terminal.`);
167
+ }
168
+ if (entry.auth === "oauth")
169
+ next.push(`If tools fail with a sign-in error or the client keeps reconnecting, the sign-in was revoked or expired. ${SIGN_IN_AGAIN[client]}`);
170
+ return { client, state: "ok", settings, auth: entry.auth, ...(entry.keyEnv !== undefined ? { keyEnv: entry.keyEnv } : {}), checks, next };
171
+ }
172
+ /** The overall state from the checks: any fail, else any warn, else ok. */
173
+ export function settle(r) {
174
+ if (r.state === "not_set_up" || r.state === "manual")
175
+ return r;
176
+ const state = r.checks.some((c) => c.result === "fail") ? "fail" : r.checks.some((c) => c.result === "warn") ? "warn" : "ok";
177
+ return { ...r, state };
178
+ }
179
+ export function renderDoctor(reports) {
180
+ const lines = [];
181
+ for (const r of reports) {
182
+ lines.push(`${r.client}: ${r.state.replaceAll("_", " ")}`);
183
+ for (const c of r.checks)
184
+ lines.push(` ${c.result.padEnd(4)} ${c.name}: ${c.detail}`);
185
+ for (const n of r.next)
186
+ lines.push(` next: ${n}`);
187
+ }
188
+ if (reports.some((r) => r.state === "not_set_up") && reports.every((r) => r.state === "not_set_up" || r.state === "manual"))
189
+ lines.push("", `No client has Flovia yet. Add it with: flovia install --client <${INSTALL_CLIENTS.join("|")}>`);
190
+ return lines.join("\n") + "\n";
191
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `flovia install --client <name>`: add Flovia's MCP server to one client's personal settings in one command.
3
+ * The key never enters a command argument, a printed line or a config file: OAuth sign-in (the default, like Console's Quick Install)
4
+ * needs no key, and --auth key points the client at the key file (Claude Code's headersHelper) or an environment variable's name.
5
+ * Pure planning lives here; cli.ts runs the plan through injectable I/O so tests never touch real settings.
6
+ */
7
+ export declare const INSTALL_CLIENTS: readonly ["claude-code", "codex", "cursor", "claude-desktop", "hermes"];
8
+ export type InstallClient = (typeof INSTALL_CLIENTS)[number];
9
+ export declare const INSTALL_AUTH: readonly ["oauth", "key"];
10
+ export type InstallAuth = (typeof INSTALL_AUTH)[number];
11
+ /** The key file Console's setup saves and the CLI reads by default. */
12
+ export declare const DEFAULT_KEY_PATH = "~/.config/flovia/key";
13
+ export type InstallStep =
14
+ /** Runs the client's own CLI; argv holds no secret (a key file path or an environment variable's name at most). */
15
+ {
16
+ kind: "exec";
17
+ command: string;
18
+ args: string[];
19
+ }
20
+ /** Merges mcpServers.flovia into a JSON file, keeping every other entry. */
21
+ | {
22
+ kind: "json";
23
+ path: string;
24
+ entry: Record<string, unknown>;
25
+ }
26
+ /** Adds flovia under mcp_servers in a YAML file, keeping every other entry. */
27
+ | {
28
+ kind: "yaml";
29
+ path: string;
30
+ entry: {
31
+ url: string;
32
+ auth: "oauth";
33
+ };
34
+ };
35
+ export interface InstallPlan {
36
+ client: InstallClient;
37
+ auth: InstallAuth;
38
+ resource: string;
39
+ steps: InstallStep[];
40
+ next: string[];
41
+ }
42
+ export declare class InstallRefusal extends Error {
43
+ }
44
+ /** The headersHelper Claude Code runs on each connect: reads the key file then, so the key is never in its settings. */
45
+ export declare function headersHelper(keyPath: string): string;
46
+ export declare function planInstall(o: {
47
+ client: InstallClient;
48
+ auth: InstallAuth;
49
+ resource: string;
50
+ home: string;
51
+ keyPath?: string;
52
+ }): InstallPlan;
53
+ type Json = Record<string, unknown>;
54
+ /** The new file text, or "unchanged". A different flovia entry is kept unless force; other entries are always kept. */
55
+ export declare function mergeJson(existing: string | null, entry: Json, force: boolean): string | "unchanged";
56
+ /** Create only new settings; existing YAML needs a manual merge unless it is exactly our generated entry. */
57
+ export declare function mergeYaml(existing: string | null, entry: {
58
+ url: string;
59
+ auth: string;
60
+ }): string | "unchanged";
61
+ export {};
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `flovia install --client <name>`: add Flovia's MCP server to one client's personal settings in one command.
3
+ * The key never enters a command argument, a printed line or a config file: OAuth sign-in (the default, like Console's Quick Install)
4
+ * needs no key, and --auth key points the client at the key file (Claude Code's headersHelper) or an environment variable's name.
5
+ * Pure planning lives here; cli.ts runs the plan through injectable I/O so tests never touch real settings.
6
+ */
7
+ export const INSTALL_CLIENTS = ["claude-code", "codex", "cursor", "claude-desktop", "hermes"];
8
+ export const INSTALL_AUTH = ["oauth", "key"];
9
+ /** The key file Console's setup saves and the CLI reads by default. */
10
+ export const DEFAULT_KEY_PATH = "~/.config/flovia/key";
11
+ export class InstallRefusal extends Error {
12
+ }
13
+ /** A single-quoted shell word; paths with a quote are refused before they get here. */
14
+ const shellWord = (s) => `'${s}'`;
15
+ /** The headersHelper Claude Code runs on each connect: reads the key file then, so the key is never in its settings. */
16
+ export function headersHelper(keyPath) {
17
+ const path = keyPath.startsWith("~/") ? `"$HOME"/${shellWord(keyPath.slice(2))}` : shellWord(keyPath);
18
+ // A pasted key can carry spaces or a CR; keys are [A-Za-z0-9_-], so dropping whitespace is safe.
19
+ return `printf '{"Authorization":"Bearer %s"}' "$(tr -d ' \\t\\r\\n' < ${path})"`;
20
+ }
21
+ export function planInstall(o) {
22
+ const { client, auth, resource, home } = o;
23
+ const keyPath = o.keyPath ?? DEFAULT_KEY_PATH;
24
+ if (keyPath.includes("'") || !(keyPath.startsWith("/") || keyPath.startsWith("~/")))
25
+ throw new InstallRefusal("install: --key-file must be an absolute path (or start with ~/) without quotes");
26
+ const check = "Then check the connection from the client: ask it to call flovia_status once.";
27
+ switch (client) {
28
+ case "claude-code":
29
+ return auth === "oauth"
30
+ ? { client, auth, resource, steps: [{ kind: "exec", command: "claude", args: ["mcp", "add", "--scope", "user", "--transport", "http", "flovia", resource] }],
31
+ next: ["Restart Claude Code, run /mcp and sign in to Flovia when asked.", check] }
32
+ : { client, auth, resource, steps: [{ kind: "exec", command: "claude", args: ["mcp", "add-json", "--scope", "user", "flovia",
33
+ JSON.stringify({ type: "http", url: resource, headersHelper: headersHelper(keyPath) })] }],
34
+ next: ["Restart Claude Code. The key is read from the key file on each connect; it is not in Claude Code's settings.", check] };
35
+ case "codex":
36
+ return auth === "oauth"
37
+ ? { client, auth, resource, steps: [{ kind: "exec", command: "codex", args: ["mcp", "add", "flovia", "--url", resource] }],
38
+ next: ["Sign in: codex mcp login flovia", "Restart Codex.", check] }
39
+ : { client, auth, resource, steps: [{ kind: "exec", command: "codex", args: ["mcp", "add", "flovia", "--url", resource, "--bearer-token-env-var", "FLOVIA_KEY"] }],
40
+ next: ["Set FLOVIA_KEY in your shell profile (for example ~/.zshrc) and start Codex from a new terminal.", check] };
41
+ case "cursor":
42
+ return { client, auth, resource,
43
+ steps: [{ kind: "json", path: `${home}/.cursor/mcp.json`,
44
+ entry: auth === "oauth" ? { url: resource } : { url: resource, headers: { Authorization: "Bearer ${env:FLOVIA_API_KEY}" } } }],
45
+ next: [auth === "oauth" ? "In Cursor, turn Flovia on in MCP settings and sign in when asked." :
46
+ "Set FLOVIA_API_KEY in your shell profile and open Cursor from a terminal (Cursor opened from the Dock won't see it). Turn Flovia on in MCP settings.", check] };
47
+ case "hermes":
48
+ if (auth === "key")
49
+ throw new InstallRefusal("install: Hermes Agent connects by sign-in only here; use --auth oauth");
50
+ return { client, auth, resource, steps: [{ kind: "yaml", path: `${home}/.hermes/config.yaml`, entry: { url: resource, auth: "oauth" } }],
51
+ next: ["In a new terminal: hermes mcp login flovia, and approve Flovia in your browser.", "Restart Hermes Agent or run /reload-mcp.", check] };
52
+ case "claude-desktop":
53
+ // Claude's desktop app adds a remote MCP server as a custom connector (sign-in), not through its local config file.
54
+ if (auth === "key")
55
+ throw new InstallRefusal("install: Claude desktop connects by sign-in only; use --auth oauth");
56
+ return { client, auth, resource, steps: [],
57
+ next: [`Open this link and add the connector: https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=Flovia&connectorUrl=${encodeURIComponent(resource)}`,
58
+ "Then sign in to Flovia when Claude asks.", check] };
59
+ }
60
+ }
61
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
62
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
63
+ /** The new file text, or "unchanged". A different flovia entry is kept unless force; other entries are always kept. */
64
+ export function mergeJson(existing, entry, force) {
65
+ let doc = {};
66
+ if (existing !== null && existing.trim() !== "") {
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(existing);
70
+ }
71
+ catch {
72
+ throw new InstallRefusal("install: the existing config is not valid JSON; fix it first, nothing was changed");
73
+ }
74
+ if (!isObject(parsed))
75
+ throw new InstallRefusal("install: the existing config is not a JSON object; nothing was changed");
76
+ doc = parsed;
77
+ }
78
+ const servers = doc["mcpServers"] ?? {};
79
+ if (!isObject(servers))
80
+ throw new InstallRefusal("install: mcpServers in the existing config is not an object; nothing was changed");
81
+ if (Object.hasOwn(servers, "flovia")) {
82
+ if (same(servers["flovia"], entry))
83
+ return "unchanged";
84
+ if (!force)
85
+ throw new InstallRefusal("install: a different flovia entry is already configured; rerun with --force to replace it");
86
+ }
87
+ return JSON.stringify({ ...doc, mcpServers: { ...servers, flovia: entry } }, null, 2) + "\n";
88
+ }
89
+ /** Create only new settings; existing YAML needs a manual merge unless it is exactly our generated entry. */
90
+ export function mergeYaml(existing, entry) {
91
+ const generated = `mcp_servers:\n flovia:\n url: ${entry.url}\n auth: ${entry.auth}\n`;
92
+ if (existing === generated)
93
+ return "unchanged";
94
+ if (existing !== null && existing.trim() !== "")
95
+ throw new InstallRefusal("install: existing Hermes settings need a manual merge; see Console's Quick Install. Nothing was changed");
96
+ return generated;
97
+ }
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.172";
2
+ export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.182";
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 ["approval_pending", "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first", "provider_not_allowed", "account_key_required", "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", "relay_internal_unknown", "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}`;
@@ -14,10 +14,31 @@ export interface Explanation {
14
14
  next_step: string;
15
15
  audience?: "agent" | "user";
16
16
  }
17
+ /** Facts when present on an individual tool reply: only settled call amounts with non-null usd may be added.
18
+ * This is not an aggregate: deduplicate repeated history records by stable IDs.
19
+ * A job_snapshot describes the original job, not another charge. */
20
+ export interface ReplyCharge {
21
+ source: "free" | "plan" | "purchased" | "own_key" | "reopen" | "unknown";
22
+ status: "settled" | "not_charged" | "unresolved" | "unavailable";
23
+ basis: "call" | "replay" | "job_snapshot";
24
+ /** Exact decimal USD taken by Flovia; null when unresolved or unproven, "0.00" for free allowance, own-key use and replay. */
25
+ usd: string | null;
26
+ /** Known free-window shares, such as "<1%"; null when not applicable or unavailable, including every replay and job snapshot. */
27
+ window_pct: {
28
+ five_hour: string | null;
29
+ week: string | null;
30
+ month: string | null;
31
+ };
32
+ }
33
+ export interface ForUser {
34
+ charge?: ReplyCharge;
35
+ [field: string]: unknown;
36
+ }
17
37
  /** Any tool reply. Fields beyond these depend on the tool; read them from the relay's documentation. */
18
38
  export interface ToolReply {
19
39
  ok?: boolean;
20
40
  explanation?: Explanation;
41
+ for_user?: ForUser;
21
42
  retry_after_seconds?: number;
22
43
  resets_at?: string;
23
44
  [field: string]: unknown;
@@ -37,8 +58,10 @@ export interface StatusReply extends ToolReply {
37
58
  services_off: string[];
38
59
  }
39
60
  export interface UsageTodayArgs {
40
- /** ISO 8601 time, at most 7 days ago. */
61
+ /** ISO 8601 time, at most 30 days ago (relays before #2641: 7 days). */
41
62
  since?: string;
63
+ /** The last N days (1-30) instead of since; not with since or a cursor. Relays before #2641 refuse it. */
64
+ days?: number;
42
65
  /** The previous next_cursor, unchanged, with the same since and conversation. */
43
66
  cursor?: string;
44
67
  /** The previous generations.next_cursor, with the same since and conversation. */
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.172";
2
+ export const EXPECTED_CONTRACT_VERSION = "2026-10-07.182";
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",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flovialabs/sdk",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
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",