@narumitw/pi-firecrawl 0.50.0 → 0.50.1

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