@flovialabs/sdk 0.1.23 → 0.1.25
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 +26 -0
- package/README.md +27 -14
- package/dist/account.d.ts +12 -0
- package/dist/account.js +110 -0
- package/dist/accountcommands.d.ts +17 -0
- package/dist/accountcommands.js +124 -0
- package/dist/args.d.ts +19 -0
- package/dist/args.js +91 -0
- package/dist/cli.d.ts +11 -36
- package/dist/cli.js +31 -993
- package/dist/client.d.ts +4 -5
- package/dist/client.js +29 -294
- package/dist/commandhelp.d.ts +7 -0
- package/dist/commandhelp.js +52 -0
- package/dist/doctor.d.ts +11 -7
- package/dist/doctor.js +50 -23
- package/dist/doctorcommand.d.ts +9 -0
- package/dist/doctorcommand.js +125 -0
- package/dist/examples.d.ts +2 -0
- package/dist/examples.js +29 -0
- package/dist/generatecommand.d.ts +15 -0
- package/dist/generatecommand.js +64 -0
- package/dist/generation.d.ts +6 -0
- package/dist/generation.js +30 -0
- package/dist/install.d.ts +15 -2
- package/dist/install.js +77 -12
- package/dist/installcommand.d.ts +4 -0
- package/dist/installcommand.js +251 -0
- package/dist/keyfile.d.ts +6 -0
- package/dist/keyfile.js +33 -0
- package/dist/nodeio.d.ts +7 -0
- package/dist/nodeio.js +62 -0
- package/dist/output.d.ts +26 -0
- package/dist/output.js +196 -0
- package/dist/reply.d.ts +9 -0
- package/dist/reply.js +36 -0
- package/dist/runwayoutput.d.ts +5 -0
- package/dist/runwayoutput.js +44 -0
- package/dist/sandbox.d.ts +13 -0
- package/dist/sandbox.js +80 -0
- package/dist/sandboxcommands.d.ts +14 -0
- package/dist/sandboxcommands.js +90 -0
- package/dist/toolcommands.d.ts +14 -0
- package/dist/toolcommands.js +65 -0
- package/dist/transport.d.ts +11 -0
- package/dist/transport.js +2 -0
- package/dist/types.d.ts +20 -7
- package/dist/types.js +3 -2
- package/package.json +5 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.1.25
|
|
6
|
+
|
|
7
|
+
- Expect Relay contract `2026-10-07.255`. The MiniMax tool schema advertises a maximum of 16,000 output tokens. `flovia_zerion` returns `next_cursor` for Zerion's longer page tokens, and its `cursor` accepts them. Where the Relay enables them, `flovia_parallel` and Venice Private chat are offered after the user accepts their own notices. Where enabled by the Relay, `flovia_fal` accepts a `model` for image creation. The available models and their costs depend on the Relay configuration.
|
|
8
|
+
- `GenerationRequest.model` accepts `gpt-6.1-terra` where the Relay offers it. For `gpt-6-luna`, the explicit `max_output_tokens` limit rises from 4,000 to 16,000. The default remains 1,000.
|
|
9
|
+
- `GenerationRequest.instructions` accepts a system prompt that counts toward the input limit. For structured output, pass `text.format` with `type: "json_schema"`, a `name`, a `schema` and an optional `strict` flag.
|
|
10
|
+
- `PUBLIC_CODES` includes `output_withheld`. When a MiniMax text response appears to contain a secret key, the Relay returns this code, withholds the answer and charges nothing.
|
|
11
|
+
- Runway's `gen4_image` accepts 16 aspect ratios. Images reserve 5 credits for `1280:720`, `720:1280` or `720:720`, and 8 for the other ratios. The final charge follows Runway's bill. Videos accept whole-second durations from 2 through 10 at 12 credits per second.
|
|
12
|
+
- CLI: `key-caps set --json` exits with status 1 when the target key is missing, matching human-readable output.
|
|
13
|
+
- QuickNode adds `debug_traceTransaction` (`callTracer` only; params `{hash, only_top_call?}`) and `trace_transaction` (`{hash}`) on the chains that serve them; other chains refuse with `not_relayed` and nothing is sent. A call tree too large for the reply comes back cut at a call depth with `result_depth`, and each cut frame has `calls_omitted` (how many sub-calls were left out). A `trace_transaction` list that is too large comes back as whole calls with `result_count` and `result_total`. The SDK passes these through unchanged.
|
|
14
|
+
- CLI: `flovia install --client codex` (sign-in) no longer waits silently while `codex mcp add` waits for browser sign-in. Before the wait it says on stderr that it is waiting for sign-in and must not be stopped, the limit, and the retry (`codex mcp login flovia`, then `flovia doctor --client codex`). Codex's own output, such as the sign-in URL, is shown on stderr instead of being dropped. The wait ends after `--timeout` seconds (default 300): Codex is stopped and install exits 1 with the same next step (`--json`: `code: "sign_in_timeout"`). Other client commands keep their output hidden and get the same limit.
|
|
15
|
+
- CLI: when `flovia install --client hermes` cannot extend `~/.hermes/config.yaml` safely, the refusal (also in `--dry-run`) now shows the minimal YAML to paste besides `hermes mcp add`.
|
|
16
|
+
- CLI: `flovia install --client hermes` adds `flovia` under `mcp_servers` in an existing `~/.hermes/config.yaml`, such as the long one Hermes's installer writes, by adding lines only. Other settings, comments and order stay. A file that cannot be extended that way, or a different `flovia` entry, is still refused, now with `hermes mcp add flovia --url … --auth oauth` or `hermes mcp remove flovia`. `--dry-run` now runs the same check, so it no longer reports an update that the real run refuses. A BOM, CRLF mixed with bare LF, an indented root, or a `flovia` it cannot read (an inline value) is refused without changes, and only a `flovia` directly under `mcp_servers` counts (also in `doctor`).
|
|
17
|
+
- CLI: `install` and `doctor` accept `--base-url` with a trailing `/mcp` (for example `https://dev.api.flovia.dev/mcp`) and refuse any other path, query or fragment instead of dropping it silently.
|
|
18
|
+
- CLI: `flovia install --client codex` no longer tells you to run `codex mcp login flovia` after adding. Codex 0.77.0 and later start sign-in in `codex mcp add`; run `login` only if sign-in did not start.
|
|
19
|
+
- CLI: running `flovia install --client claude-code` or `--client codex` again no longer fails without a reason. It first reads the client's settings the way `flovia doctor` does. The same flovia entry is left unchanged and nothing runs. A different entry (for example, switching between a key and sign-in) is refused with the command that removes only flovia (`claude mcp remove --scope user flovia` or `codex mcp remove flovia`); with `--force`, Claude Code's entry is removed and added again (if the add then fails, the error says flovia was already removed and how to add it back), and Codex's add replaces it in place. A Codex entry with `enabled = false`, its own headers or other settings install does not write is a different entry. Install and `doctor` read `$CODEX_HOME/config.toml` and `$CLAUDE_CONFIG_DIR/.claude.json` when those are set. When install cannot tell which entry the client uses (settings it cannot read, or a Codex flovia in a dotted or inline form), it changes nothing for Codex and for `--force`; Claude Code without `--force` still runs `claude mcp add`, which refuses an existing name itself. Other MCP servers are never touched. When the client still refuses, the error names the same remove command.
|
|
20
|
+
|
|
21
|
+
## 0.1.24
|
|
22
|
+
|
|
23
|
+
- Expect Relay contract `2026-10-07.217`. Tool and model availability depend on the Relay's configuration and the account's access.
|
|
24
|
+
- Saved resets can include the first available choice of each kind. The SDK preserves the optional `resets` field. The CLI shows the choices and their grant IDs. A 5-hour reset clears 5-hour usage. A weekly reset clears weekly and 5-hour usage. Monthly usage stays unchanged.
|
|
25
|
+
- `flovia_usage_today` accepts a date-only `since` at midnight UTC on the updated Relay. The SDK and CLI pass it through. A paged CLI query still needs the exact `--since` from the previous reply with its cursor.
|
|
26
|
+
- `GenerationRequest.model` includes `gpt-6.2-astra` and `gpt-6.2-sol`. Where offered, both default to `low` reasoning effort and refuse `none`. The CLI uses `gpt-6-luna`.
|
|
27
|
+
- CLI and SDK docs describe how the account's spend mode and each key's paid caps affect generation, and the separate CoinGecko daily quota.
|
|
28
|
+
|
|
3
29
|
## 0.1.23
|
|
4
30
|
|
|
5
31
|
- CLI: `flovia resets` starts the saved-reset and status reads concurrently, with one waiting indicator. Both reads start even if one fails; if both fail, the first rejection determines the error. Successful text and JSON keep the same shape, and no reset is used or request retried automatically.
|
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.25
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
+
## 0.1.25 release notes
|
|
17
|
+
|
|
18
|
+
This release expects Relay contract `2026-10-07.255`. `client.generate()` accepts `gpt-6.1-terra` when the Relay offers it; it accepts every reasoning effort and defaults to `none`. When `flovia key-caps set` cannot find the target key, scripts using `--json` receive exit status 1 and can read `outcome: "not_found"` from stdout. See [CHANGELOG.md](CHANGELOG.md) for the provider and CLI changes.
|
|
19
|
+
|
|
20
|
+
## 0.1.24 release notes
|
|
21
|
+
|
|
22
|
+
This release expects Relay contract `2026-10-07.217`. `flovia resets` shows the available 5-hour and weekly choices when the Relay includes them. `usageToday({ since })` and `flovia usage --since` accept `YYYY-MM-DD` as midnight UTC with the updated Relay.
|
|
23
|
+
|
|
24
|
+
`client.generate()` accepts the model names `gpt-6.2-astra` and `gpt-6.2-sol` when the Relay offers them. These models reject reasoning effort `none` and default to `low` when it is omitted. The CLI's `generate` command uses `gpt-6-luna`. The CLI spending guidance describes the account's spend mode and per-key caps.
|
|
25
|
+
|
|
16
26
|
## 0.1.23 release notes
|
|
17
27
|
|
|
18
28
|
`flovia resets` reads saved resets and free-window status concurrently and shows one waiting indicator. Both reads start even if one fails; if both fail, the first rejection determines the error. TTY waiting feedback updates one stderr line and clears it when the request finishes. Successful output and JSON keep their existing shape; piped stderr and `--json` have no waiting feedback. This release expects the same contract `2026-10-07.208` and changes no public client methods, types or runtime dependencies.
|
|
@@ -84,7 +94,7 @@ const usage = await flovia.usageToday(); // today, UTC
|
|
|
84
94
|
const tools = await flovia.listTools();
|
|
85
95
|
const reply = await flovia.call("flovia_status");
|
|
86
96
|
|
|
87
|
-
// A text generation
|
|
97
|
+
// A text generation. Save the operation id before sending.
|
|
88
98
|
const op = newOperationId();
|
|
89
99
|
const request = { model: "gpt-6-luna" as const, input: "Explain a DEX aggregator in one sentence.", reasoning: { effort: "low" as const } };
|
|
90
100
|
// Persist { op, request } in your application's private storage before the next line.
|
|
@@ -105,11 +115,11 @@ const priceRequest = {
|
|
|
105
115
|
request_text: "What is Bitcoin's USD price?", purpose: "check a price with its update time",
|
|
106
116
|
conversation_id: "sdk-price-example", operation_id: newOperationId(),
|
|
107
117
|
};
|
|
108
|
-
// Save priceRequest before sending
|
|
118
|
+
// Save priceRequest before sending. New upstream calls through Flovia's CoinGecko pool count toward its separate daily limit.
|
|
109
119
|
const price = await flovia.call("flovia_coingecko", priceRequest);
|
|
110
120
|
```
|
|
111
121
|
|
|
112
|
-
If either call asks for a notice or consent, stop and follow the human-answer flow below. Read the returned source time, coverage and missing-value notes; a successful lookup is not a guarantee that it answers your question. Flovia exposes selected read-only paths, methods and public HTML hosts, not every feature of the upstream plans. Use the live catalog for the supported subset. OpenAI supports text generation with `gpt-6-luna`; it does not fetch other providers or offer image/audio generation.
|
|
122
|
+
CoinGecko’s daily quota is separate from Flovia’s metered allowance, purchased balance and plan credit. If either call asks for a notice or consent, stop and follow the human-answer flow below. Read the returned source time, coverage and missing-value notes; a successful lookup is not a guarantee that it answers your question. Flovia exposes selected read-only paths, methods and public HTML hosts, not every feature of the upstream plans. Use the live catalog for the supported subset. OpenAI supports text generation with `gpt-6-luna`; it does not fetch other providers or offer image/audio generation.
|
|
113
123
|
|
|
114
124
|
### Runway images and videos
|
|
115
125
|
|
|
@@ -132,7 +142,7 @@ const output = await flovia.downloadRunwayOutput(String(result["generation_id"])
|
|
|
132
142
|
// output.data is Uint8Array; output.contentType is the checked media type.
|
|
133
143
|
```
|
|
134
144
|
|
|
135
|
-
Images are one
|
|
145
|
+
Images are one `gen4_image` result; `action: "list"` shows its ratios (`1280:720`, `720:1280` and `720:720` reserve 5 credits, the others 8; the charge is what Runway bills). Videos use `action: "video"` with `duration: 2` through `10` (12 credits a second), 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.
|
|
136
146
|
|
|
137
147
|
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.
|
|
138
148
|
|
|
@@ -215,7 +225,7 @@ try {
|
|
|
215
225
|
After installing this SDK and setting `FLOVIA_KEY` privately, run:
|
|
216
226
|
|
|
217
227
|
```sh
|
|
218
|
-
# One new CoinGecko lookup
|
|
228
|
+
# One new CoinGecko lookup. New upstream calls through Flovia's pool count toward CoinGecko's separate daily limit.
|
|
219
229
|
node first-price.mjs --new
|
|
220
230
|
# Same request and operation id; reopen promptly, while the saved answer is available.
|
|
221
231
|
node first-price.mjs --replay
|
|
@@ -225,7 +235,7 @@ node first-price.mjs --saved
|
|
|
225
235
|
|
|
226
236
|
The example saves the request and operation id **before** sending, in `.flovia-price/request.json` (0600 inside a 0700 directory), and the returned answer in `answer.json` (0600). Keep this directory private and out of Git. Repeating `--new` refuses to overwrite it. Do not delete it or change the id to recover a lost answer. `--replay` sends the saved arguments unchanged; if the saved text is unavailable or the outcome is pending/unknown, follow the error's `next_step` instead of making a new request. A notice or consent refusal needs the person's answer; this script never supplies one.
|
|
227
237
|
|
|
228
|
-
The displayed result separates the USD price, CoinGecko's update time, Flovia's original receipt time, lookup id and the server's charge guidance. Unknown values stay `null`; missing cost is not zero. A replay or local saved display is labelled as such and never presented as a live update. For period usage, run `npx flovia usage` separately; it is your private account data, not the cost of this one result. A browser demo may display the public price and attribution from your server, but must not expose the Flovia key, private reply files or account usage, or offer an unauthenticated refresh endpoint that
|
|
238
|
+
The displayed result separates the USD price, CoinGecko's update time, Flovia's original receipt time, lookup id and the server's charge guidance. Unknown values stay `null`; missing cost is not zero. A replay or local saved display is labelled as such and never presented as a live update. For period usage, run `npx flovia usage` separately; it is your private account data, not the cost of this one result. A browser demo may display the public price and attribution from your server, but must not expose the Flovia key, private reply files or account usage, or offer an unauthenticated refresh endpoint that can use up your CoinGecko daily quota. The example does not auto-refresh. Follow the provider's attribution and redistribution terms.
|
|
229
239
|
|
|
230
240
|
### Code runs and Team tasks
|
|
231
241
|
|
|
@@ -258,7 +268,7 @@ await flovia.setSandboxSchedule({
|
|
|
258
268
|
|
|
259
269
|
### Thinking effort
|
|
260
270
|
|
|
261
|
-
For Luna, set `reasoning.effort` to `none`, `low`, `medium`, `high`, `xhigh` or `max`; omitting it keeps Flovia's `none` default. Higher effort can take longer and use more reasoning tokens. Those tokens share `max_output_tokens` with the visible answer, so an answer may be shorter or `incomplete`. The default output limit remains 1,000, with an explicit maximum of
|
|
271
|
+
For Luna, set `reasoning.effort` to `none`, `low`, `medium`, `high`, `xhigh` or `max`; omitting it keeps Flovia's `none` default. Higher effort can take longer and use more reasoning tokens. Those tokens share `max_output_tokens` with the visible answer, so an answer may be shorter or `incomplete`. The default output limit remains 1,000, with an explicit maximum of 16,000. Effort does not raise Flovia's per-request spending cap or guarantee a better answer. Save the effort with the rest of the request; changing it under the same operation id is a different request and is refused.
|
|
262
272
|
|
|
263
273
|
### Operation ids and replay
|
|
264
274
|
|
|
@@ -329,7 +339,7 @@ npx flovia resets use 42 --yes # use saved reset 42 (cannot be undone)
|
|
|
329
339
|
npx flovia consent # current notice version, your yes and the notice text (read-only)
|
|
330
340
|
npx flovia consent accept relay-consent-19 --yes # your own yes to the version just shown (same as Console)
|
|
331
341
|
npx flovia key-caps # each key's daily and monthly spending cap and use (read-only)
|
|
332
|
-
npx flovia key-caps set <key-id> --day 5 --month none #
|
|
342
|
+
npx flovia key-caps set <key-id> --day 5 --month none # set this key's daily paid cap and remove its monthly cap
|
|
333
343
|
npx flovia spend-mode # free-only or allow-paid (read-only)
|
|
334
344
|
npx flovia spend-mode free-only # never use the purchased balance or plan credit
|
|
335
345
|
npx flovia sandbox run python job.py # queue your own code; prints an operation_id first, then the run_id
|
|
@@ -342,7 +352,7 @@ npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
|
|
|
342
352
|
npx flovia help
|
|
343
353
|
npx flovia --version
|
|
344
354
|
```
|
|
345
|
-
These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.
|
|
355
|
+
These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.25 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.
|
|
346
356
|
|
|
347
357
|
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.
|
|
348
358
|
|
|
@@ -363,9 +373,11 @@ npx flovia install --client claude-code # or codex, cursor, claude-des
|
|
|
363
373
|
npx flovia install --client cursor --auth key --dry-run
|
|
364
374
|
```
|
|
365
375
|
|
|
366
|
-
|
|
376
|
+
Running install again leaves an identical flovia entry unchanged. A different one is kept and the error names the command that removes only flovia; add `--force` to replace it (Claude Code: remove only flovia, then add; Codex: its add replaces the entry; Cursor: replace the entry in its file). Install and doctor read the settings in `CLAUDE_CONFIG_DIR` and `CODEX_HOME` when they are set. When install cannot tell which entry the client uses, it changes nothing.
|
|
377
|
+
|
|
378
|
+
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's `~/.hermes/config.yaml` gets the `flovia` entry under `mcp_servers` by adding lines only, so its other settings, comments and order stay as they are; an identical entry is left unchanged, and a different `flovia` entry is never replaced. A file it cannot extend that way (flow style, quoted keys, anchors, a list) is left untouched, and install names `hermes mcp add flovia --url … --auth oauth` instead. Claude desktop gets the custom-connector link. `--dry-run` shows the commands and files without changing anything, and refuses what the real run would refuse. With `--client codex` and sign-in, Codex 0.77.0 and later start browser sign-in inside `codex mcp add`: install first says on stderr that it is waiting for sign-in and must not be stopped, with the limit and the retry command, then shows Codex's own output (the sign-in URL) on stderr. The wait ends after `--timeout` seconds (default 300); then Codex is stopped and install exits 1 (`--json`: `code: "sign_in_timeout"`) and names `codex mcp login flovia` and `flovia doctor --client codex`. When Hermes's file cannot be extended, the refusal also shows the minimal YAML to paste. `--base-url` takes an origin, such as `https://dev.api.flovia.dev`; a trailing `/mcp` is accepted, and any other path is refused. `doctor` reads `--base-url` the same way.
|
|
367
379
|
|
|
368
|
-
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
|
|
380
|
+
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 never replaces an existing `flovia` entry in the Hermes settings.
|
|
369
381
|
|
|
370
382
|
To check what `install` set up (since 0.1.18; not included in 0.1.17):
|
|
371
383
|
|
|
@@ -393,9 +405,10 @@ Keep the same `--key-file` and `--base-url` too. For a prompt starting with a hy
|
|
|
393
405
|
`status` shows your purchased balance. `usage` shows lookup counts, free allowance percentages and the purchased-balance totals from the server; its generation subtotal is already included in the period total. Missing amounts show `-`, not zero. It does not add rounded endpoint percentages. To continue a listing, copy the printed command with its exact `--since` and `--cursor`; do not combine `--days` with `--cursor`.
|
|
394
406
|
|
|
395
407
|
- Every command takes `--json` (the raw reply), `--base-url URL`, `--timeout SECONDS` and `--key-file PATH`.
|
|
396
|
-
- `generate`
|
|
408
|
+
- `generate` needs `--op ID` or `--new-op` and asks for confirmation on a terminal. Add `--yes` in scripts. In `allow-paid` mode with an active plan, eligible plan credit takes priority, with purchased balance as a fallback. Without a plan, an eligible purchased balance takes priority over the free allowance. The selected source must cover the whole request.
|
|
409
|
+
- `spend-mode free-only` prevents metered calls from using purchased balance or plan credit account-wide. A metered call needs enough free allowance to run in this mode. An active plan makes that allowance unavailable, so metered calls are refused in free-only mode. `key-caps` limits each key’s paid use from purchased balance and plan credit per UTC day and month. Eligible calls can still use the free allowance. See [Free and paid use](https://docs.flovia.dev/usage/) for current limits.
|
|
397
410
|
- `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.
|
|
398
|
-
- `resets`
|
|
411
|
+
- `resets` reads the number of saved resets, the next to expire, and the 5-hour and weekly windows. It shows the first reset to expire of each kind when the Relay provides those details. `resets use <id> --yes` uses the saved reset with that ID when it can be applied. A 5-hour reset clears only 5-hour usage. A weekly reset clears weekly and 5-hour usage. Monthly usage stays unchanged. 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)`.
|
|
399
412
|
- `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)`.
|
|
400
413
|
- Exit codes: 0 ok, 1 an error from Flovia, 2 a usage error.
|
|
401
414
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Transport } from "./transport.js";
|
|
2
|
+
import type { BankedResets, BankedResetUse, ConsentState, ConsentAccept, KeyCaps, KeyCapsSet, SpendMode } from "./types.js";
|
|
3
|
+
export declare function bankedResets(t: Transport): Promise<BankedResets>;
|
|
4
|
+
export declare function useBankedReset(t: Transport, grantId: number): Promise<BankedResetUse>;
|
|
5
|
+
export declare function consent(t: Transport): Promise<ConsentState>;
|
|
6
|
+
export declare function acceptConsent(t: Transport, version: string): Promise<ConsentAccept>;
|
|
7
|
+
export declare function keyCaps(t: Transport): Promise<KeyCaps>;
|
|
8
|
+
export declare function setKeyCaps(t: Transport, keyId: string, caps: {
|
|
9
|
+
day_usd: number | null;
|
|
10
|
+
month_usd: number | null;
|
|
11
|
+
}): Promise<KeyCapsSet>;
|
|
12
|
+
export declare function spendMode(t: Transport, mode?: SpendMode): Promise<SpendMode>;
|
package/dist/account.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { FloviaError } from "./errors.js";
|
|
2
|
+
import { readReply, relayNextStep } from "./reply.js";
|
|
3
|
+
export async function bankedResets(t) {
|
|
4
|
+
const r = await t.send("/account/banked-resets", null, {}, null, "GET");
|
|
5
|
+
const body = await account(t, r, null);
|
|
6
|
+
if (!isResets(body))
|
|
7
|
+
throw t.error({ code: "invalid_reply", status: r.status, executed: "no", message: "The saved-reset reply was not in the expected form.", nextStep: null });
|
|
8
|
+
return { available: body.available, next: body.next, ...(body.resets === undefined ? {} : { resets: body.resets }) };
|
|
9
|
+
}
|
|
10
|
+
export async function useBankedReset(t, grantId) {
|
|
11
|
+
if (!Number.isSafeInteger(grantId) || grantId <= 0)
|
|
12
|
+
throw new FloviaError({ code: "invalid_request", executed: "no", message: "grantId must be a positive whole number from bankedResets()." });
|
|
13
|
+
const check = "It may have been used. Run bankedResets() (flovia resets) to see whether it was used before trying again.";
|
|
14
|
+
const { r, body } = await write(t, "/account/banked-resets/use", { grant_id: grantId }, check);
|
|
15
|
+
if (!isResets(body) || (body["outcome"] !== "used" && body["outcome"] !== "not_used"))
|
|
16
|
+
throw t.error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The saved-reset reply was not in the expected form.", nextStep: check });
|
|
17
|
+
return { outcome: body["outcome"], available: body.available, next: body.next, ...(body.resets === undefined ? {} : { resets: body.resets }) };
|
|
18
|
+
}
|
|
19
|
+
export async function consent(t) {
|
|
20
|
+
const r = await t.send("/account/consent", null, {}, null, "GET");
|
|
21
|
+
const body = await account(t, r, null);
|
|
22
|
+
if (!isConsent(body))
|
|
23
|
+
throw t.error({ code: "invalid_reply", status: r.status, executed: "no", message: "The consent reply was not in the expected form.", nextStep: null });
|
|
24
|
+
return { version: body.version, answered_version: body.answered_version, needed: body.needed, updated: body.updated, notice: body.notice };
|
|
25
|
+
}
|
|
26
|
+
export async function acceptConsent(t, version) {
|
|
27
|
+
if (typeof version !== "string" || !/^[a-z0-9-]{1,80}$/.test(version))
|
|
28
|
+
throw new FloviaError({ code: "invalid_request", executed: "no", message: "version must be the version from consent()." });
|
|
29
|
+
const check = "It may have been recorded. Run consent() (flovia consent) to see whether it was recorded before trying again.";
|
|
30
|
+
const { r, body } = await write(t, "/account/consent/accept", { version }, check);
|
|
31
|
+
if (!isConsent(body) || (body["outcome"] !== "recorded" && body["outcome"] !== "unchanged"))
|
|
32
|
+
throw t.error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The consent reply was not in the expected form.", nextStep: check });
|
|
33
|
+
return { outcome: body["outcome"], version: body.version, answered_version: body.answered_version, needed: body.needed, updated: body.updated, notice: body.notice };
|
|
34
|
+
}
|
|
35
|
+
export async function keyCaps(t) {
|
|
36
|
+
const r = await t.send("/account/key-caps", null, {}, null, "GET");
|
|
37
|
+
const body = await account(t, r, null);
|
|
38
|
+
if (!Array.isArray(body["keys"]))
|
|
39
|
+
throw t.error({ code: "invalid_reply", status: r.status, executed: "no", message: "The key-caps reply was not in the expected form.", nextStep: null });
|
|
40
|
+
return { keys: body["keys"] };
|
|
41
|
+
}
|
|
42
|
+
export async function setKeyCaps(t, keyId, caps) {
|
|
43
|
+
// The relay's own rule: whole cents, $0 to $1,000,000.
|
|
44
|
+
const ok = (v) => v === null || (typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1_000_000 && Math.abs(v * 100 - Math.round(v * 100)) < 1e-6);
|
|
45
|
+
if (typeof keyId !== "string" || !/^[0-9a-f]{32}$/.test(keyId) || !ok(caps?.day_usd) || !ok(caps?.month_usd))
|
|
46
|
+
throw new FloviaError({ code: "invalid_request", executed: "no", message: "Pass a key id from keyCaps() and day_usd and month_usd as US dollars or null." });
|
|
47
|
+
const check = "It may have changed. Run keyCaps() (flovia key-caps) to see the current caps.";
|
|
48
|
+
const { r, body } = await write(t, "/account/key-caps", { key_id: keyId, day_usd: caps.day_usd, month_usd: caps.month_usd }, check);
|
|
49
|
+
if (!Array.isArray(body["keys"]) || (body["outcome"] !== "set" && body["outcome"] !== "not_found"))
|
|
50
|
+
throw t.error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The key-caps reply was not in the expected form.", nextStep: check });
|
|
51
|
+
return { outcome: body["outcome"], keys: body["keys"] };
|
|
52
|
+
}
|
|
53
|
+
export async function spendMode(t, mode) {
|
|
54
|
+
if (mode !== undefined && mode !== "free_only" && mode !== "allow_paid")
|
|
55
|
+
throw new FloviaError({ code: "invalid_request", executed: "no", message: "mode must be free_only or allow_paid." });
|
|
56
|
+
const check = "It may have changed. Run spendMode() (flovia spend-mode) to see the current mode.";
|
|
57
|
+
let r, body;
|
|
58
|
+
if (mode === undefined) {
|
|
59
|
+
r = await t.send("/account/spend-mode", null, {}, null, "GET");
|
|
60
|
+
body = await account(t, r, null);
|
|
61
|
+
}
|
|
62
|
+
else
|
|
63
|
+
({ r, body } = await write(t, "/account/spend-mode", { mode }, check));
|
|
64
|
+
if (body["mode"] !== "free_only" && body["mode"] !== "allow_paid")
|
|
65
|
+
throw t.error({ code: "invalid_reply", status: r.status, executed: mode === undefined ? "no" : "unknown", message: "The spend-mode reply was not in the expected form.", nextStep: mode === undefined ? null : check });
|
|
66
|
+
return body["mode"];
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* One account write, never resent. A lost reply, a 401 (the relay rechecks the key after the write) or an unreadable or 5xx reply
|
|
70
|
+
* may still have changed something, so each is executed "unknown" with check (a read-only way to see) as its next step.
|
|
71
|
+
*/
|
|
72
|
+
async function write(t, path, payload, check) {
|
|
73
|
+
let r;
|
|
74
|
+
try {
|
|
75
|
+
r = await t.send(path, payload);
|
|
76
|
+
}
|
|
77
|
+
catch (e) {
|
|
78
|
+
throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? t.error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
|
|
79
|
+
nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check }) : e;
|
|
80
|
+
}
|
|
81
|
+
return { r, body: await account(t, r, check) };
|
|
82
|
+
}
|
|
83
|
+
async function account(t, r, unknownStep) {
|
|
84
|
+
let body;
|
|
85
|
+
try {
|
|
86
|
+
body = await readReply(r, null, init => t.error(init));
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
throw e instanceof FloviaError && unknownStep !== null ? t.error({ code: e.code, status: r.status, executed: "unknown", message: e.message, nextStep: unknownStep }) : e;
|
|
90
|
+
}
|
|
91
|
+
if (r.status === 200)
|
|
92
|
+
return body;
|
|
93
|
+
throw t.error({ code: typeof body["error"] === "string" ? body["error"] : `http_${r.status}`, status: r.status, executed: r.status >= 500 && unknownStep !== null ? "unknown" : "no",
|
|
94
|
+
message: typeof body["message"] === "string" ? body["message"] : `HTTP ${r.status}`, nextStep: r.status >= 500 ? unknownStep : relayNextStep(body) });
|
|
95
|
+
}
|
|
96
|
+
const count = (v, min) => typeof v === "number" && Number.isSafeInteger(v) && v >= min;
|
|
97
|
+
/** The saved-reset summary's exact public form. */
|
|
98
|
+
function isResets(b) {
|
|
99
|
+
const next = b["next"];
|
|
100
|
+
const resets = b["resets"];
|
|
101
|
+
if (resets !== undefined && (!Array.isArray(resets) || resets.length > 2 || !resets.every(r => r && typeof r === "object" && !Array.isArray(r) && count(r.id, 1) && ["five_hour", "week"].includes(r.kind) && typeof r.expires_at === "string" && !Number.isNaN(Date.parse(r.expires_at)))))
|
|
102
|
+
return false;
|
|
103
|
+
return count(b["available"], 0) && (next === null || (typeof next === "object" && !Array.isArray(next) && count(next["id"], 1)
|
|
104
|
+
&& typeof next["expires_at"] === "string" && !Number.isNaN(Date.parse(next["expires_at"])))) && (next === null) === (b["available"] === 0);
|
|
105
|
+
}
|
|
106
|
+
function isConsent(b) {
|
|
107
|
+
const text = (v) => typeof v === "string" && v.length > 0;
|
|
108
|
+
return text(b["version"]) && (b["answered_version"] === null || text(b["answered_version"])) && typeof b["needed"] === "boolean"
|
|
109
|
+
&& typeof b["updated"] === "boolean" && text(b["notice"]);
|
|
110
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { FloviaClient } from "./client.js";
|
|
2
|
+
import { type Parsed } from "./args.js";
|
|
3
|
+
import type { Io } from "./cli.js";
|
|
4
|
+
type AccountCommandContext = {
|
|
5
|
+
connect: () => Promise<FloviaClient>;
|
|
6
|
+
waitFor: <T>(request: () => Promise<T>) => Promise<T>;
|
|
7
|
+
json: boolean;
|
|
8
|
+
print: (value: unknown) => void;
|
|
9
|
+
out: (text: string) => void;
|
|
10
|
+
};
|
|
11
|
+
export declare function runwayOutputCommand(p: Parsed, io: Pick<Io, "writeOutput">, { connect, waitFor, json, print, out }: AccountCommandContext): Promise<number>;
|
|
12
|
+
export declare function resetsCommand(p: Parsed, io: Pick<Io, "now">, { connect, waitFor, json, print, out }: AccountCommandContext): Promise<number>;
|
|
13
|
+
export declare function consentCommand(p: Parsed, { connect, waitFor, json, print, out }: AccountCommandContext): Promise<number>;
|
|
14
|
+
export declare function keyCapsCommand(p: Parsed, { connect, waitFor, json, print, out }: AccountCommandContext): Promise<number>;
|
|
15
|
+
export declare function spendModeCommand(p: Parsed, { connect, waitFor, json, print, out }: AccountCommandContext): Promise<number>;
|
|
16
|
+
export declare function usageCommand(p: Parsed, io: Pick<Io, "now">, { connect, waitFor, json, print, out }: AccountCommandContext): Promise<number>;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { label as outputLabel, renderUsage, renderResets, renderConsent } from "./output.js";
|
|
2
|
+
import { Usage, positiveInt, str } from "./args.js";
|
|
3
|
+
export async function runwayOutputCommand(p, io, { connect, waitFor, json, print, out }) {
|
|
4
|
+
const [id, extra] = p.positional, path = str(p.flags.get("--out"));
|
|
5
|
+
if (!id || extra !== undefined || !path || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id))
|
|
6
|
+
throw new Usage("Usage: flovia runway-output <generation_id> --out PATH");
|
|
7
|
+
if (!io.writeOutput)
|
|
8
|
+
throw new Usage("A private output-file writer is required.");
|
|
9
|
+
const client = await connect(), output = await waitFor(() => client.downloadRunwayOutput(id));
|
|
10
|
+
try {
|
|
11
|
+
await io.writeOutput(path, output.data);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw new Usage("Could not save the output; check for a partial file. Existing files are never overwritten.");
|
|
15
|
+
}
|
|
16
|
+
const saved = { saved: true, generation_id: id, bytes: output.data.byteLength, content_type: output.contentType, attribution: "Powered by Runway", attribution_url: "https://runwayml.com" };
|
|
17
|
+
if (json)
|
|
18
|
+
print(saved);
|
|
19
|
+
else
|
|
20
|
+
out("Output saved privately. Powered by Runway (https://runwayml.com).\n");
|
|
21
|
+
return 0;
|
|
22
|
+
}
|
|
23
|
+
export async function resetsCommand(p, io, { connect, waitFor, json, print, out }) {
|
|
24
|
+
const [action, id, extra] = p.positional;
|
|
25
|
+
if (action === undefined) {
|
|
26
|
+
if (p.flags.has("--yes"))
|
|
27
|
+
throw new Usage("Usage: flovia resets use <id> --yes");
|
|
28
|
+
const client = await connect(), [r, s] = await waitFor(() => Promise.all([client.bankedResets(), client.status()]));
|
|
29
|
+
if (json)
|
|
30
|
+
print({ ...r, five_hour: s.five_hour, week: s.week });
|
|
31
|
+
else
|
|
32
|
+
out(renderResets(r, s, (io.now ?? Date.now)()));
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
35
|
+
const grant = action === "use" && extra === undefined && id !== undefined && /^[1-9][0-9]{0,15}$/.test(id) ? Number(id) : NaN;
|
|
36
|
+
if (!Number.isSafeInteger(grant))
|
|
37
|
+
throw new Usage("Usage: flovia resets use <id> --yes (the id from flovia resets)");
|
|
38
|
+
if (!p.flags.has("--yes"))
|
|
39
|
+
throw new Usage("resets use: add --yes to use it; it cannot be undone. Check first: flovia resets");
|
|
40
|
+
const client = await connect(), u = await waitFor(() => client.useBankedReset(grant));
|
|
41
|
+
if (json)
|
|
42
|
+
print(u);
|
|
43
|
+
else
|
|
44
|
+
out(u.outcome === "used" ? `Used. The selected free allowance was reset; the monthly window is unchanged.\n${outputLabel("saved resets")}${u.available}\n`
|
|
45
|
+
: `Not used; nothing changed.\n${outputLabel("saved resets")}${u.available}\nCheck: flovia resets\n`);
|
|
46
|
+
return u.outcome === "used" ? 0 : 1;
|
|
47
|
+
}
|
|
48
|
+
export async function consentCommand(p, { connect, waitFor, json, print, out }) {
|
|
49
|
+
const [action, version, extra] = p.positional;
|
|
50
|
+
if (action === undefined) {
|
|
51
|
+
if (p.flags.has("--yes"))
|
|
52
|
+
throw new Usage("Usage: flovia consent accept <version> --yes");
|
|
53
|
+
const client = await connect(), c = await waitFor(() => client.consent());
|
|
54
|
+
if (json)
|
|
55
|
+
print(c);
|
|
56
|
+
else
|
|
57
|
+
out(renderConsent(c));
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
if (action !== "accept" || version === undefined || extra !== undefined)
|
|
61
|
+
throw new Usage("Usage: flovia consent accept <version> --yes (the version from flovia consent)");
|
|
62
|
+
const client = await connect();
|
|
63
|
+
if (!p.flags.has("--yes")) {
|
|
64
|
+
// Show what would be agreed to, then stop: nothing is sent without --yes.
|
|
65
|
+
const c = await waitFor(() => client.consent());
|
|
66
|
+
if (!json)
|
|
67
|
+
out(renderConsent(c));
|
|
68
|
+
throw new Usage(`consent accept: nothing was sent. Read the notice, then add --yes to answer yes to ${version} yourself.`);
|
|
69
|
+
}
|
|
70
|
+
const a = await waitFor(() => client.acceptConsent(version));
|
|
71
|
+
if (json)
|
|
72
|
+
print(a);
|
|
73
|
+
else
|
|
74
|
+
out(a.outcome === "recorded" ? `Recorded: yes to ${a.version}.\n` : `Already answered yes to ${a.version}; nothing changed.\n`);
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
export async function keyCapsCommand(p, { connect, waitFor, json, print, out }) {
|
|
78
|
+
const [action, id, extra] = p.positional, cap = (v) => v === "none" ? null : v !== undefined && /^\d{1,7}(\.\d{1,2})?$/.test(v) && Number(v) <= 1_000_000 ? Number(v) : undefined;
|
|
79
|
+
const day = cap(str(p.flags.get("--day"))), month = cap(str(p.flags.get("--month")));
|
|
80
|
+
if (action === undefined ? p.flags.has("--day") || p.flags.has("--month")
|
|
81
|
+
: action !== "set" || id === undefined || !/^[0-9a-f]{32}$/.test(id) || extra !== undefined || day === undefined || month === undefined)
|
|
82
|
+
throw new Usage("Usage: flovia key-caps [set <key-id> --day <usd|none> --month <usd|none>] (the key id from flovia key-caps)");
|
|
83
|
+
const client = await connect(), r = action === undefined ? await waitFor(() => client.keyCaps())
|
|
84
|
+
: await waitFor(() => client.setKeyCaps(id, { day_usd: day, month_usd: month }));
|
|
85
|
+
const exitCode = "outcome" in r && r.outcome !== "set" ? 1 : 0;
|
|
86
|
+
if (json) {
|
|
87
|
+
print(r);
|
|
88
|
+
return exitCode;
|
|
89
|
+
}
|
|
90
|
+
if ("outcome" in r)
|
|
91
|
+
out(r.outcome === "set" ? "Set. Caps limit this key’s use of purchased balance and plan credit. Eligible calls can still use the free allowance.\n" : "No active key with that id; nothing changed.\n");
|
|
92
|
+
const usd = (v) => v === null ? "none" : `$${v}`;
|
|
93
|
+
for (const k of r.keys)
|
|
94
|
+
out(`${k.id} ${k.name}${k.last_four ? ` (…${k.last_four})` : ""}${k.current ? " [this key]" : ""}\n services: ${k.services === "all" ? "all" : k.services.join(", ")}\n`
|
|
95
|
+
+ ` today (UTC): $${k.day_used_usd} of ${usd(k.day_cap_usd)}; this month: $${k.month_used_usd} of ${usd(k.month_cap_usd)}\n`);
|
|
96
|
+
return exitCode;
|
|
97
|
+
}
|
|
98
|
+
export async function spendModeCommand(p, { connect, waitFor, json, print, out }) {
|
|
99
|
+
const [arg, extra] = p.positional, mode = arg === undefined ? undefined : arg === "free-only" ? "free_only" : arg === "allow-paid" ? "allow_paid" : null;
|
|
100
|
+
if (mode === null || extra !== undefined)
|
|
101
|
+
throw new Usage("Usage: flovia spend-mode [free-only | allow-paid]");
|
|
102
|
+
const client = await connect(), m = await waitFor(() => client.spendMode(mode));
|
|
103
|
+
if (json)
|
|
104
|
+
print({ mode: m });
|
|
105
|
+
else
|
|
106
|
+
out(m === "free_only" ? "spend mode: free-only. Metered calls need an available free allowance.\n"
|
|
107
|
+
: "spend mode: allow-paid. Plan credit or purchased balance may pay within your key caps.\n");
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
110
|
+
export async function usageCommand(p, io, { connect, waitFor, json, print, out }) {
|
|
111
|
+
const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")), 30), cursor = str(p.flags.get("--cursor"));
|
|
112
|
+
if (since !== undefined && days !== undefined)
|
|
113
|
+
throw new Usage("usage: pass --since or --days, not both");
|
|
114
|
+
if (cursor !== undefined && days !== undefined)
|
|
115
|
+
throw new Usage("usage: with --cursor, use the previous reply's exact --since, not --days");
|
|
116
|
+
if (since !== undefined && Number.isNaN(Date.parse(since)))
|
|
117
|
+
throw new Usage("--since must be an ISO 8601 time");
|
|
118
|
+
const client = await connect(), u = await waitFor(() => client.usageToday({ ...(since ? { since } : {}), ...(days === undefined ? {} : { days }), ...(cursor ? { cursor } : {}) }));
|
|
119
|
+
if (json)
|
|
120
|
+
print(u);
|
|
121
|
+
else
|
|
122
|
+
out(renderUsage(u, since === undefined && days === undefined && cursor === undefined, (io.now ?? Date.now)()));
|
|
123
|
+
return 0;
|
|
124
|
+
}
|
package/dist/args.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { COMMANDS, help, SAVE_OP } from "./commandhelp.js";
|
|
2
|
+
export declare class Usage extends Error {
|
|
3
|
+
}
|
|
4
|
+
export declare const didYouMean: (word: string, options: string[], quote?: string) => string;
|
|
5
|
+
/** Agents often drop the flovia_ prefix ("coingecko"), which is too far for near() alone. */
|
|
6
|
+
export declare const notOffered: (word: string, names: string[]) => string;
|
|
7
|
+
export interface Parsed {
|
|
8
|
+
command: string;
|
|
9
|
+
flags: Map<string, string | true>;
|
|
10
|
+
positional: string[];
|
|
11
|
+
}
|
|
12
|
+
export declare function parse(argv: string[]): Parsed;
|
|
13
|
+
export declare const str: (v: string | true | undefined) => string | undefined;
|
|
14
|
+
export declare function positiveInt(name: string, v: string | undefined, max?: number): number | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* install's and doctor's --base-url: an https origin, or the MCP URL itself (agents pass .../mcp), so the /mcp resource
|
|
17
|
+
* is always the one shown. Any other path, a query or a fragment is refused rather than silently dropped.
|
|
18
|
+
*/
|
|
19
|
+
export declare function mcpBase(raw: string | undefined, command: "install" | "doctor"): URL;
|
package/dist/args.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { COMMANDS } from "./commandhelp.js";
|
|
2
|
+
export { COMMANDS, help, SAVE_OP } from "./commandhelp.js";
|
|
3
|
+
const GLOBAL_FLAGS = { "--json": false, "--base-url": true, "--timeout": true, "--key-file": true, "--help": false, "-h": false };
|
|
4
|
+
export class Usage extends Error {
|
|
5
|
+
}
|
|
6
|
+
function distance(a, b) {
|
|
7
|
+
let row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
8
|
+
for (let i = 1; i <= a.length; i++) {
|
|
9
|
+
const next = [i];
|
|
10
|
+
for (let j = 1; j <= b.length; j++)
|
|
11
|
+
next[j] = Math.min((row[j] ?? 0) + 1, (next[j - 1] ?? 0) + 1, (row[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
12
|
+
row = next;
|
|
13
|
+
}
|
|
14
|
+
return row[b.length] ?? 0;
|
|
15
|
+
}
|
|
16
|
+
const near = (word, options) => options.find((k) => distance(k, word) <= 2 || k.startsWith(word));
|
|
17
|
+
export const didYouMean = (word, options, quote = "") => { const n = near(word, options); return n === undefined ? "" : `; did you mean ${quote}${n}${quote}?`; };
|
|
18
|
+
/** Agents often drop the flovia_ prefix ("coingecko"), which is too far for near() alone. */
|
|
19
|
+
export const notOffered = (word, names) => {
|
|
20
|
+
const n = near(word, names) ?? near(`flovia_${word}`, names);
|
|
21
|
+
return `Tool is not offered to this key${n === undefined ? "." : `; did you mean "${n}"?`} Run: flovia tools`;
|
|
22
|
+
};
|
|
23
|
+
export function parse(argv) {
|
|
24
|
+
const [command, ...rest] = argv;
|
|
25
|
+
if (command === undefined || command === "--help" || command === "-h")
|
|
26
|
+
return { command: "help", flags: new Map(), positional: [] };
|
|
27
|
+
if (command === "--version")
|
|
28
|
+
return { command: "version", flags: new Map(), positional: [] };
|
|
29
|
+
const spec = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : undefined;
|
|
30
|
+
if (spec === undefined)
|
|
31
|
+
throw new Usage(`unknown command${didYouMean(command, Object.keys(COMMANDS), '"')} Run: flovia help`);
|
|
32
|
+
const known = { ...GLOBAL_FLAGS, ...spec.flags }, flags = new Map(), positional = [];
|
|
33
|
+
for (let i = 0; i < rest.length; i++) {
|
|
34
|
+
const a = rest[i] ?? "";
|
|
35
|
+
if (a === "--") {
|
|
36
|
+
positional.push(...rest.slice(i + 1));
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
if (a === "-" || !a.startsWith("-")) {
|
|
40
|
+
positional.push(a);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const eq = a.indexOf("="), name = eq > 0 ? a.slice(0, eq) : a;
|
|
44
|
+
if (!(name in known))
|
|
45
|
+
throw new Usage(`${command}: unknown option${didYouMean(name, Object.keys(known))} Run: flovia help ${command}`);
|
|
46
|
+
if (!known[name]) {
|
|
47
|
+
if (eq > 0)
|
|
48
|
+
throw new Usage(`${command}: ${name} takes no value`);
|
|
49
|
+
flags.set(name, true);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const value = eq > 0 ? a.slice(eq + 1) : rest[++i];
|
|
53
|
+
// The next word is another option of this command, not a value (`--since --json`); `--name=--x` still passes a literal value.
|
|
54
|
+
const next = eq > 0 || value === undefined ? undefined : value.slice(0, value.indexOf("=") > 0 ? value.indexOf("=") : undefined);
|
|
55
|
+
if (value === undefined || (next !== undefined && next.startsWith("-") && Object.hasOwn(known, next)))
|
|
56
|
+
throw new Usage(`${command}: ${name} needs a value. Usage: flovia ${spec.usage}`);
|
|
57
|
+
flags.set(name, value);
|
|
58
|
+
}
|
|
59
|
+
if (flags.has("--help") || flags.has("-h"))
|
|
60
|
+
return { command: "help", flags: new Map(), positional: [command] };
|
|
61
|
+
if (command === "help" && positional[0] !== undefined && !Object.hasOwn(COMMANDS, positional[0]))
|
|
62
|
+
throw new Usage("unknown help topic. Run: flovia help");
|
|
63
|
+
return { command, flags, positional };
|
|
64
|
+
}
|
|
65
|
+
export const str = (v) => typeof v === "string" ? v : undefined;
|
|
66
|
+
export function positiveInt(name, v, max = Number.MAX_SAFE_INTEGER) {
|
|
67
|
+
if (v === undefined)
|
|
68
|
+
return undefined;
|
|
69
|
+
const n = Number(v);
|
|
70
|
+
if (!Number.isInteger(n) || n < 1 || n > max)
|
|
71
|
+
throw new Usage(`${name} must be a whole number from 1 to ${max}`);
|
|
72
|
+
return n;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* install's and doctor's --base-url: an https origin, or the MCP URL itself (agents pass .../mcp), so the /mcp resource
|
|
76
|
+
* is always the one shown. Any other path, a query or a fragment is refused rather than silently dropped.
|
|
77
|
+
*/
|
|
78
|
+
export function mcpBase(raw, command) {
|
|
79
|
+
let base;
|
|
80
|
+
try {
|
|
81
|
+
base = new URL(raw ?? "https://api.flovia.dev");
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
throw new Usage(`${command}: --base-url must be an https URL`);
|
|
85
|
+
}
|
|
86
|
+
if (base.protocol !== "https:" || base.username || base.password)
|
|
87
|
+
throw new Usage(`${command}: --base-url must be an https URL without credentials`);
|
|
88
|
+
if (!["", "/", "/mcp", "/mcp/"].includes(base.pathname) || base.search || base.hash)
|
|
89
|
+
throw new Usage(`${command}: --base-url must be an origin such as https://api.flovia.dev (a trailing /mcp is fine); no other path, query or fragment`);
|
|
90
|
+
return base;
|
|
91
|
+
}
|