@flovialabs/sdk 0.1.24 → 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.
Files changed (49) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +12 -6
  3. package/dist/account.d.ts +12 -0
  4. package/dist/account.js +110 -0
  5. package/dist/accountcommands.d.ts +17 -0
  6. package/dist/accountcommands.js +124 -0
  7. package/dist/args.d.ts +19 -0
  8. package/dist/args.js +91 -0
  9. package/dist/cli.d.ts +11 -36
  10. package/dist/cli.js +31 -996
  11. package/dist/client.d.ts +0 -2
  12. package/dist/client.js +25 -294
  13. package/dist/commandhelp.d.ts +7 -0
  14. package/dist/commandhelp.js +52 -0
  15. package/dist/doctor.d.ts +11 -7
  16. package/dist/doctor.js +50 -23
  17. package/dist/doctorcommand.d.ts +9 -0
  18. package/dist/doctorcommand.js +125 -0
  19. package/dist/examples.d.ts +2 -0
  20. package/dist/examples.js +29 -0
  21. package/dist/generatecommand.d.ts +15 -0
  22. package/dist/generatecommand.js +64 -0
  23. package/dist/generation.d.ts +6 -0
  24. package/dist/generation.js +30 -0
  25. package/dist/install.d.ts +15 -2
  26. package/dist/install.js +77 -12
  27. package/dist/installcommand.d.ts +4 -0
  28. package/dist/installcommand.js +251 -0
  29. package/dist/keyfile.d.ts +6 -0
  30. package/dist/keyfile.js +33 -0
  31. package/dist/nodeio.d.ts +7 -0
  32. package/dist/nodeio.js +62 -0
  33. package/dist/output.d.ts +26 -0
  34. package/dist/output.js +196 -0
  35. package/dist/reply.d.ts +9 -0
  36. package/dist/reply.js +36 -0
  37. package/dist/runwayoutput.d.ts +5 -0
  38. package/dist/runwayoutput.js +44 -0
  39. package/dist/sandbox.d.ts +13 -0
  40. package/dist/sandbox.js +80 -0
  41. package/dist/sandboxcommands.d.ts +14 -0
  42. package/dist/sandboxcommands.js +90 -0
  43. package/dist/toolcommands.d.ts +14 -0
  44. package/dist/toolcommands.js +65 -0
  45. package/dist/transport.d.ts +11 -0
  46. package/dist/transport.js +2 -0
  47. package/dist/types.d.ts +11 -4
  48. package/dist/types.js +2 -2
  49. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -3,74 +3,24 @@
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 { mkdir, open, readFile, stat, writeFile } from "node:fs/promises";
7
6
  import { readFileSync, realpathSync } from "node:fs";
8
- import { spawn } from "node:child_process";
9
- import { dirname } from "node:path";
10
- import { createInterface } from "node:readline/promises";
11
7
  import { fileURLToPath } from "node:url";
12
- import { FloviaClient, FloviaError, newOperationId } from "./index.js";
13
- import { OPERATION_ID } from "./client.js";
14
- import { INSTALL_AUTH, INSTALL_CLIENTS, InstallRefusal, mergeJson, mergeYaml, planInstall } from "./install.js";
15
- import { inspect, renderDoctor, settingsPath, settle } from "./doctor.js";
16
- /** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
17
- export async function writePrivateOutput(path, data) {
18
- const file = await open(path, "wx", 0o600);
19
- try {
20
- await file.writeFile(data);
21
- await file.sync();
22
- }
23
- finally {
24
- await file.close();
25
- }
26
- }
27
- const GLOBAL = "[--json] [--base-url URL] [--timeout SECONDS] [--key-file PATH]";
28
- const CONSOLE = "https://console.flovia.dev/groupbuy/";
8
+ import { FloviaClient, FloviaError } from "./index.js";
9
+ import { obj, renderStatus, renderError } from "./output.js";
10
+ import { Usage, help, parse, positiveInt, str } from "./args.js";
11
+ import { DEFAULT_KEY_FILE, fromFile, readKey } from "./keyfile.js";
12
+ import { nodeIo } from "./nodeio.js";
13
+ import { consentCommand, keyCapsCommand, resetsCommand, runwayOutputCommand, spendModeCommand, usageCommand } from "./accountcommands.js";
14
+ import { generateCommand } from "./generatecommand.js";
15
+ import { install } from "./installcommand.js";
16
+ import { doctor } from "./doctorcommand.js";
17
+ import { sandboxCommand, workspaceCommand } from "./sandboxcommands.js";
18
+ import { callToolCommand, listToolsCommand } from "./toolcommands.js";
19
+ export { plain } from "./output.js";
20
+ export { exampleCall } from "./examples.js";
21
+ export { readStdin, writePrivateOutput } from "./nodeio.js";
29
22
  const VERSION = String(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
30
- const COMMANDS = {
31
- status: { usage: "status", about: "usage windows, services, contract version and recent updates", flags: {} },
32
- 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 } },
33
- tools: { usage: "tools [tool]", about: "list offered tools, or inspect one tool's description and arguments", flags: {} },
34
- call: { usage: "call <tool> ['<json args>' | -]", about: "call a tool; - reads a JSON object from stdin", flags: {} },
35
- "runway-output": { usage: "runway-output <generation_id> --out PATH", about: "download an existing private output; never regenerates or overwrites", flags: { "--out": true } },
36
- generate: { usage: "generate (--op ID | --new-op) [--max-output N]\n [--reasoning-effort LEVEL] [--yes] <prompt | ->", about: "request an OpenAI text generation", flags: { "--op": true, "--new-op": false, "--max-output": true, "--reasoning-effort": true, "--yes": false } },
37
- resets: { usage: "resets [use <id> --yes]", about: "check saved resets, or use one to restore free allowance", flags: { "--yes": false } },
38
- 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 } },
39
- "key-caps": { usage: "key-caps [set <key-id> --day <usd|none> --month <usd|none>]", about: "read or set each API key's own daily and monthly spending cap", flags: { "--day": true, "--month": true } },
40
- "spend-mode": { usage: "spend-mode [free-only | allow-paid]", about: "read or set whether calls may spend purchased or plan credit", flags: {} },
41
- sandbox: { usage: "sandbox run <python|node|bash> <file | -> [--op ID]\n [--label TEXT] [--timeout-seconds N]\n sandbox result [run-id] [--wait]\n sandbox schedules",
42
- about: "run your own code in Flovia's sandbox, read results, list schedules", flags: { "--op": true, "--label": true, "--timeout-seconds": true, "--wait": false } },
43
- workspace: { usage: "workspace [read <schedule-id>]", about: "a Team key's shared tasks, or one task's latest result (read-only)", flags: {} },
44
- 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 } },
45
- doctor: { usage: "doctor [--client NAME] [--network]", about: "check clients' Flovia settings (read-only; never prints the key)", flags: { "--client": true, "--network": false } },
46
- "agents-md": { usage: "agents-md", about: "a short Flovia note to paste into CLAUDE.md or AGENTS.md (no network)", flags: {} },
47
- help: { usage: "help [command]", about: "this help", flags: {} },
48
- version: { usage: "version", about: "the installed CLI version", flags: {} },
49
- };
50
- const GLOBAL_FLAGS = { "--json": false, "--base-url": true, "--timeout": true, "--key-file": true, "--help": false, "-h": false };
51
- class Usage extends Error {
52
- }
53
- function distance(a, b) {
54
- let row = Array.from({ length: b.length + 1 }, (_, j) => j);
55
- for (let i = 1; i <= a.length; i++) {
56
- const next = [i];
57
- for (let j = 1; j <= b.length; j++)
58
- 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));
59
- row = next;
60
- }
61
- return row[b.length] ?? 0;
62
- }
63
- const near = (word, options) => options.find((k) => distance(k, word) <= 2 || k.startsWith(word));
64
- const didYouMean = (word, options, quote = "") => { const n = near(word, options); return n === undefined ? "" : `; did you mean ${quote}${n}${quote}?`; };
65
- /** Agents often drop the flovia_ prefix ("coingecko"), which is too far for near() alone. */
66
- const notOffered = (word, names) => {
67
- const n = near(word, names) ?? near(`flovia_${word}`, names);
68
- return `Tool is not offered to this key${n === undefined ? "." : `; did you mean "${n}"?`} Run: flovia tools`;
69
- };
70
- const SAVE_OP = ["Save the request and operation_id before sending a data lookup.",
71
- "To recover a lost reply, keep the same request and operation_id.",
72
- "Never create a new operation_id just to recover an answer."];
73
- export const AGENTS_MD = `## Flovia
23
+ const AGENTS_MD = `## Flovia
74
24
  - Flovia is available through the \`flovia\` CLI. The key is in the FLOVIA_KEY environment variable; never paste, print or commit it.
75
25
  - Run \`flovia status\` first: it shows allowances, services and any consent the person must answer.
76
26
  - Find a tool with \`flovia tools\`, and its arguments with \`flovia tools <tool> --json\`.
@@ -78,349 +28,6 @@ export const AGENTS_MD = `## Flovia
78
28
  - 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.
79
29
  - On an error, read \`next_step\` (and \`retry_after_seconds\`) and follow it. With \`--json\`, errors are one JSON object on stdout.
80
30
  `;
81
- /** A placeholder for one schema property: its example, default or first enum value, else a value of its type. */
82
- function placeholder(name, s) {
83
- if (s.example !== undefined)
84
- return s.example;
85
- if (Array.isArray(s.examples) && s.examples.length)
86
- return s.examples[0];
87
- if (s.default !== undefined)
88
- return s.default;
89
- if (Array.isArray(s.enum) && s.enum.length)
90
- return s.enum[0];
91
- const type = Array.isArray(s.type) ? s.type[0] : s.type;
92
- return type === "integer" || type === "number" ? 1 : type === "boolean" ? false : type === "array" ? [] : type === "object" ? {} : `<${name}>`;
93
- }
94
- /** Required properties plus Exa/Firecrawl's default-operation inputs, which are conditional in the schema. */
95
- export function exampleCall(tool, schema) {
96
- // A schema split by action (oneOf, e.g. flovia_firecrawl, #2617): the example uses the option whose action is the default.
97
- const top = obj(schema), options = Array.isArray(top["oneOf"]) ? top["oneOf"].map(obj) : [];
98
- const s = options.find((o) => obj(obj(o["properties"])["action"])["default"] !== undefined) ?? options[0] ?? top, props = obj(s["properties"]), required = Array.isArray(s["required"]) ? s["required"].map(String) : [];
99
- const defaults = tool === "flovia_exa" ? ["action", "query", "operation_id"] : tool === "flovia_firecrawl" ? ["action", "url", "operation_id"] : [];
100
- const fields = [...new Set([...required, ...defaults.filter((k) => Object.hasOwn(props, k))])];
101
- const args = Object.fromEntries(fields.map((k) => [k, placeholder(k, obj(props[k]))]));
102
- const lines = ["", "Example (replace the placeholders):", ` flovia call ${tool} '${JSON.stringify(args).replaceAll("'", "'\\''")}'`,
103
- "Or from a saved file:", ` flovia call ${tool} - < request.json`];
104
- if (Object.hasOwn(props, "operation_id"))
105
- lines.push(...SAVE_OP);
106
- return lines.join("\n") + "\n";
107
- }
108
- /** The first sentence, plus the next when both fit in about 200 characters, so what the tool is for survives. */
109
- const brief = (description) => {
110
- const [first = "", second] = description.split(/(?<=\.)\s/);
111
- return second !== undefined && first.length + second.length < 200 ? `${first} ${second}` : first;
112
- };
113
- export function help(command) {
114
- const c = command === undefined || !Object.hasOwn(COMMANDS, command) ? undefined : COMMANDS[command];
115
- const lines = c === undefined ? ["Usage: flovia <command> [options]", "",
116
- ...Object.values(COMMANDS).flatMap((x) => [` ${x.usage}`, ` ${x.about}`])] : [`Usage: flovia ${c.usage}`, ` ${c.about}`];
117
- lines.push("", "Options: " + GLOBAL, "", `Get or manage your key: ${CONSOLE}`, "Save the key privately, then: flovia status --key-file <saved-key-file>", "Or set FLOVIA_KEY, or save it to ~/.config/flovia/key.", "Never paste the key into a command argument.");
118
- if (command === "generate")
119
- lines.push("", "Default output limit: 1000 tokens; maximum: 4000.", "--reasoning-effort: none (default), low, medium, high, xhigh, max.", "Reasoning shares the output token limit; higher effort can leave less visible text.", "Check spending settings with flovia spend-mode and flovia key-caps.", "Long answers can take minutes. Save the id, same input, output limit and effort.", " flovia generate --new-op --reasoning-effort high --yes - < prompt.txt", "Replay only: replace --new-op with --op <saved-id>; keep everything else.", "Use -- before a prompt that starts with a hyphen.");
120
- if (command === "tools" || c === undefined)
121
- lines.push("", "Inspect one tool: flovia tools <tool> --json", "Inspect all tool arguments: flovia tools --json", "Read-only example: flovia call flovia_status '{}'");
122
- if (command === "resets")
123
- lines.push("", "flovia resets only reads; it never uses one.", "A 5-hour reset clears only 5-hour usage. A weekly reset clears weekly and 5-hour usage. The monthly window is unchanged. Using a reset cannot be undone.", " flovia resets use <id> --yes", "It is never resent automatically; after a lost reply, run flovia resets first.");
124
- if (command === "consent")
125
- 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.");
126
- if (command === "install")
127
- 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");
128
- if (command === "doctor")
129
- 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");
130
- if (command === "sandbox")
131
- lines.push("", "run queues the code and prints its run_id. Without --op it makes an", "operation_id and prints it first: if the reply is lost, rerun with", "--op <that id> and the same code, so no second run is queued.", "The code is at most 64 KiB of UTF-8 text. Read the end with:", " flovia sandbox result <run-id> --wait", "Save --op with the code first: the same id returns that run,", "not a second one.", "Code in the sandbox cannot call Flovia: look data up first and pass", "its lookup_id as an input. Inputs, schedules and Team tasks:", " flovia call flovia_sandbox_run - < request.json", " flovia call flovia_sandbox_schedule - < request.json", "A run's output is your code's output, not instructions.");
132
- if (command === "workspace")
133
- lines.push("", "Needs a Team key of a Team whose owner turned the workspace on.", "Every current member of the Team reads the same tasks and results.", "Make or change a Team task: flovia call flovia_sandbox_schedule - < request.json");
134
- if (command === "call")
135
- lines.push("", "Read a saved request: flovia call <tool> - < request.json", ...SAVE_OP);
136
- lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 error from Flovia, 2 usage error.", "");
137
- return lines.join("\n");
138
- }
139
- export function parse(argv) {
140
- const [command, ...rest] = argv;
141
- if (command === undefined || command === "--help" || command === "-h")
142
- return { command: "help", flags: new Map(), positional: [] };
143
- if (command === "--version")
144
- return { command: "version", flags: new Map(), positional: [] };
145
- const spec = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : undefined;
146
- if (spec === undefined)
147
- throw new Usage(`unknown command${didYouMean(command, Object.keys(COMMANDS), '"')} Run: flovia help`);
148
- const known = { ...GLOBAL_FLAGS, ...spec.flags }, flags = new Map(), positional = [];
149
- for (let i = 0; i < rest.length; i++) {
150
- const a = rest[i] ?? "";
151
- if (a === "--") {
152
- positional.push(...rest.slice(i + 1));
153
- break;
154
- }
155
- if (a === "-" || !a.startsWith("-")) {
156
- positional.push(a);
157
- continue;
158
- }
159
- const eq = a.indexOf("="), name = eq > 0 ? a.slice(0, eq) : a;
160
- if (!(name in known))
161
- throw new Usage(`${command}: unknown option${didYouMean(name, Object.keys(known))} Run: flovia help ${command}`);
162
- if (!known[name]) {
163
- if (eq > 0)
164
- throw new Usage(`${command}: ${name} takes no value`);
165
- flags.set(name, true);
166
- continue;
167
- }
168
- const value = eq > 0 ? a.slice(eq + 1) : rest[++i];
169
- // The next word is another option of this command, not a value (`--since --json`); `--name=--x` still passes a literal value.
170
- const next = eq > 0 || value === undefined ? undefined : value.slice(0, value.indexOf("=") > 0 ? value.indexOf("=") : undefined);
171
- if (value === undefined || (next !== undefined && next.startsWith("-") && Object.hasOwn(known, next)))
172
- throw new Usage(`${command}: ${name} needs a value. Usage: flovia ${spec.usage}`);
173
- flags.set(name, value);
174
- }
175
- if (flags.has("--help") || flags.has("-h"))
176
- return { command: "help", flags: new Map(), positional: [command] };
177
- if (command === "help" && positional[0] !== undefined && !Object.hasOwn(COMMANDS, positional[0]))
178
- throw new Usage("unknown help topic. Run: flovia help");
179
- return { command, flags, positional };
180
- }
181
- const str = (v) => typeof v === "string" ? v : undefined;
182
- function positiveInt(name, v, max = Number.MAX_SAFE_INTEGER) {
183
- if (v === undefined)
184
- return undefined;
185
- const n = Number(v);
186
- if (!Number.isInteger(n) || n < 1 || n > max)
187
- throw new Usage(`${name} must be a whole number from 1 to ${max}`);
188
- return n;
189
- }
190
- function reasoningEffort(v) {
191
- if (v === undefined || v === "none" || v === "low" || v === "medium" || v === "high" || v === "xhigh" || v === "max")
192
- return v;
193
- throw new Usage("--reasoning-effort must be one of: none, low, medium, high, xhigh, max");
194
- }
195
- /** The key from --key-file, FLOVIA_KEY, or the file Console's setup saves (~/.config/flovia/key), in that order, trimmed. Its text never goes into a message. */
196
- async function readKey(p, io) {
197
- const file = str(p.flags.get("--key-file"));
198
- if (file !== undefined)
199
- return fromFile(file, io, "--key-file");
200
- const key = io.env["FLOVIA_KEY"]?.trim();
201
- if (key)
202
- return key;
203
- const home = io.env["HOME"];
204
- if (home && await io.readFile(`${home}/${DEFAULT_KEY_FILE}`).then(() => true, () => false))
205
- return fromFile(`${home}/${DEFAULT_KEY_FILE}`, io, `~/${DEFAULT_KEY_FILE}`);
206
- throw new Usage(`No key: set FLOVIA_KEY, pass --key-file PATH, or save it to ~/${DEFAULT_KEY_FILE}. Never paste a key as an argument.\nGet or manage your key: ${CONSOLE}\nThen: flovia status --key-file <saved-key-file>`);
207
- }
208
- const DEFAULT_KEY_FILE = ".config/flovia/key";
209
- async function fromFile(file, io, label) {
210
- let text;
211
- // Never echo a user-given path: a key pasted in its place would land in the output.
212
- try {
213
- text = await io.readFile(file);
214
- }
215
- catch {
216
- throw new Usage(`${label}: cannot read the key file`);
217
- }
218
- const key = text.trim();
219
- if (key === "")
220
- throw new Usage(`${label}: the key file is empty`);
221
- const mode = await io.fileMode?.(file).catch(() => null);
222
- if (typeof mode === "number" && (mode & 0o077) !== 0)
223
- io.err(`warning: the key file is readable by other users (mode ${(mode & 0o777).toString(8)}); run chmod 600 on it\n`);
224
- return key;
225
- }
226
- const pct = (v) => typeof v === "number" ? `${v}%` : "-";
227
- const table = (rows) => {
228
- const widths = rows[0]?.map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length))) ?? [];
229
- return rows.map((r) => r.map((c, i) => i === r.length - 1 ? c : c.padEnd(widths[i] ?? 0)).join(" ")).join("\n") + "\n";
230
- };
231
- /** "Oct 18 07:21 UTC", with the year when it is not this UTC year; anything that is not a time is shown as it came. */
232
- export function when(v, now = Date.now()) {
233
- const d = new Date(String(v));
234
- if (v === null || v === undefined || Number.isNaN(d.getTime()))
235
- return String(v);
236
- const [, day, mon, year, hm] = d.toUTCString().split(" ");
237
- return `${mon} ${day}${d.getUTCFullYear() === new Date(now).getUTCFullYear() ? "" : ` ${year}`} ${hm?.slice(0, 5)} UTC`;
238
- }
239
- const obj = (v) => v !== null && typeof v === "object" ? v : {};
240
- /** Wrap prose only, never prompts, answers, consent notices, JSON or copyable commands. */
241
- const prose = (text) => (text.match(/.{1,76}(?:\s|$)|\S+/g) ?? []).map((line) => line.trim()).join("\n ");
242
- /** Status labels share one column; the longest is "purchased balance". */
243
- const label = (name) => name.padEnd(19);
244
- export function renderStatus(s, expected, now = Date.now()) {
245
- const lines = ["Connection: OK", `Flovia ${s.stage}, contract ${s.contract_version}`];
246
- if (expected !== null)
247
- lines.push(`warning: this CLI expects ${expected}`, "Connection succeeded; check recent updates before making calls.");
248
- const stopped = obj(s["stopped"]), consent = obj(s["data_consent"]);
249
- if (stopped["message"])
250
- lines.push(`key stopped: ${String(stopped["message"])}`);
251
- if (obj(s["consent"])["sharing"] === "withdrawn")
252
- lines.push("New usage: stopped (sharing withdrawn).");
253
- else if (consent["needed"] === true)
254
- lines.push("New usage: waits for your own y/n to the current data consent.");
255
- else if (consent["answer"] === "n")
256
- lines.push("New usage: stopped (sharing declined). Your choice is saved.");
257
- else if (consent["answer"] === "y")
258
- lines.push("Data consent: accepted. Service and allowance limits still apply.");
259
- else
260
- lines.push("Data consent: not reported (see --json).");
261
- for (const [name, w] of [["free 5-hour", s.five_hour], ["free week", s.week]])
262
- lines.push(`${label(name)}${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : name === "free 5-hour" ? ", not started" : ""}`);
263
- lines.push(`${label("purchased balance")}${String(s["purchased_balance_display"] ?? "-")}`);
264
- // An older relay, or an account with no capped key, omits api_key_caps; nothing is shown then.
265
- for (const c of Array.isArray(s["api_key_caps"]) ? s["api_key_caps"] : [])
266
- lines.push(`${label(`key cap${c["this_key"] === true ? " (this key)" : ""}`)}${String(c["name"])}: today $${String(c["day_used_usd"])} of ${c["day_cap_usd"] === null ? "none" : `$${String(c["day_cap_usd"])}`}, month $${String(c["month_used_usd"])} of ${c["month_cap_usd"] === null ? "none" : `$${String(c["month_cap_usd"])}`}`);
267
- // An older relay omits spend_mode; nothing is shown then.
268
- if (typeof s["spend_mode"] === "string")
269
- lines.push(`${label("spend mode")}${String(s["spend_mode"]).startsWith("free_only") ? "free-only (purchased balance and plan credit are never used)" : "allow-paid"}`);
270
- // An older relay omits banked_resets; nothing is shown then.
271
- const banked = obj(s["banked_resets"]), n = banked["available"];
272
- if (typeof n === "number" && n > 0)
273
- lines.push(`You have ${n} saved reset${n === 1 ? "" : "s"} (until ${String(banked["next_expires_at"]).slice(0, 10)}). Run: flovia resets`);
274
- const pending = obj(s["free_pending"]);
275
- if (pending["next_step"])
276
- lines.push(`free allowance not started: ${String(pending["next_step"])}`);
277
- const services = Object.entries(obj(s["services"])).map(([name, v]) => { const x = obj(v); return `${name} ${String(x["state"] ?? "?")}${x["until"] ? ` until ${when(x["until"], now)}` : ""}`; });
278
- lines.push(`${label("services")}(provider state)`, ...services.map((v) => ` ${v}`));
279
- lines.push(`${label("turned off")}${s.services_off.length ? s.services_off.join(", ") : "none"}`);
280
- const updates = Array.isArray(s["recent_updates"]) ? s["recent_updates"] : [];
281
- for (const u of updates.slice(0, 2)) {
282
- const x = obj(u), first = Array.isArray(x["lines"]) ? String(x["lines"][0] ?? "") : "";
283
- lines.push(prose(`update ${String(x["version"])} (${String(x["date"])}): ${first}`));
284
- }
285
- if (updates.length > 2)
286
- lines.push(`+${updates.length - 2} more (--json)`);
287
- return lines.join("\n") + "\n";
288
- }
289
- export function renderUsage(u, today = false, now = Date.now()) {
290
- const lines = [`since ${when(u["since"], now)} until ${when(u["until"], now)}${today ? " (today, UTC; use --days 7 for the week)" : ""}`];
291
- const week = obj(u["free_week"]);
292
- lines.push(`free allowance this week: ${pct(week["used_pct"])} used${week["resets_at"] ? `, resets ${when(week["resets_at"], now)}` : ""}`);
293
- lines.push(`total in this period: ${String(obj(u["total"])["free_display"] ?? "-")} of the weekly free allowance, ${String(u["count"] ?? 0)} ${u["count"] === 1 ? "lookup" : "lookups"}`);
294
- lines.push(`purchased balance used: ${String(obj(u["total"])["bought_display"] ?? "-")} total (includes generations)`);
295
- // Endpoint percentages are rounded (0 can mean <1%); only counts can be summed by source.
296
- const bySource = new Map();
297
- for (const e of Array.isArray(u["by_endpoint"]) ? u["by_endpoint"] : []) {
298
- const x = obj(e), name = String(x["provider"]);
299
- if (x["endpoint"] === "generation")
300
- continue; // generations are listed below, not as lookups (#2824)
301
- bySource.set(name, (bySource.get(name) ?? 0) + Number(x["count"] ?? 0));
302
- }
303
- if (bySource.size)
304
- lines.push("", table([["source", "lookups"], ...[...bySource].map(([n, count]) => [n, String(count)])]).trimEnd());
305
- const g = obj(u["generations"]);
306
- lines.push("", `generations: ${String(g["operations"] ?? 0)} (completed ${String(g["completed"] ?? 0)}, incomplete ${String(g["incomplete"] ?? 0)}, unknown ${String(g["unknown"] ?? 0)}), ${String(g["free_display"] ?? "-")} of the weekly free allowance, purchased ${String(g["bought_display"] ?? "-")} (included in total)`);
307
- for (const [field, name, states] of [
308
- ["gemini_generations", "Gemini text generations", ["completed", "incomplete", "unknown"]],
309
- ["minimax_generations", "MiniMax text generations", ["completed", "incomplete", "unknown"]],
310
- ["runway_generations", "Runway jobs", ["completed", "failed", "unknown", "reserved", "submitted"]],
311
- ]) {
312
- if (u[field] === undefined || u[field] === null)
313
- continue;
314
- const summary = obj(u[field]);
315
- const counts = states.map(state => `${state} ${String(summary[state] ?? "-")}`).join(", ");
316
- lines.push("", `${name}: ${String(summary["operations"] ?? "-")} (${counts}), ${String(summary["free_display"] ?? "-")} of the weekly free allowance, purchased ${String(summary["bought_display"] ?? "-")} (included in total)`);
317
- }
318
- if (u.has_more)
319
- lines.push("", `more lookups: rerun flovia usage with the same --key-file and --base-url options, adding --since ${String(u["since"])} --cursor ${String(u.next_cursor)}`);
320
- return lines.join("\n") + "\n";
321
- }
322
- export function renderResets(r, s, now = Date.now()) {
323
- const lines = [`${label("saved resets")}${r.available}`];
324
- if (r.next)
325
- lines.push(`${label("next to expire")}id ${r.next.id}, expires ${when(r.next.expires_at, now)}`);
326
- for (const [name, w] of [["free 5-hour", s.five_hour], ["free week", s.week]])
327
- lines.push(`${label(name)}${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : ""}`);
328
- if (r.resets)
329
- for (const reset of r.resets)
330
- lines.push(`${reset.kind === "five_hour" ? "5-hour reset" : "Weekly reset (includes 5-hour)"}: id ${reset.id}, expires ${when(reset.expires_at, now)}. Use: flovia resets use ${reset.id} --yes`);
331
- else if (r.next)
332
- lines.push("This reply does not specify the reset kind. Using a reset cannot be undone.", `To use it: flovia resets use ${r.next.id} --yes`);
333
- return lines.join("\n") + "\n";
334
- }
335
- export function renderConsent(c) {
336
- const lines = [`${label("current notice")}${c.version}`, `${label("your yes")}${c.answered_version ?? "none"}`];
337
- if (!c.needed && !c.updated)
338
- return lines.join("\n") + "\n";
339
- if (c.updated)
340
- 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.");
341
- lines.push("", "Notice:", c.notice);
342
- lines.push("", `To answer yes yourself: flovia consent accept ${c.version} --yes (or in Console: ${CONSOLE})`);
343
- return lines.join("\n") + "\n";
344
- }
345
- const SANDBOX_LANGUAGES = ["python", "node", "bash"];
346
- const SANDBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
347
- const SANDBOX_CODE_BYTES = 64 * 1024;
348
- const ESC = String.fromCharCode(0x1b), BEL = String.fromCharCode(0x07), ST = String.fromCharCode(0x9c), OSC = String.fromCharCode(0x9d), CSI = String.fromCharCode(0x9b);
349
- const ESCAPES = [new RegExp(`(?:${ESC}\\]|${OSC})[\\s\\S]*?(?:${BEL}|${ESC}\\\\|${ST})`, "g"), new RegExp(`(?:${ESC}\\[|${CSI})[0-?]*[ -/]*[@-~]`, "g"), new RegExp(`${ESC}[ -/]*[0-~]`, "g")];
350
- /**
351
- * Text for a terminal: a run's stdout, labels and notices come from code (for a Team task, another member's code), so escape sequences (CSI, OSC and
352
- * the rest) and control characters are removed; only newline and tab stay. --json output is not passed through here.
353
- */
354
- export const plain = (s) => ESCAPES.reduce((t, re) => t.replace(re, ""), s).replace(/[^\P{Cc}\n\t]/gu, "");
355
- export function renderSandboxRuns(r, now = Date.now()) {
356
- if (!r.runs.length)
357
- return "No code runs are kept for this account.\n";
358
- return plain(table([["run_id", "status", "queued", "label"], ...r.runs.map((x) => [x.run_id, x.status, when(x.at, now), x.label ?? ""])])) + "Result: flovia sandbox result <run-id> --wait\n";
359
- }
360
- /** stdout is the user's own code's output, printed without control characters (plain); the status lines go after it. */
361
- export function renderSandboxResult(r, now = Date.now()) {
362
- const ended = r.status !== "queued" && r.status !== "running";
363
- const lines = [...(typeof r.stdout === "string" && r.stdout !== "" ? [r.stdout.replace(/\n$/, ""), ""] : []),
364
- `run_id: ${r.run_id}`, `status: ${r.status}${r.exit_code === null ? "" : `, exit code ${r.exit_code}`}${r.timed_out ? ", timed out" : ""}${r.truncated ? ", output truncated" : ""}`,
365
- `executed: ${r.executed}`];
366
- if (!ended)
367
- lines.push(`Not finished yet. Wait for it: flovia sandbox result ${r.run_id} --wait`);
368
- else
369
- lines.push(`kept until ${when(r.expires_at, now)}`);
370
- lines.push(String(r.user_notice));
371
- return plain(lines.join("\n")) + "\n";
372
- }
373
- export function renderSandboxSchedules(r, now = Date.now()) {
374
- if (!r.schedules.length)
375
- return "No schedules.\n";
376
- return plain(table([["schedule_id", "cron", "tz", "status", "next run", "team", "label"], ...r.schedules.map((x) => [x.schedule_id, x.cron, x.tz,
377
- x.paused_reason ? `${x.status} (${x.paused_reason})` : x.status, x.next_run_at === null ? "-" : when(x.next_run_at, now), x.team === true || x.team === 1 ? "yes" : "no", x.label ?? ""])]));
378
- }
379
- export function renderWorkspace(r, now = Date.now()) {
380
- if (!r.team_tasks.length)
381
- return plain(`No Team tasks.\n${String(r.user_notice)}`) + "\n";
382
- return plain(table([["schedule_id", "cron", "tz", "status", "next run", "last run", "yours", "label"], ...r.team_tasks.map((x) => [x.schedule_id, x.cron, x.tz,
383
- x.paused_reason ? `${x.status} (${x.paused_reason})` : x.status, x.next_run_at === null ? "-" : when(x.next_run_at, now),
384
- x.last_run_status === null ? "-" : `${x.last_run_status}${x.last_run_finished_at ? ` ${when(x.last_run_finished_at, now)}` : ""}`, x.yours ? "yes" : "no", x.label ?? ""])])
385
- + `Result: flovia workspace read <schedule-id>\n${String(r.user_notice)}`) + "\n";
386
- }
387
- export function renderWorkspaceRead(r, now = Date.now()) {
388
- const lines = [...(typeof r.stdout === "string" && r.stdout !== "" ? [r.stdout.replace(/\n$/, ""), ""] : []), `schedule_id: ${r.schedule_id}${r.label ? ` (${r.label})` : ""}`, `task: ${r.task_status}`];
389
- if (r.run_id === null)
390
- lines.push("No shared run yet.");
391
- else
392
- lines.push(`run_id: ${r.run_id}`, `status: ${String(r.status)}${r.exit_code === null ? "" : `, exit code ${r.exit_code}`}${r.timed_out ? ", timed out" : ""}${r.truncated ? ", output truncated" : ""}`, ...(r.finished_at ? [`finished ${when(r.finished_at, now)}`] : []), ...(r.expires_at ? [`kept until ${when(r.expires_at, now)}`] : []));
393
- lines.push(String(r.user_notice));
394
- return plain(lines.join("\n")) + "\n";
395
- }
396
- /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
397
- export function renderError(e) {
398
- const lines = [`error: ${e.code}: ${e.message}`];
399
- if (e.nextStep)
400
- lines.push(`next_step: ${e.nextStep}`);
401
- if (e.code === "unauthorized")
402
- lines.push("After you save a current key, check it: flovia status --key-file <saved-key-file>");
403
- lines.push(`executed: ${e.executed}`);
404
- if (e.retryAfterSeconds !== null)
405
- lines.push(`retry_after_seconds: ${e.retryAfterSeconds}`);
406
- if (e.operationId)
407
- lines.push(`operation_id: ${e.operationId}${e.executed === "unknown" ? " (keep this id; never send the request again under a new one)" : ""}`);
408
- const reply = obj(e.reply);
409
- if (e.code === "notice_first" || e.code === "data_consent_needed") {
410
- const notice = reply["user_notice"] || reply["notice"];
411
- if (notice)
412
- lines.push("", "Notice:", String(notice));
413
- const consent = obj(reply["consent"]), question = consent["question"] || (e.code === "data_consent_needed" ? consent["line"] : undefined);
414
- if (question)
415
- lines.push("", `Your choice: ${String(question)}`);
416
- if (e.code === "data_consent_needed") {
417
- lines.push("", "Only the user can consent; the CLI does not answer for them.");
418
- }
419
- else
420
- lines.push("", "Follow next_step. The CLI does not opt in for the user.");
421
- }
422
- return lines.join("\n") + "\n";
423
- }
424
31
  export async function run(argv, io) {
425
32
  let key = null;
426
33
  const seen = [];
@@ -483,30 +90,11 @@ export async function run(argv, io) {
483
90
  fetch: (r) => { r.headers.set("X-Flovia-Client", "flovia-cli"); return (io.fetch ?? fetch)(r); }, onContractMismatch: (expected) => { mismatch = expected; } });
484
91
  };
485
92
  if (p.command === "install")
486
- return await install(p, io, out, err, json);
93
+ return await install(p, io, out, err, json, timeout, fromFile);
487
94
  if (p.command === "doctor")
488
- return await doctor(p, io, out, json, (k) => { seen.push(k); }, { baseUrl, timeout });
95
+ return await doctor(p, io, out, json, (k) => { seen.push(k); }, { baseUrl, timeout }, fromFile, DEFAULT_KEY_FILE);
489
96
  switch (p.command) {
490
- case "runway-output": {
491
- const [id, extra] = p.positional, path = str(p.flags.get("--out"));
492
- 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))
493
- throw new Usage("Usage: flovia runway-output <generation_id> --out PATH");
494
- if (!io.writeOutput)
495
- throw new Usage("A private output-file writer is required.");
496
- const client = await connect(), output = await waitFor(() => client.downloadRunwayOutput(id));
497
- try {
498
- await io.writeOutput(path, output.data);
499
- }
500
- catch {
501
- throw new Usage("Could not save the output; check for a partial file. Existing files are never overwritten.");
502
- }
503
- const saved = { saved: true, generation_id: id, bytes: output.data.byteLength, content_type: output.contentType, attribution: "Powered by Runway", attribution_url: "https://runwayml.com" };
504
- if (json)
505
- print(saved);
506
- else
507
- out("Output saved privately. Powered by Runway (https://runwayml.com).\n");
508
- return 0;
509
- }
97
+ case "runway-output": return await runwayOutputCommand(p, io, { connect, waitFor, json, print, out });
510
98
  case "status": {
511
99
  const client = await connect(), s = await waitFor(() => client.status());
512
100
  if (json)
@@ -517,302 +105,17 @@ export async function run(argv, io) {
517
105
  err(`warning: contract ${s.contract_version} differs from this CLI's ${String(mismatch)}\n`);
518
106
  return 0;
519
107
  }
520
- case "resets": {
521
- const [action, id, extra] = p.positional;
522
- if (action === undefined) {
523
- if (p.flags.has("--yes"))
524
- throw new Usage("Usage: flovia resets use <id> --yes");
525
- const client = await connect(), [r, s] = await waitFor(() => Promise.all([client.bankedResets(), client.status()]));
526
- if (json)
527
- print({ ...r, five_hour: s.five_hour, week: s.week });
528
- else
529
- out(renderResets(r, s, (io.now ?? Date.now)()));
530
- return 0;
531
- }
532
- const grant = action === "use" && extra === undefined && id !== undefined && /^[1-9][0-9]{0,15}$/.test(id) ? Number(id) : NaN;
533
- if (!Number.isSafeInteger(grant))
534
- throw new Usage("Usage: flovia resets use <id> --yes (the id from flovia resets)");
535
- if (!p.flags.has("--yes"))
536
- throw new Usage("resets use: add --yes to use it; it cannot be undone. Check first: flovia resets");
537
- const client = await connect(), u = await waitFor(() => client.useBankedReset(grant));
538
- if (json)
539
- print(u);
540
- else
541
- out(u.outcome === "used" ? `Used. The selected free allowance was reset; the monthly window is unchanged.\n${label("saved resets")}${u.available}\n`
542
- : `Not used; nothing changed.\n${label("saved resets")}${u.available}\nCheck: flovia resets\n`);
543
- return u.outcome === "used" ? 0 : 1;
544
- }
545
- case "consent": {
546
- const [action, version, extra] = p.positional;
547
- if (action === undefined) {
548
- if (p.flags.has("--yes"))
549
- throw new Usage("Usage: flovia consent accept <version> --yes");
550
- const client = await connect(), c = await waitFor(() => client.consent());
551
- if (json)
552
- print(c);
553
- else
554
- out(renderConsent(c));
555
- return 0;
556
- }
557
- if (action !== "accept" || version === undefined || extra !== undefined)
558
- throw new Usage("Usage: flovia consent accept <version> --yes (the version from flovia consent)");
559
- const client = await connect();
560
- if (!p.flags.has("--yes")) {
561
- // Show what would be agreed to, then stop: nothing is sent without --yes.
562
- const c = await waitFor(() => client.consent());
563
- if (!json)
564
- out(renderConsent(c));
565
- throw new Usage(`consent accept: nothing was sent. Read the notice, then add --yes to answer yes to ${version} yourself.`);
566
- }
567
- const a = await waitFor(() => client.acceptConsent(version));
568
- if (json)
569
- print(a);
570
- else
571
- out(a.outcome === "recorded" ? `Recorded: yes to ${a.version}.\n` : `Already answered yes to ${a.version}; nothing changed.\n`);
572
- return 0;
573
- }
574
- case "key-caps": {
575
- 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;
576
- const day = cap(str(p.flags.get("--day"))), month = cap(str(p.flags.get("--month")));
577
- if (action === undefined ? p.flags.has("--day") || p.flags.has("--month")
578
- : action !== "set" || id === undefined || !/^[0-9a-f]{32}$/.test(id) || extra !== undefined || day === undefined || month === undefined)
579
- throw new Usage("Usage: flovia key-caps [set <key-id> --day <usd|none> --month <usd|none>] (the key id from flovia key-caps)");
580
- const client = await connect(), r = action === undefined ? await waitFor(() => client.keyCaps())
581
- : await waitFor(() => client.setKeyCaps(id, { day_usd: day, month_usd: month }));
582
- if (json) {
583
- print(r);
584
- return 0;
585
- }
586
- if ("outcome" in r)
587
- 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");
588
- const usd = (v) => v === null ? "none" : `$${v}`;
589
- for (const k of r.keys)
590
- 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`
591
- + ` 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`);
592
- return "outcome" in r && r.outcome !== "set" ? 1 : 0;
593
- }
594
- case "spend-mode": {
595
- const [arg, extra] = p.positional, mode = arg === undefined ? undefined : arg === "free-only" ? "free_only" : arg === "allow-paid" ? "allow_paid" : null;
596
- if (mode === null || extra !== undefined)
597
- throw new Usage("Usage: flovia spend-mode [free-only | allow-paid]");
598
- const client = await connect(), m = await waitFor(() => client.spendMode(mode));
599
- if (json)
600
- print({ mode: m });
601
- else
602
- out(m === "free_only" ? "spend mode: free-only. Metered calls need an available free allowance.\n"
603
- : "spend mode: allow-paid. Plan credit or purchased balance may pay within your key caps.\n");
604
- return 0;
605
- }
606
- case "sandbox": {
607
- const [action, a, b, extra] = p.positional, usage = () => new Usage(`Usage: flovia ${COMMANDS["sandbox"]?.usage}`), now = (io.now ?? Date.now)();
608
- const runFlags = p.flags.has("--op") || p.flags.has("--label") || p.flags.has("--timeout-seconds");
609
- if (action === "schedules") {
610
- if (a !== undefined || runFlags || p.flags.has("--wait"))
611
- throw usage();
612
- const client = await connect(), r = await waitFor(() => client.sandboxSchedules());
613
- if (json)
614
- print(r);
615
- else
616
- out(renderSandboxSchedules(r, now));
617
- return 0;
618
- }
619
- if (action === "result") {
620
- if (b !== undefined || runFlags || (a === undefined && p.flags.has("--wait")) || (a !== undefined && !SANDBOX_UUID.test(a)))
621
- throw usage();
622
- const client = await connect();
623
- if (a === undefined) {
624
- const r = await waitFor(() => client.sandboxRuns());
625
- if (json)
626
- print(r);
627
- else
628
- out(renderSandboxRuns(r, now));
629
- return 0;
630
- }
631
- const r = await waitFor(() => client.sandboxResult(a, p.flags.has("--wait") ? { waitSeconds: 50 } : {}));
632
- if (json)
633
- print(r);
634
- else
635
- out(renderSandboxResult(r, now));
636
- return 0;
637
- }
638
- if (action !== "run" || a === undefined || !SANDBOX_LANGUAGES.includes(a) || b === undefined || extra !== undefined || p.flags.has("--wait"))
639
- throw usage();
640
- const op = str(p.flags.get("--op")), runLabel = str(p.flags.get("--label")), seconds = positiveInt("--timeout-seconds", str(p.flags.get("--timeout-seconds")), 60);
641
- if (op !== undefined && !OPERATION_ID.test(op))
642
- throw new Usage("sandbox run: --op must be 8-128 of A-Z a-z 0-9 _ . : -");
643
- if (runLabel !== undefined && (runLabel === "" || runLabel.length > 256))
644
- throw new Usage("sandbox run: --label must be 1 to 256 characters");
645
- let code;
646
- // Never echo a user-given path: a key pasted in its place would land in the output.
647
- try {
648
- code = b === "-" ? await io.readStdin() : await (io.readCode ?? io.readFile)(b);
649
- }
650
- catch {
651
- throw new Usage(b === "-" ? "sandbox run: cannot read the code from stdin (it must be UTF-8 text)" : "sandbox run: cannot read the code file (it must be UTF-8 text)");
652
- }
653
- if (code.trim() === "")
654
- throw new Usage("sandbox run: the code is empty");
655
- // Refused here, before a connection: the relay takes at most 64 KiB of code.
656
- if (new TextEncoder().encode(code).length > SANDBOX_CODE_BYTES)
657
- throw new Usage("sandbox run: the code is over 64 KiB (65536 bytes); nothing was sent");
658
- const client = await connect();
659
- const id = op ?? newOperationId();
660
- // The id is shown before anything is sent, so a lost reply can be asked again with it instead of queueing a second run.
661
- if (op === undefined)
662
- err(`operation_id: ${id}\nIf the reply is lost, rerun with the same code and: --op ${id}\n`);
663
- const r = await waitFor(() => client.sandboxRun({ code, language: a, ...(seconds ? { timeout_seconds: seconds } : {}), ...(runLabel ? { label: runLabel } : {}), operation_id: id }));
664
- if (json)
665
- print(r);
666
- else
667
- out(plain(`run_id: ${r.run_id}\nstatus: ${r.status}${typeof r.note === "string" ? `\n${r.note}` : ""}`) + `\nResult: flovia sandbox result ${r.run_id} --wait\n`);
668
- return 0;
669
- }
670
- case "workspace": {
671
- const [action, id, extra] = p.positional, now = (io.now ?? Date.now)();
672
- if (action === undefined) {
673
- const client = await connect(), r = await waitFor(() => client.workspaceTasks());
674
- if (json)
675
- print(r);
676
- else
677
- out(renderWorkspace(r, now));
678
- return 0;
679
- }
680
- if (action !== "read" || id === undefined || !SANDBOX_UUID.test(id) || extra !== undefined)
681
- throw new Usage(`Usage: flovia ${COMMANDS["workspace"]?.usage} (the schedule_id from flovia workspace)`);
682
- const client = await connect(), r = await waitFor(() => client.workspaceRead(id));
683
- if (json)
684
- print(r);
685
- else
686
- out(renderWorkspaceRead(r, now));
687
- return 0;
688
- }
689
- case "usage": {
690
- const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")), 30), cursor = str(p.flags.get("--cursor"));
691
- if (since !== undefined && days !== undefined)
692
- throw new Usage("usage: pass --since or --days, not both");
693
- if (cursor !== undefined && days !== undefined)
694
- throw new Usage("usage: with --cursor, use the previous reply's exact --since, not --days");
695
- if (since !== undefined && Number.isNaN(Date.parse(since)))
696
- throw new Usage("--since must be an ISO 8601 time");
697
- const client = await connect(), u = await waitFor(() => client.usageToday({ ...(since ? { since } : {}), ...(days === undefined ? {} : { days }), ...(cursor ? { cursor } : {}) }));
698
- if (json)
699
- print(u);
700
- else
701
- out(renderUsage(u, since === undefined && days === undefined && cursor === undefined, (io.now ?? Date.now)()));
702
- return 0;
703
- }
704
- case "tools": {
705
- const [name, extra] = p.positional;
706
- if (extra !== undefined)
707
- throw new Usage(`Usage: flovia ${COMMANDS["tools"]?.usage}`);
708
- const client = await connect(), tools = await waitFor(() => client.listTools());
709
- if (name !== undefined) {
710
- const tool = tools.find((t) => t.name === name);
711
- if (tool === undefined)
712
- throw new Usage(notOffered(name, tools.map((t) => t.name)));
713
- if (json)
714
- print(tool);
715
- else
716
- out(`${tool.name}\n${tool.description ?? ""}\n\nArguments (JSON Schema):\n${JSON.stringify(tool.inputSchema, null, 2)}\n${exampleCall(tool.name, tool.inputSchema)}`);
717
- }
718
- else if (json)
719
- print(tools);
720
- else
721
- out(tools.map((t) => `${t.name}\n ${prose(brief(t.description ?? ""))}\n`).join("\n") + "\nArguments: flovia tools <tool> --json\nRead-only example: flovia call flovia_status '{}'\n");
722
- return 0;
723
- }
724
- case "call": {
725
- const [tool, input, extra] = p.positional;
726
- if (tool === undefined || extra !== undefined)
727
- throw new Usage(`Usage: flovia ${COMMANDS["call"]?.usage}`);
728
- let raw = input;
729
- if (input === "-") {
730
- try {
731
- raw = await io.readStdin();
732
- }
733
- catch {
734
- throw new Usage("call: cannot read JSON from stdin");
735
- }
736
- }
737
- let args = {};
738
- if (raw !== undefined)
739
- try {
740
- args = JSON.parse(raw);
741
- }
742
- catch {
743
- throw new Usage("call: the arguments must be one JSON object, e.g. '{\"since\":\"2026-10-10T00:00:00Z\"}'");
744
- }
745
- if (args === null || typeof args !== "object" || Array.isArray(args))
746
- throw new Usage("call: the arguments must be a JSON object");
747
- const client = await connect();
748
- try {
749
- print(await waitFor(() => client.call(tool, args)));
750
- }
751
- catch (e) {
752
- // The relay's MCP server refuses an unknown name with "Tool <name> not found" before running anything; only then read the catalog to suggest one.
753
- if (!(e instanceof FloviaError && e.code === "mcp_error" && /\bTool \S+ (not found|disabled)/.test(e.message)))
754
- throw e;
755
- const names = await client.listTools().then((t) => t.map((x) => x.name), () => []);
756
- throw new FloviaError({ code: "tool_not_offered", executed: "no", message: notOffered(tool, names), nextStep: "Run: flovia tools" });
757
- }
758
- return 0;
759
- }
760
- case "generate": {
761
- const op = str(p.flags.get("--op")), fresh = p.flags.has("--new-op");
762
- if ((op === undefined) === !fresh)
763
- throw new Usage("generate: pass --op ID (to resend, the same id) or --new-op (to make one); exactly one of them");
764
- // Checked before the notice and the confirmation: the SDK would refuse it anyway, and nothing would be sent.
765
- if (op !== undefined && !OPERATION_ID.test(op))
766
- throw new Usage("generate: --op must be 8-128 of A-Z a-z 0-9 _ . : - (the id you saved, or use --new-op)");
767
- const [text, extra] = p.positional;
768
- if (text === undefined || extra !== undefined)
769
- throw new Usage(`Usage: flovia ${COMMANDS["generate"]?.usage}`);
770
- const max = positiveInt("--max-output", str(p.flags.get("--max-output")));
771
- const effort = reasoningEffort(str(p.flags.get("--reasoning-effort")));
772
- const client = await connect();
773
- let input = text;
774
- if (text === "-")
775
- try {
776
- input = await io.readStdin();
777
- }
778
- catch {
779
- throw new Usage("generate: cannot read the prompt from stdin (it must be UTF-8 text)");
780
- }
781
- if (input.trim() === "")
782
- throw new Usage("generate: the prompt is empty");
783
- recoveryLimit = max;
784
- recoveryEffort = effort;
785
- const id = op ?? newOperationId();
786
- // The id is shown before anything is sent, so a lost reply can be reopened with it (never resent under a new one).
787
- if (fresh)
788
- err(`operation_id: ${id}\nSave it. To resend or reopen this request, use: --op ${id}\n`);
789
- err("What a new generation uses depends on your plan, available balance, spend mode and key caps.\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");
790
- if (!p.flags.has("--yes")) {
791
- if (io.confirm === null || text === "-")
792
- throw new Usage("generate: add --yes to send (no terminal to confirm on)");
793
- if (!(await io.confirm("Send it?"))) {
794
- err("Not sent.\n");
795
- return 2;
796
- }
797
- }
798
- const g = await waitFor(() => client.generate({ model: "gpt-6-luna", input, ...(max ? { max_output_tokens: max } : {}), ...(effort ? { reasoning: { effort } } : {}) }, { operationId: id }));
799
- const reason = obj(g.response["incomplete_details"])["reason"];
800
- if (json)
801
- print(g);
802
- else {
803
- out(`${g.outputText}\n\nstatus: ${String(g.response["status"] ?? "unknown")}${reason ? `, reason: ${String(reason)}` : ""}\noperation_id: ${id}\n${g.generationId ? `generation: ${g.generationId}\n` : ""}`);
804
- if (g.response["status"] === "incomplete")
805
- out(`${reason === "max_output_tokens" ? "Partial answer: the output limit was reached" : "Partial answer"}; delivered and settled. No continuation was generated.\n`);
806
- else if (g.response["status"] === "completed")
807
- out("Answer delivered and settled.\n");
808
- if (g.replayed)
809
- out("replayed: the saved answer, not charged again.\n");
810
- else
811
- out("Exact Flovia cost is not included in this reply.\n");
812
- out("Period usage: flovia usage (keep the same --key-file and --base-url options).\n");
813
- }
814
- return 0;
815
- }
108
+ case "resets": return await resetsCommand(p, io, { connect, waitFor, json, print, out });
109
+ case "consent": return await consentCommand(p, { connect, waitFor, json, print, out });
110
+ case "key-caps": return await keyCapsCommand(p, { connect, waitFor, json, print, out });
111
+ case "spend-mode": return await spendModeCommand(p, { connect, waitFor, json, print, out });
112
+ case "sandbox": return await sandboxCommand(p, io, { connect, waitFor, json, print, out, err });
113
+ case "workspace": return await workspaceCommand(p, io, { connect, waitFor, json, print, out, err });
114
+ case "usage": return await usageCommand(p, io, { connect, waitFor, json, print, out });
115
+ case "tools": return await listToolsCommand(p, { connect, waitFor, json, print, out });
116
+ case "call": return await callToolCommand(p, io, { connect, waitFor, print });
117
+ case "generate": return await generateCommand(p, io, { connect, waitFor, json, print, out, err,
118
+ rememberRecovery: (limit, effort) => { recoveryLimit = limit; recoveryEffort = effort; } });
816
119
  }
817
120
  return 2;
818
121
  }
@@ -840,241 +143,6 @@ export async function run(argv, io) {
840
143
  return 1;
841
144
  }
842
145
  }
843
- const quoteArg = (a) => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replaceAll("'", "'\\''")}'`;
844
- const describeStep = (s) => s.kind === "exec" ? `run: ${[s.command, ...s.args.map(quoteArg)].join(" ")}`
845
- : `update: ${s.path} (add flovia to ${s.kind === "json" ? "mcpServers" : "mcp_servers"}, keeping other entries)`;
846
- /** No network and no key text: for Claude Code's key mode only the key file's readability is checked. */
847
- async function install(p, io, out, err, json) {
848
- const client = str(p.flags.get("--client")), auth = str(p.flags.get("--auth")) ?? "oauth";
849
- if (p.positional.length)
850
- throw new Usage(`Usage: flovia ${COMMANDS["install"]?.usage}`);
851
- if (client === undefined || !INSTALL_CLIENTS.includes(client))
852
- throw new Usage(`install: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${client === undefined ? "" : didYouMean(client, [...INSTALL_CLIENTS])}`);
853
- if (!INSTALL_AUTH.includes(auth))
854
- throw new Usage("install: --auth must be oauth or key");
855
- const home = io.env["HOME"];
856
- if (!home)
857
- throw new Usage("install: HOME is not set");
858
- let base;
859
- try {
860
- base = new URL(str(p.flags.get("--base-url")) ?? "https://api.flovia.dev");
861
- }
862
- catch {
863
- throw new Usage("install: --base-url must be an https URL");
864
- }
865
- if (base.protocol !== "https:" || base.username || base.password)
866
- throw new Usage("install: --base-url must be an https URL without credentials");
867
- const resource = `${base.origin}/mcp`, keyFile = str(p.flags.get("--key-file"));
868
- let plan;
869
- try {
870
- plan = planInstall({ client: client, auth: auth, resource, home, ...(keyFile ? { keyPath: keyFile } : {}) });
871
- }
872
- catch (e) {
873
- if (e instanceof InstallRefusal)
874
- throw new Usage(e.message);
875
- throw e;
876
- }
877
- const dry = p.flags.has("--dry-run"), force = p.flags.has("--force"), done = [];
878
- if (plan.client === "claude-code" && plan.auth === "key") {
879
- const path = keyFile ?? "~/.config/flovia/key";
880
- await fromFile(path.startsWith("~/") ? `${home}/${path.slice(2)}` : path, io, keyFile === undefined ? "~/.config/flovia/key" : "--key-file");
881
- }
882
- if (plan.client === "codex" && plan.auth === "key" && !io.env["FLOVIA_KEY"]?.trim())
883
- err("warning: FLOVIA_KEY is not set in this shell; Codex needs it where it starts\n");
884
- if (plan.client === "cursor" && plan.auth === "key" && !io.env["FLOVIA_API_KEY"]?.trim())
885
- err("warning: FLOVIA_API_KEY is not set in this shell; Cursor needs it where it starts\n");
886
- for (const step of plan.steps) {
887
- if (dry) {
888
- done.push(`would ${describeStep(step)}`);
889
- continue;
890
- }
891
- if (step.kind === "exec") {
892
- if (!io.exec)
893
- throw new Usage("install: cannot run commands here; use --dry-run and run them yourself");
894
- let code;
895
- try {
896
- code = await io.exec(step.command, step.args);
897
- }
898
- catch (e) {
899
- if (e.code === "ENOENT")
900
- throw new Usage(`install: ${step.command} was not found. Install it first, or use --dry-run and run the command yourself`);
901
- throw new Usage(`install: ${step.command} could not complete; not retried. Check its settings before running install again`);
902
- }
903
- if (code !== 0)
904
- throw new Usage(`install: ${step.command} exited with ${code}; not retried. Check its settings before running install again`);
905
- done.push(describeStep(step));
906
- continue;
907
- }
908
- if (!io.writeFile)
909
- throw new Usage("install: cannot write files here; use --dry-run");
910
- let existing;
911
- try {
912
- existing = await io.readFile(step.path);
913
- }
914
- catch (e) {
915
- if (e.code === "ENOENT")
916
- existing = null;
917
- else
918
- throw new Usage("install: cannot read the existing settings file; nothing was changed");
919
- }
920
- let next;
921
- try {
922
- const merged = step.kind === "json" ? mergeJson(existing, step.entry, force) : mergeYaml(existing, step.entry);
923
- if (merged === "unchanged") {
924
- done.push(`unchanged: ${step.path} already has this flovia entry`);
925
- continue;
926
- }
927
- next = merged;
928
- }
929
- catch (e) {
930
- if (e instanceof InstallRefusal)
931
- throw new Usage(e.message);
932
- throw e;
933
- }
934
- await io.writeFile(step.path, next);
935
- done.push(describeStep(step));
936
- }
937
- if (json)
938
- out(JSON.stringify({ ok: true, client: plan.client, auth: plan.auth, resource, dry_run: dry, done, next_steps: plan.next }, null, 2) + "\n");
939
- else
940
- 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");
941
- return 0;
942
- }
943
- /** Read-only: settings files, the key's readability, and with --network one unauthenticated /mcp request plus flovia_status with that key. */
944
- async function doctor(p, io, out, json, remember, o) {
945
- const client = str(p.flags.get("--client"));
946
- if (p.positional.length)
947
- throw new Usage(`Usage: flovia ${COMMANDS["doctor"]?.usage}`);
948
- if (client !== undefined && !INSTALL_CLIENTS.includes(client))
949
- throw new Usage(`doctor: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${didYouMean(client, [...INSTALL_CLIENTS])}`);
950
- const home = io.env["HOME"];
951
- if (!home)
952
- throw new Usage("doctor: HOME is not set");
953
- let base;
954
- try {
955
- base = new URL(o.baseUrl ?? "https://api.flovia.dev");
956
- }
957
- catch {
958
- throw new Usage("doctor: --base-url must be an https URL");
959
- }
960
- if (base.protocol !== "https:" || base.username || base.password)
961
- throw new Usage("doctor: --base-url must be an https URL without credentials");
962
- const resource = `${base.origin}/mcp`, network = p.flags.has("--network"), keyFlag = str(p.flags.get("--key-file"));
963
- const clients = client === undefined ? [...INSTALL_CLIENTS] : [client];
964
- const doFetch = io.fetch ?? fetch;
965
- /** One deadline includes fetch and body consumption/cancellation, even for injected transports. */
966
- const timed = async (request) => {
967
- const signal = AbortSignal.timeout((o.timeout ?? 300) * 1000);
968
- let abort = () => { };
969
- try {
970
- const deadline = new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); });
971
- return await Promise.race([request(signal), deadline]);
972
- }
973
- finally {
974
- signal.removeEventListener("abort", abort);
975
- }
976
- };
977
- let reachable;
978
- const reach = async () => {
979
- if (reachable)
980
- return reachable;
981
- try {
982
- const r = await timed(async (signal) => {
983
- const response = await doFetch(new Request(resource, { method: "GET", redirect: "error", signal, headers: { "X-Flovia-Client": "flovia-cli" } }));
984
- await response.body?.cancel().catch(() => undefined);
985
- return response;
986
- });
987
- reachable = r.status === 401 && /bearer/i.test(r.headers.get("www-authenticate") ?? "")
988
- ? { result: "ok", detail: `${resource} answers and asks for sign-in or a key` }
989
- : { result: "warn", detail: `${resource} answered HTTP ${r.status}, not the expected 401 with a sign-in challenge` };
990
- }
991
- catch {
992
- reachable = { result: "fail", detail: `${resource} could not be reached from this machine` };
993
- }
994
- return reachable;
995
- };
996
- /** A key is read only to check it; it goes into the scrub list first, so no line can show it. */
997
- const tryKey = async (k, r) => {
998
- remember(k);
999
- if (!network)
1000
- return;
1001
- // Same format as the Relay's issued-key schema; never send another service's credential to Flovia.
1002
- if (!/^flv_[A-Za-z0-9_-]{43}$/.test(k)) {
1003
- r.checks.push({ name: "key accepted", result: "warn", detail: "The configured value is not a Flovia key; it was not sent." });
1004
- return;
1005
- }
1006
- try {
1007
- await timed(async (signal) => {
1008
- const c = new FloviaClient({ apiKey: k, baseUrl: base.origin, ...(o.timeout ? { timeoutMs: o.timeout * 1000 } : {}),
1009
- fetch: (req) => { req.headers.set("X-Flovia-Client", "flovia-cli"); return doFetch(new Request(req, { signal })); }, onContractMismatch: () => undefined });
1010
- await c.status();
1011
- });
1012
- r.checks.push({ name: "key accepted", result: "ok", detail: "flovia_status answered with this key" });
1013
- }
1014
- catch (e) {
1015
- if (e instanceof FloviaError && (e.code === "unauthorized" || e.code === "key_disabled" || e.code === "key_stopped")) {
1016
- r.checks.push({ name: "key accepted", result: "fail", detail: `Flovia refused this key (${e.code})` });
1017
- r.next.push(`Issue or re-enable a key in Console (${CONSOLE}), save it, then restart ${r.client}.`);
1018
- }
1019
- else
1020
- r.checks.push({ name: "key accepted", result: "warn", detail: e instanceof FloviaError ? `flovia_status answered ${e.code}` : "flovia_status could not be reached" });
1021
- }
1022
- };
1023
- const reports = [];
1024
- for (const name of clients) {
1025
- const path = settingsPath(name, home);
1026
- let text = null;
1027
- if (path !== null) {
1028
- try {
1029
- text = await io.readFile(path);
1030
- }
1031
- catch (e) {
1032
- if (e.code !== "ENOENT") {
1033
- 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."] });
1034
- continue;
1035
- }
1036
- }
1037
- }
1038
- const r = inspect(name, text, resource, home, io.env, client !== undefined, keyFlag);
1039
- if (r.state === "ok" && r.auth === "key-file") {
1040
- const shown = keyFlag === undefined ? `~/${DEFAULT_KEY_FILE}` : "--key-file";
1041
- try {
1042
- const keyPath = keyFlag ?? `~/${DEFAULT_KEY_FILE}`;
1043
- const k = await fromFile(keyPath.startsWith("~/") ? `${home}/${keyPath.slice(2)}` : keyPath, io, shown);
1044
- r.checks.push({ name: "key", result: "ok", detail: `the key file (${shown}) is readable` });
1045
- await tryKey(k, r);
1046
- }
1047
- catch (e) {
1048
- if (!(e instanceof Usage))
1049
- throw e;
1050
- r.checks.push({ name: "key", result: "fail", detail: e.message });
1051
- 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).`);
1052
- }
1053
- }
1054
- if (r.state === "ok" && r.auth === "key-env" && r.keyEnv !== undefined) {
1055
- const k = io.env[r.keyEnv]?.trim();
1056
- if (k)
1057
- await tryKey(k, r);
1058
- }
1059
- if (network && r.auth !== "unknown" && (r.state === "ok" || r.state === "manual")) {
1060
- const n = await reach();
1061
- r.checks.push({ name: "network", ...n });
1062
- }
1063
- reports.push(settle(r));
1064
- }
1065
- if (json)
1066
- out(JSON.stringify({ ok: !reports.some((r) => r.state === "fail"), resource, network, clients: reports }, null, 2) + "\n");
1067
- else
1068
- out(renderDoctor(reports));
1069
- return reports.some((r) => r.state === "fail") ? 1 : 0;
1070
- }
1071
- /** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
1072
- export async function readStdin(input) {
1073
- const chunks = [];
1074
- for await (const chunk of input)
1075
- chunks.push(Buffer.from(chunk));
1076
- return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
1077
- }
1078
146
  /** Run only as the program (also through npm's bin symlink), not when imported. Node and Bun alike. */
1079
147
  const isMain = (() => { try {
1080
148
  return realpathSync(process.argv[1] ?? "") === realpathSync(fileURLToPath(import.meta.url));
@@ -1082,38 +150,5 @@ const isMain = (() => { try {
1082
150
  catch {
1083
151
  return false;
1084
152
  } })();
1085
- if (isMain) {
1086
- const tty = process.stdin.isTTY === true;
1087
- const confirm = async (q) => {
1088
- const rl = createInterface({ input: process.stdin, output: process.stderr });
1089
- try {
1090
- return /^y(es)?$/i.test((await rl.question(`${q} [y/N] `)).trim());
1091
- }
1092
- finally {
1093
- rl.close();
1094
- }
1095
- };
1096
- process.exitCode = await run(process.argv.slice(2), {
1097
- env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
1098
- writeOutput: writePrivateOutput,
1099
- exec: (command, args) => new Promise((resolve, reject) => {
1100
- // Adding settings needs no credential values or interactive sign-in. Child diagnostics may contain secrets.
1101
- const env = { ...process.env };
1102
- for (const name of ["FLOVIA_KEY", "FLOVIA_API_KEY", "FLOVIA_ACCESS_TOKEN"])
1103
- delete env[name];
1104
- const child = spawn(command, args, { stdio: "ignore", env });
1105
- child.once("error", reject);
1106
- child.once("exit", (code) => resolve(code ?? 1));
1107
- }),
1108
- writeFile: async (path, text) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, text, "utf8"); },
1109
- readFile: (path) => readFile(path, "utf8"), readCode: async (path) => new TextDecoder("utf-8", { fatal: true }).decode(await readFile(path)), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
1110
- confirm: tty ? confirm : null,
1111
- ...(process.stderr.isTTY ? { waiting: () => {
1112
- const start = Date.now();
1113
- process.stderr.write("\r\x1b[2KWaiting for Flovia.");
1114
- const timer = setInterval(() => process.stderr.write(`\r\x1b[2KWaiting for Flovia (${Math.floor((Date.now() - start) / 1000)}s elapsed).`), 5000);
1115
- timer.unref();
1116
- return () => { clearInterval(timer); process.stderr.write("\r\x1b[2K\n"); };
1117
- } } : {}),
1118
- });
1119
- }
153
+ if (isMain)
154
+ process.exitCode = await run(process.argv.slice(2), nodeIo());