@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.
Files changed (49) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +27 -14
  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 -993
  11. package/dist/client.d.ts +4 -5
  12. package/dist/client.js +29 -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 +20 -7
  48. package/dist/types.js +3 -2
  49. package/package.json +5 -2
@@ -0,0 +1,251 @@
1
+ import { INSTALL_AUTH, INSTALL_CLIENTS, InstallRefusal, mergeJson, mergeYaml, planInstall } from "./install.js";
2
+ import { inspect, settingsPath, yamlEntry } from "./doctor.js";
3
+ import { COMMANDS, Usage, didYouMean, mcpBase, str } from "./args.js";
4
+ const quoteArg = (a) => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replaceAll("'", "'\\''")}'`;
5
+ const describeStep = (s) => s.kind === "exec" ? `run: ${[s.command, ...s.args.map(quoteArg)].join(" ")}`
6
+ : `update: ${s.path} (add flovia to ${s.kind === "json" ? "mcpServers" : "mcp_servers"}, keeping other entries)`;
7
+ /** Removes only the flovia entry, at the scope install adds it to; every other MCP server is kept. */
8
+ const REMOVE_FLOVIA = {
9
+ "claude-code": { command: "claude", args: ["mcp", "remove", "--scope", "user", "flovia"] },
10
+ codex: { command: "codex", args: ["mcp", "remove", "flovia"] },
11
+ };
12
+ /** The keys install writes for flovia; any other key (Codex's `enabled = false`, custom headers, a timeout) is a different entry. */
13
+ const OWN_KEYS = {
14
+ "claude-code": { oauth: ["type", "url"], key: ["type", "url", "headersHelper"] },
15
+ codex: { oauth: ["url"], key: ["url", "bearer_token_env_var"] },
16
+ };
17
+ /** Only the keys install itself writes, with Codex's `enabled` allowed as true. Line-based for Codex, like doctor's reader. */
18
+ function onlyOwnKeys(client, auth, text) {
19
+ const own = OWN_KEYS[client]?.[auth] ?? [];
20
+ if (client === "claude-code") {
21
+ const e = JSON.parse(text).mcpServers["flovia"] ?? {};
22
+ return Object.keys(e).every((k) => own.includes(k)) && (e["type"] === undefined || e["type"] === "http");
23
+ }
24
+ let inside = false;
25
+ for (const raw of text.split(/\r?\n/)) {
26
+ const line = raw.replace(/\s+#.*$/, "").trim();
27
+ if (line === "" || line.startsWith("#"))
28
+ continue;
29
+ // A sub-table such as [mcp_servers.flovia.http_headers] is configuration install did not write.
30
+ if (line.startsWith("[")) {
31
+ if (/^\[\s*mcp_servers\.(?:flovia|"flovia")\s*\.\s*/.test(line))
32
+ return false;
33
+ inside = /^\[\s*mcp_servers\.(?:flovia|"flovia")\s*\]$/.test(line);
34
+ continue;
35
+ }
36
+ if (!inside)
37
+ continue;
38
+ const key = /^"?([A-Za-z_][\w-]*)"?\s*=\s*(.*)$/.exec(line);
39
+ if (!key)
40
+ return false;
41
+ if (key[1] === "enabled" ? key[2] !== "true" : !own.includes(key[1]))
42
+ return false;
43
+ }
44
+ return true;
45
+ }
46
+ /**
47
+ * Whether Codex's config.toml may name a flovia server in a form doctor's reader does not follow: a dotted key or inline table
48
+ * (mcp_servers.flovia = {…}, flovia = {…} under [mcp_servers]), spacing or a literal string in the header, or a quoted key with an
49
+ * escape (Codex reads "fl\u006fvia" as flovia). Only the mcp_servers part counts: a project path with flovia in it is not a server.
50
+ */
51
+ function codexMayHaveFlovia(text) {
52
+ let section = null;
53
+ const servers = /^\s*["']?mcp_servers["']?\s*(\.|$)/;
54
+ for (const raw of text.split(/\r?\n/)) {
55
+ const line = raw.trim();
56
+ if (line === "" || line.startsWith("#"))
57
+ continue;
58
+ const header = /^\[\[?(.*?)\]\]?\s*(#.*)?$/.exec(line);
59
+ if (header) {
60
+ section = header[1].trim();
61
+ if (servers.test(section) && /flovia|\\/.test(section))
62
+ return true;
63
+ continue;
64
+ }
65
+ const key = line.split("=")[0];
66
+ // mcp_servers = { flovia = {…} } at the root: the servers are in the value, and one spread over lines is not followed.
67
+ if (section === null && /^\s*["']?mcp_servers["']?\s*$/.test(key)) {
68
+ if (/flovia|\\/.test(line) || !line.includes("}"))
69
+ return true;
70
+ continue;
71
+ }
72
+ const inScope = section === null ? servers.test(key) : /^["']?mcp_servers["']?$/.test(section);
73
+ if (inScope && /flovia|\\/.test(key))
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+ /**
79
+ * The client's current flovia entry against the plan, read from the settings the client itself will use.
80
+ * "unknown" when that cannot be told: the settings cannot be read or parsed, or mention
81
+ * flovia in a form doctor's reader does not follow. It never counts as "none": Codex's `mcp add` replaces an existing name.
82
+ */
83
+ async function existingEntry(plan, io, home, resource, keyFile) {
84
+ const path = settingsPath(plan.client, home, io.env);
85
+ if (path === null)
86
+ return "none";
87
+ let text;
88
+ try {
89
+ text = await io.readFile(path);
90
+ }
91
+ catch (e) {
92
+ return e.code === "ENOENT" ? "none" : "unknown";
93
+ }
94
+ const r = inspect(plan.client, text, resource, home, io.env, true, keyFile);
95
+ if (r.auth === null) {
96
+ if (r.checks.some((c) => c.name === "settings" && c.detail.includes("not valid")))
97
+ return "unknown";
98
+ // Codex also reads dotted keys and inline tables (mcp_servers.flovia = {…}); a flovia the reader missed is not "none".
99
+ return plan.client === "codex" && codexMayHaveFlovia(text) ? "unknown" : "none";
100
+ }
101
+ const url = r.checks.find((c) => c.name === "url")?.result === "ok";
102
+ const auth = plan.auth === "oauth" ? r.auth === "oauth"
103
+ : plan.client === "claude-code" ? r.auth === "key-file" : r.auth === "key-env" && r.keyEnv === "FLOVIA_KEY";
104
+ return url && auth && onlyOwnKeys(plan.client, plan.auth, text) ? "same" : "different";
105
+ }
106
+ /** No network and no key text: for Claude Code's key mode only the key file's readability is checked. */
107
+ export async function install(p, io, out, err, json, timeout, fromFile) {
108
+ const client = str(p.flags.get("--client")), auth = str(p.flags.get("--auth")) ?? "oauth";
109
+ if (p.positional.length)
110
+ throw new Usage(`Usage: flovia ${COMMANDS["install"]?.usage}`);
111
+ if (client === undefined || !INSTALL_CLIENTS.includes(client))
112
+ throw new Usage(`install: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${client === undefined ? "" : didYouMean(client, [...INSTALL_CLIENTS])}`);
113
+ if (!INSTALL_AUTH.includes(auth))
114
+ throw new Usage("install: --auth must be oauth or key");
115
+ const home = io.env["HOME"];
116
+ if (!home)
117
+ throw new Usage("install: HOME is not set");
118
+ const base = mcpBase(str(p.flags.get("--base-url")), "install");
119
+ const resource = `${base.origin}/mcp`, keyFile = str(p.flags.get("--key-file"));
120
+ let plan;
121
+ try {
122
+ plan = planInstall({ client: client, auth: auth, resource, home, ...(keyFile ? { keyPath: keyFile } : {}) });
123
+ }
124
+ catch (e) {
125
+ if (e instanceof InstallRefusal)
126
+ throw new Usage(e.message);
127
+ throw e;
128
+ }
129
+ const dry = p.flags.has("--dry-run"), force = p.flags.has("--force"), done = [];
130
+ if (plan.client === "claude-code" && plan.auth === "key") {
131
+ const path = keyFile ?? "~/.config/flovia/key";
132
+ await fromFile(path.startsWith("~/") ? `${home}/${path.slice(2)}` : path, io, keyFile === undefined ? "~/.config/flovia/key" : "--key-file");
133
+ }
134
+ if (plan.client === "codex" && plan.auth === "key" && !io.env["FLOVIA_KEY"]?.trim())
135
+ err("warning: FLOVIA_KEY is not set in this shell; Codex needs it where it starts\n");
136
+ if (plan.client === "cursor" && plan.auth === "key" && !io.env["FLOVIA_API_KEY"]?.trim())
137
+ err("warning: FLOVIA_API_KEY is not set in this shell; Cursor needs it where it starts\n");
138
+ // A client's CLI may wait for browser sign-in (Codex 0.77.0+ in `codex mcp add`), so every run has a limit.
139
+ const limit = timeout ?? 300;
140
+ const runExec = async (step, failed) => {
141
+ if (!io.exec)
142
+ throw new Usage("install: cannot run commands here; use --dry-run and run them yourself");
143
+ let code;
144
+ try {
145
+ code = await io.exec(step.command, step.args, { timeoutMs: limit * 1000, showOutput: step.signIn === true });
146
+ }
147
+ catch (e) {
148
+ if (e.code === "ENOENT")
149
+ throw new Usage(`install: ${step.command} was not found. Install it first, or use --dry-run and run the command yourself`);
150
+ throw new Usage(`install: ${step.command} could not complete; not retried. ${failed}`);
151
+ }
152
+ if (code === "timeout") {
153
+ if (step.signIn)
154
+ return "timeout";
155
+ throw new Usage(`install: ${step.command} did not finish within ${limit} seconds and was stopped; not retried. ${failed}`);
156
+ }
157
+ if (code !== 0)
158
+ throw new Usage(`install: ${step.command} exited with ${code}; not retried. ${failed}`);
159
+ return undefined;
160
+ };
161
+ for (const step of plan.steps) {
162
+ if (step.kind === "exec") {
163
+ // claude refuses to add a name it already has; codex's add replaces it. Their output is shown only while Codex signs in.
164
+ // So read the entry first: the same one is left alone; a different one is replaced only with --force.
165
+ const remove = REMOVE_FLOVIA[plan.client];
166
+ const removeText = remove ? [remove.command, ...remove.args].join(" ") : "";
167
+ const existing = remove ? await existingEntry(plan, io, home, resource, keyFile) : "none";
168
+ if (existing === "same") {
169
+ done.push(`unchanged: ${plan.client} already has this flovia entry`);
170
+ continue;
171
+ }
172
+ if (existing === "different" && !force)
173
+ throw new Usage(`install: ${plan.client} already has a different flovia entry; nothing was changed. Remove it with: ${removeText}, then run install again (or rerun with --force to replace it)`);
174
+ // Codex would replace an entry install could not read; Claude Code refuses a duplicate itself, but --force must not remove blindly.
175
+ if (existing === "unknown" && (plan.client === "codex" || force))
176
+ throw new Usage(`install: cannot tell which flovia entry ${plan.client} uses; nothing was changed. Its settings: ${settingsPath(plan.client, home, io.env)}. Check it with ${plan.client === "codex" ? "codex mcp list" : "claude mcp list"}; if flovia is there, remove it with: ${removeText}, then run install again`);
177
+ // Codex's add updates the entry in place, so only Claude Code removes first.
178
+ const removeFirst = existing === "different" && plan.client === "claude-code" && remove !== undefined;
179
+ if (dry) {
180
+ if (removeFirst)
181
+ done.push(`would ${describeStep({ kind: "exec", ...remove })}`);
182
+ done.push(`would ${describeStep(step)}`);
183
+ continue;
184
+ }
185
+ if (removeFirst) {
186
+ await runExec(remove, "Nothing was added; check its settings before running install again");
187
+ done.push(describeStep({ kind: "exec", ...remove }));
188
+ }
189
+ // The retry keeps the same target and key file, so it does not fall back to production or the default key file.
190
+ const again = ["flovia", "install", "--client", plan.client, ...(plan.auth === "key" ? ["--auth", "key"] : []),
191
+ ...(p.flags.has("--base-url") ? ["--base-url", str(p.flags.get("--base-url")) ?? ""] : []), ...(keyFile ? ["--key-file", keyFile] : [])].map(quoteArg).join(" ");
192
+ if (step.signIn) {
193
+ // Said before the wait, so an agent that stops the command still has the next step (discovery 2026-11-19 ②).
194
+ err([`Adding flovia to ${plan.client}. Codex 0.77.0 and later then start sign-in: Codex's output, with the sign-in URL, follows.`,
195
+ `Waiting for sign-in in your browser (up to ${limit} seconds; set it with --timeout SECONDS). Sign in and approve Flovia; do not stop this command until it finishes.`,
196
+ `If this command is stopped or times out, sign in again with: codex mcp login flovia, then check with: flovia doctor --client codex`].join("\n") + "\n");
197
+ }
198
+ const result = await runExec(step, removeFirst
199
+ ? `The previous flovia entry was already removed, so ${plan.client} has no flovia now. Fix the problem, then run: ${again}`
200
+ : remove ? `If ${plan.client} already has a flovia entry, remove it with: ${removeText}, then run install again`
201
+ : "Check its settings before running install again");
202
+ if (result === "timeout") {
203
+ const meaning = `install: sign-in did not finish within ${limit} seconds, so ${step.command} was stopped. The flovia entry may already be added. Sign in again with: codex mcp login flovia (keep it running until the browser says you are signed in), then check with: flovia doctor --client codex`;
204
+ err(`${meaning}\n`);
205
+ if (json)
206
+ out(JSON.stringify({ ok: false, code: "sign_in_timeout", meaning, next_step: "codex mcp login flovia" }, null, 2) + "\n");
207
+ return 1;
208
+ }
209
+ done.push(describeStep(step));
210
+ continue;
211
+ }
212
+ // --dry-run merges too, so it refuses exactly what the real run would refuse (discovery 23).
213
+ let existing;
214
+ try {
215
+ existing = await io.readFile(step.path);
216
+ }
217
+ catch (e) {
218
+ if (e.code === "ENOENT")
219
+ existing = null;
220
+ else
221
+ throw new Usage("install: cannot read the existing settings file; nothing was changed");
222
+ }
223
+ let next;
224
+ try {
225
+ const merged = step.kind === "json" ? mergeJson(existing, step.entry, force) : mergeYaml(existing, step.entry, yamlEntry);
226
+ if (merged === "unchanged") {
227
+ done.push(`unchanged: ${step.path} already has this flovia entry`);
228
+ continue;
229
+ }
230
+ next = merged;
231
+ }
232
+ catch (e) {
233
+ if (e instanceof InstallRefusal)
234
+ throw new Usage(e.message);
235
+ throw e;
236
+ }
237
+ if (dry) {
238
+ done.push(`would ${describeStep(step)}`);
239
+ continue;
240
+ }
241
+ if (!io.writeFile)
242
+ throw new Usage("install: cannot write files here; use --dry-run");
243
+ await io.writeFile(step.path, next);
244
+ done.push(describeStep(step));
245
+ }
246
+ if (json)
247
+ out(JSON.stringify({ ok: true, client: plan.client, auth: plan.auth, resource, dry_run: dry, done, next_steps: plan.next }, null, 2) + "\n");
248
+ else
249
+ 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");
250
+ return 0;
251
+ }
@@ -0,0 +1,6 @@
1
+ import { type Parsed } from "./args.js";
2
+ import type { Io } from "./cli.js";
3
+ /** 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. */
4
+ export declare function readKey(p: Parsed, io: Io): Promise<string>;
5
+ export declare const DEFAULT_KEY_FILE = ".config/flovia/key";
6
+ export declare function fromFile(file: string, io: Io, label: string): Promise<string>;
@@ -0,0 +1,33 @@
1
+ import { CONSOLE } from "./output.js";
2
+ import { Usage, str } from "./args.js";
3
+ /** 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. */
4
+ export async function readKey(p, io) {
5
+ const file = str(p.flags.get("--key-file"));
6
+ if (file !== undefined)
7
+ return fromFile(file, io, "--key-file");
8
+ const key = io.env["FLOVIA_KEY"]?.trim();
9
+ if (key)
10
+ return key;
11
+ const home = io.env["HOME"];
12
+ if (home && await io.readFile(`${home}/${DEFAULT_KEY_FILE}`).then(() => true, () => false))
13
+ return fromFile(`${home}/${DEFAULT_KEY_FILE}`, io, `~/${DEFAULT_KEY_FILE}`);
14
+ 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>`);
15
+ }
16
+ export const DEFAULT_KEY_FILE = ".config/flovia/key";
17
+ export async function fromFile(file, io, label) {
18
+ let text;
19
+ // Never echo a user-given path: a key pasted in its place would land in the output.
20
+ try {
21
+ text = await io.readFile(file);
22
+ }
23
+ catch {
24
+ throw new Usage(`${label}: cannot read the key file`);
25
+ }
26
+ const key = text.trim();
27
+ if (key === "")
28
+ throw new Usage(`${label}: the key file is empty`);
29
+ const mode = await io.fileMode?.(file).catch(() => null);
30
+ if (typeof mode === "number" && (mode & 0o077) !== 0)
31
+ io.err(`warning: the key file is readable by other users (mode ${(mode & 0o777).toString(8)}); run chmod 600 on it\n`);
32
+ return key;
33
+ }
@@ -0,0 +1,7 @@
1
+ import type { Io } from "./cli.js";
2
+ /** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
3
+ export declare function writePrivateOutput(path: string, data: Uint8Array): Promise<void>;
4
+ /** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
5
+ export declare function readStdin(input: NodeJS.ReadableStream): Promise<string>;
6
+ /** The real process's I/O for the program run (cli.ts calls it only as the program, never on import). */
7
+ export declare function nodeIo(): Io;
package/dist/nodeio.js ADDED
@@ -0,0 +1,62 @@
1
+ import { mkdir, open, readFile, stat, writeFile } from "node:fs/promises";
2
+ import { spawn } from "node:child_process";
3
+ import { dirname } from "node:path";
4
+ import { createInterface } from "node:readline/promises";
5
+ /** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
6
+ export async function writePrivateOutput(path, data) {
7
+ const file = await open(path, "wx", 0o600);
8
+ try {
9
+ await file.writeFile(data);
10
+ await file.sync();
11
+ }
12
+ finally {
13
+ await file.close();
14
+ }
15
+ }
16
+ /** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
17
+ export async function readStdin(input) {
18
+ const chunks = [];
19
+ for await (const chunk of input)
20
+ chunks.push(Buffer.from(chunk));
21
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
22
+ }
23
+ /** The real process's I/O for the program run (cli.ts calls it only as the program, never on import). */
24
+ export function nodeIo() {
25
+ const tty = process.stdin.isTTY === true;
26
+ const confirm = async (q) => {
27
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
28
+ try {
29
+ return /^y(es)?$/i.test((await rl.question(`${q} [y/N] `)).trim());
30
+ }
31
+ finally {
32
+ rl.close();
33
+ }
34
+ };
35
+ return {
36
+ env: process.env, out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s),
37
+ writeOutput: writePrivateOutput,
38
+ exec: (command, args, o) => new Promise((resolve, reject) => {
39
+ // The child never gets a Flovia key. Its output is shown only for sign-in (the URL to open), and on stderr so stdout stays ours.
40
+ const env = { ...process.env };
41
+ for (const name of ["FLOVIA_KEY", "FLOVIA_API_KEY", "FLOVIA_ACCESS_TOKEN"])
42
+ delete env[name];
43
+ const child = spawn(command, args, { stdio: o?.showOutput ? ["ignore", "pipe", "pipe"] : "ignore", env });
44
+ child.stdout?.on("data", (d) => process.stderr.write(d));
45
+ child.stderr?.on("data", (d) => process.stderr.write(d));
46
+ let timedOut = false;
47
+ const timer = o?.timeoutMs ? setTimeout(() => { timedOut = true; child.kill("SIGTERM"); }, o.timeoutMs) : undefined;
48
+ child.once("error", (e) => { clearTimeout(timer); reject(e); });
49
+ child.once("exit", (code) => { clearTimeout(timer); resolve(timedOut ? "timeout" : code ?? 1); });
50
+ }),
51
+ writeFile: async (path, text) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, text, "utf8"); },
52
+ 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),
53
+ confirm: tty ? confirm : null,
54
+ ...(process.stderr.isTTY ? { waiting: () => {
55
+ const start = Date.now();
56
+ process.stderr.write("\r\x1b[2KWaiting for Flovia.");
57
+ const timer = setInterval(() => process.stderr.write(`\r\x1b[2KWaiting for Flovia (${Math.floor((Date.now() - start) / 1000)}s elapsed).`), 5000);
58
+ timer.unref();
59
+ return () => { clearInterval(timer); process.stderr.write("\r\x1b[2K\n"); };
60
+ } } : {}),
61
+ };
62
+ }
@@ -0,0 +1,26 @@
1
+ import type { BankedResets, ConsentState, FloviaError, StatusReply, UsageTodayReply, SandboxResultReply, SandboxRunsReply, SandboxSchedulesReply, WorkspaceListReply, WorkspaceReadReply } from "./index.js";
2
+ export declare const CONSOLE = "https://console.flovia.dev/groupbuy/";
3
+ /** "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. */
4
+ export declare function when(v: unknown, now?: number): string;
5
+ export declare const obj: (v: unknown) => Record<string, unknown>;
6
+ /** Wrap prose only, never prompts, answers, consent notices, JSON or copyable commands. */
7
+ export declare const prose: (text: string) => string;
8
+ /** Status labels share one column; the longest is "purchased balance". */
9
+ export declare const label: (name: string) => string;
10
+ export declare function renderStatus(s: StatusReply, expected: string | null, now?: number): string;
11
+ export declare function renderUsage(u: UsageTodayReply, today?: boolean, now?: number): string;
12
+ export declare function renderResets(r: BankedResets, s: StatusReply, now?: number): string;
13
+ export declare function renderConsent(c: ConsentState): string;
14
+ /**
15
+ * 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
16
+ * the rest) and control characters are removed; only newline and tab stay. --json output is not passed through here.
17
+ */
18
+ export declare const plain: (s: string) => string;
19
+ export declare function renderSandboxRuns(r: SandboxRunsReply, now?: number): string;
20
+ /** stdout is the user's own code's output, printed without control characters (plain); the status lines go after it. */
21
+ export declare function renderSandboxResult(r: SandboxResultReply, now?: number): string;
22
+ export declare function renderSandboxSchedules(r: SandboxSchedulesReply, now?: number): string;
23
+ export declare function renderWorkspace(r: WorkspaceListReply, now?: number): string;
24
+ export declare function renderWorkspaceRead(r: WorkspaceReadReply, now?: number): string;
25
+ /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
26
+ export declare function renderError(e: FloviaError): string;
package/dist/output.js ADDED
@@ -0,0 +1,196 @@
1
+ export const CONSOLE = "https://console.flovia.dev/groupbuy/";
2
+ const pct = (v) => typeof v === "number" ? `${v}%` : "-";
3
+ const table = (rows) => {
4
+ const widths = rows[0]?.map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length))) ?? [];
5
+ return rows.map((r) => r.map((c, i) => i === r.length - 1 ? c : c.padEnd(widths[i] ?? 0)).join(" ")).join("\n") + "\n";
6
+ };
7
+ /** "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. */
8
+ export function when(v, now = Date.now()) {
9
+ const d = new Date(String(v));
10
+ if (v === null || v === undefined || Number.isNaN(d.getTime()))
11
+ return String(v);
12
+ const [, day, mon, year, hm] = d.toUTCString().split(" ");
13
+ return `${mon} ${day}${d.getUTCFullYear() === new Date(now).getUTCFullYear() ? "" : ` ${year}`} ${hm?.slice(0, 5)} UTC`;
14
+ }
15
+ export const obj = (v) => v !== null && typeof v === "object" ? v : {};
16
+ /** Wrap prose only, never prompts, answers, consent notices, JSON or copyable commands. */
17
+ export const prose = (text) => (text.match(/.{1,76}(?:\s|$)|\S+/g) ?? []).map((line) => line.trim()).join("\n ");
18
+ /** Status labels share one column; the longest is "purchased balance". */
19
+ export const label = (name) => name.padEnd(19);
20
+ export function renderStatus(s, expected, now = Date.now()) {
21
+ const lines = ["Connection: OK", `Flovia ${s.stage}, contract ${s.contract_version}`];
22
+ if (expected !== null)
23
+ lines.push(`warning: this CLI expects ${expected}`, "Connection succeeded; check recent updates before making calls.");
24
+ const stopped = obj(s["stopped"]), consent = obj(s["data_consent"]);
25
+ if (stopped["message"])
26
+ lines.push(`key stopped: ${String(stopped["message"])}`);
27
+ if (obj(s["consent"])["sharing"] === "withdrawn")
28
+ lines.push("New usage: stopped (sharing withdrawn).");
29
+ else if (consent["needed"] === true)
30
+ lines.push("New usage: waits for your own y/n to the current data consent.");
31
+ else if (consent["answer"] === "n")
32
+ lines.push("New usage: stopped (sharing declined). Your choice is saved.");
33
+ else if (consent["answer"] === "y")
34
+ lines.push("Data consent: accepted. Service and allowance limits still apply.");
35
+ else
36
+ lines.push("Data consent: not reported (see --json).");
37
+ for (const [name, w] of [["free 5-hour", s.five_hour], ["free week", s.week]])
38
+ lines.push(`${label(name)}${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : name === "free 5-hour" ? ", not started" : ""}`);
39
+ lines.push(`${label("purchased balance")}${String(s["purchased_balance_display"] ?? "-")}`);
40
+ // An older relay, or an account with no capped key, omits api_key_caps; nothing is shown then.
41
+ for (const c of Array.isArray(s["api_key_caps"]) ? s["api_key_caps"] : [])
42
+ 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"])}`}`);
43
+ // An older relay omits spend_mode; nothing is shown then.
44
+ if (typeof s["spend_mode"] === "string")
45
+ lines.push(`${label("spend mode")}${String(s["spend_mode"]).startsWith("free_only") ? "free-only (purchased balance and plan credit are never used)" : "allow-paid"}`);
46
+ // An older relay omits banked_resets; nothing is shown then.
47
+ const banked = obj(s["banked_resets"]), n = banked["available"];
48
+ if (typeof n === "number" && n > 0)
49
+ lines.push(`You have ${n} saved reset${n === 1 ? "" : "s"} (until ${String(banked["next_expires_at"]).slice(0, 10)}). Run: flovia resets`);
50
+ const pending = obj(s["free_pending"]);
51
+ if (pending["next_step"])
52
+ lines.push(`free allowance not started: ${String(pending["next_step"])}`);
53
+ 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)}` : ""}`; });
54
+ lines.push(`${label("services")}(provider state)`, ...services.map((v) => ` ${v}`));
55
+ lines.push(`${label("turned off")}${s.services_off.length ? s.services_off.join(", ") : "none"}`);
56
+ const updates = Array.isArray(s["recent_updates"]) ? s["recent_updates"] : [];
57
+ for (const u of updates.slice(0, 2)) {
58
+ const x = obj(u), first = Array.isArray(x["lines"]) ? String(x["lines"][0] ?? "") : "";
59
+ lines.push(prose(`update ${String(x["version"])} (${String(x["date"])}): ${first}`));
60
+ }
61
+ if (updates.length > 2)
62
+ lines.push(`+${updates.length - 2} more (--json)`);
63
+ return lines.join("\n") + "\n";
64
+ }
65
+ export function renderUsage(u, today = false, now = Date.now()) {
66
+ const lines = [`since ${when(u["since"], now)} until ${when(u["until"], now)}${today ? " (today, UTC; use --days 7 for the week)" : ""}`];
67
+ const week = obj(u["free_week"]);
68
+ lines.push(`free allowance this week: ${pct(week["used_pct"])} used${week["resets_at"] ? `, resets ${when(week["resets_at"], now)}` : ""}`);
69
+ 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"}`);
70
+ lines.push(`purchased balance used: ${String(obj(u["total"])["bought_display"] ?? "-")} total (includes generations)`);
71
+ // Endpoint percentages are rounded (0 can mean <1%); only counts can be summed by source.
72
+ const bySource = new Map();
73
+ for (const e of Array.isArray(u["by_endpoint"]) ? u["by_endpoint"] : []) {
74
+ const x = obj(e), name = String(x["provider"]);
75
+ if (x["endpoint"] === "generation")
76
+ continue; // generations are listed below, not as lookups (#2824)
77
+ bySource.set(name, (bySource.get(name) ?? 0) + Number(x["count"] ?? 0));
78
+ }
79
+ if (bySource.size)
80
+ lines.push("", table([["source", "lookups"], ...[...bySource].map(([n, count]) => [n, String(count)])]).trimEnd());
81
+ const g = obj(u["generations"]);
82
+ 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)`);
83
+ for (const [field, name, states] of [
84
+ ["gemini_generations", "Gemini text generations", ["completed", "incomplete", "unknown"]],
85
+ ["minimax_generations", "MiniMax text generations", ["completed", "incomplete", "unknown"]],
86
+ ["runway_generations", "Runway jobs", ["completed", "failed", "unknown", "reserved", "submitted"]],
87
+ ]) {
88
+ if (u[field] === undefined || u[field] === null)
89
+ continue;
90
+ const summary = obj(u[field]);
91
+ const counts = states.map(state => `${state} ${String(summary[state] ?? "-")}`).join(", ");
92
+ lines.push("", `${name}: ${String(summary["operations"] ?? "-")} (${counts}), ${String(summary["free_display"] ?? "-")} of the weekly free allowance, purchased ${String(summary["bought_display"] ?? "-")} (included in total)`);
93
+ }
94
+ if (u.has_more)
95
+ 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)}`);
96
+ return lines.join("\n") + "\n";
97
+ }
98
+ export function renderResets(r, s, now = Date.now()) {
99
+ const lines = [`${label("saved resets")}${r.available}`];
100
+ if (r.next)
101
+ lines.push(`${label("next to expire")}id ${r.next.id}, expires ${when(r.next.expires_at, now)}`);
102
+ for (const [name, w] of [["free 5-hour", s.five_hour], ["free week", s.week]])
103
+ lines.push(`${label(name)}${pct(w?.used_pct)} used${w?.resets_at ? `, resets ${when(w.resets_at, now)}` : ""}`);
104
+ if (r.resets)
105
+ for (const reset of r.resets)
106
+ 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`);
107
+ else if (r.next)
108
+ 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`);
109
+ return lines.join("\n") + "\n";
110
+ }
111
+ export function renderConsent(c) {
112
+ const lines = [`${label("current notice")}${c.version}`, `${label("your yes")}${c.answered_version ?? "none"}`];
113
+ if (!c.needed && !c.updated)
114
+ return lines.join("\n") + "\n";
115
+ if (c.updated)
116
+ 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.");
117
+ lines.push("", "Notice:", c.notice);
118
+ lines.push("", `To answer yes yourself: flovia consent accept ${c.version} --yes (or in Console: ${CONSOLE})`);
119
+ return lines.join("\n") + "\n";
120
+ }
121
+ const ESC = String.fromCharCode(0x1b), BEL = String.fromCharCode(0x07), ST = String.fromCharCode(0x9c), OSC = String.fromCharCode(0x9d), CSI = String.fromCharCode(0x9b);
122
+ const ESCAPES = [new RegExp(`(?:${ESC}\\]|${OSC})[\\s\\S]*?(?:${BEL}|${ESC}\\\\|${ST})`, "g"), new RegExp(`(?:${ESC}\\[|${CSI})[0-?]*[ -/]*[@-~]`, "g"), new RegExp(`${ESC}[ -/]*[0-~]`, "g")];
123
+ /**
124
+ * 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
125
+ * the rest) and control characters are removed; only newline and tab stay. --json output is not passed through here.
126
+ */
127
+ export const plain = (s) => ESCAPES.reduce((t, re) => t.replace(re, ""), s).replace(/[^\P{Cc}\n\t]/gu, "");
128
+ export function renderSandboxRuns(r, now = Date.now()) {
129
+ if (!r.runs.length)
130
+ return "No code runs are kept for this account.\n";
131
+ 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";
132
+ }
133
+ /** stdout is the user's own code's output, printed without control characters (plain); the status lines go after it. */
134
+ export function renderSandboxResult(r, now = Date.now()) {
135
+ const ended = r.status !== "queued" && r.status !== "running";
136
+ const lines = [...(typeof r.stdout === "string" && r.stdout !== "" ? [r.stdout.replace(/\n$/, ""), ""] : []),
137
+ `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" : ""}`,
138
+ `executed: ${r.executed}`];
139
+ if (!ended)
140
+ lines.push(`Not finished yet. Wait for it: flovia sandbox result ${r.run_id} --wait`);
141
+ else
142
+ lines.push(`kept until ${when(r.expires_at, now)}`);
143
+ lines.push(String(r.user_notice));
144
+ return plain(lines.join("\n")) + "\n";
145
+ }
146
+ export function renderSandboxSchedules(r, now = Date.now()) {
147
+ if (!r.schedules.length)
148
+ return "No schedules.\n";
149
+ return plain(table([["schedule_id", "cron", "tz", "status", "next run", "team", "label"], ...r.schedules.map((x) => [x.schedule_id, x.cron, x.tz,
150
+ 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 ?? ""])]));
151
+ }
152
+ export function renderWorkspace(r, now = Date.now()) {
153
+ if (!r.team_tasks.length)
154
+ return plain(`No Team tasks.\n${String(r.user_notice)}`) + "\n";
155
+ 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,
156
+ x.paused_reason ? `${x.status} (${x.paused_reason})` : x.status, x.next_run_at === null ? "-" : when(x.next_run_at, now),
157
+ 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 ?? ""])])
158
+ + `Result: flovia workspace read <schedule-id>\n${String(r.user_notice)}`) + "\n";
159
+ }
160
+ export function renderWorkspaceRead(r, now = Date.now()) {
161
+ 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}`];
162
+ if (r.run_id === null)
163
+ lines.push("No shared run yet.");
164
+ else
165
+ 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)}`] : []));
166
+ lines.push(String(r.user_notice));
167
+ return plain(lines.join("\n")) + "\n";
168
+ }
169
+ /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
170
+ export function renderError(e) {
171
+ const lines = [`error: ${e.code}: ${e.message}`];
172
+ if (e.nextStep)
173
+ lines.push(`next_step: ${e.nextStep}`);
174
+ if (e.code === "unauthorized")
175
+ lines.push("After you save a current key, check it: flovia status --key-file <saved-key-file>");
176
+ lines.push(`executed: ${e.executed}`);
177
+ if (e.retryAfterSeconds !== null)
178
+ lines.push(`retry_after_seconds: ${e.retryAfterSeconds}`);
179
+ if (e.operationId)
180
+ lines.push(`operation_id: ${e.operationId}${e.executed === "unknown" ? " (keep this id; never send the request again under a new one)" : ""}`);
181
+ const reply = obj(e.reply);
182
+ if (e.code === "notice_first" || e.code === "data_consent_needed") {
183
+ const notice = reply["user_notice"] || reply["notice"];
184
+ if (notice)
185
+ lines.push("", "Notice:", String(notice));
186
+ const consent = obj(reply["consent"]), question = consent["question"] || (e.code === "data_consent_needed" ? consent["line"] : undefined);
187
+ if (question)
188
+ lines.push("", `Your choice: ${String(question)}`);
189
+ if (e.code === "data_consent_needed") {
190
+ lines.push("", "Only the user can consent; the CLI does not answer for them.");
191
+ }
192
+ else
193
+ lines.push("", "Follow next_step. The CLI does not opt in for the user.");
194
+ }
195
+ return lines.join("\n") + "\n";
196
+ }
@@ -0,0 +1,9 @@
1
+ import type { FloviaError } from "./errors.js";
2
+ export declare const SAME_OPERATION = "Resend with the same operation_id; do not use a new one.";
3
+ /** A lost or unreadable reply cannot prove that the operation did not run. */
4
+ export declare function readReply(r: Response, operationId: string | null, makeError: (init: ConstructorParameters<typeof FloviaError>[0]) => FloviaError, sse?: boolean): Promise<Record<string, unknown>>;
5
+ /** The relay's own next step on a refused account request (explanation.next_step), when it sent one. */
6
+ export declare const relayNextStep: (body: Record<string, unknown>) => string | null;
7
+ /** The output_text parts of output[].content[], in order. */
8
+ export declare function outputText(body: Record<string, unknown>): string;
9
+ export declare const seconds: (v: unknown) => number | null;
package/dist/reply.js ADDED
@@ -0,0 +1,36 @@
1
+ export const SAME_OPERATION = "Resend with the same operation_id; do not use a new one.";
2
+ /** A lost or unreadable reply cannot prove that the operation did not run. */
3
+ export async function readReply(r, operationId, makeError, sse = false) {
4
+ try {
5
+ const text = (await r.text()).trimStart();
6
+ const payload = sse && !text.startsWith("{") ? text.split(/\r?\n/).filter((l) => l.startsWith("data:"))
7
+ .map((l) => l.slice(5).replace(/^ /, "")).join("\n") : text;
8
+ const body = JSON.parse(payload);
9
+ if (body === null || typeof body !== "object" || Array.isArray(body))
10
+ throw new Error("invalid reply");
11
+ return body;
12
+ }
13
+ catch (cause) {
14
+ const timeout = cause instanceof Error && cause.name === "TimeoutError";
15
+ throw makeError({ code: timeout ? "timeout" : `http_${r.status}`, status: r.status, executed: "unknown", operationId,
16
+ message: timeout ? "Timed out while reading the reply." : `Unexpected reply (HTTP ${r.status}).`, nextStep: operationId ? SAME_OPERATION : null });
17
+ }
18
+ }
19
+ /** The relay's own next step on a refused account request (explanation.next_step), when it sent one. */
20
+ export const relayNextStep = (body) => {
21
+ const e = body["explanation"];
22
+ return e !== null && typeof e === "object" && !Array.isArray(e) && typeof e.next_step === "string" ? e.next_step : null;
23
+ };
24
+ /** The output_text parts of output[].content[], in order. */
25
+ export function outputText(body) {
26
+ const output = Array.isArray(body["output"]) ? body["output"] : [];
27
+ return output.flatMap((item) => {
28
+ const content = item?.content;
29
+ return Array.isArray(content) ? content : [];
30
+ }).filter((c) => c?.type === "output_text" && typeof c.text === "string")
31
+ .map((c) => c.text).join("");
32
+ }
33
+ export const seconds = (v) => {
34
+ const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
35
+ return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : null;
36
+ };