@narumitw/pi-firecrawl 0.50.4 → 0.51.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/dist/index.ts CHANGED
@@ -1,1009 +1,43 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
-
4
- // src/response-format.ts
5
- import { randomUUID } from "node:crypto";
6
- import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
7
- import { tmpdir } from "node:os";
8
- import { join } from "node:path";
9
- import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
10
- var responseArtifactStores = /* @__PURE__ */ new WeakMap();
11
- var closedArtifactOwners = /* @__PURE__ */ new WeakSet();
12
- async function formatJsonResult(payload, artifactOwner) {
13
- const serialized = JSON.stringify(payload, null, 2) ?? String(payload);
14
- const bounded = await boundResponseText(serialized, artifactOwner);
15
- return {
16
- content: [{ type: "text", text: bounded.text }],
17
- details: bounded.details
18
- };
19
- }
20
- async function boundResponseText(text, artifactOwner, options = {}) {
21
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
22
- const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
23
- const initial = truncateHead(text, { maxBytes, maxLines });
24
- if (!initial.truncated) {
25
- return {
26
- text: initial.content,
27
- details: {
28
- truncated: false,
29
- totalLines: initial.totalLines,
30
- totalBytes: initial.totalBytes,
31
- outputLines: initial.outputLines,
32
- outputBytes: initial.outputBytes
33
- }
34
- };
35
- }
36
- const fullResponsePath = await writeResponseArtifact(
37
- options.artifactText ?? text,
38
- options.artifactExtension ?? "json",
39
- artifactOwner
40
- );
41
- let footer = truncationFooter(initial, fullResponsePath);
42
- let excerptByteBudget = Math.max(0, maxBytes - Buffer.byteLength(footer, "utf8") - 2);
43
- let excerptLineBudget = Math.max(0, maxLines - countLines(footer) - 1);
44
- for (; ; ) {
45
- const excerpt = truncateHead(text, {
46
- maxBytes: excerptByteBudget,
47
- maxLines: excerptLineBudget
48
- });
49
- footer = truncationFooter(excerpt, fullResponsePath);
50
- const separator = excerpt.content ? "\n\n" : "";
51
- const content = `${excerpt.content}${separator}${footer}`;
52
- if (Buffer.byteLength(content, "utf8") <= maxBytes && countLines(content) <= maxLines) {
53
- return {
54
- text: content,
55
- details: {
56
- truncated: true,
57
- truncatedBy: initial.truncatedBy ?? void 0,
58
- totalLines: initial.totalLines,
59
- totalBytes: initial.totalBytes,
60
- outputLines: excerpt.outputLines,
61
- outputBytes: excerpt.outputBytes,
62
- fullResponsePath
63
- }
64
- };
65
- }
66
- const nextByteBudget = Math.max(0, Math.min(excerptByteBudget, maxBytes - Buffer.byteLength(footer, "utf8") - 2));
67
- const nextLineBudget = Math.max(0, Math.min(excerptLineBudget, maxLines - countLines(footer) - 1));
68
- if (nextByteBudget === excerptByteBudget && nextLineBudget === excerptLineBudget) {
69
- throw new Error("Firecrawl could not fit its truncation notice within Pi's output limits");
70
- }
71
- excerptByteBudget = nextByteBudget;
72
- excerptLineBudget = nextLineBudget;
73
- }
74
- }
75
- function truncationFooter(truncation, fullResponsePath) {
76
- return `[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}). Full response saved to: ${fullResponsePath}]`;
77
- }
78
- function countLines(content) {
79
- if (!content) return 0;
80
- const lines = content.split("\n");
81
- if (content.endsWith("\n")) lines.pop();
82
- return lines.length;
83
- }
84
- function writeResponseArtifact(text, extension, artifactOwner) {
85
- const store = responseArtifactStore(artifactOwner);
86
- const operation = store.directoryPromise.then(async (directory) => {
87
- const path = join(directory, `response-${Date.now()}-${randomUUID()}.${extension}`);
88
- await writeFile(path, text, { mode: 384 });
89
- await chmod(path, 384);
90
- return path;
91
- });
92
- store.pendingWrites.add(operation);
93
- operation.then(
94
- () => store.pendingWrites.delete(operation),
95
- () => store.pendingWrites.delete(operation)
96
- );
97
- return operation;
98
- }
99
- function responseArtifactStore(artifactOwner) {
100
- if (closedArtifactOwners.has(artifactOwner)) {
101
- throw new Error("Firecrawl response arrived after session shutdown; full response was discarded");
102
- }
103
- const existing = responseArtifactStores.get(artifactOwner);
104
- if (existing) return existing;
105
- const store = {
106
- directoryPromise: Promise.resolve(""),
107
- pendingWrites: /* @__PURE__ */ new Set()
108
- };
109
- store.directoryPromise = mkdtemp(join(tmpdir(), "pi-firecrawl-")).then(async (directory) => {
110
- await chmod(directory, 448);
111
- return directory;
112
- }).catch((error) => {
113
- if (responseArtifactStores.get(artifactOwner) === store) {
114
- responseArtifactStores.delete(artifactOwner);
115
- }
116
- throw error;
117
- });
118
- responseArtifactStores.set(artifactOwner, store);
119
- return store;
120
- }
121
- function openResponseArtifacts(artifactOwner) {
122
- closedArtifactOwners.delete(artifactOwner);
123
- }
124
- async function cleanupResponseArtifacts(artifactOwner) {
125
- closedArtifactOwners.add(artifactOwner);
126
- const store = responseArtifactStores.get(artifactOwner);
127
- if (!store) return;
128
- responseArtifactStores.delete(artifactOwner);
129
- await Promise.allSettled([...store.pendingWrites]);
130
- try {
131
- await rm(await store.directoryPromise, { recursive: true, force: true });
132
- } catch {
133
- }
134
- }
135
-
136
- // src/client.ts
137
- var DEFAULT_API_URL = "https://api.firecrawl.dev/v1";
138
- var STATUS_KEY = "firecrawl";
139
- var apiUrl = normalizeApiUrl(process.env.FIRECRAWL_API_URL ?? process.env.FIRECRAWL_BASE_URL);
140
- function configuredApiUrl() {
141
- return apiUrl;
142
- }
143
- async function firecrawlRequest(method, path, body, signal, artifactOwner) {
144
- const apiKey = getApiKey();
145
- const response = await fetch(`${apiUrl}${path}`, {
146
- method,
147
- headers: {
148
- Authorization: `Bearer ${apiKey}`,
149
- ...body === void 0 ? {} : { "Content-Type": "application/json" }
150
- },
151
- body: body === void 0 ? void 0 : JSON.stringify(body),
152
- signal
153
- });
154
- const responseText = await response.text();
155
- const payload = parseResponseBody(responseText);
156
- if (!response.ok) {
157
- const prefix = `Firecrawl ${method} ${path} failed (${response.status}): `;
158
- const bounded = await boundResponseText(`${prefix}${formatPayload(payload)}`, artifactOwner, {
159
- artifactText: responseText,
160
- artifactExtension: "txt"
161
- });
162
- throw new Error(bounded.text);
163
- }
164
- return payload;
165
- }
166
- function getApiKey() {
167
- const apiKey = process.env.FIRECRAWL_API_KEY?.trim();
168
- if (!apiKey) {
169
- throw new Error("FIRECRAWL_API_KEY is not configured. Set it in your shell or Pi environment, then retry once.");
170
- }
171
- return apiKey;
172
- }
173
- function hasApiKey() {
174
- return Boolean(process.env.FIRECRAWL_API_KEY?.trim());
175
- }
176
- function normalizeApiUrl(value) {
177
- return (value?.trim() || DEFAULT_API_URL).replace(/\/+$/, "");
178
- }
179
- function parseResponseBody(responseText) {
180
- if (!responseText) return {};
181
- try {
182
- return JSON.parse(responseText);
183
- } catch {
184
- return responseText;
185
- }
186
- }
187
- function formatPayload(payload) {
188
- return typeof payload === "string" ? payload : JSON.stringify(payload) ?? String(payload);
189
- }
190
- function jsonResult(payload, artifactOwner) {
191
- return formatJsonResult(payload, artifactOwner);
192
- }
193
- async function withStatus(ctx, status, callback) {
194
- ctx.ui.setStatus(STATUS_KEY, status);
195
- try {
196
- return await callback();
197
- } finally {
198
- ctx.ui.setStatus(STATUS_KEY, void 0);
199
- }
200
- }
201
- function cleanObject(value) {
202
- if (Array.isArray(value)) return value.map(cleanObject);
203
- if (!value || typeof value !== "object") return value;
204
- return Object.fromEntries(
205
- Object.entries(value).filter(([, item]) => item !== void 0).map(([key, item]) => [key, cleanObject(item)])
206
- );
207
- }
208
-
209
- // src/lazy-tools.ts
210
- import { defineTool } from "@earendil-works/pi-coding-agent";
211
- import { Type } from "typebox";
212
-
213
- // src/tool-names.ts
214
- var FIRECRAWL_TOOL_NAMES = [
215
- "firecrawl_scrape",
216
- "firecrawl_crawl",
217
- "firecrawl_crawl_status",
218
- "firecrawl_map",
219
- "firecrawl_search"
220
- ];
221
-
222
- // src/lazy-tools.ts
223
- var FIRECRAWL_LOAD_TOOL_NAME = "firecrawl_load";
224
- var AVAILABLE_TOOLS_STORE = /* @__PURE__ */ Symbol.for("@narumitw/pi-firecrawl.available-tools-store");
225
- var SESSION_AVAILABLE_TOOLS_STORE = /* @__PURE__ */ Symbol.for("@narumitw/pi-firecrawl.session-available-tools-store");
226
- var sharedGlobal = globalThis;
227
- var existingAvailableToolsStore = sharedGlobal[AVAILABLE_TOOLS_STORE];
228
- var availableToolsByApi = existingAvailableToolsStore ?? /* @__PURE__ */ new WeakMap();
229
- if (!existingAvailableToolsStore) sharedGlobal[AVAILABLE_TOOLS_STORE] = availableToolsByApi;
230
- var existingSessionAvailableToolsStore = sharedGlobal[SESSION_AVAILABLE_TOOLS_STORE];
231
- var availableToolsBySession = existingSessionAvailableToolsStore ?? /* @__PURE__ */ new WeakMap();
232
- if (!existingSessionAvailableToolsStore) {
233
- sharedGlobal[SESSION_AVAILABLE_TOOLS_STORE] = availableToolsBySession;
234
- }
235
- var lazyExposureByApi = /* @__PURE__ */ new WeakMap();
236
- var CRAWL_CREATION_TERMS = /* @__PURE__ */ new Set(["begin", "create", "launch", "start"]);
237
- var SEARCH_TEXT = {
238
- firecrawl_scrape: "scrape scraping extract extraction single url page pages markdown html raw links screenshot json structured content",
239
- firecrawl_crawl: "crawl crawling website site start pages depth paths sitemap batch",
240
- firecrawl_crawl_status: "crawl crawling status job monitor check retrieve completed progress results",
241
- firecrawl_map: "map mapping discover discovery url urls links sitemap site inventory",
242
- firecrawl_search: "search searching web internet query results research discover discovery optionally scrape"
243
- };
244
- function initializeAvailableFirecrawlTools(pi, sessionOwner) {
245
- if (sessionOwner) {
246
- const sessionTools = availableToolsBySession.get(sessionOwner);
247
- if (sessionTools) {
248
- setAvailableTools(pi, sessionTools, sessionOwner);
249
- return;
250
- }
251
- }
252
- const apiTools = availableToolsByApi.get(pi);
253
- if (apiTools) {
254
- if (sessionOwner) setAvailableTools(pi, apiTools, sessionOwner);
255
- return;
256
- }
257
- const activeTools = new Set(pi.getActiveTools());
258
- setAvailableTools(
259
- pi,
260
- FIRECRAWL_TOOL_NAMES.filter((name) => activeTools.has(name)),
261
- sessionOwner
262
- );
263
- }
264
- function configureFirecrawlToolExposure(pi, availableTools, loadedTools = [], sessionOwner, model) {
265
- const available = setAvailableTools(pi, availableTools, sessionOwner);
266
- const lazyExposure = supportsNativeDeferredToolLoading(model);
267
- lazyExposureByApi.set(pi, lazyExposure);
268
- const loaded = new Set(loadedTools);
269
- const exposedTools = lazyExposure ? FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name) && loaded.has(name)) : FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
270
- const nonCapabilityTools = pi.getActiveTools().filter((name) => !FIRECRAWL_TOOL_NAMES.includes(name));
271
- pi.setActiveTools(unique([...nonCapabilityTools, FIRECRAWL_LOAD_TOOL_NAME, ...exposedTools]));
272
- }
273
- function requireEagerFirecrawlToolExposure(pi) {
274
- lazyExposureByApi.set(pi, false);
275
- const active = pi.getActiveTools();
276
- const available = availableFirecrawlTools(pi);
277
- pi.setActiveTools(unique([...active, FIRECRAWL_LOAD_TOOL_NAME, ...available]));
278
- }
279
- function applyAvailableFirecrawlTools(pi, availableTools, sessionOwner) {
280
- const available = setAvailableTools(pi, availableTools, sessionOwner);
281
- const lazyExposure = lazyExposureByApi.get(pi) === true;
282
- const active = pi.getActiveTools().filter(
283
- (name) => !FIRECRAWL_TOOL_NAMES.includes(name) || lazyExposure && available.has(name)
284
- );
285
- const eagerTools = lazyExposure ? [] : FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
286
- pi.setActiveTools(unique([...active, FIRECRAWL_LOAD_TOOL_NAME, ...eagerTools]));
287
- }
288
- function firecrawlToolExposureMode(pi) {
289
- return lazyExposureByApi.get(pi) === true ? "native deferred" : "eager";
290
- }
291
- function supportsNativeDeferredToolLoading(model) {
292
- if (!model) return false;
293
- if (model.api === "anthropic-messages") {
294
- if (model.provider === "fireworks") return false;
295
- const configured = compatBoolean(model.compat, "supportsToolReferences");
296
- if (configured !== void 0) return configured;
297
- if (model.provider !== "anthropic" || model.id.includes("haiku")) return false;
298
- const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
299
- if (!version) return false;
300
- const major = Number(version[1]);
301
- const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
302
- return major > 4 || major === 4 && minor >= 5;
303
- }
304
- if (model.api === "openai-completions") {
305
- return compatString(model.compat, "deferredToolsMode") === "kimi";
306
- }
307
- if (model.api === "openai-responses" || model.api === "openai-codex-responses") {
308
- return compatBoolean(model.compat, "supportsAdditionalTools") === true || compatBoolean(model.compat, "supportsToolSearch") === true;
309
- }
310
- return false;
311
- }
312
- function availableFirecrawlTools(pi) {
313
- const available = availableToolsByApi.get(pi) ?? /* @__PURE__ */ new Set();
314
- return FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
315
- }
316
- function createFirecrawlLoadTool(pi) {
317
- return defineTool({
318
- name: FIRECRAWL_LOAD_TOOL_NAME,
319
- label: "Firecrawl: Load Tools",
320
- description: "Find and enable Firecrawl tools relevant to a web scraping, crawling, URL discovery, crawl-status, or search task. Loaded tools remain available for the session.",
321
- promptSnippet: "Load Firecrawl web research capabilities on demand",
322
- promptGuidelines: [
323
- "Use firecrawl_load when a task requires Firecrawl web scraping, crawling, URL discovery, crawl status, or search and the needed firecrawl_* capability is not active.",
324
- "If FIRECRAWL_API_KEY is missing, report the configuration error instead of retrying repeatedly."
325
- ],
326
- parameters: Type.Object({
327
- query: Type.String({
328
- description: "Firecrawl capability or web research task to find tools for.",
329
- maxLength: 500
330
- }),
331
- limit: Type.Optional(
332
- Type.Integer({
333
- description: "Maximum tools to load. Defaults to 3.",
334
- minimum: 1,
335
- maximum: 5
336
- })
337
- )
338
- }),
339
- async execute(_toolCallId, params, signal) {
340
- signal?.throwIfAborted();
341
- const available = new Set(availableFirecrawlTools(pi));
342
- const matches = matchFirecrawlTools(params.query, params.limit ?? 3, available);
343
- const active = pi.getActiveTools();
344
- const activeSet = new Set(active);
345
- const added = matches.filter((name) => !activeSet.has(name));
346
- if (added.length > 0) pi.setActiveTools(unique([...active, ...added]));
347
- const text = matches.length === 0 ? "No available Firecrawl tools matched the query." : added.length > 0 ? `Loaded Firecrawl tools: ${added.join(", ")}` : `Matching Firecrawl tools are already loaded: ${matches.join(", ")}`;
348
- return {
349
- content: [{ type: "text", text }],
350
- details: { matches, added }
351
- };
352
- }
353
- });
354
- }
355
- function matchFirecrawlTools(query, limit, available) {
356
- const terms = [
357
- ...new Set(
358
- query.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length >= 2)
359
- )
360
- ];
361
- if (terms.length === 0) return [];
362
- const ranked = FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name)).map((name, index) => ({
363
- name,
364
- index,
365
- score: terms.reduce((score, term) => score + (SEARCH_TEXT[name].split(" ").includes(term) ? 1 : 0), 0)
366
- })).filter((match) => match.score > 0).sort((left, right) => right.score - left.score || left.index - right.index);
367
- const bestScore = ranked[0]?.score;
368
- if (bestScore === void 0) return [];
369
- const matches = ranked.filter((match) => match.score === bestScore).slice(0, limit).map((match) => match.name);
370
- if (matches.includes("firecrawl_crawl") && available.has("firecrawl_crawl_status") && !matches.includes("firecrawl_crawl_status") && matches.length < limit) {
371
- matches.push("firecrawl_crawl_status");
372
- }
373
- if (matches.includes("firecrawl_crawl_status") && available.has("firecrawl_crawl") && !matches.includes("firecrawl_crawl") && terms.some((term) => CRAWL_CREATION_TERMS.has(term)) && matches.length < limit) {
374
- matches.unshift("firecrawl_crawl");
375
- }
376
- return matches;
377
- }
378
- function loadedFirecrawlToolsFromBranch(entries, availableTools) {
379
- const available = new Set(availableTools);
380
- const loaded = /* @__PURE__ */ new Set();
381
- for (const entry of entries) {
382
- if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) continue;
383
- const message = entry.message;
384
- if (message.role !== "toolResult" || message.toolName !== FIRECRAWL_LOAD_TOOL_NAME || message.isError === true) {
385
- continue;
386
- }
387
- const details = isRecord(message.details) ? message.details : void 0;
388
- const recordedNames = [
389
- ...Array.isArray(message.addedToolNames) ? message.addedToolNames : [],
390
- ...details && Array.isArray(details.added) ? details.added : []
391
- ];
392
- for (const name of recordedNames) {
393
- if (isFirecrawlToolName(name) && available.has(name)) loaded.add(name);
394
- }
395
- }
396
- return FIRECRAWL_TOOL_NAMES.filter((name) => loaded.has(name));
397
- }
398
- function setAvailableTools(pi, availableTools, sessionOwner) {
399
- const available = new Set(availableTools);
400
- availableToolsByApi.set(pi, available);
401
- if (sessionOwner) availableToolsBySession.set(sessionOwner, new Set(available));
402
- return available;
403
- }
404
- function isFirecrawlToolName(value) {
405
- return typeof value === "string" && FIRECRAWL_TOOL_NAMES.includes(value);
406
- }
407
- function isRecord(value) {
408
- return typeof value === "object" && value !== null && !Array.isArray(value);
409
- }
410
- function compatBoolean(value, key) {
411
- if (!isRecord(value)) return void 0;
412
- return typeof value[key] === "boolean" ? value[key] : void 0;
413
- }
414
- function compatString(value, key) {
415
- if (!isRecord(value)) return void 0;
416
- return typeof value[key] === "string" ? value[key] : void 0;
417
- }
418
- function unique(values) {
419
- return [...new Set(values)];
420
- }
421
-
422
- // src/settings.ts
423
- import { randomUUID as randomUUID2 } from "node:crypto";
424
- import { constants } from "node:fs";
425
- import { access, lstat, mkdir, readFile, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
426
- import { dirname, join as join2 } from "node:path";
427
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
428
- var NEW_SETTINGS_FILE = "pi-firecrawl.json";
429
- var LEGACY_SETTINGS_FILE = "pi-firecrawl-settings.json";
430
- var DEFAULT_FILE_OPERATIONS = {
431
- write: (path, data) => writeFile2(path, data, "utf8").then(() => void 0),
432
- rename
433
- };
434
- async function loadSettings() {
435
- await settingsSaveQueue;
436
- const newPath = settingsFilePath();
437
- const newSettings = await readSettingsFile(newPath);
438
- if (newSettings.kind !== "missing") {
439
- return withLegacyIgnoredNotice(newSettings);
440
- }
441
- const legacyPath = legacySettingsFilePath();
442
- const legacySettings = await readSettingsFile(legacyPath);
443
- const concurrentlyCreatedSettings = await readSettingsFile(newPath);
444
- if (concurrentlyCreatedSettings.kind !== "missing") {
445
- return withLegacyIgnoredNotice(concurrentlyCreatedSettings);
446
- }
447
- if (legacySettings.kind === "missing") return { kind: "missing" };
448
- if (legacySettings.kind === "invalid") return legacySettings;
449
- return {
450
- ...legacySettings,
451
- notice: `Using legacy ${LEGACY_SETTINGS_FILE}; rename it to ${NEW_SETTINGS_FILE}. Future saves write ${NEW_SETTINGS_FILE} without modifying the legacy file.`
452
- };
453
- }
454
- async function readSettingsDocument(filePath) {
455
- let text;
456
- try {
457
- text = await readFile(filePath, "utf8");
458
- } catch (error) {
459
- if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
460
- return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
461
- }
462
- try {
463
- const parsed = JSON.parse(text);
464
- const settings = normalizeFirecrawlSettings(parsed);
465
- if (settings) {
466
- return {
467
- result: { kind: "loaded", settings },
468
- document: { ...parsed }
469
- };
470
- }
471
- return {
472
- result: {
473
- kind: "invalid",
474
- reason: `${filePath}: expected tools to be an array of Firecrawl tool names`
475
- }
476
- };
477
- } catch (error) {
478
- return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
479
- }
480
- }
481
- async function readSettingsFile(filePath) {
482
- return (await readSettingsDocument(filePath)).result;
483
- }
484
- async function withLegacyIgnoredNotice(settings) {
485
- if (!await fileExists(legacySettingsFilePath())) return settings;
486
- return {
487
- ...settings,
488
- notice: `Firecrawl legacy settings ignored: ${legacySettingsFilePath()} exists, but ${settingsFilePath()} takes precedence. Delete ${LEGACY_SETTINGS_FILE} after confirming your settings.`
489
- };
490
- }
491
- async function fileExists(filePath) {
492
- try {
493
- await access(filePath, constants.F_OK);
494
- return true;
495
- } catch {
496
- return false;
497
- }
498
- }
499
- async function pathEntryExists(filePath) {
500
- try {
501
- await lstat(filePath);
502
- return true;
503
- } catch (error) {
504
- if (isNodeError(error) && error.code === "ENOENT") return false;
505
- throw error;
506
- }
507
- }
508
- function normalizeFirecrawlSettings(value) {
509
- if (!value || typeof value !== "object") return void 0;
510
- const settings = value;
511
- if (typeof settings.updatedAt !== "number" || !Number.isFinite(settings.updatedAt)) {
512
- return void 0;
513
- }
514
- if (!Array.isArray(settings.tools)) return void 0;
515
- if (!settings.tools.every(isFirecrawlToolName2)) return void 0;
516
- return { tools: orderedUniqueFirecrawlTools(settings.tools), updatedAt: settings.updatedAt };
517
- }
518
- function isFirecrawlToolName2(value) {
519
- return typeof value === "string" && FIRECRAWL_TOOL_NAMES.includes(value);
520
- }
521
- function orderedUniqueFirecrawlTools(tools) {
522
- const selectedTools = new Set(tools);
523
- return FIRECRAWL_TOOL_NAMES.filter((toolName) => selectedTools.has(toolName));
524
- }
525
- var settingsSaveQueue = Promise.resolve();
526
- function saveSettings(settings, operations = {}) {
527
- const normalizedSettings = normalizeFirecrawlSettings(settings);
528
- if (!normalizedSettings) {
529
- return Promise.reject(new Error("Cannot save invalid Firecrawl settings"));
530
- }
531
- const operation = settingsSaveQueue.then(() => saveSettingsNow(normalizedSettings, operations));
532
- settingsSaveQueue = operation.catch(() => void 0);
533
- return operation;
534
- }
535
- async function saveSettingsNow(settings, operations) {
536
- const filePath = settingsFilePath();
537
- let current = await readSettingsDocument(filePath);
538
- const replaceCanonical = current.result.kind !== "missing";
539
- if (!replaceCanonical) current = await readSettingsDocument(legacySettingsFilePath());
540
- if (current.result.kind === "invalid") {
541
- throw new Error(`Cannot save Firecrawl settings until you repair ${current.result.reason}`);
542
- }
543
- const nextDocument = {
544
- ...current.document ?? {},
545
- tools: [...settings.tools],
546
- updatedAt: settings.updatedAt
547
- };
548
- await mkdir(dirname(filePath), { recursive: true });
549
- const tempFile = `${filePath}.${process.pid}.${randomUUID2()}.tmp`;
550
- try {
551
- await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(tempFile, `${JSON.stringify(nextDocument, null, 2)}
552
- `);
553
- if (!replaceCanonical && await pathEntryExists(filePath)) {
554
- throw new Error(`${NEW_SETTINGS_FILE} was created concurrently; reopen settings and retry.`);
555
- }
556
- await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(tempFile, filePath);
557
- } catch (error) {
558
- await rm2(tempFile, { force: true }).catch(() => void 0);
559
- throw error;
560
- }
561
- }
562
- function settingsFilePath() {
563
- return join2(agentDir(), NEW_SETTINGS_FILE);
564
- }
565
- function legacySettingsFilePath() {
566
- return join2(agentDir(), LEGACY_SETTINGS_FILE);
567
- }
568
- function agentDir() {
569
- return getAgentDir();
570
- }
571
- function isNodeError(error) {
572
- return error instanceof Error && "code" in error;
573
- }
574
- function formatError(error) {
575
- return error instanceof Error ? error.message : String(error);
576
- }
577
-
578
- // src/tool-selector.ts
579
- import { stripVTControlCharacters } from "node:util";
580
- var settingsNotice;
581
- var sessionGeneration = 0;
582
- var sessionController = new AbortController();
583
- function advanceFirecrawlSessionGeneration() {
584
- sessionController.abort(new DOMException("Firecrawl session replaced", "AbortError"));
585
- sessionController = new AbortController();
586
- return ++sessionGeneration;
587
- }
588
- function currentFirecrawlSessionGeneration() {
589
- return sessionGeneration;
590
- }
591
- function isCurrentFirecrawlSession(generation) {
592
- return generation === sessionGeneration;
593
- }
594
- function currentFirecrawlSessionSignal() {
595
- return sessionController.signal;
596
- }
597
- function clearSettingsNotice() {
598
- settingsNotice = void 0;
599
- }
600
- function recordSettingsNotice(settings) {
601
- settingsNotice = settings.notice;
602
- }
603
- async function showToolSelector(pi, ctx) {
604
- const generation = sessionGeneration;
605
- if (!ctx.hasUI || ctx.mode !== "tui" && ctx.mode !== "rpc") {
606
- throw new Error("/firecrawl tools requires TUI or RPC mode");
607
- }
608
- const menuSignal = sessionController.signal;
609
- const isCurrent = () => isCurrentFirecrawlSession(generation) && !menuSignal.aborted;
610
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
611
- if (!isCurrent()) return;
612
- const menu = defineMenu({
613
- start: "tools",
614
- screens: {
615
- tools: () => {
616
- const selectedTools = new Set(availableFirecrawlTools(pi));
617
- return {
618
- kind: "multiSelect",
619
- title: toolSelectorTitle(selectedTools),
620
- items: FIRECRAWL_TOOL_NAMES.map((toolName) => ({
621
- id: toolName,
622
- label: toolName,
623
- selected: selectedTools.has(toolName)
624
- })),
625
- action: "toggle",
626
- actions: [
627
- {
628
- id: "enable-all",
629
- label: "Make all Firecrawl tools available",
630
- action: "enableAll"
631
- },
632
- {
633
- id: "disable-all",
634
- label: "Make all Firecrawl tools unavailable",
635
- action: "disableAll"
636
- },
637
- { id: "done", label: "Done", close: true }
638
- ],
639
- hint: "close",
640
- doneLabel: "Done"
641
- };
642
- }
643
- },
644
- actions: {
645
- toggle: async ({ itemId, selected }) => {
646
- if (!isFirecrawlToolName3(itemId)) return { kind: "rejected" };
647
- const acceptedTools = availableFirecrawlTools(pi);
648
- const selectedTools = new Set(acceptedTools);
649
- if (selected) selectedTools.add(itemId);
650
- else selectedTools.delete(itemId);
651
- const result2 = await transactSelectedTools(
652
- pi,
653
- ctx,
654
- orderedFirecrawlTools(selectedTools),
655
- generation,
656
- acceptedTools
657
- );
658
- return result2 === "saved" ? { kind: "stay" } : { kind: "rejected" };
659
- },
660
- enableAll: async () => {
661
- const acceptedTools = availableFirecrawlTools(pi);
662
- const result2 = await transactSelectedTools(pi, ctx, allFirecrawlTools(), generation, acceptedTools);
663
- return result2 === "saved" ? { kind: "stay" } : { kind: "rejected" };
664
- },
665
- disableAll: async () => {
666
- const acceptedTools = availableFirecrawlTools(pi);
667
- const result2 = await transactSelectedTools(pi, ctx, [], generation, acceptedTools);
668
- return result2 === "saved" ? { kind: "stay" } : { kind: "rejected" };
669
- }
670
- }
671
- });
672
- const result = await runMenu(ctx, menu, {
673
- getState: () => void 0,
674
- signal: menuSignal,
675
- isCurrent
676
- });
677
- if (result.kind !== "closed" || !isCurrentFirecrawlSession(generation)) return;
678
- const status = await buildStatusMessage(pi);
679
- if (!isCurrentFirecrawlSession(generation)) return;
680
- ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
681
- }
682
- async function updateFirecrawlTools(pi, ctx, selectedTools, action) {
683
- const generation = sessionGeneration;
684
- const result = await transactSelectedTools(pi, ctx, selectedTools, generation);
685
- if (result !== "saved" || !isCurrentFirecrawlSession(generation)) return;
686
- const status = await buildStatusMessage(pi);
687
- if (!isCurrentFirecrawlSession(generation)) return;
688
- ctx.ui.notify(
689
- sanitizeFirecrawlDisplay(`Firecrawl tool catalog ${action}.
690
-
691
- ${status}`),
692
- hasApiKey() ? "info" : "warning"
693
- );
694
- }
695
- var toolTransactionQueue = Promise.resolve();
696
- async function waitForFirecrawlSettings() {
697
- await toolTransactionQueue;
698
- }
699
- function transactSelectedTools(pi, ctx, selectedTools, expectedGeneration, expectedAvailableTools) {
700
- const operation = toolTransactionQueue.then(
701
- () => transactSelectedToolsNow(pi, ctx, selectedTools, expectedGeneration, expectedAvailableTools)
702
- );
703
- toolTransactionQueue = operation.then(
704
- () => void 0,
705
- () => void 0
706
- );
707
- return operation;
708
- }
709
- async function transactSelectedToolsNow(pi, ctx, selectedTools, expectedGeneration, expectedAvailableTools) {
710
- if (!isCurrentFirecrawlSession(expectedGeneration)) return "failed";
711
- if (expectedAvailableTools && !arraysEqual(availableFirecrawlTools(pi), expectedAvailableTools)) {
712
- ctx.ui.notify(
713
- "Firecrawl tool availability changed while the selector was open. Review the current state and try again.",
714
- "warning"
715
- );
716
- return "available-tools-changed";
717
- }
718
- const previousActiveTools = pi.getActiveTools();
719
- const previousAvailableTools = availableFirecrawlTools(pi);
720
- try {
721
- applyFirecrawlTools(pi, selectedTools, ctx.sessionManager);
722
- await persistSettings(selectedTools);
723
- return isCurrentFirecrawlSession(expectedGeneration) ? "saved" : "failed";
724
- } catch (error) {
725
- let rollbackError;
726
- try {
727
- applyAvailableFirecrawlTools(pi, previousAvailableTools, ctx.sessionManager);
728
- const currentNonCapabilityTools = pi.getActiveTools().filter((name) => !FIRECRAWL_TOOL_NAMES.includes(name));
729
- const previousLoadedTools = previousActiveTools.filter(
730
- (name) => FIRECRAWL_TOOL_NAMES.includes(name)
731
- );
732
- const restoredFirecrawlTools = firecrawlToolExposureMode(pi) === "eager" ? previousAvailableTools : previousLoadedTools;
733
- pi.setActiveTools(unique2([...currentNonCapabilityTools, ...restoredFirecrawlTools]));
734
- } catch (caught) {
735
- rollbackError = caught;
736
- }
737
- if (!isCurrentFirecrawlSession(expectedGeneration)) return "failed";
738
- ctx.ui.notify(
739
- sanitizeFirecrawlDisplay(
740
- rollbackError ? `Firecrawl settings save failed: ${formatError2(error)}; active-tool rollback failed: ${formatError2(rollbackError)}` : `Firecrawl settings save failed; active tools restored: ${formatError2(error)}`
741
- ),
742
- "warning"
743
- );
744
- return "failed";
745
- }
746
- }
747
- function arraysEqual(left, right) {
748
- return left.length === right.length && left.every((value, index) => value === right[index]);
749
- }
750
- function applyFirecrawlTools(pi, selectedTools, sessionOwner) {
751
- applyAvailableFirecrawlTools(pi, selectedTools, sessionOwner);
752
- }
753
- function getToolStatusSummary(pi) {
754
- const firecrawlToolNames = new Set(FIRECRAWL_TOOL_NAMES);
755
- const activeToolNames = new Set(pi.getActiveTools());
756
- const loadedFirecrawlToolCount = FIRECRAWL_TOOL_NAMES.filter((name) => activeToolNames.has(name)).length;
757
- const availableFirecrawlToolCount = availableFirecrawlTools(pi).length;
758
- const activeNonFirecrawlToolCount = Array.from(activeToolNames).filter(
759
- (name) => !firecrawlToolNames.has(name) && name !== FIRECRAWL_LOAD_TOOL_NAME
760
- ).length;
761
- const availabilityStatus = availableFirecrawlToolCount === FIRECRAWL_TOOL_NAMES.length ? "enabled" : availableFirecrawlToolCount === 0 ? "disabled" : "partial";
762
- return {
763
- availabilityStatus,
764
- availableFirecrawlToolCount,
765
- loadedFirecrawlToolCount,
766
- activeNonFirecrawlToolCount
767
- };
768
- }
769
- async function buildStatusMessage(pi) {
770
- const generation = sessionGeneration;
771
- const settings = await loadSettings();
772
- if (!isCurrentFirecrawlSession(generation)) return "";
773
- recordSettingsNotice(settings);
774
- const summary = getToolStatusSummary(pi);
775
- const persistedSetting = persistedSettingLabel(settings);
776
- return sanitizeFirecrawlDisplay(
777
- [
778
- `Firecrawl tools available: ${formatRuntimeStatus(summary)}`,
779
- `Tool exposure: ${firecrawlToolExposureMode(pi)}`,
780
- `Loaded capability tools this session: ${summary.loadedFirecrawlToolCount}/${FIRECRAWL_TOOL_NAMES.length}`,
781
- `Loader: ${pi.getActiveTools().includes(FIRECRAWL_LOAD_TOOL_NAME) ? "active" : "inactive"}`,
782
- `Persisted tool catalog: ${persistedSetting}`,
783
- `Settings file: ${settingsFilePath()}`,
784
- ...settingsNotice ? [`Settings note: ${settingsNotice}`] : [],
785
- `Other active tools preserved: ${summary.activeNonFirecrawlToolCount}`,
786
- `API key: ${hasApiKey() ? "present" : "missing"} (FIRECRAWL_API_KEY)`,
787
- `API URL: ${configuredApiUrl()}`
788
- ].join("\n")
789
- );
790
- }
791
- function buildConfigMessage() {
792
- return sanitizeFirecrawlDisplay(
793
- [
794
- "Firecrawl configuration:",
795
- `API key: ${hasApiKey() ? "present" : "missing"} (FIRECRAWL_API_KEY)`,
796
- `API URL: ${configuredApiUrl()}`,
797
- "Override API URL with FIRECRAWL_API_URL or FIRECRAWL_BASE_URL.",
798
- "This extension never logs, displays, or stores your Firecrawl API key."
799
- ].join("\n")
800
- );
801
- }
802
- function buildCommandGuide() {
803
- return [
804
- "Firecrawl commands:",
805
- "/firecrawl \u2014 open this menu",
806
- "/firecrawl help \u2014 show command usage",
807
- "/firecrawl config \u2014 show API key presence and API URL",
808
- "/firecrawl quickstart \u2014 alias for /firecrawl config",
809
- "/firecrawl status \u2014 show tool and settings status",
810
- "/firecrawl tools \u2014 choose available Firecrawl tools",
811
- "/firecrawl toggle \u2014 alias for /firecrawl tools",
812
- "/firecrawl enable \u2014 make all Firecrawl tools available",
813
- "/firecrawl disable \u2014 make all Firecrawl capability tools unavailable"
814
- ].join("\n");
815
- }
816
- function toolSelectorTitle(selectedTools) {
817
- return `Available Firecrawl tools (${selectedTools.size}/${FIRECRAWL_TOOL_NAMES.length}). Non-built-in tools run at user risk.`;
818
- }
819
- function isFirecrawlToolName3(value) {
820
- return FIRECRAWL_TOOL_NAMES.includes(value);
821
- }
822
- function allFirecrawlTools() {
823
- return [...FIRECRAWL_TOOL_NAMES];
824
- }
825
- function unique2(values) {
826
- return Array.from(new Set(values));
827
- }
828
- function orderedFirecrawlTools(selectedTools) {
829
- return FIRECRAWL_TOOL_NAMES.filter((toolName) => selectedTools.has(toolName));
830
- }
831
- function formatRuntimeStatus(summary) {
832
- return `${summary.availabilityStatus} (${summary.availableFirecrawlToolCount}/${FIRECRAWL_TOOL_NAMES.length} available)`;
833
- }
834
- function persistedSettingLabel(settings) {
835
- if (settings.kind === "loaded") return formatPersistedSelection(settings.settings.tools);
836
- if (settings.kind === "invalid") {
837
- return `none; current availability policy preserved (invalid settings ignored: ${settings.reason})`;
838
- }
839
- return "none; current availability policy preserved";
840
- }
841
- function formatPersistedSelection(tools) {
842
- if (tools.length === FIRECRAWL_TOOL_NAMES.length) {
843
- return `all available (${tools.length}/${FIRECRAWL_TOOL_NAMES.length} selected)`;
844
- }
845
- if (tools.length === 0) return `all unavailable (0/${FIRECRAWL_TOOL_NAMES.length} selected)`;
846
- return `${tools.length}/${FIRECRAWL_TOOL_NAMES.length} selected: ${tools.join(", ")}`;
847
- }
848
- function sanitizeFirecrawlDisplay(value, maxCharacters = 5e4) {
849
- const characters = Array.from(stripVTControlCharacters(value), (character) => {
850
- const codePoint = character.codePointAt(0) ?? 0;
851
- const unsafeControl = codePoint >= 0 && codePoint <= 8 || codePoint >= 11 && codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
852
- return unsafeControl ? "\uFFFD" : character;
853
- });
854
- const limit = Number.isFinite(maxCharacters) ? Math.max(0, Math.floor(maxCharacters)) : 0;
855
- if (characters.length <= limit) return characters.join("");
856
- if (limit === 0) return "";
857
- return `${characters.slice(0, limit - 1).join("")}\u2026`;
858
- }
859
- function formatError2(error) {
860
- return error instanceof Error ? error.message : String(error);
861
- }
862
- async function persistSettings(selectedTools) {
863
- await saveSettings({ tools: [...selectedTools], updatedAt: Date.now() });
864
- }
865
-
866
- // src/tools.ts
867
- import { DEFAULT_MAX_BYTES as DEFAULT_MAX_BYTES2, DEFAULT_MAX_LINES as DEFAULT_MAX_LINES2, defineTool as defineTool2, formatSize as formatSize2 } from "@earendil-works/pi-coding-agent";
868
- import { Type as Type2 } from "typebox";
869
- var StringArray = Type2.Array(Type2.String());
870
- var OUTPUT_LIMIT_DESCRIPTION = `Output is truncated to ${DEFAULT_MAX_LINES2} lines or ${formatSize2(DEFAULT_MAX_BYTES2)}; complete truncated responses are saved temporarily and their path is returned.`;
871
- var scrapeTool = defineTool2({
872
- name: FIRECRAWL_TOOL_NAMES[0],
873
- label: "Firecrawl: Scrape",
874
- description: `Scrape a single URL through Firecrawl and return requested formats. ${OUTPUT_LIMIT_DESCRIPTION}`,
875
- parameters: Type2.Object({
876
- url: Type2.String({ description: "URL to scrape." }),
877
- formats: Type2.Optional(
878
- Type2.Array(
879
- Type2.String({
880
- description: "Requested Firecrawl output format, such as markdown, html, rawHtml, links, screenshot, or json."
881
- }),
882
- { description: "Firecrawl output formats. Defaults to Firecrawl's API default." }
883
- )
884
- ),
885
- onlyMainContent: Type2.Optional(Type2.Boolean({ description: "Return only the main page content when supported." })),
886
- includeTags: Type2.Optional(StringArray),
887
- excludeTags: Type2.Optional(StringArray),
888
- waitFor: Type2.Optional(Type2.Number({ description: "Milliseconds to wait before scraping." })),
889
- timeout: Type2.Optional(Type2.Number({ description: "Firecrawl request timeout in milliseconds." })),
890
- mobile: Type2.Optional(Type2.Boolean({ description: "Use a mobile user agent when supported." })),
891
- skipTlsVerification: Type2.Optional(
892
- Type2.Boolean({ description: "Skip TLS certificate verification when supported." })
893
- ),
894
- removeBase64Images: Type2.Optional(
895
- Type2.Boolean({ description: "Remove base64 image data from the response when supported." })
896
- ),
897
- blockAds: Type2.Optional(Type2.Boolean({ description: "Block ads while scraping when supported." })),
898
- headers: Type2.Optional(
899
- Type2.Record(Type2.String(), Type2.String(), {
900
- description: "Additional HTTP headers Firecrawl should use while fetching the target URL."
901
- })
902
- ),
903
- jsonOptions: Type2.Optional(Type2.Any({ description: "Firecrawl jsonOptions for structured extraction." })),
904
- actions: Type2.Optional(
905
- Type2.Array(Type2.Any(), {
906
- description: "Firecrawl browser actions to perform before scraping."
907
- })
908
- ),
909
- location: Type2.Optional(Type2.Any({ description: "Firecrawl location options." }))
910
- }),
911
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
912
- return withStatus(ctx, "scrape", async () => {
913
- const payload = await firecrawlRequest("POST", "/scrape", cleanObject(params), signal, ctx.sessionManager);
914
- return await jsonResult(payload, ctx.sessionManager);
915
- });
916
- }
917
- });
918
- var crawlTool = defineTool2({
919
- name: FIRECRAWL_TOOL_NAMES[1],
920
- label: "Firecrawl: Crawl",
921
- description: `Start a Firecrawl crawl job for a website. ${OUTPUT_LIMIT_DESCRIPTION}`,
922
- parameters: Type2.Object({
923
- url: Type2.String({ description: "Starting URL for the crawl." }),
924
- limit: Type2.Optional(Type2.Number({ description: "Maximum number of pages to crawl." })),
925
- maxDepth: Type2.Optional(Type2.Number({ description: "Maximum crawl depth when supported." })),
926
- includePaths: Type2.Optional(Type2.Array(Type2.String(), { description: "URL path patterns to include." })),
927
- excludePaths: Type2.Optional(Type2.Array(Type2.String(), { description: "URL path patterns to exclude." })),
928
- allowBackwardLinks: Type2.Optional(Type2.Boolean({ description: "Allow crawling backward links when supported." })),
929
- allowExternalLinks: Type2.Optional(Type2.Boolean({ description: "Allow crawling external links when supported." })),
930
- ignoreSitemap: Type2.Optional(Type2.Boolean({ description: "Ignore sitemap discovery." })),
931
- deduplicateSimilarURLs: Type2.Optional(Type2.Boolean({ description: "Deduplicate similar URLs when supported." })),
932
- scrapeOptions: Type2.Optional(Type2.Any({ description: "Firecrawl scrapeOptions applied to crawled pages." })),
933
- webhook: Type2.Optional(Type2.Any({ description: "Firecrawl webhook configuration." }))
934
- }),
935
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
936
- return withStatus(ctx, "crawl", async () => {
937
- const payload = await firecrawlRequest("POST", "/crawl", cleanObject(params), signal, ctx.sessionManager);
938
- return await jsonResult(payload, ctx.sessionManager);
939
- });
940
- }
941
- });
942
- var crawlStatusTool = defineTool2({
943
- name: FIRECRAWL_TOOL_NAMES[2],
944
- label: "Firecrawl: Crawl Status",
945
- description: `Check a Firecrawl crawl job status and retrieve completed crawl data. ${OUTPUT_LIMIT_DESCRIPTION}`,
946
- parameters: Type2.Object({
947
- id: Type2.String({ description: "Crawl job id returned by firecrawl_crawl." })
948
- }),
949
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
950
- return withStatus(ctx, "crawl status", async () => {
951
- const payload = await firecrawlRequest(
952
- "GET",
953
- `/crawl/${encodeURIComponent(params.id)}`,
954
- void 0,
955
- signal,
956
- ctx.sessionManager
957
- );
958
- return await jsonResult(payload, ctx.sessionManager);
959
- });
960
- }
961
- });
962
- var mapTool = defineTool2({
963
- name: FIRECRAWL_TOOL_NAMES[3],
964
- label: "Firecrawl: Map",
965
- description: `Discover URLs for a site through Firecrawl's map endpoint. ${OUTPUT_LIMIT_DESCRIPTION}`,
966
- parameters: Type2.Object({
967
- url: Type2.String({ description: "Website URL to map." }),
968
- search: Type2.Optional(Type2.String({ description: "Optional search term to filter discovered URLs." })),
969
- ignoreSitemap: Type2.Optional(Type2.Boolean({ description: "Ignore sitemap discovery." })),
970
- sitemapOnly: Type2.Optional(Type2.Boolean({ description: "Only use sitemap URLs when supported." })),
971
- includeSubdomains: Type2.Optional(Type2.Boolean({ description: "Include subdomains when supported." })),
972
- limit: Type2.Optional(Type2.Number({ description: "Maximum number of URLs to return." }))
973
- }),
974
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
975
- return withStatus(ctx, "map", async () => {
976
- const payload = await firecrawlRequest("POST", "/map", cleanObject(params), signal, ctx.sessionManager);
977
- return await jsonResult(payload, ctx.sessionManager);
978
- });
979
- }
980
- });
981
- var searchTool = defineTool2({
982
- name: FIRECRAWL_TOOL_NAMES[4],
983
- label: "Firecrawl: Search",
984
- description: `Search the web through Firecrawl and optionally scrape search results. ${OUTPUT_LIMIT_DESCRIPTION}`,
985
- parameters: Type2.Object({
986
- query: Type2.String({ description: "Search query." }),
987
- limit: Type2.Optional(Type2.Number({ description: "Maximum number of search results." })),
988
- tbs: Type2.Optional(Type2.String({ description: "Google-style time based search filter when supported." })),
989
- location: Type2.Optional(Type2.String({ description: "Search location when supported." })),
990
- scrapeOptions: Type2.Optional(Type2.Any({ description: "Firecrawl scrapeOptions for search result pages." }))
991
- }),
992
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
993
- return withStatus(ctx, "search", async () => {
994
- const payload = await firecrawlRequest("POST", "/search", cleanObject(params), signal, ctx.sessionManager);
995
- return await jsonResult(payload, ctx.sessionManager);
996
- });
997
- }
998
- });
3
+ import {
4
+ DEFAULT_TOOL_MODE,
5
+ advanceFirecrawlSessionGeneration,
6
+ allFirecrawlTools,
7
+ availableFirecrawlTools,
8
+ buildCommandGuide,
9
+ buildConfigMessage,
10
+ buildStatusMessage,
11
+ cleanupResponseArtifacts,
12
+ clearSettingsNotice,
13
+ configureFirecrawlToolExposure,
14
+ currentFirecrawlSessionGeneration,
15
+ currentFirecrawlSessionSignal,
16
+ firecrawlToolMode,
17
+ hasApiKey,
18
+ initializeAvailableFirecrawlTools,
19
+ isCurrentFirecrawlSession,
20
+ loadSettings,
21
+ loadedFirecrawlToolsFromBranch,
22
+ openResponseArtifacts,
23
+ recordSettingsNotice,
24
+ registerFirecrawlTools,
25
+ requireEagerFirecrawlToolExposure,
26
+ sanitizeFirecrawlDisplay,
27
+ showToolSelector,
28
+ supportsNativeDeferredToolLoading,
29
+ updateFirecrawlTools,
30
+ waitForFirecrawlSettings
31
+ } from "./chunks/chunk-WIQUHR2L.ts";
999
32
 
1000
33
  // src/firecrawl.ts
1001
- var STATUS_KEY2 = "firecrawl";
34
+ var STATUS_KEY = "firecrawl";
1002
35
  var COMMAND_COMPLETIONS = [
1003
36
  { value: "help", label: "help", description: "Show command usage" },
1004
37
  { value: "config", label: "config", description: "Show configuration quick start" },
1005
38
  { value: "quickstart", label: "quickstart", description: "Show configuration quick start" },
1006
39
  { value: "status", label: "status", description: "Show tool and settings status" },
40
+ { value: "settings", label: "settings", description: "Choose tool mode and available tools" },
1007
41
  { value: "tools", label: "tools", description: "Choose available Firecrawl tools" },
1008
42
  { value: "toggle", label: "toggle", description: "Choose available Firecrawl tools" },
1009
43
  { value: "enable", label: "enable", description: "Make all Firecrawl tools available" },
@@ -1013,42 +47,47 @@ var MENU_OPTIONS = {
1013
47
  config: "Configuration quick start",
1014
48
  help: "Command usage guide",
1015
49
  status: "Show tool status",
50
+ settings: "Settings",
1016
51
  tools: "Choose available Firecrawl tools",
1017
52
  enable: "Make all Firecrawl tools available",
1018
53
  disable: "Make all Firecrawl tools unavailable"
1019
54
  };
1020
55
  function firecrawl(pi) {
1021
- pi.registerTool(scrapeTool);
1022
- pi.registerTool(crawlTool);
1023
- pi.registerTool(crawlStatusTool);
1024
- pi.registerTool(mapTool);
1025
- pi.registerTool(searchTool);
1026
- pi.registerTool(createFirecrawlLoadTool(pi));
56
+ registerFirecrawlTools(pi);
1027
57
  pi.registerCommand("firecrawl", {
1028
58
  description: "Open Firecrawl help and tool controls",
1029
59
  getArgumentCompletions: (prefix) => commandCompletions(prefix),
1030
60
  handler: async (args, ctx) => {
1031
61
  initializeAvailableFirecrawlTools(pi, ctx.sessionManager);
1032
- const generation = currentFirecrawlSessionGeneration();
62
+ const generation = currentFirecrawlSessionGeneration(pi);
1033
63
  await handleFirecrawlCommand(pi, args, ctx, generation);
1034
64
  }
1035
65
  });
1036
66
  pi.on("session_start", async (_event, ctx) => {
1037
- const generation = advanceFirecrawlSessionGeneration();
1038
- initializeAvailableFirecrawlTools(pi, ctx.sessionManager);
67
+ const generation = advanceFirecrawlSessionGeneration(pi);
1039
68
  openResponseArtifacts(ctx.sessionManager);
1040
- clearSettingsNotice();
1041
- ctx.ui.setStatus(STATUS_KEY2, void 0);
69
+ clearSettingsNotice(pi);
70
+ ctx.ui.setStatus(STATUS_KEY, void 0);
71
+ await waitForFirecrawlSettings();
72
+ if (!isCurrentFirecrawlSession(pi, generation)) return;
73
+ initializeAvailableFirecrawlTools(pi, ctx.sessionManager);
1042
74
  const settings = await loadSettings();
1043
- if (!isCurrentFirecrawlSession(generation)) return;
1044
- recordSettingsNotice(settings);
75
+ if (!isCurrentFirecrawlSession(pi, generation)) return;
76
+ recordSettingsNotice(pi, settings);
1045
77
  if (settings.notice) ctx.ui.notify(sanitizeFirecrawlDisplay(settings.notice), "warning");
1046
78
  const availableTools = settings.kind === "loaded" ? settings.settings.tools : availableFirecrawlTools(pi);
1047
79
  const loadedTools = loadedFirecrawlToolsFromBranch(ctx.sessionManager.getBranch(), availableTools);
1048
- configureFirecrawlToolExposure(pi, availableTools, loadedTools, ctx.sessionManager, ctx.model);
80
+ const mode = settings.kind === "loaded" ? settings.settings.toolMode ?? DEFAULT_TOOL_MODE : DEFAULT_TOOL_MODE;
81
+ configureFirecrawlToolExposure(pi, availableTools, loadedTools, ctx.sessionManager, ctx.model, mode);
1049
82
  if (settings.kind === "invalid") {
1050
83
  ctx.ui.notify(sanitizeFirecrawlDisplay(`Firecrawl settings ignored: ${settings.reason}`), "warning");
1051
84
  }
85
+ if (mode === "codemode" && !pi.getActiveTools().includes("codemode")) {
86
+ ctx.ui.notify(
87
+ 'Firecrawl uses codemode, but codemode is not active. Enable Pi defaultTools: ["+codemode"] and /reload, or choose lazy/direct in /firecrawl settings.',
88
+ "warning"
89
+ );
90
+ }
1052
91
  });
1053
92
  pi.on("model_select", (event) => {
1054
93
  if (!supportsNativeDeferredToolLoading(event.model)) {
@@ -1056,8 +95,8 @@ function firecrawl(pi) {
1056
95
  }
1057
96
  });
1058
97
  pi.on("session_shutdown", async (_event, ctx) => {
1059
- advanceFirecrawlSessionGeneration();
1060
- ctx.ui.setStatus(STATUS_KEY2, void 0);
98
+ advanceFirecrawlSessionGeneration(pi);
99
+ ctx.ui.setStatus(STATUS_KEY, void 0);
1061
100
  const artifactOwner = ctx.sessionManager;
1062
101
  await waitForFirecrawlSettings();
1063
102
  await cleanupResponseArtifacts(artifactOwner);
@@ -1081,10 +120,16 @@ async function handleFirecrawlCommand(pi, args, ctx, generation) {
1081
120
  case "status": {
1082
121
  requireObservableUi(ctx, "status");
1083
122
  const status = await buildStatusMessage(pi);
1084
- if (!isCurrentFirecrawlSession(generation)) return;
123
+ if (!isCurrentFirecrawlSession(pi, generation)) return;
1085
124
  ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
1086
125
  return;
1087
126
  }
127
+ case "settings": {
128
+ const { showFirecrawlSettings } = await import("./chunks/settings-ui-UUHNBNUE.ts");
129
+ if (!isCurrentFirecrawlSession(pi, generation)) return;
130
+ await showFirecrawlSettings(pi, ctx);
131
+ return;
132
+ }
1088
133
  case "tools":
1089
134
  requireObservableUi(ctx, "tools");
1090
135
  await showToolSelector(pi, ctx);
@@ -1108,8 +153,8 @@ ${buildCommandGuide()}`),
1108
153
  }
1109
154
  async function showMenu(pi, ctx, generation) {
1110
155
  requireObservableUi(ctx, "menu");
1111
- const menuSignal = currentFirecrawlSessionSignal();
1112
- const isCurrent = () => isCurrentFirecrawlSession(generation) && !menuSignal.aborted;
156
+ const menuSignal = currentFirecrawlSessionSignal(pi);
157
+ const isCurrent = () => isCurrentFirecrawlSession(pi, generation) && !menuSignal.aborted;
1113
158
  const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
1114
159
  if (!isCurrent()) return;
1115
160
  const menu = defineMenu({
@@ -1128,6 +173,11 @@ async function showMenu(pi, ctx, generation) {
1128
173
  })
1129
174
  },
1130
175
  actions: {
176
+ settings: async () => {
177
+ const { showFirecrawlSettings } = await import("./chunks/settings-ui-UUHNBNUE.ts");
178
+ if (isCurrent()) await showFirecrawlSettings(pi, ctx);
179
+ return { kind: "close" };
180
+ },
1131
181
  config: async () => {
1132
182
  ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
1133
183
  return { kind: "close" };
@@ -1138,7 +188,7 @@ async function showMenu(pi, ctx, generation) {
1138
188
  },
1139
189
  status: async () => {
1140
190
  const status = await buildStatusMessage(pi);
1141
- if (isCurrentFirecrawlSession(generation)) {
191
+ if (isCurrentFirecrawlSession(pi, generation)) {
1142
192
  ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
1143
193
  }
1144
194
  return { kind: "close" };
@@ -1168,6 +218,7 @@ function mainMenuLines(pi) {
1168
218
  const capabilityNames = allFirecrawlTools();
1169
219
  const loadedCount = capabilityNames.filter((name) => active.has(name)).length;
1170
220
  return [
221
+ `Tool mode: ${firecrawlToolMode(pi)}`,
1171
222
  `Tool catalog: ${availableFirecrawlTools(pi).length}/${capabilityNames.length} available`,
1172
223
  `Loaded this session: ${loadedCount}/${capabilityNames.length}`,
1173
224
  `API key: ${hasApiKey() ? "present" : "missing"}`
@@ -1185,6 +236,7 @@ function parseCommand(args) {
1185
236
  if (command === "config") return "config";
1186
237
  if (command === "quickstart") return "quickstart";
1187
238
  if (command === "status") return "status";
239
+ if (command === "settings") return "settings";
1188
240
  if (command === "tools" || command === "select" || command === "toggle") return "tools";
1189
241
  if (command === "enable" || command === "on") return "enable";
1190
242
  if (command === "disable" || command === "off") return "disable";