@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
package/dist/doctor.js CHANGED
@@ -4,26 +4,27 @@
4
4
  * writes, never runs the client, and never prints a key, header value or configured URL.
5
5
  * Parsing here is pure; cli.ts supplies the files and the optional network check.
6
6
  */
7
- import { DEFAULT_KEY_PATH, headersHelper, INSTALL_CLIENTS } from "./install.js";
7
+ import { DEFAULT_KEY_PATH, headersHelper, INSTALL_CLIENTS, isObject } from "./install.js";
8
8
  /** Where `flovia install` puts each client's personal settings (user scope). */
9
- export function settingsPath(client, home) {
9
+ export function settingsPath(client, home, env = {}) {
10
+ // The clients move their settings with these (Claude Code 2.1.328 writes `claude mcp add --scope user` to $CLAUDE_CONFIG_DIR/.claude.json).
11
+ const dir = (name) => env[name]?.trim().replace(/\/+$/, "") || null;
10
12
  switch (client) {
11
- case "claude-code": return `${home}/.claude.json`;
12
- case "codex": return `${home}/.codex/config.toml`;
13
+ case "claude-code": return `${dir("CLAUDE_CONFIG_DIR") ?? home}/.claude.json`;
14
+ case "codex": return `${dir("CODEX_HOME") ?? `${home}/.codex`}/config.toml`;
13
15
  case "cursor": return `${home}/.cursor/mcp.json`;
14
16
  case "hermes": return `${home}/.hermes/config.yaml`;
15
17
  case "claude-desktop": return null;
16
18
  }
17
19
  }
18
20
  /** How to sign in again: after a revoked or expired sign-in the client keeps retrying the old token until a person signs in anew (#2615). */
19
- export const SIGN_IN_AGAIN = {
21
+ const SIGN_IN_AGAIN = {
20
22
  "claude-code": "In Claude Code run /mcp, choose flovia, and authenticate again.",
21
23
  codex: "Run: codex mcp login flovia",
22
- cursor: "In Cursor's MCP settings, turn Flovia off and on, then sign in when asked.",
24
+ cursor: "In Cursor's MCP settings, turn Flovia off and on, then sign in when asked. In the Cursor CLI, run agent mcp login flovia, then start a new agent session.",
23
25
  hermes: "Run: hermes mcp login flovia",
24
26
  "claude-desktop": "In Claude's Settings > Connectors, disconnect Flovia and connect it again.",
25
27
  };
26
- const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
27
28
  const ENV_REF = /^Bearer \$\{env:([^}]+)\}$/;
28
29
  const envEntry = (url, keyEnv) => /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(keyEnv) && !/^(?:flv_|sk-|sk_(?:live|test)_|ghp_|phc_|github_pat_|xox[baprs]-)/i.test(keyEnv)
29
30
  ? { url, auth: "key-env", keyEnv } : { url, auth: "unknown" };
@@ -69,43 +70,65 @@ export function tomlEntry(text) {
69
70
  return null;
70
71
  return keyEnv !== undefined ? envEntry(url, keyEnv) : { url, auth: literal ? "key-in-settings" : "oauth" };
71
72
  }
72
- /** mcp_servers > flovia > url/auth in Hermes's config.yaml, as `flovia install` writes it. Line-based on purpose. */
73
+ /**
74
+ * mcp_servers > flovia > url/auth in Hermes's config.yaml, as `flovia install` writes it. Line-based on purpose.
75
+ * Only a flovia directly under mcp_servers counts, and only url/auth directly under it; a flovia nested in another
76
+ * server is not ours. A flovia with an inline value (`flovia: {url: …}`) is found but read as unknown, so install refuses it.
77
+ */
73
78
  export function yamlEntry(text) {
74
- let section = false, inside = false, indent = -1, found = false, url = null, auth = null, headers = false;
79
+ let section = false, inside = false, server = -1, field = -1, found = 0, sections = 0, url = null, auth = null, headers = false, disabled = false;
80
+ const value = (v) => unquote(v.replace(/\s+#.*$/, ""));
75
81
  for (const raw of text.split(/\r?\n/)) {
76
82
  if (raw.trim() === "" || raw.trim().startsWith("#"))
77
83
  continue;
78
84
  const depth = raw.length - raw.trimStart().length, line = raw.trim();
79
85
  if (depth === 0) {
80
- section = line === "mcp_servers:";
86
+ section = /^mcp_servers:\s*(#.*)?$/.test(line);
87
+ if (/^["']?mcp_servers["']?\s*:/.test(line))
88
+ sections++;
81
89
  inside = false;
90
+ server = -1;
82
91
  continue;
83
92
  }
84
93
  if (!section)
85
94
  continue;
86
- if (/^["']?flovia["']?:\s*$/.test(line)) {
87
- inside = true;
88
- found = true;
89
- indent = depth;
90
- continue;
91
- }
92
- if (depth <= indent) {
93
- inside = false;
95
+ if (server === -1)
96
+ server = depth;
97
+ if (depth <= server) {
98
+ const key = /^["']?flovia["']?\s*:(.*)$/.exec(line);
99
+ inside = key !== null && depth === server;
100
+ // An inline value is flow style or a scalar: found, but not read, so it is never taken as the same entry.
101
+ if (inside) {
102
+ found++;
103
+ field = -1;
104
+ inside = /^\s*(#.*)?$/.test(key?.[1]);
105
+ }
94
106
  continue;
95
107
  }
96
108
  if (!inside)
97
109
  continue;
110
+ if (field === -1)
111
+ field = depth;
112
+ if (/^authorization\s*:/i.test(line))
113
+ headers = true;
114
+ if (depth !== field)
115
+ continue;
98
116
  const m = /^([A-Za-z_]+):\s*(.*)$/.exec(line);
99
117
  if (m?.[1] === "url")
100
- url = unquote(m[2]);
118
+ url = value(m[2]);
101
119
  else if (m?.[1] === "auth")
102
- auth = unquote(m[2]);
103
- else if (m?.[1] === "headers" || /^authorization:/i.test(line))
120
+ auth = value(m[2]);
121
+ else if (m?.[1] === "enabled")
122
+ disabled = /^(false|no|off)$/i.test(value(m[2]));
123
+ else if (m?.[1] === "headers")
104
124
  headers = true;
105
125
  }
106
126
  if (!found)
107
127
  return null;
108
- return { url, auth: auth === "oauth" ? "oauth" : headers ? "key-in-settings" : "unknown" };
128
+ // Hermes uses the last of two mcp_servers or two flovia keys, so a duplicate is never the entry read above.
129
+ if (sections > 1 || found > 1)
130
+ return { url: null, auth: "unknown" };
131
+ return { url, auth: auth === "oauth" ? "oauth" : headers ? "key-in-settings" : "unknown", ...(disabled ? { disabled: true } : {}) };
109
132
  }
110
133
  export function urlCheck(url, resource) {
111
134
  if (url === null)
@@ -134,7 +157,7 @@ const AUTH_TEXT = {
134
157
  };
135
158
  /** Everything but the key file and the network: those need I/O, so cli.ts adds them. */
136
159
  export function inspect(client, text, resource, home, env, asked, keyPath = DEFAULT_KEY_PATH) {
137
- const settings = settingsPath(client, home);
160
+ const settings = settingsPath(client, home, env);
138
161
  if (client === "claude-desktop")
139
162
  return { client, state: "manual", settings: null, auth: "oauth", checks: [{ name: "settings", result: "warn", detail: "Claude desktop keeps remote connectors in your Claude account, not in a local file" }],
140
163
  next: ["Check Settings > Connectors in Claude: Flovia should be listed and connected.", `If tools fail with a sign-in error: ${SIGN_IN_AGAIN[client]}`] };
@@ -154,6 +177,10 @@ export function inspect(client, text, resource, home, env, asked, keyPath = DEFA
154
177
  return notSetUp(`${settings} has no flovia entry`);
155
178
  const checks = [{ name: "settings", result: "ok", detail: `${settings} has a flovia entry` }, urlCheck(entry.url, resource)];
156
179
  const next = [];
180
+ if (entry.disabled) {
181
+ checks.push({ name: "enabled", result: "fail", detail: "the flovia entry is turned off (enabled: false); the client does not load it" });
182
+ next.push(`Remove enabled: false from the flovia entry in ${settings} (or set it to true), then restart the client.`);
183
+ }
157
184
  if (entry.auth === "unknown")
158
185
  next.push("Check the client's authentication settings manually; doctor did not read a key or run a helper.");
159
186
  checks.push({ name: "auth", result: entry.auth === "key-in-settings" || entry.auth === "unknown" ? "warn" : "ok", detail: AUTH_TEXT[entry.auth] });
@@ -0,0 +1,9 @@
1
+ import { type Parsed } from "./args.js";
2
+ import type { Io } from "./cli.js";
3
+ type ReadKeyFile = (file: string, io: Io, label: string) => Promise<string>;
4
+ /** Read-only: settings files, the key's readability, and with --network one unauthenticated /mcp request plus flovia_status with that key. */
5
+ export declare function doctor(p: Parsed, io: Io, out: (s: string) => void, json: boolean, remember: (key: string) => void, o: {
6
+ baseUrl: string | undefined;
7
+ timeout: number | undefined;
8
+ }, fromFile: ReadKeyFile, DEFAULT_KEY_FILE: string): Promise<number>;
9
+ export {};
@@ -0,0 +1,125 @@
1
+ import { COMMANDS, Usage, didYouMean, mcpBase, str } from "./args.js";
2
+ import { inspect, renderDoctor, settingsPath, settle } from "./doctor.js";
3
+ import { FloviaClient, FloviaError } from "./index.js";
4
+ import { INSTALL_CLIENTS } from "./install.js";
5
+ import { CONSOLE } from "./output.js";
6
+ /** Read-only: settings files, the key's readability, and with --network one unauthenticated /mcp request plus flovia_status with that key. */
7
+ export async function doctor(p, io, out, json, remember, o, fromFile, DEFAULT_KEY_FILE) {
8
+ const client = str(p.flags.get("--client"));
9
+ if (p.positional.length)
10
+ throw new Usage(`Usage: flovia ${COMMANDS["doctor"]?.usage}`);
11
+ if (client !== undefined && !INSTALL_CLIENTS.includes(client))
12
+ throw new Usage(`doctor: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${didYouMean(client, [...INSTALL_CLIENTS])}`);
13
+ const home = io.env["HOME"];
14
+ if (!home)
15
+ throw new Usage("doctor: HOME is not set");
16
+ const base = mcpBase(o.baseUrl, "doctor");
17
+ const resource = `${base.origin}/mcp`, network = p.flags.has("--network"), keyFlag = str(p.flags.get("--key-file"));
18
+ const clients = client === undefined ? [...INSTALL_CLIENTS] : [client];
19
+ const doFetch = io.fetch ?? fetch;
20
+ /** One deadline includes fetch and body consumption/cancellation, even for injected transports. */
21
+ const timed = async (request) => {
22
+ const signal = AbortSignal.timeout((o.timeout ?? 300) * 1000);
23
+ let abort = () => { };
24
+ try {
25
+ const deadline = new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); });
26
+ return await Promise.race([request(signal), deadline]);
27
+ }
28
+ finally {
29
+ signal.removeEventListener("abort", abort);
30
+ }
31
+ };
32
+ let reachable;
33
+ const reach = async () => {
34
+ if (reachable)
35
+ return reachable;
36
+ try {
37
+ const r = await timed(async (signal) => {
38
+ const response = await doFetch(new Request(resource, { method: "GET", redirect: "error", signal, headers: { "X-Flovia-Client": "flovia-cli" } }));
39
+ await response.body?.cancel().catch(() => undefined);
40
+ return response;
41
+ });
42
+ reachable = r.status === 401 && /bearer/i.test(r.headers.get("www-authenticate") ?? "")
43
+ ? { result: "ok", detail: `${resource} answers and asks for sign-in or a key` }
44
+ : { result: "warn", detail: `${resource} answered HTTP ${r.status}, not the expected 401 with a sign-in challenge` };
45
+ }
46
+ catch {
47
+ reachable = { result: "fail", detail: `${resource} could not be reached from this machine` };
48
+ }
49
+ return reachable;
50
+ };
51
+ /** A key is read only to check it; it goes into the scrub list first, so no line can show it. */
52
+ const tryKey = async (k, r) => {
53
+ remember(k);
54
+ if (!network)
55
+ return;
56
+ // Same format as the Relay's issued-key schema; never send another service's credential to Flovia.
57
+ if (!/^flv_[A-Za-z0-9_-]{43}$/.test(k)) {
58
+ r.checks.push({ name: "key accepted", result: "warn", detail: "The configured value is not a Flovia key; it was not sent." });
59
+ return;
60
+ }
61
+ try {
62
+ await timed(async (signal) => {
63
+ const c = new FloviaClient({ apiKey: k, baseUrl: base.origin, ...(o.timeout ? { timeoutMs: o.timeout * 1000 } : {}),
64
+ fetch: (req) => { req.headers.set("X-Flovia-Client", "flovia-cli"); return doFetch(new Request(req, { signal })); }, onContractMismatch: () => undefined });
65
+ await c.status();
66
+ });
67
+ r.checks.push({ name: "key accepted", result: "ok", detail: "flovia_status answered with this key" });
68
+ }
69
+ catch (e) {
70
+ if (e instanceof FloviaError && (e.code === "unauthorized" || e.code === "key_disabled" || e.code === "key_stopped")) {
71
+ r.checks.push({ name: "key accepted", result: "fail", detail: `Flovia refused this key (${e.code})` });
72
+ r.next.push(`Issue or re-enable a key in Console (${CONSOLE}), save it, then restart ${r.client}.`);
73
+ }
74
+ else
75
+ r.checks.push({ name: "key accepted", result: "warn", detail: e instanceof FloviaError ? `flovia_status answered ${e.code}` : "flovia_status could not be reached" });
76
+ }
77
+ };
78
+ const reports = [];
79
+ for (const name of clients) {
80
+ const path = settingsPath(name, home, io.env);
81
+ let text = null;
82
+ if (path !== null) {
83
+ try {
84
+ text = await io.readFile(path);
85
+ }
86
+ catch (e) {
87
+ if (e.code !== "ENOENT") {
88
+ 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."] });
89
+ continue;
90
+ }
91
+ }
92
+ }
93
+ const r = inspect(name, text, resource, home, io.env, client !== undefined, keyFlag);
94
+ if (r.state === "ok" && r.auth === "key-file") {
95
+ const shown = keyFlag === undefined ? `~/${DEFAULT_KEY_FILE}` : "--key-file";
96
+ try {
97
+ const keyPath = keyFlag ?? `~/${DEFAULT_KEY_FILE}`;
98
+ const k = await fromFile(keyPath.startsWith("~/") ? `${home}/${keyPath.slice(2)}` : keyPath, io, shown);
99
+ r.checks.push({ name: "key", result: "ok", detail: `the key file (${shown}) is readable` });
100
+ await tryKey(k, r);
101
+ }
102
+ catch (e) {
103
+ if (!(e instanceof Usage))
104
+ throw e;
105
+ r.checks.push({ name: "key", result: "fail", detail: e.message });
106
+ 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).`);
107
+ }
108
+ }
109
+ if (r.state === "ok" && r.auth === "key-env" && r.keyEnv !== undefined) {
110
+ const k = io.env[r.keyEnv]?.trim();
111
+ if (k)
112
+ await tryKey(k, r);
113
+ }
114
+ if (network && r.auth !== "unknown" && (r.state === "ok" || r.state === "manual")) {
115
+ const n = await reach();
116
+ r.checks.push({ name: "network", ...n });
117
+ }
118
+ reports.push(settle(r));
119
+ }
120
+ if (json)
121
+ out(JSON.stringify({ ok: !reports.some((r) => r.state === "fail"), resource, network, clients: reports }, null, 2) + "\n");
122
+ else
123
+ out(renderDoctor(reports));
124
+ return reports.some((r) => r.state === "fail") ? 1 : 0;
125
+ }
@@ -0,0 +1,2 @@
1
+ /** Required properties plus Exa/Firecrawl's default-operation inputs, which are conditional in the schema. */
2
+ export declare function exampleCall(tool: string, schema: unknown): string;
@@ -0,0 +1,29 @@
1
+ import { SAVE_OP } from "./args.js";
2
+ import { obj } from "./output.js";
3
+ /** A placeholder for one schema property: its example, default or first enum value, else a value of its type. */
4
+ function placeholder(name, s) {
5
+ if (s.example !== undefined)
6
+ return s.example;
7
+ if (Array.isArray(s.examples) && s.examples.length)
8
+ return s.examples[0];
9
+ if (s.default !== undefined)
10
+ return s.default;
11
+ if (Array.isArray(s.enum) && s.enum.length)
12
+ return s.enum[0];
13
+ const type = Array.isArray(s.type) ? s.type[0] : s.type;
14
+ return type === "integer" || type === "number" ? 1 : type === "boolean" ? false : type === "array" ? [] : type === "object" ? {} : `<${name}>`;
15
+ }
16
+ /** Required properties plus Exa/Firecrawl's default-operation inputs, which are conditional in the schema. */
17
+ export function exampleCall(tool, schema) {
18
+ // A schema split by action (oneOf, e.g. flovia_firecrawl, #2617): the example uses the option whose action is the default.
19
+ const top = obj(schema), options = Array.isArray(top["oneOf"]) ? top["oneOf"].map(obj) : [];
20
+ 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) : [];
21
+ const defaults = tool === "flovia_exa" ? ["action", "query", "operation_id"] : tool === "flovia_firecrawl" ? ["action", "url", "operation_id"] : [];
22
+ const fields = [...new Set([...required, ...defaults.filter((k) => Object.hasOwn(props, k))])];
23
+ const args = Object.fromEntries(fields.map((k) => [k, placeholder(k, obj(props[k]))]));
24
+ const lines = ["", "Example (replace the placeholders):", ` flovia call ${tool} '${JSON.stringify(args).replaceAll("'", "'\\''")}'`,
25
+ "Or from a saved file:", ` flovia call ${tool} - < request.json`];
26
+ if (Object.hasOwn(props, "operation_id"))
27
+ lines.push(...SAVE_OP);
28
+ return lines.join("\n") + "\n";
29
+ }
@@ -0,0 +1,15 @@
1
+ import { type FloviaClient, type GenerationRequest } from "./index.js";
2
+ import { type Parsed } from "./args.js";
3
+ import type { Io } from "./cli.js";
4
+ declare function reasoningEffort(v: string | undefined): NonNullable<GenerationRequest["reasoning"]>["effort"] | undefined;
5
+ type GenerateContext = {
6
+ connect: () => Promise<FloviaClient>;
7
+ waitFor: <T>(f: () => Promise<T>) => Promise<T>;
8
+ json: boolean;
9
+ print: (v: unknown) => void;
10
+ out: (s: string) => void;
11
+ err: (s: string) => void;
12
+ rememberRecovery: (limit: number | undefined, effort: ReturnType<typeof reasoningEffort>) => void;
13
+ };
14
+ export declare function generateCommand(p: Parsed, io: Io, { connect, waitFor, json, print, out, err, rememberRecovery }: GenerateContext): Promise<number>;
15
+ export {};
@@ -0,0 +1,64 @@
1
+ import { newOperationId } from "./index.js";
2
+ import { OPERATION_ID } from "./transport.js";
3
+ import { COMMANDS, Usage, positiveInt, str } from "./args.js";
4
+ import { obj } from "./output.js";
5
+ function reasoningEffort(v) {
6
+ if (v === undefined || v === "none" || v === "low" || v === "medium" || v === "high" || v === "xhigh" || v === "max")
7
+ return v;
8
+ throw new Usage("--reasoning-effort must be one of: none, low, medium, high, xhigh, max");
9
+ }
10
+ export async function generateCommand(p, io, { connect, waitFor, json, print, out, err, rememberRecovery }) {
11
+ const op = str(p.flags.get("--op")), fresh = p.flags.has("--new-op");
12
+ if ((op === undefined) === !fresh)
13
+ throw new Usage("generate: pass --op ID (to resend, the same id) or --new-op (to make one); exactly one of them");
14
+ // Checked before the notice and the confirmation: the SDK would refuse it anyway, and nothing would be sent.
15
+ if (op !== undefined && !OPERATION_ID.test(op))
16
+ throw new Usage("generate: --op must be 8-128 of A-Z a-z 0-9 _ . : - (the id you saved, or use --new-op)");
17
+ const [text, extra] = p.positional;
18
+ if (text === undefined || extra !== undefined)
19
+ throw new Usage(`Usage: flovia ${COMMANDS["generate"]?.usage}`);
20
+ const max = positiveInt("--max-output", str(p.flags.get("--max-output")));
21
+ const effort = reasoningEffort(str(p.flags.get("--reasoning-effort")));
22
+ const client = await connect();
23
+ let input = text;
24
+ if (text === "-")
25
+ try {
26
+ input = await io.readStdin();
27
+ }
28
+ catch {
29
+ throw new Usage("generate: cannot read the prompt from stdin (it must be UTF-8 text)");
30
+ }
31
+ if (input.trim() === "")
32
+ throw new Usage("generate: the prompt is empty");
33
+ rememberRecovery(max, effort);
34
+ const id = op ?? newOperationId();
35
+ // The id is shown before anything is sent, so a lost reply can be reopened with it (never resent under a new one).
36
+ if (fresh)
37
+ err(`operation_id: ${id}\nSave it. To resend or reopen this request, use: --op ${id}\n`);
38
+ 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");
39
+ if (!p.flags.has("--yes")) {
40
+ if (io.confirm === null || text === "-")
41
+ throw new Usage("generate: add --yes to send (no terminal to confirm on)");
42
+ if (!(await io.confirm("Send it?"))) {
43
+ err("Not sent.\n");
44
+ return 2;
45
+ }
46
+ }
47
+ const g = await waitFor(() => client.generate({ model: "gpt-6-luna", input, ...(max ? { max_output_tokens: max } : {}), ...(effort ? { reasoning: { effort } } : {}) }, { operationId: id }));
48
+ const reason = obj(g.response["incomplete_details"])["reason"];
49
+ if (json)
50
+ print(g);
51
+ else {
52
+ out(`${g.outputText}\n\nstatus: ${String(g.response["status"] ?? "unknown")}${reason ? `, reason: ${String(reason)}` : ""}\noperation_id: ${id}\n${g.generationId ? `generation: ${g.generationId}\n` : ""}`);
53
+ if (g.response["status"] === "incomplete")
54
+ out(`${reason === "max_output_tokens" ? "Partial answer: the output limit was reached" : "Partial answer"}; delivered and settled. No continuation was generated.\n`);
55
+ else if (g.response["status"] === "completed")
56
+ out("Answer delivered and settled.\n");
57
+ if (g.replayed)
58
+ out("replayed: the saved answer, not charged again.\n");
59
+ else
60
+ out("Exact Flovia cost is not included in this reply.\n");
61
+ out("Period usage: flovia usage (keep the same --key-file and --base-url options).\n");
62
+ }
63
+ return 0;
64
+ }
@@ -0,0 +1,6 @@
1
+ import { type Transport } from "./transport.js";
2
+ import type { Generation, GenerationRequest } from "./types.js";
3
+ export declare function generate(t: Transport, request: GenerationRequest, options: {
4
+ operationId: string;
5
+ conversationId?: string;
6
+ }): Promise<Generation>;
@@ -0,0 +1,30 @@
1
+ import { FloviaError } from "./errors.js";
2
+ import { SAME_OPERATION, outputText, readReply, seconds } from "./reply.js";
3
+ import { OPERATION_ID } from "./transport.js";
4
+ export async function generate(t, request, options) {
5
+ const op = options.operationId;
6
+ if (!OPERATION_ID.test(op))
7
+ throw new FloviaError({ code: "invalid_operation_id", executed: "no", message: "operationId must be 8-128 of A-Z a-z 0-9 _ . : -" });
8
+ const r = await t.send("/openai/v1/responses", request, { "Flovia-Operation-Id": op, ...(options.conversationId ? { "Flovia-Conversation-Id": options.conversationId } : {}) }, op);
9
+ const body = await readReply(r, op, init => t.error(init));
10
+ if (r.status === 200 && !Array.isArray(body["output"]))
11
+ throw t.error({ code: "http_200", status: 200, executed: "unknown", operationId: op, message: "Unexpected generation reply (HTTP 200).", nextStep: SAME_OPERATION });
12
+ if (r.status === 200)
13
+ return { response: body, outputText: outputText(body), generationId: r.headers.get("Flovia-Generation-Id"),
14
+ replayed: r.headers.get("Flovia-Replayed") === "1", receivedAt: r.headers.get("Flovia-Received-At"), conversationId: r.headers.get("Flovia-Conversation-Id") };
15
+ const err = body["error"], explanation = body["explanation"];
16
+ const code = typeof err === "string" ? err : String(err?.code ?? `http_${r.status}`);
17
+ const message = String(err?.message ?? body["message"] ?? `HTTP ${r.status}`);
18
+ const executed = explanation?.executed ?? generationExecuted(code);
19
+ throw t.error({ code, message, status: r.status, operationId: op, reply: body,
20
+ executed, nextStep: explanation?.next_step ?? (executed === "unknown" ? SAME_OPERATION : null),
21
+ retryAfterSeconds: seconds(r.headers.get("Retry-After")) ?? seconds(body["retry_after_seconds"]) });
22
+ }
23
+ /** Whether a refused generation ran, from its public code (the same reading flovia_openai gives over MCP). */
24
+ function generationExecuted(code) {
25
+ if (["answer_unavailable", "answer_expired", "answer_delivery_denied"].includes(code))
26
+ return "yes";
27
+ if (["generation_unknown", "generation_pending", "record_unavailable", "operation_retired"].includes(code) || /^http_5\d\d$/.test(code))
28
+ return "unknown";
29
+ return "no";
30
+ }
package/dist/install.d.ts CHANGED
@@ -16,6 +16,7 @@ export type InstallStep =
16
16
  kind: "exec";
17
17
  command: string;
18
18
  args: string[];
19
+ signIn?: true;
19
20
  }
20
21
  /** Merges mcpServers.flovia into a JSON file, keeping every other entry. */
21
22
  | {
@@ -51,11 +52,23 @@ export declare function planInstall(o: {
51
52
  keyPath?: string;
52
53
  }): InstallPlan;
53
54
  type Json = Record<string, unknown>;
55
+ export declare const isObject: (v: unknown) => v is Json;
54
56
  /** The new file text, or "unchanged". A different flovia entry is kept unless force; other entries are always kept. */
55
57
  export declare function mergeJson(existing: string | null, entry: Json, force: boolean): string | "unchanged";
56
- /** Create only new settings; existing YAML needs a manual merge unless it is exactly our generated entry. */
58
+ /** mcp_servers > flovia's url and whether auth is oauth, read the way doctor reads it (line-based, like the merge below). */
59
+ type YamlReader = (text: string) => {
60
+ url: string | null;
61
+ auth: string;
62
+ disabled?: true;
63
+ } | null;
64
+ /**
65
+ * Adds flovia under mcp_servers by inserting lines only, so every comment, key and order already in the file stays.
66
+ * Only a plain block mapping is extended: a top-level line that is not a plain `key:` (a document marker, flow style,
67
+ * a quoted key, a list, an anchor) or an mcp_servers that is not a block mapping, {} or empty is refused, and the
68
+ * refusal names Hermes's own command. A different flovia entry is never replaced.
69
+ */
57
70
  export declare function mergeYaml(existing: string | null, entry: {
58
71
  url: string;
59
72
  auth: string;
60
- }): string | "unchanged";
73
+ }, read: YamlReader): string | "unchanged";
61
74
  export {};
package/dist/install.js CHANGED
@@ -34,15 +34,16 @@ export function planInstall(o) {
34
34
  next: ["Restart Claude Code. The key is read from the key file on each connect; it is not in Claude Code's settings.", check] };
35
35
  case "codex":
36
36
  return auth === "oauth"
37
- ? { client, auth, resource, steps: [{ kind: "exec", command: "codex", args: ["mcp", "add", "flovia", "--url", resource] }],
38
- next: ["Sign in: codex mcp login flovia", "Restart Codex.", check] }
37
+ ? { client, auth, resource, steps: [{ kind: "exec", command: "codex", args: ["mcp", "add", "flovia", "--url", resource], signIn: true }],
38
+ // Codex 0.77.0+ starts sign-in inside `codex mcp add` for an OAuth server (openai/codex#8087); login again asks twice.
39
+ next: ["If sign-in did not start, run: codex mcp login flovia", "Restart Codex.", check] }
39
40
  : { client, auth, resource, steps: [{ kind: "exec", command: "codex", args: ["mcp", "add", "flovia", "--url", resource, "--bearer-token-env-var", "FLOVIA_KEY"] }],
40
41
  next: ["Set FLOVIA_KEY in your shell profile (for example ~/.zshrc) and start Codex from a new terminal.", check] };
41
42
  case "cursor":
42
43
  return { client, auth, resource,
43
44
  steps: [{ kind: "json", path: `${home}/.cursor/mcp.json`,
44
45
  entry: auth === "oauth" ? { url: resource } : { url: resource, headers: { Authorization: "Bearer ${env:FLOVIA_API_KEY}" } } }],
45
- next: [auth === "oauth" ? "In Cursor, turn Flovia on in MCP settings and sign in when asked." :
46
+ next: [auth === "oauth" ? "In the Cursor app, turn Flovia on in MCP settings and sign in when asked. In the Cursor CLI, run agent mcp enable flovia, then agent mcp login flovia, then start a new agent session." :
46
47
  "Set FLOVIA_API_KEY in your shell profile and open Cursor from a terminal (Cursor opened from the Dock won't see it). Turn Flovia on in MCP settings.", check] };
47
48
  case "hermes":
48
49
  if (auth === "key")
@@ -58,7 +59,7 @@ export function planInstall(o) {
58
59
  "Then sign in to Flovia when Claude asks.", check] };
59
60
  }
60
61
  }
61
- const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
62
+ export const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
62
63
  const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
63
64
  /** The new file text, or "unchanged". A different flovia entry is kept unless force; other entries are always kept. */
64
65
  export function mergeJson(existing, entry, force) {
@@ -86,12 +87,76 @@ export function mergeJson(existing, entry, force) {
86
87
  }
87
88
  return JSON.stringify({ ...doc, mcpServers: { ...servers, flovia: entry } }, null, 2) + "\n";
88
89
  }
89
- /** Create only new settings; existing YAML needs a manual merge unless it is exactly our generated entry. */
90
- export function mergeYaml(existing, entry) {
91
- const generated = `mcp_servers:\n flovia:\n url: ${entry.url}\n auth: ${entry.auth}\n`;
92
- if (existing === generated)
93
- return "unchanged";
94
- if (existing !== null && existing.trim() !== "")
95
- throw new InstallRefusal("install: existing Hermes settings need a manual merge; see Console's Quick Install. Nothing was changed");
96
- return generated;
90
+ /**
91
+ * Adds flovia under mcp_servers by inserting lines only, so every comment, key and order already in the file stays.
92
+ * Only a plain block mapping is extended: a top-level line that is not a plain `key:` (a document marker, flow style,
93
+ * a quoted key, a list, an anchor) or an mcp_servers that is not a block mapping, {} or empty is refused, and the
94
+ * refusal names Hermes's own command. A different flovia entry is never replaced.
95
+ */
96
+ export function mergeYaml(existing, entry, read) {
97
+ const lines = (ind, eol) => [`${ind}flovia:`, `${ind} url: ${entry.url}`, `${ind} auth: ${entry.auth}`].join(eol) + eol;
98
+ if (existing === null || existing.trim() === "")
99
+ return `mcp_servers:\n${lines(" ", "\n")}`;
100
+ const manual = new InstallRefusal(`install: cannot add flovia to the existing Hermes settings safely; nothing was changed. Add it with Hermes's own command instead: hermes mcp add flovia --url ${entry.url} --auth ${entry.auth}\n` +
101
+ `Or add these lines to ~/.hermes/config.yaml yourself (put flovia under the existing mcp_servers if there is one):\nmcp_servers:\n${lines(" ", "\n")}`);
102
+ // Two mcp_servers keys: Hermes reads the last one, so a flovia in the first is not configured. Checked before "unchanged".
103
+ if (existing.split(/\r?\n/).filter((r) => /^["']?mcp_servers["']?\s*:/.test(r)).length > 1)
104
+ throw manual;
105
+ const current = read(existing);
106
+ if (current !== null) {
107
+ // Hermes does not load a server with enabled: false, so the same URL and sign-in is not "unchanged".
108
+ if (current.disabled)
109
+ throw new InstallRefusal("install: flovia is in the Hermes settings but turned off (enabled: false); nothing was changed. Remove enabled: false from mcp_servers > flovia in ~/.hermes/config.yaml (or set it to true), then restart Hermes Agent or run /reload-mcp");
110
+ if (current.url === entry.url && current.auth === entry.auth)
111
+ return "unchanged";
112
+ throw new InstallRefusal("install: a different flovia entry is already in the Hermes settings; nothing was changed. Remove it with: hermes mcp remove flovia, then run install again");
113
+ }
114
+ // A BOM, or CRLF mixed with bare LF, would shift what a line is; such a file is left to Hermes's command.
115
+ if (existing.startsWith("\uFEFF"))
116
+ throw manual;
117
+ const eol = existing.includes("\r\n") ? "\r\n" : "\n";
118
+ if (eol === "\r\n" && /(^|[^\r])\n/.test(existing))
119
+ throw manual;
120
+ const text = existing.endsWith(eol) ? existing : existing + eol;
121
+ const rows = text.slice(0, -eol.length).split(eol);
122
+ if (rows.some((r) => r.includes("\r") || r.includes("\n") || /^\s*\t/.test(r)))
123
+ throw manual;
124
+ const content = (r) => r.trim() !== "" && !r.trimStart().startsWith("#");
125
+ // An indented root mapping has no column-0 key to add mcp_servers beside.
126
+ if (/^\s/.test(rows.find(content) ?? ""))
127
+ throw manual;
128
+ const top = rows.flatMap((r, i) => content(r) && !/^\s/.test(r) ? [i] : []);
129
+ if (top.some((i) => !/^[A-Za-z_][\w.-]*\s*:(\s|$)/.test(rows[i])))
130
+ throw manual;
131
+ const headers = top.filter((i) => /^mcp_servers\s*:/.test(rows[i]));
132
+ let next;
133
+ if (headers.length === 0)
134
+ next = text + `mcp_servers:${eol}` + lines(" ", eol);
135
+ else if (headers.length > 1)
136
+ throw manual;
137
+ else {
138
+ const at = headers[0], header = rows[at];
139
+ const m = /^mcp_servers\s*:\s*(\{\s*\}|null|~)?\s*(#.*)?$/.exec(header);
140
+ if (!m)
141
+ throw manual;
142
+ const end = top.find((i) => i > at) ?? rows.length;
143
+ const children = rows.slice(at + 1, end).filter(content);
144
+ const first = children[0];
145
+ if (m[1] !== undefined && first !== undefined)
146
+ throw manual;
147
+ const ind = first === undefined ? " " : (/^ +/.exec(first)?.[0] ?? "");
148
+ if (first !== undefined && !children.every((r) => r.startsWith(ind)))
149
+ throw manual;
150
+ if (children.some((r) => r.length - r.trimStart().length === ind.length && !/^["']?[A-Za-z_][\w.-]*["']?\s*:(\s|$)/.test(r.trimStart())))
151
+ throw manual;
152
+ // The reader found no flovia here; one at this level it could not read is not added a second time.
153
+ if (children.some((r) => r.length - r.trimStart().length === ind.length && /^["']?flovia["']?\s*:/.test(r.trimStart())))
154
+ throw manual;
155
+ const head = m[1] === undefined ? header : header.replace(/:\s*(\{\s*\}|null|~)/, ":");
156
+ next = [...rows.slice(0, at), head].join(eol) + eol + lines(ind, eol) + (at + 1 < rows.length ? rows.slice(at + 1).join(eol) + eol : "");
157
+ }
158
+ const added = read(next);
159
+ if (added?.url !== entry.url || added.auth !== entry.auth)
160
+ throw manual;
161
+ return next;
97
162
  }
@@ -0,0 +1,4 @@
1
+ import { type Parsed } from "./args.js";
2
+ import type { Io } from "./cli.js";
3
+ /** No network and no key text: for Claude Code's key mode only the key file's readability is checked. */
4
+ export declare function install(p: Parsed, io: Io, out: (s: string) => void, err: (s: string) => void, json: boolean, timeout: number | undefined, fromFile: (file: string, io: Io, label: string) => Promise<string>): Promise<number>;