@flovialabs/sdk 0.1.16 → 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 +18 -1
- package/README.md +42 -7
- package/dist/cli.d.ts +6 -1
- package/dist/cli.js +304 -9
- package/dist/client.d.ts +12 -4
- package/dist/client.js +40 -3
- 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 +39 -3
- package/dist/types.js +3 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
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
|
+
|
|
14
|
+
## 0.1.17
|
|
15
|
+
|
|
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.
|
|
17
|
+
- `flovia consent` reads the current notice version, your last yes, whether it is to an earlier version (`updated`), and the full notice text. `flovia consent accept <version> --yes` records the account owner's own yes to exactly that version, as in Console; without `--yes` nothing is sent. In code: `client.consent()` and `client.acceptConsent(version)`. An agent must never answer for the person.
|
|
18
|
+
- Notice 18-eligible Nansen answers and generated text/audio can be reopened only by their owner for up to 30 days from creation. Eligibility starts with accepted use from 2026-12-01, or records after an earlier explicit yes to notice 18 or matching registration Terms. Retrieval availability follows the Relay rollout and the notice on each original record. Earlier records keep their original periods; reopening does not renew the deadline or restore a missing or expired copy. Runway's eligible media retrieval period remains up to 30 days.
|
|
19
|
+
- Other lookup replies and fal.ai URL copies get up to 30 days only for new notice 19 records, from 2026-12-03 or after a fresh explicit yes to notice 19. Old notice 18 and earlier lookup copies keep about 15 minutes; later agreement never extends them. These copies are owner-only retrieval data, not fresh results or a shared cache.
|
|
20
|
+
- A saved fal.ai URL still expires at the provider after about an hour. Saving its URL for longer does not extend or restore the image.
|
|
4
21
|
|
|
5
22
|
## 0.1.16
|
|
6
23
|
|
package/README.md
CHANGED
|
@@ -10,9 +10,19 @@ 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
|
+
|
|
20
|
+
## 0.1.17 release notes
|
|
21
|
+
|
|
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.
|
|
23
|
+
|
|
24
|
+
Eligible Nansen answers and generated text/audio can be reopened only by their owner for up to 30 days under notice 18, from the original record's creation. Retrieval availability follows the Relay rollout and the notice on each original record. Earlier records keep their original periods. Other lookup replies and fal.ai URL copies get this period only for new notice 19 records, from 2026-12-03 or after your fresh explicit yes to notice 19. Old notice 18 and earlier lookup copies keep about 15 minutes; later agreement never extends them. Reopening does not renew the deadline, fetch fresh data or restore a missing copy. A fal.ai image URL still expires after about an hour; a saved URL does not extend the image's lifetime.
|
|
25
|
+
|
|
16
26
|
## Your key
|
|
17
27
|
|
|
18
28
|
1. Register at https://console.flovia.dev/auth/register with email verification and a Passkey.
|
|
@@ -47,7 +57,7 @@ const flovia = new FloviaClient(); // reads FLOVIA_KEY; base URL https://api.flo
|
|
|
47
57
|
const status = await flovia.status();
|
|
48
58
|
console.log(status.five_hour.used_pct, status.week.used_pct);
|
|
49
59
|
|
|
50
|
-
// Your lookups today (or
|
|
60
|
+
// Your lookups today (or the last N days, up to 30)
|
|
51
61
|
const usage = await flovia.usageToday(); // today, UTC
|
|
52
62
|
|
|
53
63
|
// Any tool: list them, then call one
|
|
@@ -104,7 +114,7 @@ const output = await flovia.downloadRunwayOutput(String(result["generation_id"])
|
|
|
104
114
|
|
|
105
115
|
Images are one 720p `gen4_image` result. Videos use `action: "video"` with `duration: 2` through `5`, and return MP4. Runway jobs never resend automatically, even with `retryRateLimited: true`. Keep the original operation ID after a disconnect or unknown result; never generate a replacement to recover it. A failed/moderated generation may still be charged. Status distinguishes the billing state from output delivery.
|
|
106
116
|
|
|
107
|
-
Flovia keeps output privately for 24 hours, with authenticated downloads; Runway's own retention is separate. The SDK download is a bounded (32 MiB), one-request GET to Flovia, never a provider URL. A download does not generate or charge again. OAuth-only MCP users can use the returned `console_download_url` while signed in to their own Console.
|
|
117
|
+
Flovia keeps output privately for up to 30 days from generation creation under notice 18 (earlier records keep 24 hours), with authenticated downloads; Runway's own retention is separate. The SDK download is a bounded (32 MiB), one-request GET to Flovia, never a provider URL. A download does not generate or charge again. OAuth-only MCP users can use the returned `console_download_url` while signed in to their own Console.
|
|
108
118
|
|
|
109
119
|
```bash
|
|
110
120
|
flovia call flovia_runway '{"action":"list"}'
|
|
@@ -205,7 +215,7 @@ For Luna, set `reasoning.effort` to `none`, `low`, `medium`, `high`, `xhigh` or
|
|
|
205
215
|
|
|
206
216
|
`generate()` requires an operation id (8-128 characters of `A-Z a-z 0-9 _ . : -`). Create one with `newOperationId()` and store it with the request **before** sending.
|
|
207
217
|
|
|
208
|
-
If the reply is lost (timeout, network error, `executed: "unknown"`), keep the request and **same** id. A completed or incomplete answer can
|
|
218
|
+
If the reply is lost (timeout, network error, `executed: "unknown"`), keep the request and **same** id. A completed or incomplete saved answer can be reopened with the unchanged request, `replayed: true` and no additional charge. For generations made under data-use notice 18 (including matching registration Terms), the period is up to 30 days from creation. This covers accepted use from 2026-12-01T00:00Z, or work after your earlier explicit agreement to notice 18. Earlier generations keep about 15 minutes; later agreement does not extend them. A failed save or missing copy can prevent reopening even before expiry. Follow `nextStep` for `generation_pending` or `generation_unknown`; the answer may not be available yet. After `answer_expired` or `operation_retired`, Flovia cannot return the saved text. Expired or deleted copies are not restored. Never start a new id to recover a lost answer: that may run and charge twice. A new generation requires the person's decision to spend again. [Data use](https://docs.flovia.dev/data-use/) explains the retrieval periods and their limits.
|
|
209
219
|
|
|
210
220
|
## Errors
|
|
211
221
|
|
|
@@ -257,21 +267,23 @@ The package installs a `flovia` command.
|
|
|
257
267
|
```sh
|
|
258
268
|
export FLOVIA_KEY=flv_... # or: --key-file ~/.config/flovia/key
|
|
259
269
|
npx flovia status
|
|
260
|
-
npx flovia usage --days
|
|
270
|
+
npx flovia usage --days 30
|
|
261
271
|
npx flovia tools
|
|
262
272
|
npx flovia tools --json # includes each tool's inputSchema
|
|
263
273
|
npx flovia tools flovia_coingecko --json # only this tool's description and inputSchema
|
|
264
274
|
npx flovia call flovia_usage_today '{}'
|
|
265
275
|
npx flovia generate --op sdk-example-0001 --max-output 1000 --reasoning-effort low "Explain a DEX aggregator."
|
|
266
|
-
# Only to reopen that exact request
|
|
276
|
+
# Only to reopen that exact request while its saved answer is available:
|
|
267
277
|
npx flovia generate --op sdk-example-0001 --max-output 1000 --reasoning-effort low --yes "Explain a DEX aggregator."
|
|
268
278
|
npx flovia resets # saved resets and both free windows (read-only)
|
|
269
279
|
npx flovia resets use 42 --yes # use saved reset 42 (cannot be undone)
|
|
280
|
+
npx flovia consent # current notice version, your yes and the notice text (read-only)
|
|
281
|
+
npx flovia consent accept relay-consent-19 --yes # your own yes to the version just shown (same as Console)
|
|
270
282
|
npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
|
|
271
283
|
npx flovia help
|
|
272
284
|
npx flovia --version
|
|
273
285
|
```
|
|
274
|
-
These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.
|
|
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.
|
|
275
287
|
|
|
276
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.
|
|
277
289
|
|
|
@@ -285,6 +297,28 @@ This sends the saved request once. Reopening it uses the same file and operation
|
|
|
285
297
|
|
|
286
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.
|
|
287
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
|
+
|
|
288
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.
|
|
289
323
|
|
|
290
324
|
For multiline generation text, keep the original input in a private file:
|
|
@@ -303,6 +337,7 @@ Keep the same `--key-file` and `--base-url` too. For a prompt starting with a hy
|
|
|
303
337
|
- `generate` uses your free allowance first, then your purchased balance. It needs `--op ID` or `--new-op`, and asks for confirmation on a terminal; add `--yes` in scripts.
|
|
304
338
|
- `generate` prints the response status and incomplete reason. `incomplete` / `max_output_tokens` means the delivered text stopped at the output limit, not that a continuation ran. Exit 0 means the response was delivered, not that the text is complete or correct. `--json` retains the full public response.
|
|
305
339
|
- `resets` only reads: the number of saved resets, the next to expire, and the 5-hour and weekly windows. `resets use <id> --yes` uses one; both free windows (5-hour and week) start again from 0%. Without `--yes` nothing is sent, even on a terminal. It is never resent automatically: after a lost reply, run `flovia resets` before trying again. `Not used; nothing changed.` exits 1. In code: `client.bankedResets()` and `client.useBankedReset(id)`.
|
|
340
|
+
- `consent` only reads: the current notice version, the version you last said yes to, whether that yes is to an earlier version (it keeps working; continued use accepts the current one), and the full notice. `consent accept <version> --yes` records your own yes to exactly that version, the same as answering in Console; an older version is refused and nothing is recorded, and a repeat changes nothing. Without `--yes` it shows the text and sends nothing (exit 2). Only the account owner should run it, never an agent on their behalf. In code: `client.consent()` and `client.acceptConsent(version)`.
|
|
306
341
|
- Exit codes: 0 ok, 1 an error from Flovia, 2 a usage error.
|
|
307
342
|
|
|
308
343
|
### Safety
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { FloviaError, type BankedResets, type StatusReply, type UsageTodayReply } from "./index.js";
|
|
2
|
+
import { FloviaError, type BankedResets, type ConsentState, type StatusReply, type UsageTodayReply } from "./index.js";
|
|
3
3
|
/** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
|
|
4
4
|
export declare function writePrivateOutput(path: string, data: Uint8Array): Promise<void>;
|
|
5
5
|
export interface Io {
|
|
@@ -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. */
|
|
@@ -33,6 +37,7 @@ export declare function when(v: unknown, now?: number): string;
|
|
|
33
37
|
export declare function renderStatus(s: StatusReply, expected: string | null, now?: number): string;
|
|
34
38
|
export declare function renderUsage(u: UsageTodayReply, today?: boolean, now?: number): string;
|
|
35
39
|
export declare function renderResets(r: BankedResets, s: StatusReply, now?: number): string;
|
|
40
|
+
export declare function renderConsent(c: ConsentState): string;
|
|
36
41
|
/** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
|
|
37
42
|
export declare function renderError(e: FloviaError): string;
|
|
38
43
|
export declare function run(argv: string[], io: Io): Promise<number>;
|
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,12 +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 } },
|
|
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 } },
|
|
33
40
|
"agents-md": { usage: "agents-md", about: "a short Flovia note to paste into CLAUDE.md or AGENTS.md (no network)", flags: {} },
|
|
34
41
|
help: { usage: "help [command]", about: "this help", flags: {} },
|
|
35
42
|
version: { usage: "version", about: "the installed CLI version", flags: {} },
|
|
@@ -106,6 +113,12 @@ export function help(command) {
|
|
|
106
113
|
lines.push("", "Inspect one tool: flovia tools <tool> --json", "Inspect all tool arguments: flovia tools --json", "Read-only example: flovia call flovia_status '{}'");
|
|
107
114
|
if (command === "resets")
|
|
108
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.");
|
|
116
|
+
if (command === "consent")
|
|
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");
|
|
109
122
|
if (command === "call")
|
|
110
123
|
lines.push("", "Read a saved request: flovia call <tool> - < request.json", ...SAVE_OP);
|
|
111
124
|
lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 error from Flovia, 2 usage error.", "");
|
|
@@ -283,6 +296,16 @@ export function renderResets(r, s, now = Date.now()) {
|
|
|
283
296
|
lines.push("Using one starts both free windows (5-hour and week) again from 0%. It cannot be undone.", `To use it: flovia resets use ${r.next.id} --yes`);
|
|
284
297
|
return lines.join("\n") + "\n";
|
|
285
298
|
}
|
|
299
|
+
export function renderConsent(c) {
|
|
300
|
+
const lines = [`${label("current notice")}${c.version}`, `${label("your yes")}${c.answered_version ?? "none"}`];
|
|
301
|
+
if (!c.needed && !c.updated)
|
|
302
|
+
return lines.join("\n") + "\n";
|
|
303
|
+
if (c.updated)
|
|
304
|
+
lines.push("", c.version === "relay-consent-19" ? "Your earlier yes keeps working. Notice 19 adds owner-only lookup reply copies for up to 30 days for new records from 2026-12-03 or after your fresh explicit yes. Earlier records keep their original periods; no answer is needed to keep looking up." : "Your earlier yes keeps working. If you keep using Flovia from 2026-12-01 (30 days after the notice), you agree to the current notice; recording a yes below now is optional and applies from when you give it.");
|
|
305
|
+
lines.push("", "Notice:", c.notice);
|
|
306
|
+
lines.push("", `To answer yes yourself: flovia consent accept ${c.version} --yes (or in Console: ${CONSOLE})`);
|
|
307
|
+
return lines.join("\n") + "\n";
|
|
308
|
+
}
|
|
286
309
|
/** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
|
|
287
310
|
export function renderError(e) {
|
|
288
311
|
const lines = [`error: ${e.code}: ${e.message}`];
|
|
@@ -313,10 +336,13 @@ export function renderError(e) {
|
|
|
313
336
|
}
|
|
314
337
|
export async function run(argv, io) {
|
|
315
338
|
let key = null;
|
|
339
|
+
const seen = [];
|
|
316
340
|
// Belt and braces: whatever is printed passes through here, so the key cannot appear even if a reply or error echoed it.
|
|
317
341
|
const accessToken = io.env["FLOVIA_ACCESS_TOKEN"]?.trim();
|
|
318
342
|
const scrub = (s) => {
|
|
319
|
-
|
|
343
|
+
let masked = key === null ? s : s.replaceAll(key, "[key]");
|
|
344
|
+
for (const k of seen)
|
|
345
|
+
masked = masked.replaceAll(k, "[key]");
|
|
320
346
|
return accessToken ? masked.replaceAll(accessToken, "[access-token]") : masked;
|
|
321
347
|
};
|
|
322
348
|
const out = (s) => io.out(scrub(s)), err = (s) => io.err(scrub(s));
|
|
@@ -368,6 +394,10 @@ export async function run(argv, io) {
|
|
|
368
394
|
...(accessToken ? { accessToken } : {}),
|
|
369
395
|
fetch: (r) => { r.headers.set("X-Flovia-Client", "flovia-cli"); return (io.fetch ?? fetch)(r); }, onContractMismatch: (expected) => { mismatch = expected; } });
|
|
370
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 });
|
|
371
401
|
switch (p.command) {
|
|
372
402
|
case "runway-output": {
|
|
373
403
|
const [id, extra] = p.positional, path = str(p.flags.get("--out"));
|
|
@@ -424,21 +454,48 @@ export async function run(argv, io) {
|
|
|
424
454
|
: `Not used; nothing changed.\n${label("saved resets")}${u.available}\nCheck: flovia resets\n`);
|
|
425
455
|
return u.outcome === "used" ? 0 : 1;
|
|
426
456
|
}
|
|
457
|
+
case "consent": {
|
|
458
|
+
const [action, version, extra] = p.positional;
|
|
459
|
+
if (action === undefined) {
|
|
460
|
+
if (p.flags.has("--yes"))
|
|
461
|
+
throw new Usage("Usage: flovia consent accept <version> --yes");
|
|
462
|
+
const client = await connect(), c = await waitFor(() => client.consent());
|
|
463
|
+
if (json)
|
|
464
|
+
print(c);
|
|
465
|
+
else
|
|
466
|
+
out(renderConsent(c));
|
|
467
|
+
return 0;
|
|
468
|
+
}
|
|
469
|
+
if (action !== "accept" || version === undefined || extra !== undefined)
|
|
470
|
+
throw new Usage("Usage: flovia consent accept <version> --yes (the version from flovia consent)");
|
|
471
|
+
const client = await connect();
|
|
472
|
+
if (!p.flags.has("--yes")) {
|
|
473
|
+
// Show what would be agreed to, then stop: nothing is sent without --yes.
|
|
474
|
+
const c = await waitFor(() => client.consent());
|
|
475
|
+
if (!json)
|
|
476
|
+
out(renderConsent(c));
|
|
477
|
+
throw new Usage(`consent accept: nothing was sent. Read the notice, then add --yes to answer yes to ${version} yourself.`);
|
|
478
|
+
}
|
|
479
|
+
const a = await waitFor(() => client.acceptConsent(version));
|
|
480
|
+
if (json)
|
|
481
|
+
print(a);
|
|
482
|
+
else
|
|
483
|
+
out(a.outcome === "recorded" ? `Recorded: yes to ${a.version}.\n` : `Already answered yes to ${a.version}; nothing changed.\n`);
|
|
484
|
+
return 0;
|
|
485
|
+
}
|
|
427
486
|
case "usage": {
|
|
428
|
-
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"));
|
|
429
488
|
if (since !== undefined && days !== undefined)
|
|
430
489
|
throw new Usage("usage: pass --since or --days, not both");
|
|
431
490
|
if (cursor !== undefined && days !== undefined)
|
|
432
491
|
throw new Usage("usage: with --cursor, use the previous reply's exact --since, not --days");
|
|
433
492
|
if (since !== undefined && Number.isNaN(Date.parse(since)))
|
|
434
493
|
throw new Usage("--since must be an ISO 8601 time");
|
|
435
|
-
|
|
436
|
-
const from = days === undefined ? since : new Date((io.now ?? Date.now)() - days * 86_400_000 + 60_000).toISOString();
|
|
437
|
-
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 } : {}) }));
|
|
438
495
|
if (json)
|
|
439
496
|
print(u);
|
|
440
497
|
else
|
|
441
|
-
out(renderUsage(u,
|
|
498
|
+
out(renderUsage(u, since === undefined && days === undefined && cursor === undefined, (io.now ?? Date.now)()));
|
|
442
499
|
return 0;
|
|
443
500
|
}
|
|
444
501
|
case "tools": {
|
|
@@ -523,7 +580,7 @@ export async function run(argv, io) {
|
|
|
523
580
|
// The id is shown before anything is sent, so a lost reply can be reopened with it (never resent under a new one).
|
|
524
581
|
if (fresh)
|
|
525
582
|
err(`operation_id: ${id}\nSave it. To resend or reopen this request, use: --op ${id}\n`);
|
|
526
|
-
err("This generation uses your free allowance first, then your purchased balance.\nIf the reply is lost, rerun with the same --op, prompt, output limit and effort.\nA saved answer
|
|
583
|
+
err("This generation uses your free allowance first, then your purchased balance.\nIf the reply is lost, rerun with the same --op, prompt, output limit and effort.\nA saved answer may reopen free: up to 30 days from creation for notice 18 generations; earlier ones about 15 minutes. Missing or deleted copies are not restored. Never use a new id to recover an answer.\n");
|
|
527
584
|
if (!p.flags.has("--yes")) {
|
|
528
585
|
if (io.confirm === null || text === "-")
|
|
529
586
|
throw new Usage("generate: add --yes to send (no terminal to confirm on)");
|
|
@@ -577,6 +634,234 @@ export async function run(argv, io) {
|
|
|
577
634
|
return 1;
|
|
578
635
|
}
|
|
579
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
|
+
}
|
|
580
865
|
/** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
|
|
581
866
|
export async function readStdin(input) {
|
|
582
867
|
const chunks = [];
|
|
@@ -605,6 +890,16 @@ if (isMain) {
|
|
|
605
890
|
process.exitCode = await run(process.argv.slice(2), {
|
|
606
891
|
env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
|
|
607
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"); },
|
|
608
903
|
readFile: (path) => readFile(path, "utf8"), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
|
|
609
904
|
confirm: tty ? confirm : null,
|
|
610
905
|
...(process.stderr.isTTY ? { waiting: () => {
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Generation, type GenerationRequest, type StatusReply, type ToolReply, type UsageTodayArgs, type UsageTodayReply, type BankedResets, type BankedResetUse } from "./types.js";
|
|
1
|
+
import { type Generation, type GenerationRequest, type StatusReply, type ToolReply, type UsageTodayArgs, type UsageTodayReply, type BankedResets, type BankedResetUse, type ConsentState, type ConsentAccept } from "./types.js";
|
|
2
2
|
export interface FloviaClientOptions {
|
|
3
3
|
/** A Flovia key (flv_...). Defaults to the FLOVIA_KEY environment variable. Never logged. */
|
|
4
4
|
apiKey?: string;
|
|
@@ -27,7 +27,7 @@ export declare const newOperationId: () => string;
|
|
|
27
27
|
export declare class FloviaClient {
|
|
28
28
|
#private;
|
|
29
29
|
constructor(options?: FloviaClientOptions);
|
|
30
|
-
/** Download an existing Runway output before
|
|
30
|
+
/** Download an existing Runway output before output.expires_at (up to 30 days under notice 18; earlier outputs keep 24h). This GET never creates, regenerates or retries a task. */
|
|
31
31
|
downloadRunwayOutput(generationId: string): Promise<{
|
|
32
32
|
data: Uint8Array;
|
|
33
33
|
contentType: string;
|
|
@@ -39,17 +39,25 @@ export declare class FloviaClient {
|
|
|
39
39
|
* "not_used" means nothing changed. After a lost, refused (401) or unreadable reply, check bankedResets() before deciding to try again.
|
|
40
40
|
*/
|
|
41
41
|
useBankedReset(grantId: number): Promise<BankedResetUse>;
|
|
42
|
+
/** The account's answer to Flovia's current notice and the notice text. Read-only; nothing is answered. */
|
|
43
|
+
consent(): Promise<ConsentState>;
|
|
44
|
+
/**
|
|
45
|
+
* Record the account owner's own yes to exactly this notice version (from consent()). Only call it on the owner's explicit instruction; an agent must
|
|
46
|
+
* never answer for them. An older version is refused and nothing is recorded; a repeat changes nothing.
|
|
47
|
+
*/
|
|
48
|
+
acceptConsent(version: string): Promise<ConsentAccept>;
|
|
42
49
|
/** tools/list: the tools this key is offered, with their input schemas. */
|
|
43
50
|
listTools(): Promise<ToolInfo[]>;
|
|
44
51
|
/** tools/call for any tool. A reply with ok: false throws FloviaError (handshakes such as notice_first too; see error.reply). */
|
|
45
52
|
call<R extends ToolReply = ToolReply>(tool: string, args?: Record<string, unknown>): Promise<R>;
|
|
46
53
|
/** flovia_status. Warns once when the relay's contract_version is not the one this SDK expects. */
|
|
47
54
|
status(): Promise<StatusReply>;
|
|
48
|
-
/** 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). */
|
|
49
56
|
usageToday(args?: UsageTodayArgs): Promise<UsageTodayReply>;
|
|
50
57
|
/**
|
|
51
58
|
* POST /openai/v1/responses. operationId is required: save it with the request before calling. Sending the same request with the same id
|
|
52
|
-
* again can return the saved answer (replayed: true)
|
|
59
|
+
* again can return the saved answer (replayed: true) at no charge: notice 18 generations up to 30 days from creation, earlier ones about 15 minutes.
|
|
60
|
+
* Missing or deleted copies are not restored. Pending, unknown and expired answers
|
|
53
61
|
* are not proof that nothing ran. Never resent automatically, and never under a new id to recover an answer.
|
|
54
62
|
*/
|
|
55
63
|
generate(request: GenerationRequest, options: {
|
package/dist/client.js
CHANGED
|
@@ -119,7 +119,7 @@ export class FloviaClient {
|
|
|
119
119
|
message: String(message.error?.message ?? "No result."), nextStep: operationId ? SAME_OPERATION : null });
|
|
120
120
|
return message.result;
|
|
121
121
|
}
|
|
122
|
-
/** Download an existing Runway output before
|
|
122
|
+
/** Download an existing Runway output before output.expires_at (up to 30 days under notice 18; earlier outputs keep 24h). This GET never creates, regenerates or retries a task. */
|
|
123
123
|
async downloadRunwayOutput(generationId) {
|
|
124
124
|
const unavailable = () => this.#error({ code: "output_unavailable", executed: "no", message: "The private output could not be downloaded.", nextStep: "Check the original generation's status and expiry; never regenerate it automatically." });
|
|
125
125
|
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(generationId))
|
|
@@ -194,6 +194,37 @@ export class FloviaClient {
|
|
|
194
194
|
throw this.#error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The saved-reset reply was not in the expected form.", nextStep: check });
|
|
195
195
|
return { outcome: body["outcome"], available: body.available, next: body.next };
|
|
196
196
|
}
|
|
197
|
+
/** The account's answer to Flovia's current notice and the notice text. Read-only; nothing is answered. */
|
|
198
|
+
async consent() {
|
|
199
|
+
const r = await this.#send("/account/consent", null, {}, null, "GET");
|
|
200
|
+
const body = await this.#account(r, null);
|
|
201
|
+
if (!isConsent(body))
|
|
202
|
+
throw this.#error({ code: "invalid_reply", status: r.status, executed: "no", message: "The consent reply was not in the expected form.", nextStep: null });
|
|
203
|
+
return { version: body.version, answered_version: body.answered_version, needed: body.needed, updated: body.updated, notice: body.notice };
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Record the account owner's own yes to exactly this notice version (from consent()). Only call it on the owner's explicit instruction; an agent must
|
|
207
|
+
* never answer for them. An older version is refused and nothing is recorded; a repeat changes nothing.
|
|
208
|
+
*/
|
|
209
|
+
async acceptConsent(version) {
|
|
210
|
+
if (typeof version !== "string" || !/^[a-z0-9-]{1,80}$/.test(version))
|
|
211
|
+
throw new FloviaError({ code: "invalid_request", executed: "no", message: "version must be the version from consent()." });
|
|
212
|
+
const check = "It may have been recorded. Run consent() (flovia consent) to see whether it was recorded before trying again.";
|
|
213
|
+
const unknown = (e) => this.#error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
|
|
214
|
+
nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check });
|
|
215
|
+
let r;
|
|
216
|
+
try {
|
|
217
|
+
r = await this.#send("/account/consent/accept", { version });
|
|
218
|
+
}
|
|
219
|
+
// The relay rechecks the key after the write, so a 401 does not prove that nothing was recorded.
|
|
220
|
+
catch (e) {
|
|
221
|
+
throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? unknown(e) : e;
|
|
222
|
+
}
|
|
223
|
+
const body = await this.#account(r, check);
|
|
224
|
+
if (!isConsent(body) || (body["outcome"] !== "recorded" && body["outcome"] !== "unchanged"))
|
|
225
|
+
throw this.#error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The consent reply was not in the expected form.", nextStep: check });
|
|
226
|
+
return { outcome: body["outcome"], version: body.version, answered_version: body.answered_version, needed: body.needed, updated: body.updated, notice: body.notice };
|
|
227
|
+
}
|
|
197
228
|
async #account(r, unknownStep) {
|
|
198
229
|
let body;
|
|
199
230
|
try {
|
|
@@ -256,13 +287,14 @@ export class FloviaClient {
|
|
|
256
287
|
}
|
|
257
288
|
return s;
|
|
258
289
|
}
|
|
259
|
-
/** 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). */
|
|
260
291
|
usageToday(args = {}) {
|
|
261
292
|
return this.call("flovia_usage_today", { ...args });
|
|
262
293
|
}
|
|
263
294
|
/**
|
|
264
295
|
* POST /openai/v1/responses. operationId is required: save it with the request before calling. Sending the same request with the same id
|
|
265
|
-
* again can return the saved answer (replayed: true)
|
|
296
|
+
* again can return the saved answer (replayed: true) at no charge: notice 18 generations up to 30 days from creation, earlier ones about 15 minutes.
|
|
297
|
+
* Missing or deleted copies are not restored. Pending, unknown and expired answers
|
|
266
298
|
* are not proof that nothing ran. Never resent automatically, and never under a new id to recover an answer.
|
|
267
299
|
*/
|
|
268
300
|
async generate(request, options) {
|
|
@@ -292,6 +324,11 @@ function isResets(b) {
|
|
|
292
324
|
return count(b["available"], 0) && (next === null || (typeof next === "object" && !Array.isArray(next) && count(next["id"], 1)
|
|
293
325
|
&& typeof next["expires_at"] === "string" && !Number.isNaN(Date.parse(next["expires_at"])))) && (next === null) === (b["available"] === 0);
|
|
294
326
|
}
|
|
327
|
+
function isConsent(b) {
|
|
328
|
+
const text = (v) => typeof v === "string" && v.length > 0;
|
|
329
|
+
return text(b["version"]) && (b["answered_version"] === null || text(b["answered_version"])) && typeof b["needed"] === "boolean"
|
|
330
|
+
&& typeof b["updated"] === "boolean" && text(b["notice"]);
|
|
331
|
+
}
|
|
295
332
|
/** Whether a refused generation ran, from its public code (the same reading flovia_openai gives over MCP). */
|
|
296
333
|
function generationExecuted(code) {
|
|
297
334
|
if (["answer_unavailable", "answer_expired", "answer_delivery_denied"].includes(code))
|
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,7 +1,7 @@
|
|
|
1
1
|
/** The relay's tool contract this SDK was written against (flovia_status.contract_version). */
|
|
2
|
-
export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.
|
|
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
|
-
export declare const PUBLIC_CODES: readonly ["approval_pending", "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first", "provider_not_allowed", "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large", "answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long", "over_max_credits", "window_5h", "window_month", "window_week", "over_week", "free_limited", "free_needs_email", "free_not_granted", "global_cap", "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed", "operation_conflict", "operation_pending", "relay_internal_error", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "replay_response_unavailable", "rpc_error", "unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off"];
|
|
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}`;
|
|
6
6
|
/** Whether the request ran upstream: "unknown" means keep the same operation_id and never send a replacement. */
|
|
7
7
|
export type Executed = "yes" | "no" | "unknown";
|
|
@@ -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. */
|
|
@@ -92,3 +115,16 @@ export interface BankedResets {
|
|
|
92
115
|
export interface BankedResetUse extends BankedResets {
|
|
93
116
|
outcome: "used" | "not_used";
|
|
94
117
|
}
|
|
118
|
+
/** GET /account/consent: the current notice version, the version this account last said yes to (null: none), and the notice text.
|
|
119
|
+
* updated: the yes is to an earlier version; it keeps working and continued use accepts the current one, so an explicit yes is optional. */
|
|
120
|
+
export interface ConsentState {
|
|
121
|
+
version: string;
|
|
122
|
+
answered_version: string | null;
|
|
123
|
+
needed: boolean;
|
|
124
|
+
updated: boolean;
|
|
125
|
+
notice: string;
|
|
126
|
+
}
|
|
127
|
+
/** "recorded": the yes to the current notice was saved now. "unchanged": it was already saved; nothing changed. */
|
|
128
|
+
export interface ConsentAccept extends ConsentState {
|
|
129
|
+
outcome: "recorded" | "unchanged";
|
|
130
|
+
}
|
package/dist/types.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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",
|
|
6
|
-
"provider_not_allowed", "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large",
|
|
6
|
+
"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",
|
|
7
7
|
"answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long",
|
|
8
8
|
"over_max_credits", "window_5h", "window_month", "window_week", "over_week", "free_limited", "free_needs_email", "free_not_granted", "global_cap",
|
|
9
9
|
"flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed",
|
|
10
|
-
"operation_conflict", "operation_pending", "relay_internal_error", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "replay_response_unavailable", "rpc_error",
|
|
10
|
+
"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",
|
|
11
11
|
"unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off",
|
|
12
12
|
];
|
package/package.json
CHANGED