@narumitw/pi-firecrawl 0.31.0 → 0.34.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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-firecrawl",
3
- "version": "0.31.0",
3
+ "version": "0.34.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,5 +1,6 @@
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 {
5
6
  allFirecrawlTools,
@@ -59,6 +60,7 @@ export default function firecrawl(pi: ExtensionAPI) {
59
60
  });
60
61
 
61
62
  pi.on("session_start", async (_event, ctx) => {
63
+ openResponseArtifacts(ctx.sessionManager);
62
64
  clearSettingsNotice();
63
65
  ctx.ui.setStatus(STATUS_KEY, undefined);
64
66
  const settings = await loadSettings();
@@ -73,8 +75,9 @@ export default function firecrawl(pi: ExtensionAPI) {
73
75
  }
74
76
  });
75
77
 
76
- pi.on("session_shutdown", (_event, ctx) => {
78
+ pi.on("session_shutdown", async (_event, ctx) => {
77
79
  ctx.ui.setStatus(STATUS_KEY, undefined);
80
+ await cleanupResponseArtifacts(ctx.sessionManager);
78
81
  });
79
82
  }
80
83
 
@@ -165,10 +168,12 @@ export function commandCompletions(prefix: string) {
165
168
 
166
169
  export {
167
170
  cleanObject,
171
+ firecrawlRequest,
168
172
  formatPayload,
169
173
  jsonResult,
170
174
  normalizeApiUrl,
171
175
  parseResponseBody,
172
176
  } from "./client.js";
177
+ export { cleanupResponseArtifacts } from "./response-format.js";
173
178
  export { installSettingsFileExclusively, normalizeFirecrawlSettings } from "./settings.js";
174
179
  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/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
  });