@tiny-fish/cli 0.12.1-next.138 → 0.12.1-next.142

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.
@@ -3,10 +3,12 @@ import * as path from "node:path";
3
3
  import spawn from "cross-spawn";
4
4
  import { CONNECT_SOURCE, loadConfig, persistApiKeyToEnvironment, saveConnectContext, validateKeyFormat, writeConfig, } from "../lib/auth.js";
5
5
  import { CLI_VERSION } from "../lib/constants.js";
6
- import { cursorMcpPath, writeCursorMcpConfig } from "../lib/cursor-config.js";
6
+ import { cursorInstallDeeplink, cursorMcpPath, writeCursorMcpConfig } from "../lib/cursor-config.js";
7
+ import { runConnectAll } from "../lib/connect-all.js";
8
+ import { detectHumanInitiated } from "../lib/harness.js";
7
9
  import { errLine } from "../lib/output.js";
8
10
  import { telemetryDisabled, telemetryHeaders } from "../lib/setup-telemetry.js";
9
- import { recordInstalledVersion } from "../lib/version-marker.js";
11
+ import { verifyMcpAuth } from "../lib/verify.js";
10
12
  export const DEFAULT_MCP_URL = "https://agent.tinyfish.ai/mcp";
11
13
  const NON_INTERACTIVE_TIMEOUT_MS = 10_000;
12
14
  const SKILL_INSTALL_TIMEOUT_MS = 120_000;
@@ -94,7 +96,7 @@ function installSignalGuard(state, telemetry) {
94
96
  async function runGuarded(state, telemetry, body) {
95
97
  const uninstallSignalGuard = installSignalGuard(state, telemetry);
96
98
  try {
97
- body();
99
+ await body();
98
100
  }
99
101
  catch (error) {
100
102
  if (error instanceof ConnectInterruptedError) {
@@ -125,6 +127,7 @@ const CLAUDE_CODE = {
125
127
  patterns: [/^\s*login(?:\s|\[)/m],
126
128
  unavailableMessage: MCP_LOGIN_UNAVAILABLE_MESSAGE,
127
129
  },
130
+ headerAuthSupported: true,
128
131
  loginArgs: ["mcp", "login", "tinyfish"],
129
132
  // Project scope is shared in .mcp.json; a user setup command must not rewrite it.
130
133
  removals: [
@@ -538,9 +541,17 @@ async function connectNativeMcpClient(client, options) {
538
541
  mcpUrl.searchParams.set("source", CONNECT_SOURCE);
539
542
  mcpUrl.searchParams.set("client", client.connectClient);
540
543
  mcpUrl.searchParams.set("connect_attempt_id", telemetry.attemptId);
544
+ // Prod MCP accepts X-API-Key, so a stored key replaces the browser OAuth hop.
545
+ const storedKey = options.apiKey ?? process.env["TINYFISH_API_KEY"] ?? loadConfig().api_key;
546
+ const useKeyAuth = client.headerAuthSupported === true && !!storedKey && validateKeyFormat(storedKey);
541
547
  state.stage = client.loginArgs ? "registration" : "registration_or_authentication";
542
548
  errLine(`Adding TinyFish to ${client.displayName}...`);
543
- const addResult = spawn.sync(client.command, client.addArgs(mcpUrl.toString(), options.mcpUrl), {
549
+ const addResult = spawn.sync(client.command, [
550
+ ...client.addArgs(mcpUrl.toString(), options.mcpUrl),
551
+ // Key rides argv — readable via /proc/<pid>/cmdline. Accepted because these CLIs
552
+ // take headers no other way.
553
+ ...(useKeyAuth ? ["--header", `X-API-Key: ${storedKey}`] : []),
554
+ ], {
544
555
  stdio: "inherit",
545
556
  });
546
557
  if (addResult.error || addResult.status !== 0) {
@@ -550,7 +561,10 @@ async function connectNativeMcpClient(client, options) {
550
561
  });
551
562
  }
552
563
  telemetry.track("checkpoint", { phase: "registered" });
553
- if (client.loginArgs) {
564
+ if (useKeyAuth) {
565
+ errLine("Using your stored TinyFish API key — no browser sign-in needed.");
566
+ }
567
+ if (client.loginArgs && !useKeyAuth) {
554
568
  state.stage = "client_oauth";
555
569
  errLine("Signing in to TinyFish...");
556
570
  const loginResult = spawn.sync(client.command, client.loginArgs, {
@@ -576,7 +590,6 @@ async function connectNativeMcpClient(client, options) {
576
590
  // Persist once here (skill installed + authenticated) so both success paths, launch
577
591
  // or not, record the install; buildConnectHeaders reads it on subsequent requests.
578
592
  saveConnectContext(client.connectClient, telemetry.attemptId);
579
- recordInstalledVersion();
580
593
  errLine(UPGRADE_HINT);
581
594
  if (!options.launch) {
582
595
  errLine(`TinyFish is connected. Open ${client.displayName} to start using it.`);
@@ -607,15 +620,7 @@ export async function connectOpenClaw(options) {
607
620
  telemetry.track("checkpoint", { phase: "prerequisite_ok" });
608
621
  if (options.installCli !== false) {
609
622
  state.stage = "cli_install";
610
- errLine("Installing the TinyFish CLI...");
611
- const cliInstallResult = spawn.sync("npm", ["install", "--global", "@tiny-fish/cli@latest"], {
612
- stdio: "inherit",
613
- timeout: SKILL_INSTALL_TIMEOUT_MS,
614
- });
615
- if (cliInstallResult.error || cliInstallResult.status !== 0) {
616
- throwIfInterrupted(cliInstallResult);
617
- throw new Error("Could not install the TinyFish CLI", { cause: cliInstallResult.error });
618
- }
623
+ installTinyFishCli();
619
624
  telemetry.track("checkpoint", { phase: "cli_installed" });
620
625
  }
621
626
  state.stage = "skill_install";
@@ -655,7 +660,6 @@ export async function connectOpenClaw(options) {
655
660
  }
656
661
  telemetry.track("checkpoint", { phase: "authenticated" });
657
662
  saveConnectContext("openclaw", telemetry.attemptId);
658
- recordInstalledVersion();
659
663
  errLine(UPGRADE_HINT);
660
664
  if (!options.launch) {
661
665
  errLine("TinyFish is connected. Open OpenClaw to start using it.");
@@ -672,16 +676,21 @@ export async function connectOpenClaw(options) {
672
676
  export async function connectCursor(options) {
673
677
  const telemetry = createConnectTelemetry(options.mcpUrl, "cursor", options.apiKey);
674
678
  const state = { stage: "prerequisite_check", settled: false };
675
- await runGuarded(state, telemetry, () => {
679
+ await runGuarded(state, telemetry, async () => {
676
680
  telemetry.track("started");
677
681
  telemetry.track("checkpoint", { phase: "prerequisite_ok" });
682
+ // Auth first: a key lets the config carry an X-API-Key header, removing the sign-in hand-back.
683
+ state.stage = "authentication";
684
+ ensureCliAuthenticated("cursor", options.apiKey);
685
+ telemetry.track("checkpoint", { phase: "authenticated" });
686
+ const resolvedKey = options.apiKey ?? process.env["TINYFISH_API_KEY"] ?? loadConfig().api_key;
678
687
  state.stage = "registration";
679
688
  errLine("Adding TinyFish to Cursor...");
680
689
  const mcpUrl = new URL(options.mcpUrl);
681
690
  mcpUrl.searchParams.set("source", CONNECT_SOURCE);
682
691
  mcpUrl.searchParams.set("client", "cursor");
683
692
  // Attempt id rides telemetry only; persisting it would break idempotency.
684
- const result = writeCursorMcpConfig(mcpUrl.toString());
693
+ const result = writeCursorMcpConfig(mcpUrl.toString(), resolvedKey);
685
694
  if (result.status === "corrupt_skip") {
686
695
  throw new Error(`Could not update ${cursorMcpPath()}: existing file could not be read or is not valid JSON (${result.error}). ` +
687
696
  `Fix the file, then re-run: tinyfish connect cursor`);
@@ -689,19 +698,42 @@ export async function connectCursor(options) {
689
698
  if (result.backupPath) {
690
699
  errLine(`Backed up existing Cursor MCP config to ${result.backupPath}`);
691
700
  }
701
+ if (result.repaired) {
702
+ errLine("Repaired the existing TinyFish entry (updated auth/config to current).");
703
+ }
692
704
  telemetry.track("checkpoint", { phase: "registered" });
693
- state.stage = "authentication";
694
- ensureCliAuthenticated("cursor", options.apiKey);
695
- telemetry.track("checkpoint", { phase: "authenticated" });
696
705
  saveConnectContext("cursor", telemetry.attemptId);
697
- recordInstalledVersion();
698
- // A server written into mcp.json lands unauthenticated: only Cursor's own "Add to
699
- // Cursor" deep link auto-starts OAuth, so name the click or the install never completes.
700
- errLine("Added to Cursor. Restart Cursor (or reload the window), then open");
701
- errLine('Settings -> Tools & MCP and click Connect on "tinyfish" to sign in.');
706
+ if (resolvedKey) {
707
+ // Deeplink would embed the key in a URL (process args, LaunchServices logs) — reload instead.
708
+ const verify = await verifyMcpAuth(resolvedKey);
709
+ if (verify.ok) {
710
+ errLine("TinyFish is connected and verified (health+auth). Reload the Cursor window (or restart cursor-agent) and it's live.");
711
+ }
712
+ else {
713
+ errLine(`TinyFish is configured, but the authenticated check failed (${verify.reason ?? "unknown"}). ` +
714
+ "Fix: rotate/re-enter your key with `tinyfish auth login`, then re-run: tinyfish connect cursor");
715
+ }
716
+ }
717
+ else if (detectHumanInitiated() && launchCursorDeeplink(mcpUrl.toString())) {
718
+ errLine("Cursor should pop a TinyFish install confirmation — approve it, then sign in when prompted.");
719
+ }
720
+ else {
721
+ errLine("TinyFish is connected. Reload the Cursor window, then approve/sign in under Settings → MCP.");
722
+ }
702
723
  settle(state, telemetry, "completed");
703
724
  });
704
725
  }
726
+ /** Best-effort: false when no handler/open fails — caller falls back to reload copy. */
727
+ function launchCursorDeeplink(mcpUrl) {
728
+ const deepLink = cursorInstallDeeplink(mcpUrl);
729
+ const [command, args] = process.platform === "darwin"
730
+ ? ["open", [deepLink]]
731
+ : process.platform === "win32"
732
+ ? ["cmd", ["/c", "start", "", deepLink]]
733
+ : ["xdg-open", [deepLink]];
734
+ const result = spawn.sync(command, args, { stdio: "ignore" });
735
+ return !result.error && result.status === 0;
736
+ }
705
737
  export function launchAgent(client) {
706
738
  if (client === "claude-code") {
707
739
  launchNativeMcpClient(CLAUDE_CODE);
@@ -728,7 +760,11 @@ export function registerConnect(program) {
728
760
  program
729
761
  .command("connect")
730
762
  .description("Connect TinyFish to an AI agent")
731
- .argument("<client>", "Agent client to connect (claude-code, codex, cursor, hermes, or openclaw)")
763
+ .argument("[client]", "Agent client to connect (claude-code, codex, cursor, hermes, or openclaw)")
764
+ .option("--all", "Detect and connect every supported harness found on this machine")
765
+ .option("--dry-run", "Print planned writes per harness without touching anything (--all only)")
766
+ .option("--uninstall", "Remove TinyFish entries written by connect --all")
767
+ .option("--skip-launch", "Skip the end-of-install agent launch (--all only)")
732
768
  .option("--api-key <apiKey>", "TinyFish API key to persist for the installed skill")
733
769
  .option("--launch", "Launch the agent and start the TinyFish walkthrough")
734
770
  .option("--url <mcpUrl>", "MCP endpoint override")
@@ -750,6 +786,31 @@ export function registerConnect(program) {
750
786
  if (!["http:", "https:"].includes(parsedUrl.protocol)) {
751
787
  throw new Error(`Invalid --url value: ${mcpUrl}`);
752
788
  }
789
+ if (options.all) {
790
+ if (client) {
791
+ throw new Error("Pass either a client or --all, not both.");
792
+ }
793
+ if (options.launch) {
794
+ throw new Error("--launch is not supported with --all. Connect a single client to launch it.");
795
+ }
796
+ const exitCode = await runConnectAll({
797
+ apiKey: options.apiKey,
798
+ mcpUrl,
799
+ dryRun: options.dryRun ?? false,
800
+ uninstall: options.uninstall ?? false,
801
+ noLaunch: options.skipLaunch === true,
802
+ });
803
+ // Preserve the 130 runGuarded set on Ctrl+C.
804
+ if (!process.exitCode)
805
+ process.exitCode = exitCode;
806
+ return;
807
+ }
808
+ if (options.dryRun || options.uninstall) {
809
+ throw new Error("--dry-run and --uninstall are only supported with --all.");
810
+ }
811
+ if (!client) {
812
+ throw new Error("Pass a client (claude-code, codex, cursor, hermes, openclaw) or --all.");
813
+ }
753
814
  const connectOptions = { apiKey: options.apiKey, mcpUrl, launch: options.launch ?? false };
754
815
  if (client === "claude-code") {
755
816
  await connectClaudeCode(connectOptions);
@@ -0,0 +1,9 @@
1
+ export interface ConnectAllOptions {
2
+ apiKey?: string;
3
+ mcpUrl: string;
4
+ dryRun: boolean;
5
+ uninstall: boolean;
6
+ /** Skip the end-of-install agent launch (finale still prints the ask). */
7
+ noLaunch?: boolean;
8
+ }
9
+ export declare function runConnectAll(opts: ConnectAllOptions): Promise<number>;
@@ -0,0 +1,342 @@
1
+ import * as readline from "node:readline/promises";
2
+ import spawn from "cross-spawn";
3
+ import { connectClaudeCode, connectCodex, connectCursor, connectHermes, connectOpenClaw, } from "../commands/connect.js";
4
+ import { loadConfig, validateKeyFormat } from "./auth.js";
5
+ import { detectInstalledHarnesses, FIVE_HARNESSES, } from "./harness-detect.js";
6
+ import { detectHumanInitiated } from "./harness.js";
7
+ import { removeCursorMcpServer, planCursorWrite } from "./cursor-config.js";
8
+ import { errLine, outLine } from "./output.js";
9
+ import { sendSetupCompleted } from "./setup-telemetry.js";
10
+ import { verifyMcpAuth, verifyMcpHealth } from "./verify.js";
11
+ const DISPLAY_NAMES = {
12
+ "claude-code": "Claude Code",
13
+ codex: "Codex",
14
+ cursor: "Cursor",
15
+ hermes: "Hermes",
16
+ openclaw: "OpenClaw",
17
+ };
18
+ // `codex mcp add` succeeds unauthenticated; OAuth lands at first tool use.
19
+ const AUTH_DEFERRED_AT_INSTALL = new Set(["codex"]);
20
+ // Harnesses that drive their own OAuth at install — a stored TinyFish key says nothing
21
+ // about their session, so it must never unlock a headless run for them.
22
+ const HARNESS_OWN_AUTH = new Set(["claude-code", "codex", "hermes"]);
23
+ const AUTH_CHECK_CAPABLE = new Set(["cursor", "openclaw"]);
24
+ // Real removal commands — harness id is not the binary name.
25
+ const UNINSTALL_POINTERS = {
26
+ "claude-code": "claude mcp remove tinyfish --scope user",
27
+ codex: "codex mcp remove tinyfish",
28
+ hermes: "hermes mcp remove tinyfish",
29
+ openclaw: "openclaw skills uninstall @tinyfish/tinyfish --global",
30
+ };
31
+ function resolvedApiKey(explicitApiKey) {
32
+ if (explicitApiKey)
33
+ return explicitApiKey;
34
+ const envKey = process.env["TINYFISH_API_KEY"];
35
+ if (envKey)
36
+ return envKey;
37
+ try {
38
+ return loadConfig().api_key;
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ function hasStoredAuth(explicitApiKey) {
45
+ const key = resolvedApiKey(explicitApiKey);
46
+ return !!key && validateKeyFormat(key);
47
+ }
48
+ async function runHarnessConnect(harness, opts) {
49
+ const base = { apiKey: opts.apiKey, mcpUrl: opts.mcpUrl, launch: false };
50
+ if (harness === "claude-code")
51
+ return connectClaudeCode(base);
52
+ if (harness === "codex")
53
+ return connectCodex(base);
54
+ if (harness === "hermes")
55
+ return connectHermes(base);
56
+ if (harness === "openclaw")
57
+ return connectOpenClaw({ mcpUrl: opts.mcpUrl, launch: false });
58
+ return connectCursor({ apiKey: opts.apiKey, mcpUrl: opts.mcpUrl });
59
+ }
60
+ async function verifyHarness(harness, mcpUrl, apiKey) {
61
+ const health = await verifyMcpHealth(mcpUrl);
62
+ // claude-code is auth-checkable only in key mode (header-authed config).
63
+ const capable = AUTH_CHECK_CAPABLE.has(harness) || (harness === "claude-code" && !!apiKey);
64
+ if (!capable || !health.ok)
65
+ return health;
66
+ if (!apiKey)
67
+ return { depth: "health+auth", ok: false, reason: "no stored API key" };
68
+ return verifyMcpAuth(apiKey);
69
+ }
70
+ function planText(harness, mcpUrl, apiKey) {
71
+ if (harness === "cursor")
72
+ return planCursorWrite(mcpUrl, apiKey);
73
+ return `would run \`tinyfish connect ${harness}\` (harness-owned MCP write; no local file touched by the CLI)`;
74
+ }
75
+ function uninstallPlanText(harness) {
76
+ if (harness === "cursor") {
77
+ return "would remove the tinyfish entry from ~/.cursor/mcp.json";
78
+ }
79
+ return `would print the removal command \`${UNINSTALL_POINTERS[harness]}\` (config is harness-owned; the CLI removes nothing)`;
80
+ }
81
+ function uninstallHarness(harness, configPath) {
82
+ const detection = { harness, detected: true, configPath, installed: false };
83
+ if (harness !== "cursor") {
84
+ // Harness-owned config — removal happens via each tool's own CLI.
85
+ return { ...detection, outcome: "uninstall_pointer", fixCommand: UNINSTALL_POINTERS[harness] };
86
+ }
87
+ let result;
88
+ try {
89
+ result = removeCursorMcpServer();
90
+ }
91
+ catch (e) {
92
+ result = { status: "corrupt_skip", error: e instanceof Error ? e.message : String(e) };
93
+ }
94
+ if (result.status === "corrupt_skip") {
95
+ return {
96
+ ...detection,
97
+ outcome: "uninstalled",
98
+ errorMessage: `could not update Cursor's mcp.json (${result.error}) — nothing removed.`,
99
+ fixCommand: "Fix ~/.cursor/mcp.json by hand, then re-run: tinyfish connect --all --uninstall",
100
+ };
101
+ }
102
+ if (result.status === "unchanged") {
103
+ return { ...detection, outcome: "uninstall_noop" };
104
+ }
105
+ return { ...detection, outcome: "uninstalled" };
106
+ }
107
+ async function processHarness(detection, opts, prompt) {
108
+ const { harness, configPath } = detection;
109
+ if (!detection.detected) {
110
+ return { harness, detected: false, configPath, installed: false, outcome: "not_detected" };
111
+ }
112
+ const base = { harness, detected: true, configPath, installed: false };
113
+ // dryRun first: --dry-run --uninstall must plan, never reach removeCursorMcpServer().
114
+ if (opts.dryRun) {
115
+ const plan = opts.uninstall ? uninstallPlanText(harness) : planText(harness, opts.mcpUrl, resolvedApiKey(opts.apiKey));
116
+ return { ...base, outcome: "dry_run", fixCommand: plan };
117
+ }
118
+ if (opts.uninstall)
119
+ return uninstallHarness(harness, configPath);
120
+ const isTTY = detectHumanInitiated();
121
+ // claude-code leaves the own-OAuth set when a key is stored: `mcp add --header
122
+ // X-API-Key` replaces its login. codex/hermes have no header path, so they keep the skip.
123
+ const keyed = hasStoredAuth(opts.apiKey);
124
+ const ownAuthHarness = HARNESS_OWN_AUTH.has(harness) && !(harness === "claude-code" && keyed);
125
+ const alreadyAuthed = !ownAuthHarness && keyed;
126
+ if (!isTTY && !alreadyAuthed) {
127
+ return { ...base, outcome: "no_tty_auth_skip", fixCommand: `tinyfish connect ${harness}` };
128
+ }
129
+ if (isTTY && !alreadyAuthed && prompt) {
130
+ errLine(`step: waiting for browser sign-in to TinyFish for ${DISPLAY_NAMES[harness]}`);
131
+ try {
132
+ await prompt(`Press enter to open the browser and sign in to TinyFish for ${DISPLAY_NAMES[harness]}... `);
133
+ }
134
+ catch {
135
+ // Ctrl+D closed stdin — treat like the no-TTY skip.
136
+ return { ...base, outcome: "no_tty_auth_skip", fixCommand: `tinyfish connect ${harness}` };
137
+ }
138
+ }
139
+ // runGuarded swallows Ctrl+C and sets exitCode 130 instead of throwing.
140
+ const interruptedBefore = process.exitCode === 130;
141
+ try {
142
+ await runHarnessConnect(harness, opts);
143
+ }
144
+ catch (e) {
145
+ return {
146
+ ...base,
147
+ outcome: "failed",
148
+ errorMessage: e instanceof Error ? e.message : String(e),
149
+ fixCommand: `tinyfish connect ${harness}`,
150
+ };
151
+ }
152
+ if (!interruptedBefore && process.exitCode === 130) {
153
+ return { ...base, outcome: "interrupted", fixCommand: `tinyfish connect ${harness}` };
154
+ }
155
+ const verify = await verifyHarness(harness, opts.mcpUrl, resolvedApiKey(opts.apiKey));
156
+ return {
157
+ ...base,
158
+ installed: true,
159
+ outcome: "installed",
160
+ verifyDepth: verify.depth,
161
+ verifyOk: verify.ok,
162
+ verifyReason: verify.reason,
163
+ };
164
+ }
165
+ function summaryLine(result, uninstall) {
166
+ const name = DISPLAY_NAMES[result.harness];
167
+ if (!result.detected) {
168
+ const next = uninstall
169
+ ? "nothing to remove"
170
+ : `Install ${name}, then run: tinyfish connect ${result.harness}`;
171
+ return `- ${name} — not detected (searched ${result.configPath}). ${next}`;
172
+ }
173
+ if (result.outcome === "not_reached") {
174
+ return `… ${name} — not reached, the run stopped early. Fix: ${result.fixCommand}`;
175
+ }
176
+ if (result.outcome === "dry_run") {
177
+ return `… ${name} — ${result.fixCommand}`;
178
+ }
179
+ if (result.outcome === "no_tty_auth_skip") {
180
+ return `… ${name} — skipped, no stored credentials and no terminal to sign in. Fix: ${result.fixCommand}`;
181
+ }
182
+ if (result.outcome === "uninstall_pointer") {
183
+ return `… ${name} — not removed automatically (config is owned by ${name}). Run: ${result.fixCommand}`;
184
+ }
185
+ if (result.outcome === "uninstall_noop") {
186
+ return `… ${name} — no tinyfish entry found, nothing removed`;
187
+ }
188
+ if (result.outcome === "uninstalled") {
189
+ return result.errorMessage
190
+ ? `✗ ${name} — ${result.errorMessage} Fix: ${result.fixCommand}`
191
+ : `✓ ${name} — removed`;
192
+ }
193
+ if (result.outcome === "interrupted") {
194
+ return `✗ ${name} — interrupted before finishing. Fix: ${result.fixCommand}`;
195
+ }
196
+ if (result.outcome === "failed") {
197
+ return `✗ ${name} — install failed: ${result.errorMessage}. Fix: ${result.fixCommand}`;
198
+ }
199
+ const authDeferred = AUTH_DEFERRED_AT_INSTALL.has(result.harness);
200
+ const verifyLabel = result.verifyDepth ? `verified: ${result.verifyDepth}` : "not verified";
201
+ if (authDeferred || result.verifyOk === false) {
202
+ const reason = authDeferred
203
+ ? "one step left: sign in when your agent first runs"
204
+ : `verify warning (${verifyLabel}): ${result.verifyReason ?? "unknown"}`;
205
+ return `⚠ ${name} — installed, ${reason}. Fix: run \`/tinyfish:doctor\` in ${name} once it's open.`;
206
+ }
207
+ return `✓ ${name} — installed, ${verifyLabel}`;
208
+ }
209
+ function computeExitCode(results) {
210
+ const detected = results.filter((r) => r.detected);
211
+ if (detected.length === 0)
212
+ return 1;
213
+ // Only real install attempts count toward the success/failure denominator.
214
+ const attempted = detected.filter((r) => r.outcome === "installed" || r.outcome === "failed" || r.outcome === "interrupted");
215
+ if (attempted.length === 0)
216
+ return 0;
217
+ return attempted.some((r) => r.outcome === "installed") ? 0 : 1;
218
+ }
219
+ export async function runConnectAll(opts) {
220
+ const isTTY = detectHumanInitiated();
221
+ const rl = isTTY
222
+ ? readline.createInterface({ input: process.stdin, output: process.stderr })
223
+ : undefined;
224
+ let prompt;
225
+ if (rl) {
226
+ // Without a close-linked signal, question() never settles on Ctrl+D.
227
+ const closed = new AbortController();
228
+ rl.on("close", () => closed.abort());
229
+ prompt = (question) => rl.question(question, { signal: closed.signal });
230
+ }
231
+ const detections = detectInstalledHarnesses();
232
+ const results = [];
233
+ try {
234
+ for (const [index, detection] of detections.entries()) {
235
+ const { harness } = detection;
236
+ errLine(`step ${index + 1} of ${detections.length} — ${DISPLAY_NAMES[harness]}`);
237
+ let result;
238
+ try {
239
+ result = await processHarness(detection, opts, prompt);
240
+ }
241
+ catch (e) {
242
+ // Isolation: one harness throwing never stops the others.
243
+ result = {
244
+ harness,
245
+ detected: detection.detected,
246
+ configPath: detection.configPath,
247
+ installed: false,
248
+ outcome: "failed",
249
+ errorMessage: e instanceof Error ? e.message : String(e),
250
+ fixCommand: `tinyfish connect ${harness}`,
251
+ };
252
+ }
253
+ results.push(result);
254
+ // Ctrl+C means stop, not continue to the next harness.
255
+ if (result.outcome === "interrupted")
256
+ break;
257
+ }
258
+ }
259
+ finally {
260
+ rl?.close();
261
+ }
262
+ // The interrupt break truncates `results`; pad so the 5-entry telemetry schema still parses.
263
+ for (const detection of detections) {
264
+ if (results.some((r) => r.harness === detection.harness))
265
+ continue;
266
+ results.push({
267
+ ...detection,
268
+ installed: false,
269
+ outcome: detection.detected ? "not_reached" : "not_detected",
270
+ fixCommand: `tinyfish connect ${detection.harness}`,
271
+ });
272
+ }
273
+ outLine("");
274
+ outLine("TinyFish setup summary:");
275
+ for (const result of results)
276
+ outLine(summaryLine(result, opts.uninstall));
277
+ if (results.every((r) => !r.detected)) {
278
+ outLine("");
279
+ outLine("No supported harness found. Install one of: " + FIVE_HARNESSES.join(", "));
280
+ if (!opts.uninstall)
281
+ outLine("Then run: npx @tiny-fish/cli connect --all");
282
+ return 1;
283
+ }
284
+ if (!opts.dryRun && !opts.uninstall) {
285
+ const harnessTelemetry = results.map((r) => ({
286
+ harness: r.harness,
287
+ detected: r.detected,
288
+ installed: r.installed,
289
+ verify_depth: r.verifyDepth ?? null,
290
+ verify_ok: r.verifyOk ?? null,
291
+ }));
292
+ await sendSetupCompleted(opts.mcpUrl, harnessTelemetry, resolvedApiKey(opts.apiKey));
293
+ }
294
+ const exitCode = computeExitCode(results);
295
+ const interrupted = results.some((r) => r.outcome === "interrupted");
296
+ if (exitCode === 0 && !interrupted && !opts.dryRun && !opts.uninstall && results.some((r) => r.installed)) {
297
+ outLine("");
298
+ if (isTTY && !opts.noLaunch && (await launchFirstTask(results))) {
299
+ return exitCode;
300
+ }
301
+ outLine('Now ask your agent: "use TinyFish to find today\'s top Hacker News story"');
302
+ }
303
+ return exitCode;
304
+ }
305
+ const FIRST_TASK_PROMPT = "My TinyFish setup just finished — verify it with a real run: use the TinyFish search tool to " +
306
+ "find today's top Hacker News story, then fetch that page with the TinyFish fetch tool and give " +
307
+ "me a two-line summary. Show which tools you call.";
308
+ // Launchable seeded agents, best-first — cursor-agent shares ~/.cursor/mcp.json with the IDE.
309
+ const LAUNCHERS = [
310
+ { harness: "cursor", command: "cursor-agent", args: [FIRST_TASK_PROMPT] },
311
+ { harness: "claude-code", command: "claude", args: [FIRST_TASK_PROMPT] },
312
+ ];
313
+ async function launchFirstTask(results) {
314
+ const candidates = LAUNCHERS.filter((l) => results.some((r) => r.harness === l.harness && r.installed));
315
+ if (candidates.length === 0)
316
+ return false;
317
+ // Several installs: ask rather than pick a favorite; plain enter skips.
318
+ let chosen = candidates[0];
319
+ if (candidates.length > 1) {
320
+ const menu = candidates.map((l, i) => `[${i + 1}] ${DISPLAY_NAMES[l.harness]}`).join(" ");
321
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
322
+ let answer;
323
+ try {
324
+ answer = await rl.question(`Try your first TinyFish task now? ${menu} [enter] skip: `);
325
+ }
326
+ catch {
327
+ return false;
328
+ }
329
+ finally {
330
+ rl.close();
331
+ }
332
+ const pick = Number.parseInt(answer.trim(), 10);
333
+ if (!pick || pick < 1 || pick > candidates.length)
334
+ return false;
335
+ chosen = candidates[pick - 1];
336
+ }
337
+ if (!chosen)
338
+ return false;
339
+ outLine(`Starting ${DISPLAY_NAMES[chosen.harness]} with your first TinyFish task...`);
340
+ const result = spawn.sync(chosen.command, chosen.args, { stdio: "inherit" });
341
+ return !result.error;
342
+ }
@@ -4,10 +4,14 @@ export interface CursorMcpWriteResult {
4
4
  status: "written" | "unchanged" | "corrupt_skip";
5
5
  backupPath?: string;
6
6
  error?: string;
7
+ /** A pre-existing tinyfish entry was replaced — a repair, not a fresh install. */
8
+ repaired?: boolean;
7
9
  }
8
10
  /** Dry-run description of the pending write; touches nothing. */
9
- export declare function planCursorWrite(mcpUrl: string): string;
11
+ export declare function planCursorWrite(mcpUrl: string, apiKey?: string): string;
10
12
  /** Merges only the `tinyfish` key; skips unreadable/corrupt files rather than clobber. */
11
- export declare function writeCursorMcpConfig(mcpUrl: string): CursorMcpWriteResult;
13
+ export declare function writeCursorMcpConfig(mcpUrl: string, apiKey?: string): CursorMcpWriteResult;
14
+ /** Cursor deeplink format: cursor://anysphere.cursor-deeplink/mcp/install?name=$NAME&config=$BASE64 */
15
+ export declare function cursorInstallDeeplink(mcpUrl: string): string;
12
16
  /** Removes only the `tinyfish` key. */
13
17
  export declare function removeCursorMcpServer(): CursorMcpWriteResult;
@@ -12,8 +12,9 @@ export function cursorMcpPath() {
12
12
  function isPlainRecord(value) {
13
13
  return value !== null && typeof value === "object" && !Array.isArray(value);
14
14
  }
15
- function buildTinyfishServerEntry(mcpUrl) {
16
- return { url: mcpUrl };
15
+ // Footgun: the key lands plaintext in mcp.json (0600) — per-device keys are the GA hardening.
16
+ function buildTinyfishServerEntry(mcpUrl, apiKey) {
17
+ return apiKey ? { url: mcpUrl, headers: { "X-API-Key": apiKey } } : { url: mcpUrl };
17
18
  }
18
19
  function parseMcpJson(raw) {
19
20
  try {
@@ -46,20 +47,23 @@ function readExisting() {
46
47
  return { raw, parsed: parsed.value };
47
48
  }
48
49
  /** Dry-run description of the pending write; touches nothing. */
49
- export function planCursorWrite(mcpUrl) {
50
+ export function planCursorWrite(mcpUrl, apiKey) {
50
51
  const existing = readExisting();
51
52
  const filePath = cursorMcpPath();
52
53
  if ("error" in existing) {
53
54
  return `${filePath}: existing file is corrupt (${existing.error}) — would skip and leave it untouched`;
54
55
  }
56
+ const authNote = apiKey
57
+ ? " with an API-key header — the key is stored in plaintext in that file (value not shown here)"
58
+ : "";
55
59
  const servers = existing.parsed.mcpServers;
56
60
  const current = isPlainRecord(servers) ? servers[TINYFISH_SERVER_KEY] : undefined;
57
- if (JSON.stringify(current) === JSON.stringify(buildTinyfishServerEntry(mcpUrl))) {
61
+ if (JSON.stringify(current) === JSON.stringify(buildTinyfishServerEntry(mcpUrl, apiKey))) {
58
62
  return `${filePath}: already has the tinyfish MCP entry — no change`;
59
63
  }
60
64
  return existing.raw === undefined
61
- ? `${filePath}: would create with a "tinyfish" MCP server entry`
62
- : `${filePath}: would back up to a timestamped copy, then merge in the "tinyfish" MCP server entry`;
65
+ ? `${filePath}: would create with a "tinyfish" MCP server entry${authNote}`
66
+ : `${filePath}: would back up to a timestamped copy, then merge in the "tinyfish" MCP server entry${authNote}`;
63
67
  }
64
68
  // Backup, then atomic temp+rename; pid avoids same-millisecond backup collisions.
65
69
  function commitServers(filePath, existing, servers) {
@@ -82,7 +86,7 @@ function commitServers(filePath, existing, servers) {
82
86
  return { status: "written", backupPath };
83
87
  }
84
88
  /** Merges only the `tinyfish` key; skips unreadable/corrupt files rather than clobber. */
85
- export function writeCursorMcpConfig(mcpUrl) {
89
+ export function writeCursorMcpConfig(mcpUrl, apiKey) {
86
90
  const filePath = cursorMcpPath();
87
91
  const existing = readExisting();
88
92
  if ("error" in existing)
@@ -90,12 +94,18 @@ export function writeCursorMcpConfig(mcpUrl) {
90
94
  const servers = isPlainRecord(existing.parsed.mcpServers)
91
95
  ? { ...existing.parsed.mcpServers }
92
96
  : {};
93
- const nextEntry = buildTinyfishServerEntry(mcpUrl);
97
+ const nextEntry = buildTinyfishServerEntry(mcpUrl, apiKey);
94
98
  if (JSON.stringify(servers[TINYFISH_SERVER_KEY]) === JSON.stringify(nextEntry)) {
95
99
  return { status: "unchanged" };
96
100
  }
101
+ const repaired = TINYFISH_SERVER_KEY in servers;
97
102
  servers[TINYFISH_SERVER_KEY] = nextEntry;
98
- return commitServers(filePath, existing, servers);
103
+ return { ...commitServers(filePath, existing, servers), repaired };
104
+ }
105
+ /** Cursor deeplink format: cursor://anysphere.cursor-deeplink/mcp/install?name=$NAME&config=$BASE64 */
106
+ export function cursorInstallDeeplink(mcpUrl) {
107
+ const config = Buffer.from(JSON.stringify(buildTinyfishServerEntry(mcpUrl))).toString("base64");
108
+ return `cursor://anysphere.cursor-deeplink/mcp/install?name=${TINYFISH_SERVER_KEY}&config=${encodeURIComponent(config)}`;
99
109
  }
100
110
  /** Removes only the `tinyfish` key. */
101
111
  export function removeCursorMcpServer() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiny-fish/cli",
3
- "version": "0.12.1-next.138",
3
+ "version": "0.12.1-next.142",
4
4
  "description": "TinyFish CLI — run web automations from your terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -32,7 +32,7 @@
32
32
  "prepublishOnly": "npm run build"
33
33
  },
34
34
  "dependencies": {
35
- "@tiny-fish/sdk": "^0.2.0",
35
+ "@tiny-fish/sdk": "^0.3.0",
36
36
  "chrome-cookies-secure": "^3.0.2",
37
37
  "commander": "^12.0.0",
38
38
  "cross-spawn": "^7.0.6",
@@ -56,6 +56,7 @@
56
56
  "brace-expansion": "^5.0.9",
57
57
  "ip-address": ">=10.3.1",
58
58
  "postcss": ">=8.5.23",
59
+ "nanoid": "^3.3.17",
59
60
  "tar": "^7.5.21"
60
61
  },
61
62
  "engines": {
@@ -1,10 +0,0 @@
1
- /** Install-time, offline-safe; best-effort — never fails a finished install. */
2
- export declare function recordInstalledVersion(): void;
3
- interface UpdateCheckResult {
4
- updateAvailable: boolean;
5
- latest?: string;
6
- }
7
- /** Throttled npm-currency check; never auto-mutates the install. */
8
- export declare function checkForCliUpdate(now?: number): Promise<UpdateCheckResult>;
9
- export declare function printUpdateNoticeIfDrifted(): Promise<void>;
10
- export {};
@@ -1,109 +0,0 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import { z } from "zod";
4
- import { configDir } from "./auth.js";
5
- import { CLI_VERSION } from "./constants.js";
6
- import { errLine } from "./output.js";
7
- import { telemetryDisabled } from "./setup-telemetry.js";
8
- const MARKER_FILE = "skill-version-marker.json";
9
- const THROTTLE_MS = 24 * 60 * 60 * 1000;
10
- const CHECK_TIMEOUT_MS = 5_000;
11
- // npm is the only currency signal with a publisher behind it: the cookbook repo has no
12
- // releases and no release automation, so a tag check would report "up to date" forever.
13
- const REGISTRY_URL = "https://registry.npmjs.org/@tiny-fish/cli/latest";
14
- const markerSchema = z.object({
15
- last_checked_at: z.number().optional(),
16
- last_known_latest: z.string().optional(),
17
- });
18
- function markerPath() {
19
- return path.join(configDir(), MARKER_FILE);
20
- }
21
- function readMarker() {
22
- try {
23
- const parsed = markerSchema.safeParse(JSON.parse(fs.readFileSync(markerPath(), "utf8")));
24
- return parsed.success ? parsed.data : undefined;
25
- }
26
- catch {
27
- return undefined;
28
- }
29
- }
30
- function writeMarker(state) {
31
- fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
32
- const tmpPath = `${markerPath()}.tmp-${process.pid}`;
33
- fs.writeFileSync(tmpPath, JSON.stringify(state), { mode: 0o600 });
34
- fs.renameSync(tmpPath, markerPath());
35
- }
36
- /** Install-time, offline-safe; best-effort — never fails a finished install. */
37
- export function recordInstalledVersion() {
38
- try {
39
- writeMarker({ ...readMarker() });
40
- }
41
- catch {
42
- // marker is a nice-to-have
43
- }
44
- }
45
- const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)$/;
46
- /** Strictly newer; false on unparsable input. */
47
- function isNewer(current, latest) {
48
- const c = SEMVER.exec(current);
49
- const l = SEMVER.exec(latest);
50
- if (!c || !l)
51
- return false;
52
- for (let i = 1; i <= 3; i++) {
53
- const cn = Number(c[i]);
54
- const ln = Number(l[i]);
55
- if (ln !== cn)
56
- return ln > cn;
57
- }
58
- return false;
59
- }
60
- /** Throttled npm-currency check; never auto-mutates the install. */
61
- export async function checkForCliUpdate(now = Date.now()) {
62
- const marker = readMarker();
63
- // No marker means the CLI never installed anything — nothing to nag about.
64
- if (!marker || telemetryDisabled())
65
- return { updateAvailable: false };
66
- const cached = () => ({
67
- updateAvailable: marker.last_known_latest !== undefined && isNewer(CLI_VERSION, marker.last_known_latest),
68
- ...(marker.last_known_latest !== undefined ? { latest: marker.last_known_latest } : {}),
69
- });
70
- // Time-based only — failed fetch must not stall every invocation.
71
- if (marker.last_checked_at !== undefined && now - marker.last_checked_at < THROTTLE_MS) {
72
- return cached();
73
- }
74
- let latest;
75
- try {
76
- const response = await fetch(REGISTRY_URL, {
77
- headers: { accept: "application/json" },
78
- signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
79
- });
80
- if (response.ok) {
81
- const body = (await response.json());
82
- if (typeof body.version === "string")
83
- latest = body.version;
84
- }
85
- }
86
- catch {
87
- // Unreachable registry — don't fail setup, don't erase the cache.
88
- }
89
- try {
90
- writeMarker({
91
- ...marker,
92
- last_checked_at: now,
93
- last_known_latest: latest ?? marker.last_known_latest,
94
- });
95
- }
96
- catch {
97
- // best-effort
98
- }
99
- // Fall back to the cache so consecutive invocations can't disagree.
100
- if (!latest)
101
- return cached();
102
- return { updateAvailable: isNewer(CLI_VERSION, latest), latest };
103
- }
104
- export async function printUpdateNoticeIfDrifted() {
105
- const { updateAvailable } = await checkForCliUpdate();
106
- if (updateAvailable) {
107
- errLine("a newer TinyFish CLI is available — re-run `npx @tiny-fish/cli connect --all`");
108
- }
109
- }