@narumitw/pi-firecrawl 0.34.0 → 0.36.0

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/README.md CHANGED
@@ -16,7 +16,7 @@ Use it to give your AI coding agent reliable web research capabilities for docum
16
16
  - Supports Firecrawl API endpoint overrides.
17
17
  - Shows statusline activity only while Firecrawl tools are running.
18
18
  - Provides a `/firecrawl` menu with configuration help and tool controls.
19
- - Provides a Plan-mode-style selector for choosing individual Firecrawl tools.
19
+ - Uses `@narumitw/pi-tui-kit` for width-safe menus and individual tool selection.
20
20
  - Persists the selected Firecrawl tools across Pi restarts.
21
21
  - Bounds tool output to Pi's 50 KB or 2,000-line limit while preserving oversized responses in private temporary files.
22
22
  - Never logs, displays, or stores your Firecrawl API key.
@@ -99,7 +99,7 @@ Direct subcommands are also available:
99
99
  - `quickstart` is an alias for `config`.
100
100
  - `status` shows runtime tool state, persisted selection, settings file path, API-key presence,
101
101
  API URL, and active non-Firecrawl tool count.
102
- - `tools` opens a Plan-mode-style selector for choosing individual `firecrawl_*` tools.
102
+ - `tools` opens a width-safe selector for choosing individual `firecrawl_*` tools.
103
103
  - `toggle` is an alias for `tools`.
104
104
  - `enable` enables all `firecrawl_*` tools for future turns.
105
105
  - `disable` disables all `firecrawl_*` tools for future turns. The slash command remains
@@ -113,12 +113,16 @@ ${PI_CODING_AGENT_DIR:-~/.pi/agent}/pi-firecrawl.json
113
113
 
114
114
  When the file is missing or invalid, the extension preserves Pi's current active-tool policy
115
115
  instead of enabling tools by itself. A valid saved selection is restored on Pi startup and
116
- `/reload`. The settings file stores only tool names and a timestamp; it never stores
117
- `FIRECRAWL_API_KEY`, request headers, or other secrets.
118
-
119
- Compatibility: older versions used `pi-firecrawl-settings.json`. During the migration window,
120
- a legacy-only file is automatically migrated to `pi-firecrawl.json` with a warning. If both
121
- files exist, `pi-firecrawl.json` wins and the legacy file is ignored. The legacy filename is
116
+ `/reload`. A missing file is created by the first successful selection change. Within one Pi process, selection saves run in invocation order, reread the latest valid document, and preserve unknown fields. Malformed JSON
117
+ or invalid recognized fields block the save without replacement; a failed save restores the prior
118
+ Firecrawl tool selection while preserving other extensions' current tools. The settings file
119
+ stores only tool names and a timestamp; it never stores `FIRECRAWL_API_KEY`, request headers, or
120
+ other secrets.
121
+
122
+ Compatibility: older versions used `pi-firecrawl-settings.json`. A legacy-only file remains
123
+ readable with a warning and is never modified automatically; rename it to `pi-firecrawl.json`.
124
+ The first subsequent settings save writes the canonical file. If both files exist,
125
+ `pi-firecrawl.json` wins and the legacy file is ignored. The legacy filename is
122
126
  deprecated and will be removed in a future major release.
123
127
 
124
128
  ## 🚀 Examples
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-firecrawl",
3
- "version": "0.34.0",
3
+ "version": "0.36.0",
4
4
  "description": "Pi extension that exposes Firecrawl web scraping and crawling tools.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -29,6 +29,7 @@
29
29
  "typecheck": "tsc --noEmit"
30
30
  },
31
31
  "dependencies": {
32
+ "@narumitw/pi-tui-kit": "<1",
32
33
  "typebox": "^1.3.8"
33
34
  },
34
35
  "devDependencies": {
package/src/firecrawl.ts CHANGED
@@ -1,17 +1,23 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
2
3
  import { hasApiKey } from "./client.js";
3
4
  import { cleanupResponseArtifacts, openResponseArtifacts } from "./response-format.js";
4
5
  import { loadSettings } from "./settings.js";
5
6
  import {
7
+ advanceFirecrawlSessionGeneration,
6
8
  allFirecrawlTools,
7
9
  applyFirecrawlTools,
8
10
  buildCommandGuide,
9
11
  buildConfigMessage,
10
12
  buildStatusMessage,
11
13
  clearSettingsNotice,
14
+ currentFirecrawlSessionGeneration,
15
+ currentFirecrawlSessionSignal,
16
+ isCurrentFirecrawlSession,
12
17
  recordSettingsNotice,
13
18
  showToolSelector,
14
19
  updateFirecrawlTools,
20
+ waitForFirecrawlSettings,
15
21
  } from "./tool-selector.js";
16
22
  import { crawlStatusTool, crawlTool, mapTool, scrapeTool, searchTool } from "./tools.js";
17
23
 
@@ -55,15 +61,18 @@ export default function firecrawl(pi: ExtensionAPI) {
55
61
  description: "Open Firecrawl help and tool controls",
56
62
  getArgumentCompletions: (prefix) => commandCompletions(prefix),
57
63
  handler: async (args, ctx) => {
58
- await handleFirecrawlCommand(pi, args, ctx);
64
+ const generation = currentFirecrawlSessionGeneration();
65
+ await handleFirecrawlCommand(pi, args, ctx, generation);
59
66
  },
60
67
  });
61
68
 
62
69
  pi.on("session_start", async (_event, ctx) => {
70
+ const generation = advanceFirecrawlSessionGeneration();
63
71
  openResponseArtifacts(ctx.sessionManager);
64
72
  clearSettingsNotice();
65
73
  ctx.ui.setStatus(STATUS_KEY, undefined);
66
74
  const settings = await loadSettings();
75
+ if (!isCurrentFirecrawlSession(generation)) return;
67
76
  recordSettingsNotice(settings);
68
77
  if (settings.notice) ctx.ui.notify(settings.notice, "warning");
69
78
  if (settings.kind === "loaded") {
@@ -76,16 +85,24 @@ export default function firecrawl(pi: ExtensionAPI) {
76
85
  });
77
86
 
78
87
  pi.on("session_shutdown", async (_event, ctx) => {
88
+ advanceFirecrawlSessionGeneration();
79
89
  ctx.ui.setStatus(STATUS_KEY, undefined);
80
- await cleanupResponseArtifacts(ctx.sessionManager);
90
+ const artifactOwner = ctx.sessionManager;
91
+ await waitForFirecrawlSettings();
92
+ await cleanupResponseArtifacts(artifactOwner);
81
93
  });
82
94
  }
83
95
 
84
- async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: CommandContext) {
96
+ async function handleFirecrawlCommand(
97
+ pi: ExtensionAPI,
98
+ args: string,
99
+ ctx: CommandContext,
100
+ generation: number,
101
+ ) {
85
102
  const command = parseCommand(args);
86
103
  switch (command) {
87
104
  case "menu":
88
- await showMenu(pi, ctx);
105
+ await showMenu(pi, ctx, generation);
89
106
  return;
90
107
  case "help":
91
108
  ctx.ui.notify(buildCommandGuide(), "info");
@@ -94,9 +111,12 @@ async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: Comma
94
111
  case "quickstart":
95
112
  ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
96
113
  return;
97
- case "status":
98
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
114
+ case "status": {
115
+ const status = await buildStatusMessage(pi);
116
+ if (!isCurrentFirecrawlSession(generation)) return;
117
+ ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
99
118
  return;
119
+ }
100
120
  case "tools":
101
121
  await showToolSelector(pi, ctx);
102
122
  return;
@@ -111,36 +131,65 @@ async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: Comma
111
131
  ctx.ui.notify(`Unknown /firecrawl command: ${args.trim()}\n\n${buildCommandGuide()}`, "warning");
112
132
  }
113
133
 
114
- async function showMenu(pi: ExtensionAPI, ctx: CommandContext) {
134
+ async function showMenu(pi: ExtensionAPI, ctx: CommandContext, generation: number) {
115
135
  if (!ctx.hasUI) {
116
- ctx.ui.notify(
117
- `${buildCommandGuide()}\n\n${await buildStatusMessage(pi)}`,
118
- hasApiKey() ? "info" : "warning",
119
- );
136
+ const status = await buildStatusMessage(pi);
137
+ if (!isCurrentFirecrawlSession(generation)) return;
138
+ ctx.ui.notify(`${buildCommandGuide()}\n\n${status}`, hasApiKey() ? "info" : "warning");
120
139
  return;
121
140
  }
122
141
 
123
- const choice = await ctx.ui.select("Firecrawl", Object.values(MENU_OPTIONS));
124
- switch (choice) {
125
- case MENU_OPTIONS.config:
126
- ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
127
- return;
128
- case MENU_OPTIONS.help:
129
- ctx.ui.notify(buildCommandGuide(), "info");
130
- return;
131
- case MENU_OPTIONS.status:
132
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
133
- return;
134
- case MENU_OPTIONS.tools:
135
- await showToolSelector(pi, ctx);
136
- return;
137
- case MENU_OPTIONS.enable:
138
- await updateFirecrawlTools(pi, ctx, allFirecrawlTools(), "enabled all");
139
- return;
140
- case MENU_OPTIONS.disable:
141
- await updateFirecrawlTools(pi, ctx, [], "disabled all");
142
- return;
143
- }
142
+ type Screen = "main";
143
+ type Action = keyof typeof MENU_OPTIONS;
144
+ const menu = defineMenu<undefined, Screen, Action>({
145
+ start: "main",
146
+ screens: {
147
+ main: () => ({
148
+ kind: "actions",
149
+ title: "Firecrawl",
150
+ items: Object.entries(MENU_OPTIONS).map(([id, label]) => ({
151
+ id,
152
+ label,
153
+ action: id as Action,
154
+ })),
155
+ hint: "close",
156
+ }),
157
+ },
158
+ actions: {
159
+ config: async () => {
160
+ ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
161
+ return { kind: "close" };
162
+ },
163
+ help: async () => {
164
+ ctx.ui.notify(buildCommandGuide(), "info");
165
+ return { kind: "close" };
166
+ },
167
+ status: async () => {
168
+ const status = await buildStatusMessage(pi);
169
+ if (isCurrentFirecrawlSession(generation)) {
170
+ ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
171
+ }
172
+ return { kind: "close" };
173
+ },
174
+ tools: async () => {
175
+ await showToolSelector(pi, ctx);
176
+ return { kind: "close" };
177
+ },
178
+ enable: async () => {
179
+ await updateFirecrawlTools(pi, ctx, allFirecrawlTools(), "enabled all");
180
+ return { kind: "close" };
181
+ },
182
+ disable: async () => {
183
+ await updateFirecrawlTools(pi, ctx, [], "disabled all");
184
+ return { kind: "close" };
185
+ },
186
+ },
187
+ });
188
+ await runMenu(ctx, menu, {
189
+ getState: () => undefined,
190
+ signal: currentFirecrawlSessionSignal(),
191
+ isCurrent: () => isCurrentFirecrawlSession(generation),
192
+ });
144
193
  }
145
194
 
146
195
  export function parseCommand(args: string): CommandAction | "unknown" {
@@ -175,5 +224,5 @@ export {
175
224
  parseResponseBody,
176
225
  } from "./client.js";
177
226
  export { cleanupResponseArtifacts } from "./response-format.js";
178
- export { installSettingsFileExclusively, normalizeFirecrawlSettings } from "./settings.js";
227
+ export { normalizeFirecrawlSettings } from "./settings.js";
179
228
  export { formatPersistedSelection, orderedFirecrawlTools } from "./tool-selector.js";
package/src/settings.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { constants } from "node:fs";
3
- import { access, link, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
- import { homedir } from "node:os";
3
+ import { access, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
4
  import { dirname, join } from "node:path";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
6
  import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tools.js";
7
7
 
8
8
  const NEW_SETTINGS_FILE = "pi-firecrawl.json";
@@ -13,17 +13,23 @@ export interface FirecrawlSettings {
13
13
  updatedAt: number;
14
14
  }
15
15
 
16
+ export interface SettingsFileOperations {
17
+ write(path: string, data: string): Promise<void>;
18
+ rename(source: string, destination: string): Promise<void>;
19
+ }
20
+
21
+ const DEFAULT_FILE_OPERATIONS: SettingsFileOperations = {
22
+ write: (path, data) => writeFile(path, data, "utf8").then(() => undefined),
23
+ rename,
24
+ };
25
+
16
26
  export type SettingsLoadResult =
17
27
  | { kind: "missing"; notice?: string }
18
28
  | { kind: "invalid"; reason: string; notice?: string }
19
29
  | { kind: "loaded"; settings: FirecrawlSettings; notice?: string };
20
30
 
21
- type SettingsMigrationResult = {
22
- kind: "migrated" | "failed";
23
- notice: string;
24
- };
25
-
26
31
  export async function loadSettings(): Promise<SettingsLoadResult> {
32
+ await settingsSaveQueue;
27
33
  const newPath = settingsFilePath();
28
34
  const newSettings = await readSettingsFile(newPath);
29
35
  if (newSettings.kind !== "missing") {
@@ -39,39 +45,50 @@ export async function loadSettings(): Promise<SettingsLoadResult> {
39
45
  if (legacySettings.kind === "missing") return { kind: "missing" };
40
46
  if (legacySettings.kind === "invalid") return legacySettings;
41
47
 
42
- const migration = await migrateLegacySettings(legacyPath, legacySettings.settings);
43
- if (migration.kind === "failed") {
44
- const settingsCreatedDuringMigration = await readSettingsFile(newPath);
45
- if (settingsCreatedDuringMigration.kind !== "missing") {
46
- return withLegacyIgnoredNotice(settingsCreatedDuringMigration);
47
- }
48
- }
48
+ return {
49
+ ...legacySettings,
50
+ notice: `Using legacy ${LEGACY_SETTINGS_FILE}; rename it to ${NEW_SETTINGS_FILE}. Future saves write ${NEW_SETTINGS_FILE} without modifying the legacy file.`,
51
+ };
52
+ }
49
53
 
50
- return { ...legacySettings, notice: migration.notice };
54
+ interface SettingsDocumentResult {
55
+ result: SettingsLoadResult;
56
+ document?: Record<string, unknown>;
51
57
  }
52
58
 
53
- async function readSettingsFile(filePath: string): Promise<SettingsLoadResult> {
59
+ async function readSettingsDocument(filePath: string): Promise<SettingsDocumentResult> {
54
60
  let text: string;
55
61
  try {
56
62
  text = await readFile(filePath, "utf8");
57
63
  } catch (error) {
58
- if (isNodeError(error) && error.code === "ENOENT") return { kind: "missing" };
59
- return { kind: "invalid", reason: `${filePath}: ${formatError(error)}` };
64
+ if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
65
+ return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
60
66
  }
61
67
 
62
68
  try {
63
69
  const parsed = JSON.parse(text) as unknown;
64
70
  const settings = normalizeFirecrawlSettings(parsed);
65
- if (settings) return { kind: "loaded", settings };
71
+ if (settings) {
72
+ return {
73
+ result: { kind: "loaded", settings },
74
+ document: { ...(parsed as Record<string, unknown>) },
75
+ };
76
+ }
66
77
  return {
67
- kind: "invalid",
68
- reason: `${filePath}: expected tools to be an array of Firecrawl tool names`,
78
+ result: {
79
+ kind: "invalid",
80
+ reason: `${filePath}: expected tools to be an array of Firecrawl tool names`,
81
+ },
69
82
  };
70
83
  } catch (error) {
71
- return { kind: "invalid", reason: `${filePath}: ${formatError(error)}` };
84
+ return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
72
85
  }
73
86
  }
74
87
 
88
+ async function readSettingsFile(filePath: string): Promise<SettingsLoadResult> {
89
+ return (await readSettingsDocument(filePath)).result;
90
+ }
91
+
75
92
  async function withLegacyIgnoredNotice(settings: SettingsLoadResult): Promise<SettingsLoadResult> {
76
93
  if (!(await fileExists(legacySettingsFilePath()))) return settings;
77
94
  return {
@@ -80,46 +97,6 @@ async function withLegacyIgnoredNotice(settings: SettingsLoadResult): Promise<Se
80
97
  };
81
98
  }
82
99
 
83
- export async function installSettingsFileExclusively(filePath: string, contents: string) {
84
- await mkdir(dirname(filePath), { recursive: true });
85
- const tempFile = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
86
- try {
87
- await writeFile(tempFile, contents, { encoding: "utf8", flag: "wx" });
88
- await link(tempFile, filePath);
89
- } finally {
90
- await rm(tempFile, { force: true }).catch(() => undefined);
91
- }
92
- }
93
-
94
- async function migrateLegacySettings(
95
- legacyPath: string,
96
- settings: FirecrawlSettings,
97
- ): Promise<SettingsMigrationResult> {
98
- const newPath = settingsFilePath();
99
- try {
100
- await installSettingsFileExclusively(newPath, `${JSON.stringify(settings, null, 2)}\n`);
101
- } catch (error) {
102
- return {
103
- kind: "failed",
104
- notice: `Firecrawl legacy settings migration failed: could not migrate ${legacyPath} to ${newPath}: ${formatError(error)}. The legacy file was used for this session; future saves will write ${NEW_SETTINGS_FILE}.`,
105
- };
106
- }
107
-
108
- try {
109
- await rm(legacyPath, { force: true });
110
- } catch (error) {
111
- return {
112
- kind: "migrated",
113
- notice: `Firecrawl settings migrated from ${legacyPath} to ${newPath}, but the legacy file could not be removed: ${formatError(error)}. Delete ${LEGACY_SETTINGS_FILE} after confirming your settings.`,
114
- };
115
- }
116
-
117
- return {
118
- kind: "migrated",
119
- notice: `Firecrawl settings migrated from ${legacyPath} to ${newPath}. ${LEGACY_SETTINGS_FILE} is deprecated and will be removed in a future major release.`,
120
- };
121
- }
122
-
123
100
  async function fileExists(filePath: string) {
124
101
  try {
125
102
  await access(filePath, constants.F_OK);
@@ -129,6 +106,16 @@ async function fileExists(filePath: string) {
129
106
  }
130
107
  }
131
108
 
109
+ async function pathEntryExists(filePath: string) {
110
+ try {
111
+ await lstat(filePath);
112
+ return true;
113
+ } catch (error) {
114
+ if (isNodeError(error) && error.code === "ENOENT") return false;
115
+ throw error;
116
+ }
117
+ }
118
+
132
119
  export function normalizeFirecrawlSettings(value: unknown): FirecrawlSettings | undefined {
133
120
  if (!value || typeof value !== "object") return undefined;
134
121
  const settings = value as { tools?: unknown; updatedAt?: unknown };
@@ -147,13 +134,44 @@ function orderedUniqueFirecrawlTools(tools: readonly FirecrawlToolName[]) {
147
134
  return FIRECRAWL_TOOL_NAMES.filter((toolName) => selectedTools.has(toolName));
148
135
  }
149
136
 
150
- export async function saveSettings(settings: FirecrawlSettings) {
137
+ let settingsSaveQueue = Promise.resolve();
138
+
139
+ export function saveSettings(
140
+ settings: FirecrawlSettings,
141
+ operations: Partial<SettingsFileOperations> = {},
142
+ ): Promise<void> {
143
+ const operation = settingsSaveQueue.then(() => saveSettingsNow(settings, operations));
144
+ settingsSaveQueue = operation.catch(() => undefined);
145
+ return operation;
146
+ }
147
+
148
+ async function saveSettingsNow(
149
+ settings: FirecrawlSettings,
150
+ operations: Partial<SettingsFileOperations>,
151
+ ): Promise<void> {
151
152
  const filePath = settingsFilePath();
153
+ let current = await readSettingsDocument(filePath);
154
+ const replaceCanonical = current.result.kind !== "missing";
155
+ if (!replaceCanonical) current = await readSettingsDocument(legacySettingsFilePath());
156
+ if (current.result.kind === "invalid") {
157
+ throw new Error(`Cannot save Firecrawl settings until you repair ${current.result.reason}`);
158
+ }
159
+ const nextDocument = {
160
+ ...(current.document ?? {}),
161
+ tools: [...settings.tools],
162
+ updatedAt: settings.updatedAt,
163
+ };
152
164
  await mkdir(dirname(filePath), { recursive: true });
153
- const tempFile = `${filePath}.${process.pid}.${Date.now()}.tmp`;
165
+ const tempFile = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
154
166
  try {
155
- await writeFile(tempFile, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
156
- await rename(tempFile, filePath);
167
+ await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(
168
+ tempFile,
169
+ `${JSON.stringify(nextDocument, null, 2)}\n`,
170
+ );
171
+ if (!replaceCanonical && (await pathEntryExists(filePath))) {
172
+ throw new Error(`${NEW_SETTINGS_FILE} was created concurrently; reopen settings and retry.`);
173
+ }
174
+ await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(tempFile, filePath);
157
175
  } catch (error) {
158
176
  await rm(tempFile, { force: true }).catch(() => undefined);
159
177
  throw error;
@@ -169,7 +187,7 @@ function legacySettingsFilePath() {
169
187
  }
170
188
 
171
189
  function agentDir() {
172
- return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
190
+ return getAgentDir();
173
191
  }
174
192
 
175
193
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
2
3
  import { configuredApiUrl, hasApiKey } from "./client.js";
3
4
  import {
4
5
  loadSettings,
@@ -9,15 +10,9 @@ import {
9
10
  import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tools.js";
10
11
 
11
12
  type CommandContext = ExtensionCommandContext;
12
-
13
- const TOOL_SELECTOR_DONE = "Done";
14
- const TOOL_SELECTOR_ENABLE_ALL = "Enable all Firecrawl tools";
15
- const TOOL_SELECTOR_DISABLE_ALL = "Disable all Firecrawl tools";
16
13
  type ToolRuntimeStatus = "enabled" | "disabled" | "partial";
17
- type ToolSelectorAction = "enableAll" | "disableAll" | "done";
18
- type ToolSelectorRow =
19
- | { kind: "tool"; toolName: FirecrawlToolName }
20
- | { kind: "action"; action: ToolSelectorAction; label: string };
14
+ type ToolSelectorScreen = "tools";
15
+ type ToolSelectorAction = "toggle" | "enableAll" | "disableAll";
21
16
  interface ToolStatusSummary {
22
17
  runtimeStatus: ToolRuntimeStatus;
23
18
  activeFirecrawlToolCount: number;
@@ -25,6 +20,26 @@ interface ToolStatusSummary {
25
20
  }
26
21
 
27
22
  let settingsNotice: string | undefined;
23
+ let sessionGeneration = 0;
24
+ let sessionController = new AbortController();
25
+
26
+ export function advanceFirecrawlSessionGeneration(): number {
27
+ sessionController.abort(new DOMException("Firecrawl session replaced", "AbortError"));
28
+ sessionController = new AbortController();
29
+ return ++sessionGeneration;
30
+ }
31
+
32
+ export function currentFirecrawlSessionGeneration(): number {
33
+ return sessionGeneration;
34
+ }
35
+
36
+ export function isCurrentFirecrawlSession(generation: number): boolean {
37
+ return generation === sessionGeneration;
38
+ }
39
+
40
+ export function currentFirecrawlSessionSignal(): AbortSignal {
41
+ return sessionController.signal;
42
+ }
28
43
 
29
44
  export function clearSettingsNotice() {
30
45
  settingsNotice = undefined;
@@ -35,161 +50,150 @@ export function recordSettingsNotice(settings: SettingsLoadResult) {
35
50
  }
36
51
 
37
52
  export async function showToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
38
- if (!ctx.hasUI) {
39
- ctx.ui.notify(
40
- `Firecrawl tool selection needs an interactive UI.\n\n${await buildStatusMessage(pi)}`,
41
- hasApiKey() ? "info" : "warning",
42
- );
43
- return;
44
- }
45
-
46
- let selectedTools = new Set<FirecrawlToolName>(getActiveFirecrawlTools(pi));
47
- let persistQueue = Promise.resolve();
48
- const commitSelectedTools = () => {
49
- const nextSelectedTools = orderedFirecrawlTools(selectedTools);
50
- applyFirecrawlTools(pi, nextSelectedTools);
51
- persistQueue = persistQueue.then(() => persistSettings(ctx, nextSelectedTools));
52
- };
53
-
54
- const customResult = await ctx.ui.custom<"closed" | undefined>(
55
- (tui, theme, keybindings, done) => {
56
- const rows = firecrawlToolSelectorRows();
57
- let selectedIndex = 0;
58
- const moveSelection = (delta: number) => {
59
- selectedIndex = (selectedIndex + delta + rows.length) % rows.length;
60
- };
61
- const activateSelectedRow = () => {
62
- const row = rows[selectedIndex];
63
- if (!row) return;
64
-
65
- if (row.kind === "tool") {
66
- if (selectedTools.has(row.toolName)) selectedTools.delete(row.toolName);
67
- else selectedTools.add(row.toolName);
68
- commitSelectedTools();
69
- return;
70
- }
71
-
72
- if (row.action === "enableAll") {
73
- selectedTools = new Set(allFirecrawlTools());
74
- commitSelectedTools();
75
- return;
76
- }
77
- if (row.action === "disableAll") {
78
- selectedTools = new Set();
79
- commitSelectedTools();
80
- return;
81
- }
82
-
83
- done("closed");
84
- };
85
-
86
- return {
87
- invalidate() {},
88
- render() {
89
- return [
90
- theme.fg("accent", theme.bold(toolSelectorTitle(selectedTools))),
91
- "",
92
- ...rows.map((row, index) => {
93
- const label = formatToolSelectorRow(row, selectedTools);
94
- if (index === selectedIndex) {
95
- return `${theme.fg("accent", "›")} ${theme.fg("accent", label)}`;
96
- }
97
- return ` ${label}`;
98
- }),
99
- "",
100
- theme.fg("dim", "↑↓ navigate • Enter/Space toggle • Esc close"),
101
- ];
102
- },
103
- handleInput(data: string) {
104
- if (keybindings.matches(data, "tui.select.up")) {
105
- moveSelection(-1);
106
- tui.requestRender();
107
- return;
108
- }
109
- if (keybindings.matches(data, "tui.select.down")) {
110
- moveSelection(1);
111
- tui.requestRender();
112
- return;
113
- }
114
- if (keybindings.matches(data, "tui.select.pageUp")) {
115
- selectedIndex = 0;
116
- tui.requestRender();
117
- return;
118
- }
119
- if (keybindings.matches(data, "tui.select.pageDown")) {
120
- selectedIndex = rows.length - 1;
121
- tui.requestRender();
122
- return;
123
- }
124
- if (keybindings.matches(data, "tui.select.confirm") || data === " ") {
125
- activateSelectedRow();
126
- tui.requestRender();
127
- return;
128
- }
129
- if (keybindings.matches(data, "tui.select.cancel")) {
130
- done("closed");
131
- }
132
- },
133
- };
53
+ const generation = sessionGeneration;
54
+ if (!ctx.hasUI) return;
55
+ const menu = defineMenu<undefined, ToolSelectorScreen, ToolSelectorAction>({
56
+ start: "tools",
57
+ screens: {
58
+ tools: () => {
59
+ const selectedTools = new Set(getActiveFirecrawlTools(pi));
60
+ return {
61
+ kind: "multiSelect",
62
+ title: toolSelectorTitle(selectedTools),
63
+ items: FIRECRAWL_TOOL_NAMES.map((toolName) => ({
64
+ id: toolName,
65
+ label: toolName,
66
+ selected: selectedTools.has(toolName),
67
+ })),
68
+ action: "toggle",
69
+ actions: [
70
+ {
71
+ id: "enable-all",
72
+ label: "Enable all Firecrawl tools",
73
+ action: "enableAll",
74
+ },
75
+ {
76
+ id: "disable-all",
77
+ label: "Disable all Firecrawl tools",
78
+ action: "disableAll",
79
+ },
80
+ { id: "done", label: "Done", close: true },
81
+ ],
82
+ hint: "close",
83
+ doneLabel: "Done",
84
+ };
85
+ },
134
86
  },
135
- );
136
-
137
- if (customResult !== "closed") {
138
- await showDialogToolSelector(pi, ctx);
139
- return;
140
- }
87
+ actions: {
88
+ toggle: async ({ itemId, selected }) => {
89
+ if (!isFirecrawlToolName(itemId)) return { kind: "rejected" };
90
+ const selectedTools = new Set(getActiveFirecrawlTools(pi));
91
+ if (selected) selectedTools.add(itemId);
92
+ else selectedTools.delete(itemId);
93
+ const saved = await transactSelectedTools(
94
+ pi,
95
+ ctx,
96
+ orderedFirecrawlTools(selectedTools),
97
+ generation,
98
+ );
99
+ return saved ? { kind: "stay" } : { kind: "rejected" };
100
+ },
101
+ enableAll: async () => {
102
+ const saved = await transactSelectedTools(pi, ctx, allFirecrawlTools(), generation);
103
+ return saved ? { kind: "stay" } : { kind: "rejected" };
104
+ },
105
+ disableAll: async () => {
106
+ const saved = await transactSelectedTools(pi, ctx, [], generation);
107
+ return saved ? { kind: "stay" } : { kind: "rejected" };
108
+ },
109
+ },
110
+ });
111
+ const result = await runMenu(ctx, menu, {
112
+ getState: () => undefined,
113
+ signal: sessionController.signal,
114
+ isCurrent: () => isCurrentFirecrawlSession(generation),
115
+ });
116
+ if (result.kind !== "closed" || !isCurrentFirecrawlSession(generation)) return;
117
+ const status = await buildStatusMessage(pi);
118
+ if (!isCurrentFirecrawlSession(generation)) return;
119
+ ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
120
+ }
141
121
 
142
- await persistQueue;
143
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
122
+ export async function updateFirecrawlTools(
123
+ pi: ExtensionAPI,
124
+ ctx: CommandContext,
125
+ selectedTools: readonly FirecrawlToolName[],
126
+ action: string,
127
+ ) {
128
+ const generation = sessionGeneration;
129
+ const saved = await transactSelectedTools(pi, ctx, selectedTools, generation);
130
+ if (!saved || !isCurrentFirecrawlSession(generation)) return;
131
+ const status = await buildStatusMessage(pi);
132
+ if (!isCurrentFirecrawlSession(generation)) return;
133
+ ctx.ui.notify(`Firecrawl tools ${action}.\n\n${status}`, hasApiKey() ? "info" : "warning");
144
134
  }
145
135
 
146
- async function showDialogToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
147
- let selectedTools = new Set<FirecrawlToolName>(getActiveFirecrawlTools(pi));
148
- while (true) {
149
- const rows = firecrawlToolSelectorRows();
150
- const choices = rows.map((row) => formatToolSelectorRow(row, selectedTools));
151
- const choice = await ctx.ui.select(toolSelectorTitle(selectedTools), choices);
152
- if (!choice) break;
153
-
154
- const row = rows[choices.indexOf(choice)];
155
- if (!row) continue;
156
- if (row.kind === "action" && row.action === "done") break;
157
-
158
- if (row.kind === "tool") {
159
- if (selectedTools.has(row.toolName)) selectedTools.delete(row.toolName);
160
- else selectedTools.add(row.toolName);
161
- } else if (row.action === "enableAll") {
162
- selectedTools = new Set(allFirecrawlTools());
163
- } else if (row.action === "disableAll") {
164
- selectedTools = new Set();
165
- }
136
+ export async function setSelectedFirecrawlTools(
137
+ pi: ExtensionAPI,
138
+ ctx: CommandContext,
139
+ selectedTools: readonly FirecrawlToolName[],
140
+ ): Promise<boolean> {
141
+ return transactSelectedTools(pi, ctx, selectedTools, sessionGeneration);
142
+ }
166
143
 
167
- await setSelectedFirecrawlTools(pi, ctx, orderedFirecrawlTools(selectedTools));
168
- }
144
+ let toolTransactionQueue = Promise.resolve();
169
145
 
170
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
146
+ export async function waitForFirecrawlSettings(): Promise<void> {
147
+ await toolTransactionQueue;
171
148
  }
172
149
 
173
- export async function updateFirecrawlTools(
150
+ function transactSelectedTools(
174
151
  pi: ExtensionAPI,
175
152
  ctx: CommandContext,
176
153
  selectedTools: readonly FirecrawlToolName[],
177
- action: string,
178
- ) {
179
- await setSelectedFirecrawlTools(pi, ctx, selectedTools);
180
- ctx.ui.notify(
181
- `Firecrawl tools ${action}.\n\n${await buildStatusMessage(pi)}`,
182
- hasApiKey() ? "info" : "warning",
154
+ expectedGeneration: number,
155
+ ): Promise<boolean> {
156
+ const operation = toolTransactionQueue.then(() =>
157
+ transactSelectedToolsNow(pi, ctx, selectedTools, expectedGeneration),
158
+ );
159
+ toolTransactionQueue = operation.then(
160
+ () => undefined,
161
+ () => undefined,
183
162
  );
163
+ return operation;
184
164
  }
185
165
 
186
- export async function setSelectedFirecrawlTools(
166
+ async function transactSelectedToolsNow(
187
167
  pi: ExtensionAPI,
188
168
  ctx: CommandContext,
189
169
  selectedTools: readonly FirecrawlToolName[],
190
- ) {
191
- applyFirecrawlTools(pi, selectedTools);
192
- await persistSettings(ctx, selectedTools);
170
+ expectedGeneration: number,
171
+ ): Promise<boolean> {
172
+ if (!isCurrentFirecrawlSession(expectedGeneration)) return false;
173
+ const previousActiveTools = pi.getActiveTools();
174
+ try {
175
+ applyFirecrawlTools(pi, selectedTools);
176
+ await persistSettings(selectedTools);
177
+ return isCurrentFirecrawlSession(expectedGeneration);
178
+ } catch (error) {
179
+ let rollbackError: unknown;
180
+ try {
181
+ const previousFirecrawlTools = previousActiveTools.filter((name) =>
182
+ FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName),
183
+ ) as FirecrawlToolName[];
184
+ applyFirecrawlTools(pi, previousFirecrawlTools);
185
+ } catch (caught) {
186
+ rollbackError = caught;
187
+ }
188
+ if (!isCurrentFirecrawlSession(expectedGeneration)) return false;
189
+ ctx.ui.notify(
190
+ rollbackError
191
+ ? `Firecrawl settings save failed: ${formatError(error)}; active-tool rollback failed: ${formatError(rollbackError)}`
192
+ : `Firecrawl settings save failed; active tools restored: ${formatError(error)}`,
193
+ "warning",
194
+ );
195
+ return false;
196
+ }
193
197
  }
194
198
 
195
199
  export function applyFirecrawlTools(pi: ExtensionAPI, selectedTools: readonly FirecrawlToolName[]) {
@@ -263,21 +267,8 @@ function toolSelectorTitle(selectedTools: ReadonlySet<FirecrawlToolName>) {
263
267
  return `Firecrawl tools (${selectedTools.size}/${FIRECRAWL_TOOL_NAMES.length}). Non-built-in tools run at user risk.`;
264
268
  }
265
269
 
266
- function firecrawlToolSelectorRows(): ToolSelectorRow[] {
267
- return [
268
- ...FIRECRAWL_TOOL_NAMES.map((toolName) => ({ kind: "tool" as const, toolName })),
269
- { kind: "action", action: "enableAll", label: TOOL_SELECTOR_ENABLE_ALL },
270
- { kind: "action", action: "disableAll", label: TOOL_SELECTOR_DISABLE_ALL },
271
- { kind: "action", action: "done", label: TOOL_SELECTOR_DONE },
272
- ];
273
- }
274
-
275
- function formatToolSelectorRow(
276
- row: ToolSelectorRow,
277
- selectedTools: ReadonlySet<FirecrawlToolName>,
278
- ) {
279
- if (row.kind === "action") return row.label;
280
- return `${selectedTools.has(row.toolName) ? "[x]" : "[ ]"} ${row.toolName}`;
270
+ function isFirecrawlToolName(value: string): value is FirecrawlToolName {
271
+ return FIRECRAWL_TOOL_NAMES.includes(value as FirecrawlToolName);
281
272
  }
282
273
 
283
274
  function getActiveFirecrawlTools(pi: ExtensionAPI) {
@@ -323,10 +314,6 @@ function formatError(error: unknown) {
323
314
  return error instanceof Error ? error.message : String(error);
324
315
  }
325
316
 
326
- async function persistSettings(ctx: CommandContext, selectedTools: readonly FirecrawlToolName[]) {
327
- try {
328
- await saveSettings({ tools: [...selectedTools], updatedAt: Date.now() });
329
- } catch (error) {
330
- ctx.ui.notify(`Firecrawl settings save failed: ${formatError(error)}`, "warning");
331
- }
317
+ async function persistSettings(selectedTools: readonly FirecrawlToolName[]) {
318
+ await saveSettings({ tools: [...selectedTools], updatedAt: Date.now() });
332
319
  }