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