@narumitw/pi-firecrawl 0.34.0 → 0.35.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
@@ -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.35.0",
4
4
  "description": "Pi extension that exposes Firecrawl web scraping and crawling tools.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/firecrawl.ts CHANGED
@@ -3,15 +3,19 @@ import { hasApiKey } from "./client.js";
3
3
  import { cleanupResponseArtifacts, openResponseArtifacts } from "./response-format.js";
4
4
  import { loadSettings } from "./settings.js";
5
5
  import {
6
+ advanceFirecrawlSessionGeneration,
6
7
  allFirecrawlTools,
7
8
  applyFirecrawlTools,
8
9
  buildCommandGuide,
9
10
  buildConfigMessage,
10
11
  buildStatusMessage,
11
12
  clearSettingsNotice,
13
+ currentFirecrawlSessionGeneration,
14
+ isCurrentFirecrawlSession,
12
15
  recordSettingsNotice,
13
16
  showToolSelector,
14
17
  updateFirecrawlTools,
18
+ waitForFirecrawlSettings,
15
19
  } from "./tool-selector.js";
16
20
  import { crawlStatusTool, crawlTool, mapTool, scrapeTool, searchTool } from "./tools.js";
17
21
 
@@ -55,15 +59,18 @@ export default function firecrawl(pi: ExtensionAPI) {
55
59
  description: "Open Firecrawl help and tool controls",
56
60
  getArgumentCompletions: (prefix) => commandCompletions(prefix),
57
61
  handler: async (args, ctx) => {
58
- await handleFirecrawlCommand(pi, args, ctx);
62
+ const generation = currentFirecrawlSessionGeneration();
63
+ await handleFirecrawlCommand(pi, args, ctx, generation);
59
64
  },
60
65
  });
61
66
 
62
67
  pi.on("session_start", async (_event, ctx) => {
68
+ const generation = advanceFirecrawlSessionGeneration();
63
69
  openResponseArtifacts(ctx.sessionManager);
64
70
  clearSettingsNotice();
65
71
  ctx.ui.setStatus(STATUS_KEY, undefined);
66
72
  const settings = await loadSettings();
73
+ if (!isCurrentFirecrawlSession(generation)) return;
67
74
  recordSettingsNotice(settings);
68
75
  if (settings.notice) ctx.ui.notify(settings.notice, "warning");
69
76
  if (settings.kind === "loaded") {
@@ -76,16 +83,24 @@ export default function firecrawl(pi: ExtensionAPI) {
76
83
  });
77
84
 
78
85
  pi.on("session_shutdown", async (_event, ctx) => {
86
+ advanceFirecrawlSessionGeneration();
79
87
  ctx.ui.setStatus(STATUS_KEY, undefined);
80
- await cleanupResponseArtifacts(ctx.sessionManager);
88
+ const artifactOwner = ctx.sessionManager;
89
+ await waitForFirecrawlSettings();
90
+ await cleanupResponseArtifacts(artifactOwner);
81
91
  });
82
92
  }
83
93
 
84
- async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: CommandContext) {
94
+ async function handleFirecrawlCommand(
95
+ pi: ExtensionAPI,
96
+ args: string,
97
+ ctx: CommandContext,
98
+ generation: number,
99
+ ) {
85
100
  const command = parseCommand(args);
86
101
  switch (command) {
87
102
  case "menu":
88
- await showMenu(pi, ctx);
103
+ await showMenu(pi, ctx, generation);
89
104
  return;
90
105
  case "help":
91
106
  ctx.ui.notify(buildCommandGuide(), "info");
@@ -94,9 +109,12 @@ async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: Comma
94
109
  case "quickstart":
95
110
  ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
96
111
  return;
97
- case "status":
98
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
112
+ case "status": {
113
+ const status = await buildStatusMessage(pi);
114
+ if (!isCurrentFirecrawlSession(generation)) return;
115
+ ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
99
116
  return;
117
+ }
100
118
  case "tools":
101
119
  await showToolSelector(pi, ctx);
102
120
  return;
@@ -111,16 +129,16 @@ async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: Comma
111
129
  ctx.ui.notify(`Unknown /firecrawl command: ${args.trim()}\n\n${buildCommandGuide()}`, "warning");
112
130
  }
113
131
 
114
- async function showMenu(pi: ExtensionAPI, ctx: CommandContext) {
132
+ async function showMenu(pi: ExtensionAPI, ctx: CommandContext, generation: number) {
115
133
  if (!ctx.hasUI) {
116
- ctx.ui.notify(
117
- `${buildCommandGuide()}\n\n${await buildStatusMessage(pi)}`,
118
- hasApiKey() ? "info" : "warning",
119
- );
134
+ const status = await buildStatusMessage(pi);
135
+ if (!isCurrentFirecrawlSession(generation)) return;
136
+ ctx.ui.notify(`${buildCommandGuide()}\n\n${status}`, hasApiKey() ? "info" : "warning");
120
137
  return;
121
138
  }
122
139
 
123
140
  const choice = await ctx.ui.select("Firecrawl", Object.values(MENU_OPTIONS));
141
+ if (!isCurrentFirecrawlSession(generation)) return;
124
142
  switch (choice) {
125
143
  case MENU_OPTIONS.config:
126
144
  ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
@@ -128,9 +146,12 @@ async function showMenu(pi: ExtensionAPI, ctx: CommandContext) {
128
146
  case MENU_OPTIONS.help:
129
147
  ctx.ui.notify(buildCommandGuide(), "info");
130
148
  return;
131
- case MENU_OPTIONS.status:
132
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
149
+ case MENU_OPTIONS.status: {
150
+ const status = await buildStatusMessage(pi);
151
+ if (!isCurrentFirecrawlSession(generation)) return;
152
+ ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
133
153
  return;
154
+ }
134
155
  case MENU_OPTIONS.tools:
135
156
  await showToolSelector(pi, ctx);
136
157
  return;
@@ -175,5 +196,5 @@ export {
175
196
  parseResponseBody,
176
197
  } from "./client.js";
177
198
  export { cleanupResponseArtifacts } from "./response-format.js";
178
- export { installSettingsFileExclusively, normalizeFirecrawlSettings } from "./settings.js";
199
+ export { normalizeFirecrawlSettings } from "./settings.js";
179
200
  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 {
@@ -25,6 +25,19 @@ interface ToolStatusSummary {
25
25
  }
26
26
 
27
27
  let settingsNotice: string | undefined;
28
+ let sessionGeneration = 0;
29
+
30
+ export function advanceFirecrawlSessionGeneration(): number {
31
+ return ++sessionGeneration;
32
+ }
33
+
34
+ export function currentFirecrawlSessionGeneration(): number {
35
+ return sessionGeneration;
36
+ }
37
+
38
+ export function isCurrentFirecrawlSession(generation: number): boolean {
39
+ return generation === sessionGeneration;
40
+ }
28
41
 
29
42
  export function clearSettingsNotice() {
30
43
  settingsNotice = undefined;
@@ -35,24 +48,32 @@ export function recordSettingsNotice(settings: SettingsLoadResult) {
35
48
  }
36
49
 
37
50
  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
- );
51
+ const generation = sessionGeneration;
52
+ if (!ctx.hasUI) return;
53
+ if (ctx.mode !== "tui") {
54
+ await showDialogToolSelector(pi, ctx, generation);
43
55
  return;
44
56
  }
45
57
 
46
58
  let selectedTools = new Set<FirecrawlToolName>(getActiveFirecrawlTools(pi));
47
59
  let persistQueue = Promise.resolve();
60
+ let requestedRevision = 0;
61
+ let requestRender: () => void = () => undefined;
48
62
  const commitSelectedTools = () => {
49
63
  const nextSelectedTools = orderedFirecrawlTools(selectedTools);
50
- applyFirecrawlTools(pi, nextSelectedTools);
51
- persistQueue = persistQueue.then(() => persistSettings(ctx, nextSelectedTools));
64
+ const revision = ++requestedRevision;
65
+ persistQueue = persistQueue.then(async () => {
66
+ const saved = await transactSelectedTools(pi, ctx, nextSelectedTools, generation);
67
+ if (!saved && isCurrentFirecrawlSession(generation) && revision === requestedRevision) {
68
+ selectedTools = new Set(getActiveFirecrawlTools(pi));
69
+ requestRender();
70
+ }
71
+ });
52
72
  };
53
73
 
54
74
  const customResult = await ctx.ui.custom<"closed" | undefined>(
55
75
  (tui, theme, keybindings, done) => {
76
+ requestRender = () => tui.requestRender();
56
77
  const rows = firecrawlToolSelectorRows();
57
78
  let selectedIndex = 0;
58
79
  const moveSelection = (delta: number) => {
@@ -134,22 +155,26 @@ export async function showToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
134
155
  },
135
156
  );
136
157
 
158
+ if (!isCurrentFirecrawlSession(generation)) return;
137
159
  if (customResult !== "closed") {
138
- await showDialogToolSelector(pi, ctx);
160
+ await showDialogToolSelector(pi, ctx, generation);
139
161
  return;
140
162
  }
141
163
 
142
164
  await persistQueue;
143
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
165
+ if (!isCurrentFirecrawlSession(generation)) return;
166
+ const status = await buildStatusMessage(pi);
167
+ if (!isCurrentFirecrawlSession(generation)) return;
168
+ ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
144
169
  }
145
170
 
146
- async function showDialogToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
171
+ async function showDialogToolSelector(pi: ExtensionAPI, ctx: CommandContext, generation: number) {
147
172
  let selectedTools = new Set<FirecrawlToolName>(getActiveFirecrawlTools(pi));
148
173
  while (true) {
149
174
  const rows = firecrawlToolSelectorRows();
150
175
  const choices = rows.map((row) => formatToolSelectorRow(row, selectedTools));
151
176
  const choice = await ctx.ui.select(toolSelectorTitle(selectedTools), choices);
152
- if (!choice) break;
177
+ if (!isCurrentFirecrawlSession(generation) || !choice) break;
153
178
 
154
179
  const row = rows[choices.indexOf(choice)];
155
180
  if (!row) continue;
@@ -164,10 +189,20 @@ async function showDialogToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
164
189
  selectedTools = new Set();
165
190
  }
166
191
 
167
- await setSelectedFirecrawlTools(pi, ctx, orderedFirecrawlTools(selectedTools));
192
+ const saved = await transactSelectedTools(
193
+ pi,
194
+ ctx,
195
+ orderedFirecrawlTools(selectedTools),
196
+ generation,
197
+ );
198
+ if (!isCurrentFirecrawlSession(generation)) return;
199
+ if (!saved) selectedTools = new Set(getActiveFirecrawlTools(pi));
168
200
  }
169
201
 
170
- ctx.ui.notify(await buildStatusMessage(pi), hasApiKey() ? "info" : "warning");
202
+ if (!isCurrentFirecrawlSession(generation)) return;
203
+ const status = await buildStatusMessage(pi);
204
+ if (!isCurrentFirecrawlSession(generation)) return;
205
+ ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
171
206
  }
172
207
 
173
208
  export async function updateFirecrawlTools(
@@ -176,20 +211,75 @@ export async function updateFirecrawlTools(
176
211
  selectedTools: readonly FirecrawlToolName[],
177
212
  action: string,
178
213
  ) {
179
- await setSelectedFirecrawlTools(pi, ctx, selectedTools);
180
- ctx.ui.notify(
181
- `Firecrawl tools ${action}.\n\n${await buildStatusMessage(pi)}`,
182
- hasApiKey() ? "info" : "warning",
183
- );
214
+ const generation = sessionGeneration;
215
+ const saved = await transactSelectedTools(pi, ctx, selectedTools, generation);
216
+ if (!saved || !isCurrentFirecrawlSession(generation)) return;
217
+ const status = await buildStatusMessage(pi);
218
+ if (!isCurrentFirecrawlSession(generation)) return;
219
+ ctx.ui.notify(`Firecrawl tools ${action}.\n\n${status}`, hasApiKey() ? "info" : "warning");
184
220
  }
185
221
 
186
222
  export async function setSelectedFirecrawlTools(
187
223
  pi: ExtensionAPI,
188
224
  ctx: CommandContext,
189
225
  selectedTools: readonly FirecrawlToolName[],
190
- ) {
191
- applyFirecrawlTools(pi, selectedTools);
192
- await persistSettings(ctx, selectedTools);
226
+ ): Promise<boolean> {
227
+ return transactSelectedTools(pi, ctx, selectedTools, sessionGeneration);
228
+ }
229
+
230
+ let toolTransactionQueue = Promise.resolve();
231
+
232
+ export async function waitForFirecrawlSettings(): Promise<void> {
233
+ await toolTransactionQueue;
234
+ }
235
+
236
+ function transactSelectedTools(
237
+ pi: ExtensionAPI,
238
+ ctx: CommandContext,
239
+ selectedTools: readonly FirecrawlToolName[],
240
+ expectedGeneration: number,
241
+ ): Promise<boolean> {
242
+ const operation = toolTransactionQueue.then(() =>
243
+ transactSelectedToolsNow(pi, ctx, selectedTools, expectedGeneration),
244
+ );
245
+ toolTransactionQueue = operation.then(
246
+ () => undefined,
247
+ () => undefined,
248
+ );
249
+ return operation;
250
+ }
251
+
252
+ async function transactSelectedToolsNow(
253
+ pi: ExtensionAPI,
254
+ ctx: CommandContext,
255
+ selectedTools: readonly FirecrawlToolName[],
256
+ expectedGeneration: number,
257
+ ): Promise<boolean> {
258
+ if (!isCurrentFirecrawlSession(expectedGeneration)) return false;
259
+ const previousActiveTools = pi.getActiveTools();
260
+ try {
261
+ applyFirecrawlTools(pi, selectedTools);
262
+ await persistSettings(selectedTools);
263
+ return isCurrentFirecrawlSession(expectedGeneration);
264
+ } catch (error) {
265
+ let rollbackError: unknown;
266
+ try {
267
+ const previousFirecrawlTools = previousActiveTools.filter((name) =>
268
+ FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName),
269
+ ) as FirecrawlToolName[];
270
+ applyFirecrawlTools(pi, previousFirecrawlTools);
271
+ } catch (caught) {
272
+ rollbackError = caught;
273
+ }
274
+ if (!isCurrentFirecrawlSession(expectedGeneration)) return false;
275
+ ctx.ui.notify(
276
+ rollbackError
277
+ ? `Firecrawl settings save failed: ${formatError(error)}; active-tool rollback failed: ${formatError(rollbackError)}`
278
+ : `Firecrawl settings save failed; active tools restored: ${formatError(error)}`,
279
+ "warning",
280
+ );
281
+ return false;
282
+ }
193
283
  }
194
284
 
195
285
  export function applyFirecrawlTools(pi: ExtensionAPI, selectedTools: readonly FirecrawlToolName[]) {
@@ -323,10 +413,6 @@ function formatError(error: unknown) {
323
413
  return error instanceof Error ? error.message : String(error);
324
414
  }
325
415
 
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
- }
416
+ async function persistSettings(selectedTools: readonly FirecrawlToolName[]) {
417
+ await saveSettings({ tools: [...selectedTools], updatedAt: Date.now() });
332
418
  }