@narumitw/pi-firecrawl 0.31.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
@@ -18,6 +18,7 @@ Use it to give your AI coding agent reliable web research capabilities for docum
18
18
  - Provides a `/firecrawl` menu with configuration help and tool controls.
19
19
  - Provides a Plan-mode-style selector for choosing individual Firecrawl tools.
20
20
  - Persists the selected Firecrawl tools across Pi restarts.
21
+ - Bounds tool output to Pi's 50 KB or 2,000-line limit while preserving oversized responses in private temporary files.
21
22
  - Never logs, displays, or stores your Firecrawl API key.
22
23
 
23
24
  ## 📦 Install
@@ -64,6 +65,13 @@ export FIRECRAWL_API_URL=https://api.firecrawl.dev/v1
64
65
 
65
66
  All tools fail with a clear configuration error when `FIRECRAWL_API_KEY` is missing.
66
67
 
68
+ Tool output is limited to 50 KB or 2,000 lines, whichever is reached first. When a response is
69
+ truncated, the result reports the original and displayed sizes and the path to a complete temporary
70
+ JSON file. These files use private permissions, remain available for the current session, and are
71
+ removed during session shutdown or reload. Tool-result metadata contains only size and artifact
72
+ information rather than a duplicate of the raw Firecrawl response. Oversized Firecrawl error bodies
73
+ are bounded in the same way.
74
+
67
75
  ## 💬 Command
68
76
 
69
77
  ```text
@@ -105,12 +113,16 @@ ${PI_CODING_AGENT_DIR:-~/.pi/agent}/pi-firecrawl.json
105
113
 
106
114
  When the file is missing or invalid, the extension preserves Pi's current active-tool policy
107
115
  instead of enabling tools by itself. A valid saved selection is restored on Pi startup and
108
- `/reload`. The settings file stores only tool names and a timestamp; it never stores
109
- `FIRECRAWL_API_KEY`, request headers, or other secrets.
110
-
111
- Compatibility: older versions used `pi-firecrawl-settings.json`. During the migration window,
112
- a legacy-only file is automatically migrated to `pi-firecrawl.json` with a warning. If both
113
- 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
114
126
  deprecated and will be removed in a future major release.
115
127
 
116
128
  ## 🚀 Examples
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-firecrawl",
3
- "version": "0.31.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/client.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { boundResponseText, formatJsonResult } from "./response-format.js";
2
3
 
3
4
  const DEFAULT_API_URL = "https://api.firecrawl.dev/v1";
4
5
  const STATUS_KEY = "firecrawl";
@@ -17,7 +18,8 @@ export async function firecrawlRequest(
17
18
  method: "GET" | "POST",
18
19
  path: string,
19
20
  body: unknown,
20
- signal?: AbortSignal,
21
+ signal: AbortSignal | undefined,
22
+ artifactOwner: object,
21
23
  ) {
22
24
  const apiKey = getApiKey();
23
25
  const response = await fetch(`${apiUrl}${path}`, {
@@ -32,9 +34,12 @@ export async function firecrawlRequest(
32
34
  const responseText = await response.text();
33
35
  const payload = parseResponseBody(responseText);
34
36
  if (!response.ok) {
35
- throw new Error(
36
- `Firecrawl ${method} ${path} failed (${response.status}): ${formatPayload(payload)}`,
37
- );
37
+ const prefix = `Firecrawl ${method} ${path} failed (${response.status}): `;
38
+ const bounded = await boundResponseText(`${prefix}${formatPayload(payload)}`, artifactOwner, {
39
+ artifactText: responseText,
40
+ artifactExtension: "txt",
41
+ });
42
+ throw new Error(bounded.text);
38
43
  }
39
44
  return payload;
40
45
  }
@@ -67,14 +72,11 @@ export function parseResponseBody(responseText: string) {
67
72
  }
68
73
 
69
74
  export function formatPayload(payload: unknown) {
70
- return typeof payload === "string" ? payload : JSON.stringify(payload);
75
+ return typeof payload === "string" ? payload : (JSON.stringify(payload) ?? String(payload));
71
76
  }
72
77
 
73
- export function jsonResult(payload: unknown) {
74
- return {
75
- content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
76
- details: payload,
77
- };
78
+ export function jsonResult(payload: unknown, artifactOwner: object) {
79
+ return formatJsonResult(payload, artifactOwner);
78
80
  }
79
81
 
80
82
  export async function withStatus<T>(
package/src/firecrawl.ts CHANGED
@@ -1,16 +1,21 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
2
  import { hasApiKey } from "./client.js";
3
+ import { cleanupResponseArtifacts, openResponseArtifacts } from "./response-format.js";
3
4
  import { loadSettings } from "./settings.js";
4
5
  import {
6
+ advanceFirecrawlSessionGeneration,
5
7
  allFirecrawlTools,
6
8
  applyFirecrawlTools,
7
9
  buildCommandGuide,
8
10
  buildConfigMessage,
9
11
  buildStatusMessage,
10
12
  clearSettingsNotice,
13
+ currentFirecrawlSessionGeneration,
14
+ isCurrentFirecrawlSession,
11
15
  recordSettingsNotice,
12
16
  showToolSelector,
13
17
  updateFirecrawlTools,
18
+ waitForFirecrawlSettings,
14
19
  } from "./tool-selector.js";
15
20
  import { crawlStatusTool, crawlTool, mapTool, scrapeTool, searchTool } from "./tools.js";
16
21
 
@@ -54,14 +59,18 @@ export default function firecrawl(pi: ExtensionAPI) {
54
59
  description: "Open Firecrawl help and tool controls",
55
60
  getArgumentCompletions: (prefix) => commandCompletions(prefix),
56
61
  handler: async (args, ctx) => {
57
- await handleFirecrawlCommand(pi, args, ctx);
62
+ const generation = currentFirecrawlSessionGeneration();
63
+ await handleFirecrawlCommand(pi, args, ctx, generation);
58
64
  },
59
65
  });
60
66
 
61
67
  pi.on("session_start", async (_event, ctx) => {
68
+ const generation = advanceFirecrawlSessionGeneration();
69
+ openResponseArtifacts(ctx.sessionManager);
62
70
  clearSettingsNotice();
63
71
  ctx.ui.setStatus(STATUS_KEY, undefined);
64
72
  const settings = await loadSettings();
73
+ if (!isCurrentFirecrawlSession(generation)) return;
65
74
  recordSettingsNotice(settings);
66
75
  if (settings.notice) ctx.ui.notify(settings.notice, "warning");
67
76
  if (settings.kind === "loaded") {
@@ -73,16 +82,25 @@ export default function firecrawl(pi: ExtensionAPI) {
73
82
  }
74
83
  });
75
84
 
76
- pi.on("session_shutdown", (_event, ctx) => {
85
+ pi.on("session_shutdown", async (_event, ctx) => {
86
+ advanceFirecrawlSessionGeneration();
77
87
  ctx.ui.setStatus(STATUS_KEY, undefined);
88
+ const artifactOwner = ctx.sessionManager;
89
+ await waitForFirecrawlSettings();
90
+ await cleanupResponseArtifacts(artifactOwner);
78
91
  });
79
92
  }
80
93
 
81
- 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
+ ) {
82
100
  const command = parseCommand(args);
83
101
  switch (command) {
84
102
  case "menu":
85
- await showMenu(pi, ctx);
103
+ await showMenu(pi, ctx, generation);
86
104
  return;
87
105
  case "help":
88
106
  ctx.ui.notify(buildCommandGuide(), "info");
@@ -91,9 +109,12 @@ async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: Comma
91
109
  case "quickstart":
92
110
  ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
93
111
  return;
94
- case "status":
95
- 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");
96
116
  return;
117
+ }
97
118
  case "tools":
98
119
  await showToolSelector(pi, ctx);
99
120
  return;
@@ -108,16 +129,16 @@ async function handleFirecrawlCommand(pi: ExtensionAPI, args: string, ctx: Comma
108
129
  ctx.ui.notify(`Unknown /firecrawl command: ${args.trim()}\n\n${buildCommandGuide()}`, "warning");
109
130
  }
110
131
 
111
- async function showMenu(pi: ExtensionAPI, ctx: CommandContext) {
132
+ async function showMenu(pi: ExtensionAPI, ctx: CommandContext, generation: number) {
112
133
  if (!ctx.hasUI) {
113
- ctx.ui.notify(
114
- `${buildCommandGuide()}\n\n${await buildStatusMessage(pi)}`,
115
- hasApiKey() ? "info" : "warning",
116
- );
134
+ const status = await buildStatusMessage(pi);
135
+ if (!isCurrentFirecrawlSession(generation)) return;
136
+ ctx.ui.notify(`${buildCommandGuide()}\n\n${status}`, hasApiKey() ? "info" : "warning");
117
137
  return;
118
138
  }
119
139
 
120
140
  const choice = await ctx.ui.select("Firecrawl", Object.values(MENU_OPTIONS));
141
+ if (!isCurrentFirecrawlSession(generation)) return;
121
142
  switch (choice) {
122
143
  case MENU_OPTIONS.config:
123
144
  ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
@@ -125,9 +146,12 @@ async function showMenu(pi: ExtensionAPI, ctx: CommandContext) {
125
146
  case MENU_OPTIONS.help:
126
147
  ctx.ui.notify(buildCommandGuide(), "info");
127
148
  return;
128
- case MENU_OPTIONS.status:
129
- 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");
130
153
  return;
154
+ }
131
155
  case MENU_OPTIONS.tools:
132
156
  await showToolSelector(pi, ctx);
133
157
  return;
@@ -165,10 +189,12 @@ export function commandCompletions(prefix: string) {
165
189
 
166
190
  export {
167
191
  cleanObject,
192
+ firecrawlRequest,
168
193
  formatPayload,
169
194
  jsonResult,
170
195
  normalizeApiUrl,
171
196
  parseResponseBody,
172
197
  } from "./client.js";
173
- export { installSettingsFileExclusively, normalizeFirecrawlSettings } from "./settings.js";
198
+ export { cleanupResponseArtifacts } from "./response-format.js";
199
+ export { normalizeFirecrawlSettings } from "./settings.js";
174
200
  export { formatPersistedSelection, orderedFirecrawlTools } from "./tool-selector.js";
@@ -0,0 +1,195 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ DEFAULT_MAX_BYTES,
7
+ DEFAULT_MAX_LINES,
8
+ formatSize,
9
+ truncateHead,
10
+ } from "@earendil-works/pi-coding-agent";
11
+
12
+ export interface FirecrawlResultDetails {
13
+ truncated: boolean;
14
+ truncatedBy?: "lines" | "bytes";
15
+ totalLines: number;
16
+ totalBytes: number;
17
+ outputLines: number;
18
+ outputBytes: number;
19
+ fullResponsePath?: string;
20
+ }
21
+
22
+ interface BoundTextOptions {
23
+ maxBytes?: number;
24
+ maxLines?: number;
25
+ artifactText?: string;
26
+ artifactExtension?: "json" | "txt";
27
+ }
28
+
29
+ interface BoundTextResult {
30
+ text: string;
31
+ details: FirecrawlResultDetails;
32
+ }
33
+
34
+ interface ResponseArtifactStore {
35
+ directoryPromise: Promise<string>;
36
+ pendingWrites: Set<Promise<unknown>>;
37
+ }
38
+
39
+ const responseArtifactStores = new WeakMap<object, ResponseArtifactStore>();
40
+ const closedArtifactOwners = new WeakSet<object>();
41
+
42
+ export async function formatJsonResult(payload: unknown, artifactOwner: object) {
43
+ const serialized = JSON.stringify(payload, null, 2) ?? String(payload);
44
+ const bounded = await boundResponseText(serialized, artifactOwner);
45
+ return {
46
+ content: [{ type: "text" as const, text: bounded.text }],
47
+ details: bounded.details,
48
+ };
49
+ }
50
+
51
+ export async function boundResponseText(
52
+ text: string,
53
+ artifactOwner: object,
54
+ options: BoundTextOptions = {},
55
+ ): Promise<BoundTextResult> {
56
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
57
+ const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
58
+ const initial = truncateHead(text, { maxBytes, maxLines });
59
+ if (!initial.truncated) {
60
+ return {
61
+ text: initial.content,
62
+ details: {
63
+ truncated: false,
64
+ totalLines: initial.totalLines,
65
+ totalBytes: initial.totalBytes,
66
+ outputLines: initial.outputLines,
67
+ outputBytes: initial.outputBytes,
68
+ },
69
+ };
70
+ }
71
+
72
+ const fullResponsePath = await writeResponseArtifact(
73
+ options.artifactText ?? text,
74
+ options.artifactExtension ?? "json",
75
+ artifactOwner,
76
+ );
77
+ let footer = truncationFooter(initial, fullResponsePath);
78
+ let excerptByteBudget = Math.max(0, maxBytes - Buffer.byteLength(footer, "utf8") - 2);
79
+ let excerptLineBudget = Math.max(0, maxLines - countLines(footer) - 1);
80
+ for (;;) {
81
+ const excerpt = truncateHead(text, {
82
+ maxBytes: excerptByteBudget,
83
+ maxLines: excerptLineBudget,
84
+ });
85
+ footer = truncationFooter(excerpt, fullResponsePath);
86
+ const separator = excerpt.content ? "\n\n" : "";
87
+ const content = `${excerpt.content}${separator}${footer}`;
88
+ if (Buffer.byteLength(content, "utf8") <= maxBytes && countLines(content) <= maxLines) {
89
+ return {
90
+ text: content,
91
+ details: {
92
+ truncated: true,
93
+ truncatedBy: initial.truncatedBy ?? undefined,
94
+ totalLines: initial.totalLines,
95
+ totalBytes: initial.totalBytes,
96
+ outputLines: excerpt.outputLines,
97
+ outputBytes: excerpt.outputBytes,
98
+ fullResponsePath,
99
+ },
100
+ };
101
+ }
102
+
103
+ const nextByteBudget = Math.max(
104
+ 0,
105
+ Math.min(excerptByteBudget, maxBytes - Buffer.byteLength(footer, "utf8") - 2),
106
+ );
107
+ const nextLineBudget = Math.max(
108
+ 0,
109
+ Math.min(excerptLineBudget, maxLines - countLines(footer) - 1),
110
+ );
111
+ if (nextByteBudget === excerptByteBudget && nextLineBudget === excerptLineBudget) {
112
+ throw new Error("Firecrawl could not fit its truncation notice within Pi's output limits");
113
+ }
114
+ excerptByteBudget = nextByteBudget;
115
+ excerptLineBudget = nextLineBudget;
116
+ }
117
+ }
118
+
119
+ function truncationFooter(
120
+ truncation: Pick<
121
+ FirecrawlResultDetails,
122
+ "outputLines" | "totalLines" | "outputBytes" | "totalBytes"
123
+ >,
124
+ fullResponsePath: string,
125
+ ) {
126
+ return `[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}). Full response saved to: ${fullResponsePath}]`;
127
+ }
128
+
129
+ function countLines(content: string) {
130
+ if (!content) return 0;
131
+ const lines = content.split("\n");
132
+ if (content.endsWith("\n")) lines.pop();
133
+ return lines.length;
134
+ }
135
+
136
+ function writeResponseArtifact(text: string, extension: "json" | "txt", artifactOwner: object) {
137
+ const store = responseArtifactStore(artifactOwner);
138
+ const operation = store.directoryPromise.then(async (directory) => {
139
+ const path = join(directory, `response-${Date.now()}-${randomUUID()}.${extension}`);
140
+ await writeFile(path, text, { mode: 0o600 });
141
+ await chmod(path, 0o600);
142
+ return path;
143
+ });
144
+ store.pendingWrites.add(operation);
145
+ operation.then(
146
+ () => store.pendingWrites.delete(operation),
147
+ () => store.pendingWrites.delete(operation),
148
+ );
149
+ return operation;
150
+ }
151
+
152
+ function responseArtifactStore(artifactOwner: object) {
153
+ if (closedArtifactOwners.has(artifactOwner)) {
154
+ throw new Error(
155
+ "Firecrawl response arrived after session shutdown; full response was discarded",
156
+ );
157
+ }
158
+ const existing = responseArtifactStores.get(artifactOwner);
159
+ if (existing) return existing;
160
+
161
+ const store: ResponseArtifactStore = {
162
+ directoryPromise: Promise.resolve(""),
163
+ pendingWrites: new Set(),
164
+ };
165
+ store.directoryPromise = mkdtemp(join(tmpdir(), "pi-firecrawl-"))
166
+ .then(async (directory) => {
167
+ await chmod(directory, 0o700);
168
+ return directory;
169
+ })
170
+ .catch((error) => {
171
+ if (responseArtifactStores.get(artifactOwner) === store) {
172
+ responseArtifactStores.delete(artifactOwner);
173
+ }
174
+ throw error;
175
+ });
176
+ responseArtifactStores.set(artifactOwner, store);
177
+ return store;
178
+ }
179
+
180
+ export function openResponseArtifacts(artifactOwner: object) {
181
+ closedArtifactOwners.delete(artifactOwner);
182
+ }
183
+
184
+ export async function cleanupResponseArtifacts(artifactOwner: object) {
185
+ closedArtifactOwners.add(artifactOwner);
186
+ const store = responseArtifactStores.get(artifactOwner);
187
+ if (!store) return;
188
+ responseArtifactStores.delete(artifactOwner);
189
+ await Promise.allSettled([...store.pendingWrites]);
190
+ try {
191
+ await rm(await store.directoryPromise, { recursive: true, force: true });
192
+ } catch {
193
+ // Best-effort cleanup must not make session shutdown fail.
194
+ }
195
+ }
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
  }
package/src/tools.ts CHANGED
@@ -1,4 +1,9 @@
1
- import { defineTool } from "@earendil-works/pi-coding-agent";
1
+ import {
2
+ DEFAULT_MAX_BYTES,
3
+ DEFAULT_MAX_LINES,
4
+ defineTool,
5
+ formatSize,
6
+ } from "@earendil-works/pi-coding-agent";
2
7
  import { Type } from "typebox";
3
8
  import { cleanObject, firecrawlRequest, jsonResult, withStatus } from "./client.js";
4
9
 
@@ -12,11 +17,12 @@ export const FIRECRAWL_TOOL_NAMES = [
12
17
  export type FirecrawlToolName = (typeof FIRECRAWL_TOOL_NAMES)[number];
13
18
 
14
19
  const StringArray = Type.Array(Type.String());
20
+ const OUTPUT_LIMIT_DESCRIPTION = `Output is truncated to ${DEFAULT_MAX_LINES} lines or ${formatSize(DEFAULT_MAX_BYTES)}; complete truncated responses are saved temporarily and their path is returned.`;
15
21
 
16
22
  export const scrapeTool = defineTool({
17
23
  name: FIRECRAWL_TOOL_NAMES[0],
18
24
  label: "Firecrawl: Scrape",
19
- description: "Scrape a single URL through Firecrawl and return requested formats.",
25
+ description: `Scrape a single URL through Firecrawl and return requested formats. ${OUTPUT_LIMIT_DESCRIPTION}`,
20
26
  promptSnippet: "Scrape a URL through Firecrawl",
21
27
  promptGuidelines: [
22
28
  "Use firecrawl_scrape when you need clean markdown, HTML, links, screenshots, or structured extraction for one URL.",
@@ -69,8 +75,14 @@ export const scrapeTool = defineTool({
69
75
  }),
70
76
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
71
77
  return withStatus(ctx, "scrape", async () => {
72
- const payload = await firecrawlRequest("POST", "/scrape", cleanObject(params), signal);
73
- return jsonResult(payload);
78
+ const payload = await firecrawlRequest(
79
+ "POST",
80
+ "/scrape",
81
+ cleanObject(params),
82
+ signal,
83
+ ctx.sessionManager,
84
+ );
85
+ return await jsonResult(payload, ctx.sessionManager);
74
86
  });
75
87
  },
76
88
  });
@@ -78,7 +90,7 @@ export const scrapeTool = defineTool({
78
90
  export const crawlTool = defineTool({
79
91
  name: FIRECRAWL_TOOL_NAMES[1],
80
92
  label: "Firecrawl: Crawl",
81
- description: "Start a Firecrawl crawl job for a website.",
93
+ description: `Start a Firecrawl crawl job for a website. ${OUTPUT_LIMIT_DESCRIPTION}`,
82
94
  promptSnippet: "Start a Firecrawl site crawl job",
83
95
  parameters: Type.Object({
84
96
  url: Type.String({ description: "Starting URL for the crawl." }),
@@ -107,8 +119,14 @@ export const crawlTool = defineTool({
107
119
  }),
108
120
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
109
121
  return withStatus(ctx, "crawl", async () => {
110
- const payload = await firecrawlRequest("POST", "/crawl", cleanObject(params), signal);
111
- return jsonResult(payload);
122
+ const payload = await firecrawlRequest(
123
+ "POST",
124
+ "/crawl",
125
+ cleanObject(params),
126
+ signal,
127
+ ctx.sessionManager,
128
+ );
129
+ return await jsonResult(payload, ctx.sessionManager);
112
130
  });
113
131
  },
114
132
  });
@@ -116,7 +134,7 @@ export const crawlTool = defineTool({
116
134
  export const crawlStatusTool = defineTool({
117
135
  name: FIRECRAWL_TOOL_NAMES[2],
118
136
  label: "Firecrawl: Crawl Status",
119
- description: "Check a Firecrawl crawl job status and retrieve completed crawl data.",
137
+ description: `Check a Firecrawl crawl job status and retrieve completed crawl data. ${OUTPUT_LIMIT_DESCRIPTION}`,
120
138
  promptSnippet: "Check a Firecrawl crawl job status",
121
139
  parameters: Type.Object({
122
140
  id: Type.String({ description: "Crawl job id returned by firecrawl_crawl." }),
@@ -128,8 +146,9 @@ export const crawlStatusTool = defineTool({
128
146
  `/crawl/${encodeURIComponent(params.id)}`,
129
147
  undefined,
130
148
  signal,
149
+ ctx.sessionManager,
131
150
  );
132
- return jsonResult(payload);
151
+ return await jsonResult(payload, ctx.sessionManager);
133
152
  });
134
153
  },
135
154
  });
@@ -137,7 +156,7 @@ export const crawlStatusTool = defineTool({
137
156
  export const mapTool = defineTool({
138
157
  name: FIRECRAWL_TOOL_NAMES[3],
139
158
  label: "Firecrawl: Map",
140
- description: "Discover URLs for a site through Firecrawl's map endpoint.",
159
+ description: `Discover URLs for a site through Firecrawl's map endpoint. ${OUTPUT_LIMIT_DESCRIPTION}`,
141
160
  promptSnippet: "Map/discover URLs for a site through Firecrawl",
142
161
  parameters: Type.Object({
143
162
  url: Type.String({ description: "Website URL to map." }),
@@ -155,8 +174,14 @@ export const mapTool = defineTool({
155
174
  }),
156
175
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
157
176
  return withStatus(ctx, "map", async () => {
158
- const payload = await firecrawlRequest("POST", "/map", cleanObject(params), signal);
159
- return jsonResult(payload);
177
+ const payload = await firecrawlRequest(
178
+ "POST",
179
+ "/map",
180
+ cleanObject(params),
181
+ signal,
182
+ ctx.sessionManager,
183
+ );
184
+ return await jsonResult(payload, ctx.sessionManager);
160
185
  });
161
186
  },
162
187
  });
@@ -164,7 +189,7 @@ export const mapTool = defineTool({
164
189
  export const searchTool = defineTool({
165
190
  name: FIRECRAWL_TOOL_NAMES[4],
166
191
  label: "Firecrawl: Search",
167
- description: "Search the web through Firecrawl and optionally scrape search results.",
192
+ description: `Search the web through Firecrawl and optionally scrape search results. ${OUTPUT_LIMIT_DESCRIPTION}`,
168
193
  promptSnippet: "Search the web through Firecrawl",
169
194
  parameters: Type.Object({
170
195
  query: Type.String({ description: "Search query." }),
@@ -179,8 +204,14 @@ export const searchTool = defineTool({
179
204
  }),
180
205
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
181
206
  return withStatus(ctx, "search", async () => {
182
- const payload = await firecrawlRequest("POST", "/search", cleanObject(params), signal);
183
- return jsonResult(payload);
207
+ const payload = await firecrawlRequest(
208
+ "POST",
209
+ "/search",
210
+ cleanObject(params),
211
+ signal,
212
+ ctx.sessionManager,
213
+ );
214
+ return await jsonResult(payload, ctx.sessionManager);
184
215
  });
185
216
  },
186
217
  });