@flovialabs/sdk 0.1.17 → 0.1.18
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 +11 -0
- package/README.md +30 -4
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +261 -8
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/doctor.d.ts +47 -0
- package/dist/doctor.js +191 -0
- package/dist/install.d.ts +61 -0
- package/dist/install.js +97 -0
- package/dist/types.d.ts +25 -2
- package/dist/types.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.18
|
|
4
|
+
|
|
5
|
+
- `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.
|
|
6
|
+
- `flovia usage --days N` は1〜30日を受け、開始時刻はRelayの時計で決める。#2641より前のRelayは `days` を受けないため、7日以内の `--since` を使う。`--days` は `--since` や `--cursor` と併用できない。
|
|
7
|
+
- 想定する契約を `2026-10-07.178` に更新。提供時のZerionの入力schemaと、精算情報の現行応答を記録する。SDKは `for_user`・`charge` が存在する場合の `ForUser`・`ReplyCharge` 型を公開し、その他の `for_user` 項目は `unknown` のまま残す。項目の欠如から支払額ゼロとは判断しない。
|
|
8
|
+
- `flovia_usage_today`の履歴の行に、記録済みの支払元・精算状態・正確な支払USDを示す`charge`を加えた。Gemini・MiniMaxの個別のMCP応答も、`for_user.charge`が存在する場合に同じ情報を返す。精算済みの無料分と、保存済みの応答の再表示の追加費用は`0.00`。未確定・取得不能の額は`null`で、項目が無い場合もゼロとは扱わない。履歴の生成プレビューはページをまたいで再掲されるため、同じ`lookup_id`は一度だけ数える。期間の合計は`total`を使い、replay・job snapshotを新しい課金として加えない。
|
|
9
|
+
- `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.
|
|
10
|
+
- 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.
|
|
11
|
+
- 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.
|
|
12
|
+
- `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.
|
|
13
|
+
|
|
3
14
|
## 0.1.17
|
|
4
15
|
|
|
5
16
|
- 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,13 @@ TypeScript client and command-line tool for [Flovia](https://api.flovia.dev). It
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
12
12
|
```sh
|
|
13
|
-
npm install --save-exact @flovialabs/sdk@0.1.
|
|
13
|
+
npm install --save-exact @flovialabs/sdk@0.1.18
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
+
## 0.1.18 release notes
|
|
17
|
+
|
|
18
|
+
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.
|
|
19
|
+
|
|
16
20
|
## 0.1.17 release notes
|
|
17
21
|
|
|
18
22
|
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 +57,7 @@ const flovia = new FloviaClient(); // reads FLOVIA_KEY; base URL https://api.flo
|
|
|
53
57
|
const status = await flovia.status();
|
|
54
58
|
console.log(status.five_hour.used_pct, status.week.used_pct);
|
|
55
59
|
|
|
56
|
-
// Your lookups today (or
|
|
60
|
+
// Your lookups today (or the last N days, up to 30)
|
|
57
61
|
const usage = await flovia.usageToday(); // today, UTC
|
|
58
62
|
|
|
59
63
|
// Any tool: list them, then call one
|
|
@@ -263,7 +267,7 @@ The package installs a `flovia` command.
|
|
|
263
267
|
```sh
|
|
264
268
|
export FLOVIA_KEY=flv_... # or: --key-file ~/.config/flovia/key
|
|
265
269
|
npx flovia status
|
|
266
|
-
npx flovia usage --days
|
|
270
|
+
npx flovia usage --days 30
|
|
267
271
|
npx flovia tools
|
|
268
272
|
npx flovia tools --json # includes each tool's inputSchema
|
|
269
273
|
npx flovia tools flovia_coingecko --json # only this tool's description and inputSchema
|
|
@@ -279,7 +283,7 @@ npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
|
|
|
279
283
|
npx flovia help
|
|
280
284
|
npx flovia --version
|
|
281
285
|
```
|
|
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.
|
|
286
|
+
These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.18 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
287
|
|
|
284
288
|
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
289
|
|
|
@@ -293,6 +297,28 @@ This sends the saved request once. Reopening it uses the same file and operation
|
|
|
293
297
|
|
|
294
298
|
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
299
|
|
|
300
|
+
To connect one AI client to Flovia's MCP server in one command (since 0.1.18; not included in 0.1.17):
|
|
301
|
+
|
|
302
|
+
```sh
|
|
303
|
+
npx flovia install --client claude-code # or codex, cursor, claude-desktop, hermes
|
|
304
|
+
npx flovia install --client cursor --auth key --dry-run
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
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.
|
|
308
|
+
|
|
309
|
+
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.
|
|
310
|
+
|
|
311
|
+
To check what `install` set up (since 0.1.18; not included in 0.1.17):
|
|
312
|
+
|
|
313
|
+
```sh
|
|
314
|
+
npx flovia doctor # every client
|
|
315
|
+
npx flovia doctor --client codex --network
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
`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.
|
|
319
|
+
|
|
320
|
+
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.
|
|
321
|
+
|
|
296
322
|
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
323
|
|
|
298
324
|
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
|
|
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
|
-
|
|
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));
|
|
@@ -381,6 +394,10 @@ export async function run(argv, io) {
|
|
|
381
394
|
...(accessToken ? { accessToken } : {}),
|
|
382
395
|
fetch: (r) => { r.headers.set("X-Flovia-Client", "flovia-cli"); return (io.fetch ?? fetch)(r); }, onContractMismatch: (expected) => { mismatch = expected; } });
|
|
383
396
|
};
|
|
397
|
+
if (p.command === "install")
|
|
398
|
+
return await install(p, io, out, err, json);
|
|
399
|
+
if (p.command === "doctor")
|
|
400
|
+
return await doctor(p, io, out, json, (k) => { seen.push(k); }, { baseUrl, timeout });
|
|
384
401
|
switch (p.command) {
|
|
385
402
|
case "runway-output": {
|
|
386
403
|
const [id, extra] = p.positional, path = str(p.flags.get("--out"));
|
|
@@ -467,20 +484,18 @@ export async function run(argv, io) {
|
|
|
467
484
|
return 0;
|
|
468
485
|
}
|
|
469
486
|
case "usage": {
|
|
470
|
-
const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")),
|
|
487
|
+
const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")), 30), cursor = str(p.flags.get("--cursor"));
|
|
471
488
|
if (since !== undefined && days !== undefined)
|
|
472
489
|
throw new Usage("usage: pass --since or --days, not both");
|
|
473
490
|
if (cursor !== undefined && days !== undefined)
|
|
474
491
|
throw new Usage("usage: with --cursor, use the previous reply's exact --since, not --days");
|
|
475
492
|
if (since !== undefined && Number.isNaN(Date.parse(since)))
|
|
476
493
|
throw new Usage("--since must be an ISO 8601 time");
|
|
477
|
-
|
|
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 } : {}) }));
|
|
494
|
+
const client = await connect(), u = await waitFor(() => client.usageToday({ ...(since ? { since } : {}), ...(days === undefined ? {} : { days }), ...(cursor ? { cursor } : {}) }));
|
|
480
495
|
if (json)
|
|
481
496
|
print(u);
|
|
482
497
|
else
|
|
483
|
-
out(renderUsage(u,
|
|
498
|
+
out(renderUsage(u, since === undefined && days === undefined && cursor === undefined, (io.now ?? Date.now)()));
|
|
484
499
|
return 0;
|
|
485
500
|
}
|
|
486
501
|
case "tools": {
|
|
@@ -619,6 +634,234 @@ export async function run(argv, io) {
|
|
|
619
634
|
return 1;
|
|
620
635
|
}
|
|
621
636
|
}
|
|
637
|
+
const quoteArg = (a) => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replaceAll("'", "'\\''")}'`;
|
|
638
|
+
const describeStep = (s) => s.kind === "exec" ? `run: ${[s.command, ...s.args.map(quoteArg)].join(" ")}`
|
|
639
|
+
: `update: ${s.path} (add flovia to ${s.kind === "json" ? "mcpServers" : "mcp_servers"}, keeping other entries)`;
|
|
640
|
+
/** No network and no key text: for Claude Code's key mode only the key file's readability is checked. */
|
|
641
|
+
async function install(p, io, out, err, json) {
|
|
642
|
+
const client = str(p.flags.get("--client")), auth = str(p.flags.get("--auth")) ?? "oauth";
|
|
643
|
+
if (p.positional.length)
|
|
644
|
+
throw new Usage(`Usage: flovia ${COMMANDS["install"]?.usage}`);
|
|
645
|
+
if (client === undefined || !INSTALL_CLIENTS.includes(client))
|
|
646
|
+
throw new Usage(`install: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${client === undefined ? "" : didYouMean(client, [...INSTALL_CLIENTS])}`);
|
|
647
|
+
if (!INSTALL_AUTH.includes(auth))
|
|
648
|
+
throw new Usage("install: --auth must be oauth or key");
|
|
649
|
+
const home = io.env["HOME"];
|
|
650
|
+
if (!home)
|
|
651
|
+
throw new Usage("install: HOME is not set");
|
|
652
|
+
let base;
|
|
653
|
+
try {
|
|
654
|
+
base = new URL(str(p.flags.get("--base-url")) ?? "https://api.flovia.dev");
|
|
655
|
+
}
|
|
656
|
+
catch {
|
|
657
|
+
throw new Usage("install: --base-url must be an https URL");
|
|
658
|
+
}
|
|
659
|
+
if (base.protocol !== "https:" || base.username || base.password)
|
|
660
|
+
throw new Usage("install: --base-url must be an https URL without credentials");
|
|
661
|
+
const resource = `${base.origin}/mcp`, keyFile = str(p.flags.get("--key-file"));
|
|
662
|
+
let plan;
|
|
663
|
+
try {
|
|
664
|
+
plan = planInstall({ client: client, auth: auth, resource, home, ...(keyFile ? { keyPath: keyFile } : {}) });
|
|
665
|
+
}
|
|
666
|
+
catch (e) {
|
|
667
|
+
if (e instanceof InstallRefusal)
|
|
668
|
+
throw new Usage(e.message);
|
|
669
|
+
throw e;
|
|
670
|
+
}
|
|
671
|
+
const dry = p.flags.has("--dry-run"), force = p.flags.has("--force"), done = [];
|
|
672
|
+
if (plan.client === "claude-code" && plan.auth === "key") {
|
|
673
|
+
const path = keyFile ?? "~/.config/flovia/key";
|
|
674
|
+
await fromFile(path.startsWith("~/") ? `${home}/${path.slice(2)}` : path, io, keyFile === undefined ? "~/.config/flovia/key" : "--key-file");
|
|
675
|
+
}
|
|
676
|
+
if (plan.client === "codex" && plan.auth === "key" && !io.env["FLOVIA_KEY"]?.trim())
|
|
677
|
+
err("warning: FLOVIA_KEY is not set in this shell; Codex needs it where it starts\n");
|
|
678
|
+
if (plan.client === "cursor" && plan.auth === "key" && !io.env["FLOVIA_API_KEY"]?.trim())
|
|
679
|
+
err("warning: FLOVIA_API_KEY is not set in this shell; Cursor needs it where it starts\n");
|
|
680
|
+
for (const step of plan.steps) {
|
|
681
|
+
if (dry) {
|
|
682
|
+
done.push(`would ${describeStep(step)}`);
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
if (step.kind === "exec") {
|
|
686
|
+
if (!io.exec)
|
|
687
|
+
throw new Usage("install: cannot run commands here; use --dry-run and run them yourself");
|
|
688
|
+
let code;
|
|
689
|
+
try {
|
|
690
|
+
code = await io.exec(step.command, step.args);
|
|
691
|
+
}
|
|
692
|
+
catch (e) {
|
|
693
|
+
if (e.code === "ENOENT")
|
|
694
|
+
throw new Usage(`install: ${step.command} was not found. Install it first, or use --dry-run and run the command yourself`);
|
|
695
|
+
throw new Usage(`install: ${step.command} could not complete; not retried. Check its settings before running install again`);
|
|
696
|
+
}
|
|
697
|
+
if (code !== 0)
|
|
698
|
+
throw new Usage(`install: ${step.command} exited with ${code}; not retried. Check its settings before running install again`);
|
|
699
|
+
done.push(describeStep(step));
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
if (!io.writeFile)
|
|
703
|
+
throw new Usage("install: cannot write files here; use --dry-run");
|
|
704
|
+
let existing;
|
|
705
|
+
try {
|
|
706
|
+
existing = await io.readFile(step.path);
|
|
707
|
+
}
|
|
708
|
+
catch (e) {
|
|
709
|
+
if (e.code === "ENOENT")
|
|
710
|
+
existing = null;
|
|
711
|
+
else
|
|
712
|
+
throw new Usage("install: cannot read the existing settings file; nothing was changed");
|
|
713
|
+
}
|
|
714
|
+
let next;
|
|
715
|
+
try {
|
|
716
|
+
const merged = step.kind === "json" ? mergeJson(existing, step.entry, force) : mergeYaml(existing, step.entry);
|
|
717
|
+
if (merged === "unchanged") {
|
|
718
|
+
done.push(`unchanged: ${step.path} already has this flovia entry`);
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
next = merged;
|
|
722
|
+
}
|
|
723
|
+
catch (e) {
|
|
724
|
+
if (e instanceof InstallRefusal)
|
|
725
|
+
throw new Usage(e.message);
|
|
726
|
+
throw e;
|
|
727
|
+
}
|
|
728
|
+
await io.writeFile(step.path, next);
|
|
729
|
+
done.push(describeStep(step));
|
|
730
|
+
}
|
|
731
|
+
if (json)
|
|
732
|
+
out(JSON.stringify({ ok: true, client: plan.client, auth: plan.auth, resource, dry_run: dry, done, next_steps: plan.next }, null, 2) + "\n");
|
|
733
|
+
else
|
|
734
|
+
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");
|
|
735
|
+
return 0;
|
|
736
|
+
}
|
|
737
|
+
/** Read-only: settings files, the key's readability, and with --network one unauthenticated /mcp request plus flovia_status with that key. */
|
|
738
|
+
async function doctor(p, io, out, json, remember, o) {
|
|
739
|
+
const client = str(p.flags.get("--client"));
|
|
740
|
+
if (p.positional.length)
|
|
741
|
+
throw new Usage(`Usage: flovia ${COMMANDS["doctor"]?.usage}`);
|
|
742
|
+
if (client !== undefined && !INSTALL_CLIENTS.includes(client))
|
|
743
|
+
throw new Usage(`doctor: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${didYouMean(client, [...INSTALL_CLIENTS])}`);
|
|
744
|
+
const home = io.env["HOME"];
|
|
745
|
+
if (!home)
|
|
746
|
+
throw new Usage("doctor: HOME is not set");
|
|
747
|
+
let base;
|
|
748
|
+
try {
|
|
749
|
+
base = new URL(o.baseUrl ?? "https://api.flovia.dev");
|
|
750
|
+
}
|
|
751
|
+
catch {
|
|
752
|
+
throw new Usage("doctor: --base-url must be an https URL");
|
|
753
|
+
}
|
|
754
|
+
if (base.protocol !== "https:" || base.username || base.password)
|
|
755
|
+
throw new Usage("doctor: --base-url must be an https URL without credentials");
|
|
756
|
+
const resource = `${base.origin}/mcp`, network = p.flags.has("--network"), keyFlag = str(p.flags.get("--key-file"));
|
|
757
|
+
const clients = client === undefined ? [...INSTALL_CLIENTS] : [client];
|
|
758
|
+
const doFetch = io.fetch ?? fetch;
|
|
759
|
+
/** One deadline includes fetch and body consumption/cancellation, even for injected transports. */
|
|
760
|
+
const timed = async (request) => {
|
|
761
|
+
const signal = AbortSignal.timeout((o.timeout ?? 300) * 1000);
|
|
762
|
+
let abort = () => { };
|
|
763
|
+
try {
|
|
764
|
+
const deadline = new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); });
|
|
765
|
+
return await Promise.race([request(signal), deadline]);
|
|
766
|
+
}
|
|
767
|
+
finally {
|
|
768
|
+
signal.removeEventListener("abort", abort);
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
let reachable;
|
|
772
|
+
const reach = async () => {
|
|
773
|
+
if (reachable)
|
|
774
|
+
return reachable;
|
|
775
|
+
try {
|
|
776
|
+
const r = await timed(async (signal) => {
|
|
777
|
+
const response = await doFetch(new Request(resource, { method: "GET", redirect: "error", signal, headers: { "X-Flovia-Client": "flovia-cli" } }));
|
|
778
|
+
await response.body?.cancel().catch(() => undefined);
|
|
779
|
+
return response;
|
|
780
|
+
});
|
|
781
|
+
reachable = r.status === 401 && /bearer/i.test(r.headers.get("www-authenticate") ?? "")
|
|
782
|
+
? { result: "ok", detail: `${resource} answers and asks for sign-in or a key` }
|
|
783
|
+
: { result: "warn", detail: `${resource} answered HTTP ${r.status}, not the expected 401 with a sign-in challenge` };
|
|
784
|
+
}
|
|
785
|
+
catch {
|
|
786
|
+
reachable = { result: "fail", detail: `${resource} could not be reached from this machine` };
|
|
787
|
+
}
|
|
788
|
+
return reachable;
|
|
789
|
+
};
|
|
790
|
+
/** A key is read only to check it; it goes into the scrub list first, so no line can show it. */
|
|
791
|
+
const tryKey = async (k, r) => {
|
|
792
|
+
remember(k);
|
|
793
|
+
if (!network)
|
|
794
|
+
return;
|
|
795
|
+
// Same format as the Relay's issued-key schema; never send another service's credential to Flovia.
|
|
796
|
+
if (!/^flv_[A-Za-z0-9_-]{43}$/.test(k)) {
|
|
797
|
+
r.checks.push({ name: "key accepted", result: "warn", detail: "The configured value is not a Flovia key; it was not sent." });
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
try {
|
|
801
|
+
await timed(async (signal) => {
|
|
802
|
+
const c = new FloviaClient({ apiKey: k, baseUrl: base.origin, ...(o.timeout ? { timeoutMs: o.timeout * 1000 } : {}),
|
|
803
|
+
fetch: (req) => { req.headers.set("X-Flovia-Client", "flovia-cli"); return doFetch(new Request(req, { signal })); }, onContractMismatch: () => undefined });
|
|
804
|
+
await c.status();
|
|
805
|
+
});
|
|
806
|
+
r.checks.push({ name: "key accepted", result: "ok", detail: "flovia_status answered with this key" });
|
|
807
|
+
}
|
|
808
|
+
catch (e) {
|
|
809
|
+
if (e instanceof FloviaError && (e.code === "unauthorized" || e.code === "key_disabled" || e.code === "key_stopped")) {
|
|
810
|
+
r.checks.push({ name: "key accepted", result: "fail", detail: `Flovia refused this key (${e.code})` });
|
|
811
|
+
r.next.push(`Issue or re-enable a key in Console (${CONSOLE}), save it, then restart ${r.client}.`);
|
|
812
|
+
}
|
|
813
|
+
else
|
|
814
|
+
r.checks.push({ name: "key accepted", result: "warn", detail: e instanceof FloviaError ? `flovia_status answered ${e.code}` : "flovia_status could not be reached" });
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
const reports = [];
|
|
818
|
+
for (const name of clients) {
|
|
819
|
+
const path = settingsPath(name, home);
|
|
820
|
+
let text = null;
|
|
821
|
+
if (path !== null) {
|
|
822
|
+
try {
|
|
823
|
+
text = await io.readFile(path);
|
|
824
|
+
}
|
|
825
|
+
catch (e) {
|
|
826
|
+
if (e.code !== "ENOENT") {
|
|
827
|
+
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."] });
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
const r = inspect(name, text, resource, home, io.env, client !== undefined, keyFlag);
|
|
833
|
+
if (r.state === "ok" && r.auth === "key-file") {
|
|
834
|
+
const shown = keyFlag === undefined ? `~/${DEFAULT_KEY_FILE}` : "--key-file";
|
|
835
|
+
try {
|
|
836
|
+
const keyPath = keyFlag ?? `~/${DEFAULT_KEY_FILE}`;
|
|
837
|
+
const k = await fromFile(keyPath.startsWith("~/") ? `${home}/${keyPath.slice(2)}` : keyPath, io, shown);
|
|
838
|
+
r.checks.push({ name: "key", result: "ok", detail: `the key file (${shown}) is readable` });
|
|
839
|
+
await tryKey(k, r);
|
|
840
|
+
}
|
|
841
|
+
catch (e) {
|
|
842
|
+
if (!(e instanceof Usage))
|
|
843
|
+
throw e;
|
|
844
|
+
r.checks.push({ name: "key", result: "fail", detail: e.message });
|
|
845
|
+
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).`);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
if (r.state === "ok" && r.auth === "key-env" && r.keyEnv !== undefined) {
|
|
849
|
+
const k = io.env[r.keyEnv]?.trim();
|
|
850
|
+
if (k)
|
|
851
|
+
await tryKey(k, r);
|
|
852
|
+
}
|
|
853
|
+
if (network && r.auth !== "unknown" && (r.state === "ok" || r.state === "manual")) {
|
|
854
|
+
const n = await reach();
|
|
855
|
+
r.checks.push({ name: "network", ...n });
|
|
856
|
+
}
|
|
857
|
+
reports.push(settle(r));
|
|
858
|
+
}
|
|
859
|
+
if (json)
|
|
860
|
+
out(JSON.stringify({ ok: !reports.some((r) => r.state === "fail"), resource, network, clients: reports }, null, 2) + "\n");
|
|
861
|
+
else
|
|
862
|
+
out(renderDoctor(reports));
|
|
863
|
+
return reports.some((r) => r.state === "fail") ? 1 : 0;
|
|
864
|
+
}
|
|
622
865
|
/** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
|
|
623
866
|
export async function readStdin(input) {
|
|
624
867
|
const chunks = [];
|
|
@@ -647,6 +890,16 @@ if (isMain) {
|
|
|
647
890
|
process.exitCode = await run(process.argv.slice(2), {
|
|
648
891
|
env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
|
|
649
892
|
writeOutput: writePrivateOutput,
|
|
893
|
+
exec: (command, args) => new Promise((resolve, reject) => {
|
|
894
|
+
// Adding settings needs no credential values or interactive sign-in. Child diagnostics may contain secrets.
|
|
895
|
+
const env = { ...process.env };
|
|
896
|
+
for (const name of ["FLOVIA_KEY", "FLOVIA_API_KEY", "FLOVIA_ACCESS_TOKEN"])
|
|
897
|
+
delete env[name];
|
|
898
|
+
const child = spawn(command, args, { stdio: "ignore", env });
|
|
899
|
+
child.once("error", reject);
|
|
900
|
+
child.once("exit", (code) => resolve(code ?? 1));
|
|
901
|
+
}),
|
|
902
|
+
writeFile: async (path, text) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, text, "utf8"); },
|
|
650
903
|
readFile: (path) => readFile(path, "utf8"), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
|
|
651
904
|
confirm: tty ? confirm : null,
|
|
652
905
|
...(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
|
|
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
|
@@ -287,7 +287,7 @@ export class FloviaClient {
|
|
|
287
287
|
}
|
|
288
288
|
return s;
|
|
289
289
|
}
|
|
290
|
-
/** flovia_usage_today: the user's lookups (today, or since a time within
|
|
290
|
+
/** flovia_usage_today: the user's lookups (today, the last N days up to 30, or since a time within 30 days). */
|
|
291
291
|
usageToday(args = {}) {
|
|
292
292
|
return this.call("flovia_usage_today", { ...args });
|
|
293
293
|
}
|
package/dist/doctor.d.ts
ADDED
|
@@ -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 {};
|
package/dist/install.js
ADDED
|
@@ -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.
|
|
2
|
+
export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.178";
|
|
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
|
|
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.
|
|
2
|
+
export const EXPECTED_CONTRACT_VERSION = "2026-10-07.178";
|
|
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