@flovialabs/sdk 0.1.30 → 0.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -1
- package/README.md +8 -4
- package/dist/cli.d.ts +7 -0
- package/dist/commandhelp.js +2 -2
- package/dist/doctor.d.ts +23 -2
- package/dist/doctor.js +142 -17
- package/dist/doctorcommand.js +172 -12
- package/dist/homedir.d.ts +2 -0
- package/dist/homedir.js +5 -0
- package/dist/install.js +23 -4
- package/dist/installcommand.js +18 -4
- package/dist/keyfile.js +2 -1
- package/dist/nodeio.d.ts +17 -0
- package/dist/nodeio.js +83 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 0.1.31
|
|
4
|
+
|
|
5
|
+
- `flovia doctor --client claude-code` reads `claude mcp list`. A plain `flovia doctor` does not. When that shows `claude.ai Flovia` as Connected and there is no local flovia entry, it warns and says to quit Claude Code and open it again, then check in a new session. The add command is `claude mcp add --scope user --transport http flovia` with this environment's MCP URL, then `/mcp`, and it is suggested only when there is no flovia row. A local flovia entry stays in place and is not told to add again.
|
|
6
|
+
- `flovia doctor` no longer prints the key variable's name. The text says whether a saved key is available. `--json` still includes `keyEnv`. When the settings read a key from the environment that starts the app and that value is missing, the next step says to set it there. When `--network` cannot reach Flovia, the next step says restarting does not fix it and names the site to allow.
|
|
7
|
+
- `flovia doctor` checks a saved key with `flovia_status` (a refusal fails and names Console). A value that is not a Flovia key is not sent, and the next step says to create one in Console. Codex `enabled = false` fails. Codex sign-in that `codex mcp list` reports as Not logged in, including after a browser page says Authentication complete, fails and names `codex mcp login flovia`. A machine with no network fails within `--timeout` seconds (default 15) and says what could not be reached. `flovia install --client cursor --auth key` stores `FLOVIA_KEY`. An entry that already names `FLOVIA_API_KEY` still reads that variable.
|
|
4
8
|
|
|
5
9
|
## 0.1.30
|
|
6
10
|
|
package/README.md
CHANGED
|
@@ -10,9 +10,13 @@ TypeScript client and command-line tool for [Flovia](https://api.flovia.dev). It
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
12
12
|
```sh
|
|
13
|
-
npm install --save-exact @flovialabs/sdk@0.1.
|
|
13
|
+
npm install --save-exact @flovialabs/sdk@0.1.31
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
+
## 0.1.31 release notes
|
|
17
|
+
|
|
18
|
+
This release expects the same Relay contract as 0.1.30, `2026-10-07.270`. `flovia doctor` checks a saved key with `flovia_status` and, for Claude Code, reads `claude mcp list` before suggesting an add. See [CHANGELOG.md](CHANGELOG.md) for details.
|
|
19
|
+
|
|
16
20
|
## 0.1.30 release notes
|
|
17
21
|
|
|
18
22
|
This release expects Relay contract `2026-10-07.270`. Small Zerion position reads must name one chain and `fungible_ids`, and return at most 10 rows. See [CHANGELOG.md](CHANGELOG.md) for details.
|
|
@@ -374,7 +378,7 @@ npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
|
|
|
374
378
|
npx flovia help
|
|
375
379
|
npx flovia --version
|
|
376
380
|
```
|
|
377
|
-
These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.
|
|
381
|
+
These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.31 flovia --help`. Use a unique operation id for each new request; `sdk-example-0001` is only an example. Save the id, prompt and options before sending, and keep them unchanged for replay.
|
|
378
382
|
|
|
379
383
|
Get or manage your key in [Console](https://console.flovia.dev/groupbuy/), save it privately, then run `flovia status --key-file <saved-key-file>`. A connected key can still have sharing declined, withdrawn or stopped; `status` shows those separately from provider availability. It never answers consent for you.
|
|
380
384
|
|
|
@@ -397,7 +401,7 @@ npx flovia install --client cursor --auth key --dry-run
|
|
|
397
401
|
|
|
398
402
|
Running install again leaves an identical flovia entry unchanged. A different one is kept and the error names the command that removes only flovia; add `--force` to replace it (Claude Code: remove only flovia, then add; Codex: its add replaces the entry; Cursor: replace the entry in its file). Install and doctor read the settings in `CLAUDE_CONFIG_DIR` and `CODEX_HOME` when they are set. When install cannot tell which entry the client uses, it changes nothing.
|
|
399
403
|
|
|
400
|
-
The default `--auth oauth` adds the server and lets the client sign in; no key is used. `--auth key` points Claude Code at the key file (`--key-file`, default `~/.config/flovia/key`) and Codex and Cursor at `FLOVIA_KEY
|
|
404
|
+
The default `--auth oauth` adds the server and lets the client sign in; no key is used. `--auth key` points Claude Code at the key file (`--key-file`, default `~/.config/flovia/key`) and Codex and Cursor at `FLOVIA_KEY`; the key is never written into the client's settings, a command argument or the output. An older Cursor entry that names `FLOVIA_API_KEY` still reads that variable. Claude Code and Codex are changed through their own `claude mcp add` and `codex mcp add`. Cursor's `~/.cursor/mcp.json` keeps its other entries. Hermes Agent's `~/.hermes/config.yaml` gets the `flovia` entry under `mcp_servers` by adding lines only, so its other settings, comments and order stay as they are; an identical entry is left unchanged, and a different `flovia` entry is never replaced. A file it cannot extend that way (flow style, quoted keys, anchors, a list) is left untouched, and install names `hermes mcp add flovia --url … --auth oauth` instead. Claude desktop gets the custom-connector link. `--dry-run` shows the commands and files without changing anything, and refuses what the real run would refuse. With `--client codex` and sign-in, Codex 0.77.0 and later start browser sign-in inside `codex mcp add`: install first says on stderr that it is waiting for sign-in and must not be stopped, with the limit and the retry command, then shows Codex's own output (the sign-in URL) on stderr. The wait ends after `--timeout` seconds (default 300); then Codex is stopped and install exits 1 (`--json`: `code: "sign_in_timeout"`) and names `codex mcp login flovia` and `flovia doctor --client codex`. When Hermes's file cannot be extended, the refusal also shows the minimal YAML to paste. `--base-url` takes an origin, such as `https://dev.api.flovia.dev`; a trailing `/mcp` is accepted, and any other path is refused. `doctor` reads `--base-url` the same way.
|
|
401
405
|
|
|
402
406
|
Hermes Agent uses its Client ID Metadata Document by default. If sign-in reports `invalid_client` or times out, follow the manual [DCR fallback in the Hermes guide](https://docs.flovia.dev/connect/hermes/#if-sign-in-fails). The installer never replaces an existing `flovia` entry in the Hermes settings.
|
|
403
407
|
|
|
@@ -408,7 +412,7 @@ npx flovia doctor # every client
|
|
|
408
412
|
npx flovia doctor --client codex --network
|
|
409
413
|
```
|
|
410
414
|
|
|
411
|
-
`doctor`
|
|
415
|
+
`doctor` reads each client's personal settings (`~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.hermes/config.yaml`). It reports whether the `flovia` entry points at `https://api.flovia.dev/mcp`, whether it signs in or uses a key, and whether that key file is readable or a saved key is available. The text does not print the variable's name; `--json` includes `keyEnv`. A saved Flovia-format key is checked with `flovia_status`. For Codex sign-in it runs `codex mcp list` and fails when that says Not logged in or Authorization state not found, including when the browser said Authentication complete. `flovia doctor --client claude-code` runs `claude mcp list`. A plain `flovia doctor` does not. When that shows `claude.ai Flovia` as Connected and there is no local flovia entry, it warns: quit Claude Code and open it again, then check in a new session. The add command is suggested only when there is no flovia row. The person then runs `claude mcp add --scope user --transport http flovia` with this environment's MCP URL and signs in with `/mcp`. It never writes a settings file, and never prints a key, a header value or a URL's query. A sign-in entry gets the client's command to sign in again: after a revoked or expired sign-in, clients keep retrying until a person signs in anew. Claude desktop is checked in Claude's Settings > Connectors. `--network` also asks Flovia: `/mcp` must answer with its sign-in challenge. Fetching and reading the reply share the `--timeout` deadline, which defaults to 15 seconds. A machine with no network fails with what could not be reached and what to do, instead of waiting. Without `--client`, clients that are not set up are listed but do not fail; the exit code is 1 when a check fails.
|
|
412
416
|
|
|
413
417
|
For Claude Code, doctor checks the key file only when `headersHelper` exactly matches the helper `install` generates for the default path or the supplied `--key-file` path. Other helpers and unsafe or credential-like environment-variable names produce an authentication warning and require manual inspection; doctor neither reads another key nor sends a request for that entry. URL warnings show the expected endpoint without echoing the configured URL's host or path. It does not parse full TOML or YAML: inline tables and flow mappings may be reported as an absent entry and need manual inspection.
|
|
414
418
|
|
package/dist/cli.d.ts
CHANGED
|
@@ -27,6 +27,13 @@ export interface Io {
|
|
|
27
27
|
timeoutMs?: number;
|
|
28
28
|
showOutput?: boolean;
|
|
29
29
|
}) => Promise<number | "timeout">;
|
|
30
|
+
/** Read-only command output (doctor runs `codex mcp list`). stdout is not printed. Rejects with code ENOENT when the command is missing. */
|
|
31
|
+
capture?: (command: string, args: string[], o?: {
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
}) => Promise<{
|
|
34
|
+
code: number | "timeout";
|
|
35
|
+
stdout: string;
|
|
36
|
+
}>;
|
|
30
37
|
/** Writes a client's settings file (install), creating its directory. */
|
|
31
38
|
writeFile?: (path: string, text: string) => Promise<void>;
|
|
32
39
|
}
|
package/dist/commandhelp.js
CHANGED
|
@@ -38,9 +38,9 @@ export function help(command) {
|
|
|
38
38
|
if (command === "consent")
|
|
39
39
|
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.");
|
|
40
40
|
if (command === "install")
|
|
41
|
-
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
|
|
41
|
+
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 and Cursor read FLOVIA_KEY", " from the environment. No config gets the key. An older Cursor entry that", " names FLOVIA_API_KEY still reads that variable.", "--dry-run shows the commands and files without running or writing anything.", "Codex sign-in waits for the browser up to --timeout SECONDS (default 300); do not stop it.", " If it is stopped or times out (exit 1), run: codex mcp login flovia", "An identical flovia entry is left unchanged. A different one is kept unless --force:", " Cursor's file entry is replaced; Claude Code removes only flovia, then adds it; Codex's add replaces it.", " flovia install --client claude-code", " flovia install --client cursor --auth key --dry-run");
|
|
42
42
|
if (command === "doctor")
|
|
43
|
-
lines.push("", `--client: ${INSTALL_CLIENTS.join(", ")} (default: every client)`, "Reads each client's personal settings
|
|
43
|
+
lines.push("", `--client: ${INSTALL_CLIENTS.join(", ")} (default: every client)`, "Reads each client's personal settings. Nothing is written.", "A saved key is checked with flovia_status. Codex sign-in is read with codex mcp list. flovia doctor --client claude-code reads a claude.ai Flovia row with claude mcp list.", "--network also checks that /mcp answers. The check waits --timeout seconds (default 15).", " flovia doctor", " flovia doctor --client codex --network");
|
|
44
44
|
if (command === "sandbox")
|
|
45
45
|
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.");
|
|
46
46
|
if (command === "workspace")
|
package/dist/doctor.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `flovia doctor [--client <name>]`: a read-only check of the Flovia entry `flovia install` writes. It reads each client's personal
|
|
3
3
|
* settings, reports whether the entry points at Flovia's /mcp and how it signs in, and whether the key it needs is readable. It never
|
|
4
|
-
* writes
|
|
4
|
+
* writes settings, and never prints a key, header value or configured URL. Codex sign-in is read with `codex mcp list`.
|
|
5
|
+
* A claude.ai-synced Flovia row is read with `claude mcp list`.
|
|
5
6
|
* Parsing here is pure; cli.ts supplies the files and the optional network check.
|
|
6
7
|
*/
|
|
7
8
|
import { type InstallClient } from "./install.js";
|
|
9
|
+
/** Claude Code's user-scope add. Local scope would hide this entry in the directory where it was added. */
|
|
10
|
+
export declare const claudeUserAdd: (resource: string) => string;
|
|
8
11
|
type CheckResult = "ok" | "warn" | "fail";
|
|
9
12
|
export interface Check {
|
|
10
13
|
name: string;
|
|
@@ -30,12 +33,30 @@ export interface Entry {
|
|
|
30
33
|
url: string | null;
|
|
31
34
|
auth: DoctorAuth;
|
|
32
35
|
keyEnv?: string; /** Hermes `enabled: false`: present but not loaded. */
|
|
33
|
-
disabled?: true;
|
|
36
|
+
disabled?: true; /** Set when the JSON key is not exactly `flovia` (for example `Flovia`). */
|
|
37
|
+
name?: string;
|
|
34
38
|
}
|
|
35
39
|
/** The mcpServers.flovia entry of a Claude Code or Cursor JSON file; null when there is none; throws on invalid JSON. */
|
|
36
40
|
export declare function jsonEntry(text: string, keyPath?: string | null): Entry | null;
|
|
41
|
+
/** `flovia` wins. `Flovia` is the same server name with different case, which Cursor and VS Code keep as a second entry. */
|
|
42
|
+
export declare function floviaServer(servers: unknown): Record<string, unknown> | undefined;
|
|
43
|
+
export declare function floviaServerName(servers: unknown): string | null;
|
|
44
|
+
/** Claude Code's local scope lives at projects[cwd].mcpServers and overrides the user entry in the same file. */
|
|
45
|
+
export declare function claudeLocalEntry(text: string, cwd: string, keyPath?: string | null): Entry | null;
|
|
37
46
|
/** [mcp_servers.flovia] in Codex's config.toml: url and bearer_token_env_var (or a literal http_headers bearer). Line-based on purpose. */
|
|
38
47
|
export declare function tomlEntry(text: string): Entry | null;
|
|
48
|
+
/** The row whose name is exactly flovia. `flovia-dev` is a different server. Following lines belong to it until the next server URL. */
|
|
49
|
+
export declare function codexFloviaBlock(stdout: string): string | null;
|
|
50
|
+
/**
|
|
51
|
+
* A `claude.ai Flovia` row in `claude mcp list`. The local server named `flovia` is a different row.
|
|
52
|
+
* `connected` is the ✔ Connected status. "Not connected" is not it.
|
|
53
|
+
*/
|
|
54
|
+
export declare function claudeSyncedFlovia(stdout: string): {
|
|
55
|
+
url: string;
|
|
56
|
+
connected: boolean;
|
|
57
|
+
} | null;
|
|
58
|
+
/** Read the effective row, keeping the URL, enabled state and Auth column separate. */
|
|
59
|
+
export declare function codexLoginState(stdout: string, resource: string): "out" | "in" | "absent" | "unknown" | "wrong-url" | "disabled" | "wrong-auth";
|
|
39
60
|
/**
|
|
40
61
|
* mcp_servers > flovia > url/auth in Hermes's config.yaml, as `flovia install` writes it. Line-based on purpose.
|
|
41
62
|
* Only a flovia directly under mcp_servers counts, and only url/auth directly under it; a flovia nested in another
|
package/dist/doctor.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `flovia doctor [--client <name>]`: a read-only check of the Flovia entry `flovia install` writes. It reads each client's personal
|
|
3
3
|
* settings, reports whether the entry points at Flovia's /mcp and how it signs in, and whether the key it needs is readable. It never
|
|
4
|
-
* writes
|
|
4
|
+
* writes settings, and never prints a key, header value or configured URL. Codex sign-in is read with `codex mcp list`.
|
|
5
|
+
* A claude.ai-synced Flovia row is read with `claude mcp list`.
|
|
5
6
|
* Parsing here is pure; cli.ts supplies the files and the optional network check.
|
|
6
7
|
*/
|
|
7
8
|
import { DEFAULT_KEY_PATH, headersHelper, INSTALL_CLIENTS, isObject } from "./install.js";
|
|
9
|
+
/** Claude Code's user-scope add. Local scope would hide this entry in the directory where it was added. */
|
|
10
|
+
export const claudeUserAdd = (resource) => `claude mcp add --scope user --transport http flovia ${resource}`;
|
|
8
11
|
/** Where `flovia install` puts each client's personal settings (user scope). */
|
|
9
12
|
export function settingsPath(client, home, env = {}) {
|
|
10
13
|
// The clients move their settings with these (Claude Code 2.1.328 writes `claude mcp add --scope user` to $CLAUDE_CONFIG_DIR/.claude.json).
|
|
@@ -25,28 +28,61 @@ const SIGN_IN_AGAIN = {
|
|
|
25
28
|
hermes: "Run: hermes mcp login flovia",
|
|
26
29
|
"claude-desktop": "In Claude's Settings > Connectors, disconnect Flovia and connect it again.",
|
|
27
30
|
};
|
|
28
|
-
|
|
31
|
+
/** Claude Code stores `Bearer ${FLOVIA_KEY}`; Cursor stores `Bearer ${env:FLOVIA_KEY}`. Both name a variable. */
|
|
32
|
+
const ENV_REF = /^Bearer \$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)\}$/;
|
|
29
33
|
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)
|
|
30
34
|
? { url, auth: "key-env", keyEnv } : { url, auth: "unknown" };
|
|
31
35
|
/** The mcpServers.flovia entry of a Claude Code or Cursor JSON file; null when there is none; throws on invalid JSON. */
|
|
32
36
|
export function jsonEntry(text, keyPath = DEFAULT_KEY_PATH) {
|
|
33
|
-
const doc = JSON.parse(text);
|
|
34
|
-
if (!isObject(doc) || !isObject(doc["mcpServers"])
|
|
37
|
+
const doc = JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
38
|
+
if (!isObject(doc) || !isObject(doc["mcpServers"]))
|
|
35
39
|
return null;
|
|
36
|
-
const
|
|
40
|
+
const serverName = floviaServerName(doc["mcpServers"]);
|
|
41
|
+
const named = floviaServer(doc["mcpServers"]);
|
|
42
|
+
if (named === undefined || !isObject(named) || serverName === null)
|
|
43
|
+
return null;
|
|
44
|
+
const e = named, url = typeof e["url"] === "string" ? e["url"] : null;
|
|
45
|
+
const namedEntry = (entry) => serverName === "flovia" ? entry : { ...entry, name: serverName };
|
|
37
46
|
if (Object.hasOwn(e, "headersHelper"))
|
|
38
|
-
return { url, auth: keyPath !== null && !keyPath.includes("'") && (keyPath.startsWith("/") || keyPath.startsWith("~/")) && e["headersHelper"] === headersHelper(keyPath) ? "key-file" : "unknown" };
|
|
47
|
+
return namedEntry({ url, auth: keyPath !== null && !keyPath.includes("'") && (keyPath.startsWith("/") || keyPath.startsWith("~/")) && e["headersHelper"] === headersHelper(keyPath) ? "key-file" : "unknown" });
|
|
39
48
|
const headers = isObject(e["headers"]) ? e["headers"] : {};
|
|
40
49
|
const authHeader = Object.entries(headers).find(([k]) => k.toLowerCase() === "authorization")?.[1];
|
|
41
50
|
if (authHeader === undefined)
|
|
42
|
-
return { url, auth: "oauth" };
|
|
51
|
+
return namedEntry({ url, auth: "oauth" });
|
|
43
52
|
const ref = typeof authHeader === "string" ? ENV_REF.exec(authHeader) : null;
|
|
44
|
-
return ref ? envEntry(url, ref[1]) : { url, auth: typeof authHeader === "string" && authHeader.includes("${
|
|
53
|
+
return namedEntry(ref ? envEntry(url, ref[1]) : { url, auth: typeof authHeader === "string" && authHeader.includes("${") ? "unknown" : "key-in-settings" });
|
|
54
|
+
}
|
|
55
|
+
/** `flovia` wins. `Flovia` is the same server name with different case, which Cursor and VS Code keep as a second entry. */
|
|
56
|
+
export function floviaServer(servers) {
|
|
57
|
+
if (!isObject(servers))
|
|
58
|
+
return undefined;
|
|
59
|
+
if (isObject(servers["flovia"]))
|
|
60
|
+
return servers["flovia"];
|
|
61
|
+
const key = Object.keys(servers).find((name) => name.toLowerCase() === "flovia");
|
|
62
|
+
return key !== undefined && isObject(servers[key]) ? servers[key] : undefined;
|
|
63
|
+
}
|
|
64
|
+
export function floviaServerName(servers) {
|
|
65
|
+
if (!isObject(servers))
|
|
66
|
+
return null;
|
|
67
|
+
if (isObject(servers["flovia"]))
|
|
68
|
+
return "flovia";
|
|
69
|
+
return Object.keys(servers).find((name) => name.toLowerCase() === "flovia") ?? null;
|
|
70
|
+
}
|
|
71
|
+
/** Claude Code's local scope lives at projects[cwd].mcpServers and overrides the user entry in the same file. */
|
|
72
|
+
export function claudeLocalEntry(text, cwd, keyPath = DEFAULT_KEY_PATH) {
|
|
73
|
+
const doc = JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
74
|
+
if (!isObject(doc) || !isObject(doc["projects"]) || cwd === "")
|
|
75
|
+
return null;
|
|
76
|
+
const folder = Object.keys(doc["projects"]).find((path) => path === cwd || path.replace(/\/+$/, "") === cwd.replace(/\/+$/, ""));
|
|
77
|
+
const project = folder !== undefined ? doc["projects"][folder] : undefined;
|
|
78
|
+
if (!isObject(project) || floviaServer(project["mcpServers"]) === undefined)
|
|
79
|
+
return null;
|
|
80
|
+
return jsonEntry(JSON.stringify({ mcpServers: project["mcpServers"] }), keyPath);
|
|
45
81
|
}
|
|
46
82
|
const unquote = (v) => v.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
|
|
47
83
|
/** [mcp_servers.flovia] in Codex's config.toml: url and bearer_token_env_var (or a literal http_headers bearer). Line-based on purpose. */
|
|
48
84
|
export function tomlEntry(text) {
|
|
49
|
-
let inside = false, found = false, url = null, keyEnv, literal = false;
|
|
85
|
+
let inside = false, found = false, url = null, keyEnv, literal = false, disabled = false;
|
|
50
86
|
for (const raw of text.split(/\r?\n/)) {
|
|
51
87
|
const line = raw.replace(/\s+#.*$/, "").trim();
|
|
52
88
|
if (line.startsWith("[")) {
|
|
@@ -63,12 +99,92 @@ export function tomlEntry(text) {
|
|
|
63
99
|
url = unquote(m[2]);
|
|
64
100
|
else if (m[1] === "bearer_token_env_var")
|
|
65
101
|
keyEnv = unquote(m[2]);
|
|
102
|
+
else if (m[1] === "enabled")
|
|
103
|
+
disabled = /^(false|no|off|0)$/i.test(unquote(m[2]));
|
|
66
104
|
else if (m[1] === "http_headers" && /authorization/i.test(m[2]))
|
|
67
105
|
literal = true;
|
|
68
106
|
}
|
|
69
107
|
if (!found)
|
|
70
108
|
return null;
|
|
71
|
-
|
|
109
|
+
const entry = keyEnv !== undefined ? envEntry(url, keyEnv) : { url, auth: literal ? "key-in-settings" : "oauth" };
|
|
110
|
+
return disabled ? { ...entry, disabled: true } : entry;
|
|
111
|
+
}
|
|
112
|
+
/** The row whose name is exactly flovia. `flovia-dev` is a different server. Following lines belong to it until the next server URL. */
|
|
113
|
+
export function codexFloviaBlock(stdout) {
|
|
114
|
+
const lines = stdout.split(/\r?\n/);
|
|
115
|
+
const at = lines.findIndex((line) => /^\s*flovia(?:\s|$)/i.test(line));
|
|
116
|
+
if (at < 0)
|
|
117
|
+
return null;
|
|
118
|
+
const block = [lines[at] ?? ""];
|
|
119
|
+
for (const line of lines.slice(at + 1)) {
|
|
120
|
+
if (line.trim() === "")
|
|
121
|
+
break;
|
|
122
|
+
if (/^\s*\S+\s+https?:\/\//i.test(line))
|
|
123
|
+
break;
|
|
124
|
+
block.push(line);
|
|
125
|
+
}
|
|
126
|
+
return block.join("\n");
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* A `claude.ai Flovia` row in `claude mcp list`. The local server named `flovia` is a different row.
|
|
130
|
+
* `connected` is the ✔ Connected status. "Not connected" is not it.
|
|
131
|
+
*/
|
|
132
|
+
export function claudeSyncedFlovia(stdout) {
|
|
133
|
+
for (const raw of stdout.split(/\r?\n/)) {
|
|
134
|
+
const line = raw.trim();
|
|
135
|
+
const m = /^claude\.ai\s+Flovia\b.*?(\bhttps:\/\/\S+)/i.exec(line);
|
|
136
|
+
if (!m?.[1])
|
|
137
|
+
continue;
|
|
138
|
+
const url = m[1].replace(/[^A-Za-z0-9:/._~-].*$/, "").replace(/\/$/, "");
|
|
139
|
+
const connected = /\bconnected\b/i.test(line) && !/\bnot\s+connected\b/i.test(line) && !/\bdisconnected\b/i.test(line);
|
|
140
|
+
return { url, connected };
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
/** Codex prints Auth as one of these, and pads every column but the last full one with spaces (mcp_cmd.rs). */
|
|
145
|
+
const CODEX_AUTH = ["Not logged in", "Bearer token", "Unsupported", "Unknown", "OAuth"];
|
|
146
|
+
/** Status is `enabled`, `disabled`, or `disabled: reason`. A full column leaves only one space before the next. */
|
|
147
|
+
function codexStatusAndAuth(tail) {
|
|
148
|
+
const trimmed = tail.trim();
|
|
149
|
+
let auth = null;
|
|
150
|
+
let before = trimmed;
|
|
151
|
+
for (const name of CODEX_AUTH) {
|
|
152
|
+
if (trimmed === name) {
|
|
153
|
+
auth = name;
|
|
154
|
+
before = "";
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
if (trimmed.endsWith(` ${name}`)) {
|
|
158
|
+
auth = name;
|
|
159
|
+
before = trimmed.slice(0, -(name.length + 1)).trim();
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const status = /(?:^|\s)disabled(?::\s+\S.*)?$/.test(before) ? "disabled"
|
|
164
|
+
: /(?:^|\s)enabled$/.test(before) ? "enabled" : "missing";
|
|
165
|
+
return { status, auth };
|
|
166
|
+
}
|
|
167
|
+
/** Read the effective row, keeping the URL, enabled state and Auth column separate. */
|
|
168
|
+
export function codexLoginState(stdout, resource) {
|
|
169
|
+
const block = codexFloviaBlock(stdout);
|
|
170
|
+
if (block === null)
|
|
171
|
+
return "absent";
|
|
172
|
+
const firstLine = block.split("\n", 1)[0] ?? "";
|
|
173
|
+
const row = /^\s*flovia\s+(\S+)\s+(.+)$/i.exec(firstLine);
|
|
174
|
+
if (!row?.[1] || !row[2])
|
|
175
|
+
return "unknown";
|
|
176
|
+
if (urlCheck(row[1], resource).result !== "ok")
|
|
177
|
+
return "wrong-url";
|
|
178
|
+
const { status, auth } = codexStatusAndAuth(row[2]);
|
|
179
|
+
if (status === "disabled")
|
|
180
|
+
return "disabled";
|
|
181
|
+
if (auth === "Not logged in" || /not logged in|authorization state not found/i.test(block))
|
|
182
|
+
return "out";
|
|
183
|
+
if (status === "enabled" && auth === "OAuth")
|
|
184
|
+
return "in";
|
|
185
|
+
if (status === "enabled" && (auth === "Unsupported" || auth === "Bearer token" || auth === "Unknown"))
|
|
186
|
+
return "wrong-auth";
|
|
187
|
+
return "unknown";
|
|
72
188
|
}
|
|
73
189
|
/**
|
|
74
190
|
* mcp_servers > flovia > url/auth in Hermes's config.yaml, as `flovia install` writes it. Line-based on purpose.
|
|
@@ -161,7 +277,8 @@ export function inspect(client, text, resource, home, env, asked, keyPath = DEFA
|
|
|
161
277
|
if (client === "claude-desktop")
|
|
162
278
|
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" }],
|
|
163
279
|
next: ["Check Settings > Connectors in Claude: Flovia should be listed and connected.", `If tools fail with a sign-in error: ${SIGN_IN_AGAIN[client]}`] };
|
|
164
|
-
|
|
280
|
+
// Codex's setup.md step is the person's own `codex mcp add`, not `flovia install` (that needs npx and is a different next step).
|
|
281
|
+
const install = client === "codex" ? `codex mcp add flovia --url ${resource} (the person runs this in their own terminal)` : `flovia install --client ${client}`;
|
|
165
282
|
const notSetUp = (detail) => ({ client, state: asked ? "fail" : "not_set_up", settings, auth: null,
|
|
166
283
|
checks: [{ name: "settings", result: asked ? "fail" : "warn", detail }], next: [`To add Flovia: ${install}`] });
|
|
167
284
|
if (text === null)
|
|
@@ -171,7 +288,7 @@ export function inspect(client, text, resource, home, env, asked, keyPath = DEFA
|
|
|
171
288
|
entry = client === "codex" ? tomlEntry(text) : client === "hermes" ? yamlEntry(text) : jsonEntry(text, client === "claude-code" ? keyPath : null);
|
|
172
289
|
}
|
|
173
290
|
catch {
|
|
174
|
-
return { client, state: "fail", settings, auth: null, checks: [{ name: "settings", result: "fail", detail: `${settings} is not valid JSON;
|
|
291
|
+
return { client, state: "fail", settings, auth: null, checks: [{ name: "settings", result: "fail", detail: `${settings} is not valid JSON; doctor could not parse it` }], next: ["Fix the file's syntax, then run flovia doctor again. Whether the client accepts comments or a trailing comma is separate from this parse."] };
|
|
175
292
|
}
|
|
176
293
|
if (entry === null)
|
|
177
294
|
return notSetUp(`${settings} has no flovia entry`);
|
|
@@ -179,20 +296,28 @@ export function inspect(client, text, resource, home, env, asked, keyPath = DEFA
|
|
|
179
296
|
const next = [];
|
|
180
297
|
if (entry.disabled) {
|
|
181
298
|
checks.push({ name: "enabled", result: "fail", detail: "the flovia entry is turned off (enabled: false); the client does not load it" });
|
|
182
|
-
next.push(
|
|
299
|
+
next.push(client === "codex"
|
|
300
|
+
? `Turn Flovia on (delete enabled = false), or run: codex mcp remove flovia, then codex mcp add flovia --url ${resource}. Then quit the app fully and open it again.`
|
|
301
|
+
: `Remove enabled: false from the flovia entry in ${settings} (or set it to true), then restart the client.`);
|
|
183
302
|
}
|
|
184
303
|
if (entry.auth === "unknown")
|
|
185
304
|
next.push("Check the client's authentication settings manually; doctor did not read a key or run a helper.");
|
|
305
|
+
if (entry.name !== undefined) {
|
|
306
|
+
checks.push({ name: "name", result: "warn", detail: `the entry is named ${entry.name}; install and doctor use flovia, so this is a second server` });
|
|
307
|
+
next.push(`Rename mcpServers.${entry.name} to flovia in ${settings}. Until then, flovia install adds a second server with the same URL.`);
|
|
308
|
+
}
|
|
186
309
|
checks.push({ name: "auth", result: entry.auth === "key-in-settings" || entry.auth === "unknown" ? "warn" : "ok", detail: AUTH_TEXT[entry.auth] });
|
|
187
310
|
if (entry.auth === "key-in-settings")
|
|
188
|
-
next.push(
|
|
311
|
+
next.push(client === "codex"
|
|
312
|
+
? `Move the key out of ${settings}. The person runs: codex mcp remove flovia, then codex mcp add flovia --url ${resource} --bearer-token-env-var FLOVIA_KEY, with the key in the environment that starts Codex. Then issue a new key in Console if this file was ever shared.`
|
|
313
|
+
: `Move the key out of ${settings}: rerun flovia install --client ${client} --auth key (it reads the key at connect time), then issue a new key in Console if this file was ever shared.`);
|
|
189
314
|
if (entry.auth === "key-env" && entry.keyEnv !== undefined) {
|
|
190
315
|
const set = Boolean(env[entry.keyEnv]?.trim());
|
|
191
|
-
checks.push({ name: "key", result: set ? "ok" : "warn", detail:
|
|
316
|
+
checks.push({ name: "key", result: set ? "ok" : "warn", detail: set ? "a saved key is available where this app starts" : "no saved key is available where this app starts" });
|
|
192
317
|
if (!set)
|
|
193
|
-
next.push(
|
|
318
|
+
next.push("This app reads the key from the environment that starts it, and that value is missing. Set the key there, then open the app again. Do not paste the key into the chat.");
|
|
194
319
|
}
|
|
195
|
-
if (entry.auth === "oauth")
|
|
320
|
+
if (entry.auth === "oauth" && !entry.disabled)
|
|
196
321
|
next.push(`If tools fail with a sign-in error or the client keeps reconnecting, the sign-in was revoked or expired. ${SIGN_IN_AGAIN[client]}`);
|
|
197
322
|
return { client, state: "ok", settings, auth: entry.auth, ...(entry.keyEnv !== undefined ? { keyEnv: entry.keyEnv } : {}), checks, next };
|
|
198
323
|
}
|
package/dist/doctorcommand.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { COMMANDS, Usage, didYouMean, mcpBase, str } from "./args.js";
|
|
2
|
-
import { inspect, renderDoctor, settingsPath, settle } from "./doctor.js";
|
|
2
|
+
import { claudeLocalEntry, claudeSyncedFlovia, claudeUserAdd, codexLoginState, inspect, jsonEntry, renderDoctor, settingsPath, settle } from "./doctor.js";
|
|
3
|
+
import { homeDir } from "./homedir.js";
|
|
3
4
|
import { FloviaClient, FloviaError } from "./index.js";
|
|
4
5
|
import { INSTALL_CLIENTS } from "./install.js";
|
|
5
6
|
import { CONSOLE } from "./output.js";
|
|
@@ -10,16 +11,20 @@ export async function doctor(p, io, out, json, remember, o, fromFile, DEFAULT_KE
|
|
|
10
11
|
throw new Usage(`Usage: flovia ${COMMANDS["doctor"]?.usage}`);
|
|
11
12
|
if (client !== undefined && !INSTALL_CLIENTS.includes(client))
|
|
12
13
|
throw new Usage(`doctor: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${didYouMean(client, [...INSTALL_CLIENTS])}`);
|
|
13
|
-
const home = io.env
|
|
14
|
+
const home = homeDir(io.env);
|
|
14
15
|
if (!home)
|
|
15
|
-
throw new Usage("doctor: HOME is not set");
|
|
16
|
+
throw new Usage("doctor: HOME is not set (on Windows, USERPROFILE is used when HOME is absent)");
|
|
16
17
|
const base = mcpBase(o.baseUrl, "doctor");
|
|
17
18
|
const resource = `${base.origin}/mcp`, network = p.flags.has("--network"), keyFlag = str(p.flags.get("--key-file"));
|
|
18
19
|
const clients = client === undefined ? [...INSTALL_CLIENTS] : [client];
|
|
19
20
|
const doFetch = io.fetch ?? fetch;
|
|
21
|
+
// A saved key is checked against Flovia even without --network. 15s, not the 300s sign-in wait: a machine with no network must say so instead of sitting silent.
|
|
22
|
+
const seconds = o.timeout ?? 15;
|
|
23
|
+
const offline = (what, timedOut) => `${what} could not be reached from this machine${timedOut ? ` within ${seconds} seconds` : ""}. Connect this computer to the internet, or add the Flovia connector on a computer that can. Do not retry in a loop.`;
|
|
24
|
+
const isTimeout = (e) => e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
|
|
20
25
|
/** One deadline includes fetch and body consumption/cancellation, even for injected transports. */
|
|
21
26
|
const timed = async (request) => {
|
|
22
|
-
const signal = AbortSignal.timeout(
|
|
27
|
+
const signal = AbortSignal.timeout(seconds * 1000);
|
|
23
28
|
let abort = () => { };
|
|
24
29
|
try {
|
|
25
30
|
const deadline = new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); });
|
|
@@ -43,24 +48,23 @@ export async function doctor(p, io, out, json, remember, o, fromFile, DEFAULT_KE
|
|
|
43
48
|
? { result: "ok", detail: `${resource} answers and asks for sign-in or a key` }
|
|
44
49
|
: { result: "warn", detail: `${resource} answered HTTP ${r.status}, not the expected 401 with a sign-in challenge` };
|
|
45
50
|
}
|
|
46
|
-
catch {
|
|
47
|
-
reachable = { result: "fail", detail:
|
|
51
|
+
catch (e) {
|
|
52
|
+
reachable = { result: "fail", detail: offline(resource, isTimeout(e)) };
|
|
48
53
|
}
|
|
49
54
|
return reachable;
|
|
50
55
|
};
|
|
51
56
|
/** A key is read only to check it; it goes into the scrub list first, so no line can show it. */
|
|
52
57
|
const tryKey = async (k, r) => {
|
|
53
58
|
remember(k);
|
|
54
|
-
if (!network)
|
|
55
|
-
return;
|
|
56
59
|
// Same format as the Relay's issued-key schema; never send another service's credential to Flovia.
|
|
57
60
|
if (!/^flv_[A-Za-z0-9_-]{43}$/.test(k)) {
|
|
58
61
|
r.checks.push({ name: "key accepted", result: "warn", detail: "The configured value is not a Flovia key; it was not sent." });
|
|
62
|
+
r.next.push(`The saved value is not a Flovia key. Create one in Console (${CONSOLE}), save it, then restart ${r.client}.`);
|
|
59
63
|
return;
|
|
60
64
|
}
|
|
61
65
|
try {
|
|
62
66
|
await timed(async (signal) => {
|
|
63
|
-
const c = new FloviaClient({ apiKey: k, baseUrl: base.origin,
|
|
67
|
+
const c = new FloviaClient({ apiKey: k, baseUrl: base.origin, timeoutMs: seconds * 1000,
|
|
64
68
|
fetch: (req) => { req.headers.set("X-Flovia-Client", "flovia-cli"); return doFetch(new Request(req, { signal })); }, onContractMismatch: () => undefined });
|
|
65
69
|
await c.status();
|
|
66
70
|
});
|
|
@@ -73,8 +77,11 @@ export async function doctor(p, io, out, json, remember, o, fromFile, DEFAULT_KE
|
|
|
73
77
|
r.next.push(needsRegistration && e.nextStep
|
|
74
78
|
? e.nextStep : `Issue or re-enable a key in Console (${CONSOLE}), save it, then restart ${r.client}.`);
|
|
75
79
|
}
|
|
80
|
+
else if (e instanceof FloviaError && e.code !== "timeout" && e.code !== "network_error") {
|
|
81
|
+
r.checks.push({ name: "key accepted", result: "warn", detail: `flovia_status answered ${e.code}` });
|
|
82
|
+
}
|
|
76
83
|
else
|
|
77
|
-
r.checks.push({ name: "key accepted", result: "
|
|
84
|
+
r.checks.push({ name: "key accepted", result: "fail", detail: offline("flovia_status", e instanceof FloviaError ? e.code === "timeout" : isTimeout(e)) });
|
|
78
85
|
}
|
|
79
86
|
};
|
|
80
87
|
const reports = [];
|
|
@@ -93,7 +100,9 @@ export async function doctor(p, io, out, json, remember, o, fromFile, DEFAULT_KE
|
|
|
93
100
|
}
|
|
94
101
|
}
|
|
95
102
|
const r = inspect(name, text, resource, home, io.env, client !== undefined, keyFlag);
|
|
96
|
-
|
|
103
|
+
// A saved key is sent only when this entry is the one that would call this environment: the URL matches and the entry is on.
|
|
104
|
+
const maySend = r.checks.some((c) => c.name === "url" && c.result === "ok") && !r.checks.some((c) => c.name === "enabled" && c.result === "fail");
|
|
105
|
+
if (maySend && r.state === "ok" && r.auth === "key-file") {
|
|
97
106
|
const shown = keyFlag === undefined ? `~/${DEFAULT_KEY_FILE}` : "--key-file";
|
|
98
107
|
try {
|
|
99
108
|
const keyPath = keyFlag ?? `~/${DEFAULT_KEY_FILE}`;
|
|
@@ -108,14 +117,165 @@ export async function doctor(p, io, out, json, remember, o, fromFile, DEFAULT_KE
|
|
|
108
117
|
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).`);
|
|
109
118
|
}
|
|
110
119
|
}
|
|
111
|
-
if (r.state === "ok" && r.auth === "key-env" && r.keyEnv !== undefined) {
|
|
120
|
+
if (maySend && r.state === "ok" && r.auth === "key-env" && r.keyEnv !== undefined) {
|
|
112
121
|
const k = io.env[r.keyEnv]?.trim();
|
|
113
122
|
if (k)
|
|
114
123
|
await tryKey(k, r);
|
|
115
124
|
}
|
|
125
|
+
// OAuth in the file is not a finished sign-in. Codex can show Authentication complete in the browser while `codex mcp list` still says Not logged in.
|
|
126
|
+
if (name === "codex" && r.state === "ok" && r.auth === "oauth" && io.capture && !r.checks.some((c) => c.name === "enabled" && c.result === "fail")) {
|
|
127
|
+
const again = "The person runs codex mcp login flovia in their own terminal and leaves it open until it prints Successfully logged in. A browser page that says Authentication complete is not a finished sign-in. Then call flovia_status. If the browser cannot connect, the command had already ended: they start it again there, or use a key from Console.";
|
|
128
|
+
try {
|
|
129
|
+
const listed = await io.capture("codex", ["mcp", "list"], { timeoutMs: 10_000 });
|
|
130
|
+
const state = listed.code === 0 ? codexLoginState(listed.stdout, resource) : "absent";
|
|
131
|
+
if (listed.code === "timeout") {
|
|
132
|
+
r.checks.push({ name: "sign-in", result: "fail", detail: "codex mcp list did not finish within 10 seconds" });
|
|
133
|
+
r.next.push(again);
|
|
134
|
+
}
|
|
135
|
+
else if (state === "wrong-url" || state === "disabled" || state === "wrong-auth") {
|
|
136
|
+
const detail = state === "wrong-url" ? "the flovia row in codex mcp list does not point at the expected Flovia URL"
|
|
137
|
+
: state === "disabled" ? "the flovia row in codex mcp list is disabled"
|
|
138
|
+
: "the flovia row in codex mcp list does not use OAuth";
|
|
139
|
+
r.checks.push({ name: "sign-in", result: "fail", detail });
|
|
140
|
+
r.next = r.next.filter((step) => !step.startsWith("If tools fail with a sign-in error"));
|
|
141
|
+
r.next.push("Check the active Flovia MCP entry in Codex before trying to sign in again.");
|
|
142
|
+
}
|
|
143
|
+
else if (state === "out") {
|
|
144
|
+
r.checks.push({ name: "sign-in", result: "fail", detail: "codex mcp list says Not logged in" });
|
|
145
|
+
r.next = r.next.filter((step) => !step.startsWith("If tools fail with a sign-in error"));
|
|
146
|
+
r.next.push(again);
|
|
147
|
+
}
|
|
148
|
+
else if (listed.code !== 0) {
|
|
149
|
+
r.checks.push({ name: "sign-in", result: "warn", detail: `codex mcp list exited ${listed.code}` });
|
|
150
|
+
}
|
|
151
|
+
else if (state === "in") {
|
|
152
|
+
r.checks.push({ name: "sign-in", result: "ok", detail: "codex mcp list shows OAuth for flovia. Call flovia_status before treating sign-in as finished." });
|
|
153
|
+
}
|
|
154
|
+
else if (state === "absent") {
|
|
155
|
+
r.checks.push({ name: "sign-in", result: "warn", detail: "codex mcp list did not show a flovia row. Call flovia_status before treating sign-in as finished." });
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
r.checks.push({ name: "sign-in", result: "warn", detail: "codex mcp list did not show OAuth for flovia. Call flovia_status before treating sign-in as finished." });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
if (e.code === "ENOENT") {
|
|
163
|
+
r.checks.push({ name: "sign-in", result: "warn", detail: "codex was not found, so sign-in was not checked. Call flovia_status before treating sign-in as finished." });
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
r.checks.push({ name: "sign-in", result: "fail", detail: "codex mcp list could not be run" });
|
|
167
|
+
r.next.push(again);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
// Only an explicit `flovia doctor --client claude-code` reads `claude mcp list`. A plain doctor does not start Claude's servers.
|
|
172
|
+
// Connected alone is a warning: the session may already have the tools, and doctor cannot see them.
|
|
173
|
+
if (name === "claude-code" && client === "claude-code" && io.capture) {
|
|
174
|
+
const restart = "If this session has no Flovia tools, quit Claude Code and open it again, then check in a new session. A connector synced from claude.ai is not in the session until that restart. A new session in the app that is already running does not load it.";
|
|
175
|
+
const add = `If the tools are still missing, the person runs: ${claudeUserAdd(resource)} then opens /mcp and signs in.`;
|
|
176
|
+
try {
|
|
177
|
+
const listed = await io.capture("claude", ["mcp", "list"], { timeoutMs: 10_000 });
|
|
178
|
+
const row = listed.code === 0 ? claudeSyncedFlovia(listed.stdout) : null;
|
|
179
|
+
if (row?.connected) {
|
|
180
|
+
const detail = "claude mcp list shows claude.ai Flovia as Connected. A connector synced from claude.ai is not in the session until Claude Code is quit and opened again.";
|
|
181
|
+
// A missing file is fail when --client was asked. Connected with no local flovia may still work, so it is a warning.
|
|
182
|
+
const ownFlovia = listed.stdout.split(/\r?\n/).some((line) => /^\s*flovia\b/i.test(line));
|
|
183
|
+
const noLocal = r.auth === null && !ownFlovia && r.checks.some((c) => c.name === "settings" && /was not found|has no flovia entry/.test(c.detail));
|
|
184
|
+
if (noLocal) {
|
|
185
|
+
r.state = "ok";
|
|
186
|
+
r.auth = "oauth";
|
|
187
|
+
const settings = r.checks.find((c) => c.name === "settings");
|
|
188
|
+
r.checks = [settings ? { ...settings, result: "warn" } : { name: "settings", result: "warn", detail: `${path} has no flovia entry` }, { name: "claude.ai", result: "warn", detail }];
|
|
189
|
+
r.next = [`${restart} ${add}`];
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
r.checks.push({ name: "claude.ai", result: "warn", detail });
|
|
193
|
+
r.next.push(restart);
|
|
194
|
+
}
|
|
195
|
+
if (row.url.replace(/\/$/, "") !== resource)
|
|
196
|
+
r.checks.push({ name: "claude.ai url", result: "warn", detail: `the claude.ai Flovia row does not point at ${resource}` });
|
|
197
|
+
}
|
|
198
|
+
else if (listed.code === "timeout") {
|
|
199
|
+
r.checks.push({ name: "claude.ai", result: "warn", detail: "claude mcp list did not finish within 10 seconds" });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
if (e.code !== "ENOENT")
|
|
204
|
+
r.checks.push({ name: "claude.ai", result: "warn", detail: "claude mcp list could not be run" });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (name === "claude-code" && text !== null) {
|
|
208
|
+
const cwd = io.env["PWD"]?.trim() || "";
|
|
209
|
+
let userEntry = null;
|
|
210
|
+
try {
|
|
211
|
+
userEntry = jsonEntry(text);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
userEntry = null;
|
|
215
|
+
}
|
|
216
|
+
const norm = (u) => (u ?? "").replace(/\/$/, "");
|
|
217
|
+
const applyScope = (kind, entry, remove) => {
|
|
218
|
+
const only = userEntry === null;
|
|
219
|
+
const differs = userEntry !== null && (norm(entry.url) !== norm(userEntry.url) || entry.auth !== userEntry.auth);
|
|
220
|
+
const bad = norm(entry.url) !== resource || entry.auth === "unknown" || entry.disabled === true;
|
|
221
|
+
if (!only && (differs || bad)) {
|
|
222
|
+
r.state = "ok";
|
|
223
|
+
r.checks.push({ name: kind, result: "fail", detail: kind === "local scope"
|
|
224
|
+
? "this directory has a Claude Code local-scope flovia that does not match the user entry"
|
|
225
|
+
: `${cwd}/.mcp.json has a flovia entry that does not match the user entry` });
|
|
226
|
+
r.next.unshift(remove);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (only && bad) {
|
|
230
|
+
r.state = "ok";
|
|
231
|
+
r.checks.push({ name: kind, result: "fail", detail: kind === "local scope"
|
|
232
|
+
? "this directory's only flovia entry is local scope, and it does not match this environment"
|
|
233
|
+
: `${cwd}/.mcp.json is the only flovia entry, and it does not match this environment` });
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (only) {
|
|
237
|
+
const settings = r.checks.find((c) => c.name === "settings" && c.result === "fail");
|
|
238
|
+
if (settings)
|
|
239
|
+
settings.result = "warn";
|
|
240
|
+
if (r.state === "fail" || r.state === "not_set_up")
|
|
241
|
+
r.state = "ok";
|
|
242
|
+
}
|
|
243
|
+
r.checks.push({ name: kind, result: "warn", detail: only
|
|
244
|
+
? (kind === "local scope" ? "this directory's local-scope flovia is the entry Claude Code uses" : `${cwd}/.mcp.json is the flovia entry Claude Code uses`)
|
|
245
|
+
: (kind === "local scope" ? "this directory's local-scope flovia matches the user entry" : `${cwd}/.mcp.json matches the user entry`) });
|
|
246
|
+
};
|
|
247
|
+
if (cwd !== "") {
|
|
248
|
+
try {
|
|
249
|
+
const local = claudeLocalEntry(text, cwd);
|
|
250
|
+
if (local)
|
|
251
|
+
applyScope("local scope", local, "Run claude mcp remove flovia --scope local in this directory, then reopen Claude Code. doctor was reading the user entry, which is not the one this directory uses.");
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
r.checks.push({ name: "local scope", result: "warn", detail: "doctor could not parse the local-scope flovia entry" });
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
const projectFile = await io.readFile(`${cwd}/.mcp.json`);
|
|
258
|
+
try {
|
|
259
|
+
const project = jsonEntry(projectFile);
|
|
260
|
+
if (project)
|
|
261
|
+
applyScope("project file", project, `Remove flovia from ${cwd}/.mcp.json, then reopen Claude Code.`);
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
r.checks.push({ name: "project file", result: "warn", detail: `${cwd}/.mcp.json could not be parsed` });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
catch (e) {
|
|
268
|
+
const code = e.code;
|
|
269
|
+
if (code !== "ENOENT")
|
|
270
|
+
r.checks.push({ name: "project file", result: "warn", detail: `${cwd}/.mcp.json could not be read` });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
116
274
|
if (network && r.auth !== "unknown" && (r.state === "ok" || r.state === "manual")) {
|
|
117
275
|
const n = await reach();
|
|
118
276
|
r.checks.push({ name: "network", ...n });
|
|
277
|
+
if (n.result === "fail")
|
|
278
|
+
r.next.push(`Flovia's site (${base.host}) could not be reached from this machine. Restarting the app does not fix that. Allow ${base.host === "api.flovia.dev" ? "api.flovia.dev and console.flovia.dev" : base.host} in this app's network settings, then try again.`);
|
|
119
279
|
}
|
|
120
280
|
reports.push(settle(r));
|
|
121
281
|
}
|
package/dist/homedir.js
ADDED
package/dist/install.js
CHANGED
|
@@ -42,9 +42,9 @@ export function planInstall(o) {
|
|
|
42
42
|
case "cursor":
|
|
43
43
|
return { client, auth, resource,
|
|
44
44
|
steps: [{ kind: "json", path: `${home}/.cursor/mcp.json`,
|
|
45
|
-
entry: auth === "oauth" ? { url: resource } : { url: resource, headers: { Authorization: "Bearer ${env:
|
|
45
|
+
entry: auth === "oauth" ? { url: resource } : { url: resource, headers: { Authorization: "Bearer ${env:FLOVIA_KEY}" } } }],
|
|
46
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." :
|
|
47
|
-
"Set
|
|
47
|
+
"Set FLOVIA_KEY in your shell profile and open Cursor from a terminal (Cursor opened from the Dock won't see it). An entry that already names FLOVIA_API_KEY still reads that variable. Turn Flovia on in MCP settings.", check] };
|
|
48
48
|
case "hermes":
|
|
49
49
|
if (auth === "key")
|
|
50
50
|
throw new InstallRefusal("install: Hermes Agent connects by sign-in only here; use --auth oauth");
|
|
@@ -61,13 +61,26 @@ export function planInstall(o) {
|
|
|
61
61
|
}
|
|
62
62
|
export const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
63
63
|
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
64
|
+
/** `{type:"http", url}` is the same OAuth entry as `{url}`. A different header or URL is not. */
|
|
65
|
+
const equivalentServer = (existing, entry) => {
|
|
66
|
+
if (!isObject(existing))
|
|
67
|
+
return false;
|
|
68
|
+
if (same(existing, entry))
|
|
69
|
+
return true;
|
|
70
|
+
if (existing["url"] !== entry["url"])
|
|
71
|
+
return false;
|
|
72
|
+
if (existing["type"] !== undefined && existing["type"] !== "http" && existing["type"] !== entry["type"])
|
|
73
|
+
return false;
|
|
74
|
+
const rest = (value) => Object.fromEntries(Object.entries(value).filter(([key]) => key !== "type"));
|
|
75
|
+
return same(rest(existing), rest(entry));
|
|
76
|
+
};
|
|
64
77
|
/** The new file text, or "unchanged". A different flovia entry is kept unless force; other entries are always kept. */
|
|
65
78
|
export function mergeJson(existing, entry, force) {
|
|
66
79
|
let doc = {};
|
|
67
80
|
if (existing !== null && existing.trim() !== "") {
|
|
68
81
|
let parsed;
|
|
69
82
|
try {
|
|
70
|
-
parsed = JSON.parse(existing);
|
|
83
|
+
parsed = JSON.parse(existing.replace(/^\uFEFF/, ""));
|
|
71
84
|
}
|
|
72
85
|
catch {
|
|
73
86
|
throw new InstallRefusal("install: the existing config is not valid JSON; fix it first, nothing was changed");
|
|
@@ -79,8 +92,14 @@ export function mergeJson(existing, entry, force) {
|
|
|
79
92
|
const servers = doc["mcpServers"] ?? {};
|
|
80
93
|
if (!isObject(servers))
|
|
81
94
|
throw new InstallRefusal("install: mcpServers in the existing config is not an object; nothing was changed");
|
|
95
|
+
const alias = Object.keys(servers).find((name) => name !== "flovia" && name.toLowerCase() === "flovia");
|
|
96
|
+
if (alias !== undefined && !Object.hasOwn(servers, "flovia")) {
|
|
97
|
+
if (!force)
|
|
98
|
+
throw new InstallRefusal(`install: mcpServers.${alias} is a different name from flovia, so adding flovia would make a second server. Rename ${alias} to flovia, or rerun with --force to replace it`);
|
|
99
|
+
delete servers[alias];
|
|
100
|
+
}
|
|
82
101
|
if (Object.hasOwn(servers, "flovia")) {
|
|
83
|
-
if (
|
|
102
|
+
if (equivalentServer(servers["flovia"], entry))
|
|
84
103
|
return "unchanged";
|
|
85
104
|
if (!force)
|
|
86
105
|
throw new InstallRefusal("install: a different flovia entry is already configured; rerun with --force to replace it");
|
package/dist/installcommand.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { INSTALL_AUTH, INSTALL_CLIENTS, InstallRefusal, mergeJson, mergeYaml, planInstall } from "./install.js";
|
|
2
2
|
import { inspect, settingsPath, yamlEntry } from "./doctor.js";
|
|
3
3
|
import { COMMANDS, Usage, didYouMean, mcpBase, str } from "./args.js";
|
|
4
|
+
import { homeDir } from "./homedir.js";
|
|
4
5
|
const quoteArg = (a) => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replaceAll("'", "'\\''")}'`;
|
|
5
6
|
const describeStep = (s) => s.kind === "exec" ? `run: ${[s.command, ...s.args.map(quoteArg)].join(" ")}`
|
|
6
7
|
: `update: ${s.path} (add flovia to ${s.kind === "json" ? "mcpServers" : "mcp_servers"}, keeping other entries)`;
|
|
@@ -112,9 +113,9 @@ export async function install(p, io, out, err, json, timeout, fromFile) {
|
|
|
112
113
|
throw new Usage(`install: --client must be one of: ${INSTALL_CLIENTS.join(", ")}${client === undefined ? "" : didYouMean(client, [...INSTALL_CLIENTS])}`);
|
|
113
114
|
if (!INSTALL_AUTH.includes(auth))
|
|
114
115
|
throw new Usage("install: --auth must be oauth or key");
|
|
115
|
-
const home = io.env
|
|
116
|
+
const home = homeDir(io.env);
|
|
116
117
|
if (!home)
|
|
117
|
-
throw new Usage("install: HOME is not set");
|
|
118
|
+
throw new Usage("install: HOME is not set (on Windows, USERPROFILE is used when HOME is absent)");
|
|
118
119
|
const base = mcpBase(str(p.flags.get("--base-url")), "install");
|
|
119
120
|
const resource = `${base.origin}/mcp`, keyFile = str(p.flags.get("--key-file"));
|
|
120
121
|
let plan;
|
|
@@ -133,8 +134,13 @@ export async function install(p, io, out, err, json, timeout, fromFile) {
|
|
|
133
134
|
}
|
|
134
135
|
if (plan.client === "codex" && plan.auth === "key" && !io.env["FLOVIA_KEY"]?.trim())
|
|
135
136
|
err("warning: FLOVIA_KEY is not set in this shell; Codex needs it where it starts\n");
|
|
136
|
-
|
|
137
|
-
|
|
137
|
+
const cursorKeyWarning = () => {
|
|
138
|
+
if (plan.client !== "cursor" || plan.auth !== "key" || io.env["FLOVIA_KEY"]?.trim())
|
|
139
|
+
return;
|
|
140
|
+
err(io.env["FLOVIA_API_KEY"]?.trim()
|
|
141
|
+
? "warning: the entry this install writes reads FLOVIA_KEY. FLOVIA_API_KEY is set, but that new entry does not read it. Set FLOVIA_KEY where Cursor starts.\n"
|
|
142
|
+
: "warning: FLOVIA_KEY is not set in this shell; the entry this install writes reads FLOVIA_KEY where Cursor starts\n");
|
|
143
|
+
};
|
|
138
144
|
// 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
145
|
const limit = timeout ?? 300;
|
|
140
146
|
const runExec = async (step, failed) => {
|
|
@@ -190,6 +196,13 @@ export async function install(p, io, out, err, json, timeout, fromFile) {
|
|
|
190
196
|
const again = ["flovia", "install", "--client", plan.client, ...(plan.auth === "key" ? ["--auth", "key"] : []),
|
|
191
197
|
...(p.flags.has("--base-url") ? ["--base-url", str(p.flags.get("--base-url")) ?? ""] : []), ...(keyFile ? ["--key-file", keyFile] : [])].map(quoteArg).join(" ");
|
|
192
198
|
if (step.signIn) {
|
|
199
|
+
try {
|
|
200
|
+
await io.exec?.(step.command, ["--version"], { timeoutMs: 5_000 });
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
if (e.code === "ENOENT")
|
|
204
|
+
throw new Usage(`install: ${step.command} was not found. Install it first, or use --dry-run and run the command yourself`);
|
|
205
|
+
}
|
|
193
206
|
// Said before the wait, so an agent that stops the command still has the next step (discovery 2026-11-19 ②).
|
|
194
207
|
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
208
|
`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.`,
|
|
@@ -227,6 +240,7 @@ export async function install(p, io, out, err, json, timeout, fromFile) {
|
|
|
227
240
|
done.push(`unchanged: ${step.path} already has this flovia entry`);
|
|
228
241
|
continue;
|
|
229
242
|
}
|
|
243
|
+
cursorKeyWarning();
|
|
230
244
|
next = merged;
|
|
231
245
|
}
|
|
232
246
|
catch (e) {
|
package/dist/keyfile.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CONSOLE } from "./output.js";
|
|
2
2
|
import { Usage, str } from "./args.js";
|
|
3
|
+
import { homeDir } from "./homedir.js";
|
|
3
4
|
/** 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
5
|
export async function readKey(p, io) {
|
|
5
6
|
const file = str(p.flags.get("--key-file"));
|
|
@@ -8,7 +9,7 @@ export async function readKey(p, io) {
|
|
|
8
9
|
const key = io.env["FLOVIA_KEY"]?.trim();
|
|
9
10
|
if (key)
|
|
10
11
|
return key;
|
|
11
|
-
const home = io.env
|
|
12
|
+
const home = homeDir(io.env);
|
|
12
13
|
if (home && await io.readFile(`${home}/${DEFAULT_KEY_FILE}`).then(() => true, () => false))
|
|
13
14
|
return fromFile(`${home}/${DEFAULT_KEY_FILE}`, io, `~/${DEFAULT_KEY_FILE}`);
|
|
14
15
|
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>`);
|
package/dist/nodeio.d.ts
CHANGED
|
@@ -3,5 +3,22 @@ import type { Io } from "./cli.js";
|
|
|
3
3
|
export declare function writePrivateOutput(path: string, data: Uint8Array): Promise<void>;
|
|
4
4
|
/** Decode UTF-8 once over all bytes (a character split between reads survives); invalid bytes throw instead of becoming U+FFFD. */
|
|
5
5
|
export declare function readStdin(input: NodeJS.ReadableStream): Promise<string>;
|
|
6
|
+
/**
|
|
7
|
+
* One argument for `cmd.exe /c` launching a `.cmd` shim, which then hands `%*` to node.
|
|
8
|
+
* First the MSVC C runtime rules (backslashes before `"`, then a wrapping quote). Then each cmd
|
|
9
|
+
* metacharacter is caret-escaped twice, because cmd.exe and the batch file each consume one caret.
|
|
10
|
+
*/
|
|
11
|
+
export declare function quoteCmdShimArg(arg: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* How to spawn a client CLI. Unix and Windows `.exe` pass `args` through. A Windows batch shim goes through
|
|
14
|
+
* `cmd.exe /d /s /c` with CRT-then-caret quoting. `shell: true` is never set.
|
|
15
|
+
*/
|
|
16
|
+
export declare function clientChild(platform: string, command: string, args: string[]): {
|
|
17
|
+
file: string;
|
|
18
|
+
args: string[];
|
|
19
|
+
windowsVerbatimArguments?: true;
|
|
20
|
+
};
|
|
21
|
+
/** PATHEXT order: a native `.exe` wins over `claude.cmd`. Not found stays the bare name, still without a shell. */
|
|
22
|
+
export declare function resolveWindowsCommand(command: string, env: NodeJS.ProcessEnv, exists: (path: string) => boolean): string;
|
|
6
23
|
/** The real process's I/O for the program run (cli.ts calls it only as the program, never on import). */
|
|
7
24
|
export declare function nodeIo(): Io;
|
package/dist/nodeio.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
1
2
|
import { mkdir, open, readFile, stat, writeFile } from "node:fs/promises";
|
|
2
3
|
import { spawn } from "node:child_process";
|
|
3
4
|
import { dirname } from "node:path";
|
|
@@ -20,6 +21,61 @@ export async function readStdin(input) {
|
|
|
20
21
|
chunks.push(Buffer.from(chunk));
|
|
21
22
|
return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
|
|
22
23
|
}
|
|
24
|
+
/** A `.cmd` / `.bat` shim is the only Windows case that needs `cmd.exe`. A shell around every child re-parses JSON. */
|
|
25
|
+
const BATCH = /\.(cmd|bat)$/i;
|
|
26
|
+
/** cmd.exe metacharacters. A `.cmd` shim parses the line twice, so each one is caret-escaped twice. */
|
|
27
|
+
const CMD_META = /[()%!^"<>&|]/g;
|
|
28
|
+
/**
|
|
29
|
+
* One argument for `cmd.exe /c` launching a `.cmd` shim, which then hands `%*` to node.
|
|
30
|
+
* First the MSVC C runtime rules (backslashes before `"`, then a wrapping quote). Then each cmd
|
|
31
|
+
* metacharacter is caret-escaped twice, because cmd.exe and the batch file each consume one caret.
|
|
32
|
+
*/
|
|
33
|
+
export function quoteCmdShimArg(arg) {
|
|
34
|
+
let quoted = arg.replace(/(\\*)"/g, "$1$1\\\"");
|
|
35
|
+
quoted = `"${quoted.replace(/(\\*)$/, "$1$1")}"`;
|
|
36
|
+
const caret = (ch) => "^" + ch;
|
|
37
|
+
quoted = quoted.replace(CMD_META, caret);
|
|
38
|
+
return quoted.replace(CMD_META, caret);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* How to spawn a client CLI. Unix and Windows `.exe` pass `args` through. A Windows batch shim goes through
|
|
42
|
+
* `cmd.exe /d /s /c` with CRT-then-caret quoting. `shell: true` is never set.
|
|
43
|
+
*/
|
|
44
|
+
export function clientChild(platform, command, args) {
|
|
45
|
+
if (platform !== "win32" || !BATCH.test(command))
|
|
46
|
+
return { file: command, args };
|
|
47
|
+
const line = [command, ...args].map(quoteCmdShimArg).join(" ");
|
|
48
|
+
return { file: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], windowsVerbatimArguments: true };
|
|
49
|
+
}
|
|
50
|
+
/** PATHEXT order: a native `.exe` wins over `claude.cmd`. Not found stays the bare name, still without a shell. */
|
|
51
|
+
export function resolveWindowsCommand(command, env, exists) {
|
|
52
|
+
if (/[\\/]/.test(command) || /\.[^\\/.]+$/.test(command))
|
|
53
|
+
return command;
|
|
54
|
+
const exts = (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";").map((ext) => ext.trim()).filter((ext) => ext.length > 0);
|
|
55
|
+
for (const dir of (env["PATH"] ?? "").split(";")) {
|
|
56
|
+
if (dir === "")
|
|
57
|
+
continue;
|
|
58
|
+
for (const ext of exts) {
|
|
59
|
+
const suffix = ext.startsWith(".") ? ext : `.${ext}`;
|
|
60
|
+
const candidate = `${dir.replace(/[\\/]+$/, "")}\\${command}${suffix}`;
|
|
61
|
+
if (exists(candidate))
|
|
62
|
+
return candidate;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return command;
|
|
66
|
+
}
|
|
67
|
+
function spawnClient(command, args, stdio, env) {
|
|
68
|
+
const file = process.platform === "win32" ? resolveWindowsCommand(command, env, existsSync) : command;
|
|
69
|
+
const spec = clientChild(process.platform, file, args);
|
|
70
|
+
return spawn(spec.file, spec.args, { stdio, env, shell: false, windowsVerbatimArguments: spec.windowsVerbatimArguments });
|
|
71
|
+
}
|
|
72
|
+
/** A timed-out child whose pipes stay open keeps the CLI process alive after the command has already returned. */
|
|
73
|
+
function dropChild(child) {
|
|
74
|
+
child.stdout?.destroy();
|
|
75
|
+
child.stderr?.destroy();
|
|
76
|
+
child.stdin?.destroy();
|
|
77
|
+
child.unref();
|
|
78
|
+
}
|
|
23
79
|
/** The real process's I/O for the program run (cli.ts calls it only as the program, never on import). */
|
|
24
80
|
export function nodeIo() {
|
|
25
81
|
const tty = process.stdin.isTTY === true;
|
|
@@ -40,13 +96,37 @@ export function nodeIo() {
|
|
|
40
96
|
const env = { ...process.env };
|
|
41
97
|
for (const name of ["FLOVIA_KEY", "FLOVIA_API_KEY", "FLOVIA_ACCESS_TOKEN"])
|
|
42
98
|
delete env[name];
|
|
43
|
-
const child =
|
|
99
|
+
const child = spawnClient(command, args, o?.showOutput ? ["ignore", "pipe", "pipe"] : "ignore", env);
|
|
44
100
|
child.stdout?.on("data", (d) => process.stderr.write(d));
|
|
45
101
|
child.stderr?.on("data", (d) => process.stderr.write(d));
|
|
46
102
|
let timedOut = false;
|
|
47
|
-
const timer = o?.timeoutMs ? setTimeout(() => { timedOut = true; child.kill("SIGTERM"); }, o.timeoutMs) : undefined;
|
|
103
|
+
const timer = o?.timeoutMs ? setTimeout(() => { timedOut = true; child.kill("SIGTERM"); dropChild(child); }, o.timeoutMs) : undefined;
|
|
48
104
|
child.once("error", (e) => { clearTimeout(timer); reject(e); });
|
|
49
|
-
child.once("exit", (code) => { clearTimeout(timer);
|
|
105
|
+
child.once("exit", (code) => { clearTimeout(timer); if (timedOut)
|
|
106
|
+
dropChild(child); resolve(timedOut ? "timeout" : code ?? 1); });
|
|
107
|
+
}),
|
|
108
|
+
capture: (command, args, o) => new Promise((resolve, reject) => {
|
|
109
|
+
const env = { ...process.env };
|
|
110
|
+
for (const name of ["FLOVIA_KEY", "FLOVIA_API_KEY", "FLOVIA_ACCESS_TOKEN"])
|
|
111
|
+
delete env[name];
|
|
112
|
+
const child = spawnClient(command, args, ["ignore", "pipe", "pipe"], env);
|
|
113
|
+
const chunks = [];
|
|
114
|
+
let size = 0;
|
|
115
|
+
child.stdout?.on("data", (d) => { size += d.length; if (size <= 65_536)
|
|
116
|
+
chunks.push(d); });
|
|
117
|
+
child.stderr?.resume();
|
|
118
|
+
let code = 1, settled = false;
|
|
119
|
+
// A normal exit can leave the last stdout line unread until `close`. A timeout must not wait for that.
|
|
120
|
+
const timer = o?.timeoutMs ? setTimeout(() => { code = "timeout"; child.kill("SIGTERM"); dropChild(child); finish(); child.kill("SIGKILL"); }, o.timeoutMs) : undefined;
|
|
121
|
+
const fail = (e) => { if (settled)
|
|
122
|
+
return; settled = true; clearTimeout(timer); reject(e); };
|
|
123
|
+
const finish = () => { if (settled)
|
|
124
|
+
return; settled = true; clearTimeout(timer); resolve({ code, stdout: Buffer.concat(chunks).toString("utf8") }); };
|
|
125
|
+
child.once("error", fail);
|
|
126
|
+
child.once("exit", (status) => { if (code !== "timeout")
|
|
127
|
+
code = status ?? 1; });
|
|
128
|
+
child.once("close", () => { if (code !== "timeout")
|
|
129
|
+
finish(); });
|
|
50
130
|
}),
|
|
51
131
|
writeFile: async (path, text) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, text, "utf8"); },
|
|
52
132
|
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),
|
package/package.json
CHANGED