@narumitw/pi-firecrawl 0.49.2 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -24
- package/package.json +8 -5
- package/src/firecrawl.ts +71 -26
- package/src/lazy-tools.ts +246 -0
- package/src/settings.ts +9 -3
- package/src/tool-names.ts +9 -0
- package/src/tool-selector.ts +148 -81
- package/src/tools.ts +1 -18
package/README.md
CHANGED
|
@@ -15,9 +15,10 @@ Use it to give your AI coding agent reliable web research capabilities for docum
|
|
|
15
15
|
- Search the web and optionally scrape search result pages.
|
|
16
16
|
- Supports Firecrawl API endpoint overrides.
|
|
17
17
|
- Shows statusline activity only while Firecrawl tools are running.
|
|
18
|
-
-
|
|
18
|
+
- Keeps one loader tool active and exposes matching Firecrawl capabilities only when needed.
|
|
19
|
+
- Provides a `/firecrawl` menu with configuration help and availability controls.
|
|
19
20
|
- Uses `@narumitw/pi-tui-kit` for width-safe menus and individual tool selection.
|
|
20
|
-
- Persists the
|
|
21
|
+
- Persists the Firecrawl lazy-load catalog across Pi restarts.
|
|
21
22
|
- Bounds tool output to Pi's 50 KB or 2,000-line limit while preserving oversized responses in private temporary files.
|
|
22
23
|
- Never logs, displays, or stores your Firecrawl API key.
|
|
23
24
|
|
|
@@ -36,7 +37,7 @@ FIRECRAWL_API_KEY=fc-... pi -e npm:@narumitw/pi-firecrawl
|
|
|
36
37
|
Try this package locally from the repository root:
|
|
37
38
|
|
|
38
39
|
```bash
|
|
39
|
-
FIRECRAWL_API_KEY=fc-... pi -e ./
|
|
40
|
+
FIRECRAWL_API_KEY=fc-... pi -e ./packages/pi-firecrawl
|
|
40
41
|
```
|
|
41
42
|
|
|
42
43
|
## ⚙️ Configuration
|
|
@@ -57,13 +58,40 @@ export FIRECRAWL_API_URL=https://api.firecrawl.dev/v1
|
|
|
57
58
|
|
|
58
59
|
## 🛠️ Pi tools
|
|
59
60
|
|
|
61
|
+
- `firecrawl_load` — find and load Firecrawl capabilities relevant to a web research task.
|
|
60
62
|
- `firecrawl_scrape` — scrape a single URL and return requested formats such as markdown, HTML, links, screenshots, or JSON.
|
|
61
63
|
- `firecrawl_crawl` — start a site crawl job and return the Firecrawl job id.
|
|
62
64
|
- `firecrawl_crawl_status` — check a crawl job status and retrieve completed crawl data.
|
|
63
65
|
- `firecrawl_map` — discover URLs for a site.
|
|
64
66
|
- `firecrawl_search` — search the web through Firecrawl and optionally scrape result pages.
|
|
65
67
|
|
|
66
|
-
|
|
68
|
+
### Lazy tool loading
|
|
69
|
+
|
|
70
|
+
All six tools are registered, but only `firecrawl_load` starts active for this extension.
|
|
71
|
+
|
|
72
|
+
The loader accepts a task-oriented `query`, filters to capabilities allowed by settings, and adds up to three matching tools by default without removing any active Pi tool.
|
|
73
|
+
|
|
74
|
+
Set `limit` from 1 to 5 to change the maximum number loaded by one call.
|
|
75
|
+
|
|
76
|
+
A general website-crawl query can load both `firecrawl_crawl` and `firecrawl_crawl_status`, while a status-specific query loads the status capability.
|
|
77
|
+
|
|
78
|
+
Loaded capability tools remain active for the session unless the user makes them unavailable through `/firecrawl`.
|
|
79
|
+
|
|
80
|
+
On reload, resume, or fork, capabilities recorded by `firecrawl_load` on the active branch are restored when the current catalog still allows them.
|
|
81
|
+
|
|
82
|
+
Pi uses native deferred tool references on compatible Anthropic and OpenAI models.
|
|
83
|
+
|
|
84
|
+
Other models receive Pi's safe fallback and see the newly active definitions in the normal tool list on the next model request.
|
|
85
|
+
|
|
86
|
+
The capability tools omit active-only prompt metadata so loading them does not rebuild the system-prompt prefix.
|
|
87
|
+
|
|
88
|
+
The saved `tools` array controls which capabilities `firecrawl_load` may expose.
|
|
89
|
+
|
|
90
|
+
An empty array leaves the loader active but makes every Firecrawl API capability unavailable.
|
|
91
|
+
|
|
92
|
+
`firecrawl_load` performs no network request and does not create response artifacts.
|
|
93
|
+
|
|
94
|
+
Every API capability fails with a clear configuration error when `FIRECRAWL_API_KEY` is missing, and the always-active loader guidance tells the agent not to retry repeatedly.
|
|
67
95
|
|
|
68
96
|
Tool output is limited to 50 KB or 2,000 lines, whichever is reached first. When a response is
|
|
69
97
|
truncated, the result reports the original and displayed sizes and the path to a complete temporary
|
|
@@ -78,8 +106,8 @@ are bounded in the same way.
|
|
|
78
106
|
/firecrawl
|
|
79
107
|
```
|
|
80
108
|
|
|
81
|
-
Opens a menu with configuration quick start, command usage,
|
|
82
|
-
|
|
109
|
+
Opens a menu with configuration quick start, command usage, lazy-catalog status, controls for making
|
|
110
|
+
all Firecrawl capabilities available or unavailable, and a selector for choosing individual tools.
|
|
83
111
|
|
|
84
112
|
Direct subcommands are also available:
|
|
85
113
|
|
|
@@ -97,27 +125,41 @@ Direct subcommands are also available:
|
|
|
97
125
|
- `help` shows command usage.
|
|
98
126
|
- `config` shows API-key presence and API URL without displaying the API key value.
|
|
99
127
|
- `quickstart` is an alias for `config`.
|
|
100
|
-
- `status` shows
|
|
101
|
-
API URL, and active non-Firecrawl tool count.
|
|
102
|
-
- `tools` opens a width-safe selector for choosing
|
|
128
|
+
- `status` shows available and loaded capability counts, loader state, the persisted catalog,
|
|
129
|
+
settings file path, API-key presence, API URL, and active non-Firecrawl tool count.
|
|
130
|
+
- `tools` opens a width-safe immediate-save selector for choosing capabilities available to lazy-load.
|
|
103
131
|
- `toggle` is an alias for `tools`.
|
|
104
|
-
- `enable`
|
|
105
|
-
- `disable`
|
|
106
|
-
available.
|
|
132
|
+
- `enable` makes all five API capabilities available but leaves newly available definitions deferred.
|
|
133
|
+
- `disable` makes all five API capabilities unavailable and unloads affected active definitions.
|
|
134
|
+
The slash command and `firecrawl_load` remain available.
|
|
135
|
+
|
|
136
|
+
The menu, `tools`, `help`, `config`, `quickstart`, and `status` routes require TUI or RPC mode so their
|
|
137
|
+
results are observable.
|
|
138
|
+
|
|
139
|
+
Print and JSON modes reject those routes and unknown commands explicitly instead of entering
|
|
140
|
+
unavailable UI or silently notifying a no-op channel.
|
|
141
|
+
|
|
142
|
+
The deterministic `enable` and `disable` routes remain available in every mode.
|
|
143
|
+
|
|
144
|
+
Tool-selector toggles save immediately in user action order.
|
|
145
|
+
|
|
146
|
+
Done, Escape, or cancellation closes the selector without undoing changes that were already saved.
|
|
107
147
|
|
|
108
|
-
The
|
|
148
|
+
The available capability names are saved to:
|
|
109
149
|
|
|
110
150
|
```text
|
|
111
151
|
${PI_CODING_AGENT_DIR:-~/.pi/agent}/pi-firecrawl.json
|
|
112
152
|
```
|
|
113
153
|
|
|
114
|
-
When the file is missing or invalid, the extension preserves Pi's current
|
|
115
|
-
instead of
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
154
|
+
When the file is missing or invalid, the extension preserves Pi's current Firecrawl availability
|
|
155
|
+
policy instead of replacing it. An unsaved catalog remains stable across runtime reloads. A valid
|
|
156
|
+
saved catalog is restored on Pi startup and `/reload`, while its capability definitions remain
|
|
157
|
+
deferred. A missing file is created by the first successful
|
|
158
|
+
availability change. Within one Pi process, catalog saves run in invocation order, reread the latest
|
|
159
|
+
valid document, and preserve unknown fields. Malformed JSON or invalid recognized fields block the
|
|
160
|
+
save without replacement; a failed save restores both the prior availability and loaded capability
|
|
161
|
+
state while preserving other extensions' active tools. The settings file stores only tool names and
|
|
162
|
+
a timestamp; it never stores `FIRECRAWL_API_KEY`, request headers, or other secrets.
|
|
121
163
|
|
|
122
164
|
Compatibility: older versions used `pi-firecrawl-settings.json`. A legacy-only file remains
|
|
123
165
|
readable with a warning and is never modified automatically; rename it to `pi-firecrawl.json`.
|
|
@@ -168,11 +210,12 @@ Start a crawl with markdown extraction:
|
|
|
168
210
|
## 🗂️ Package layout
|
|
169
211
|
|
|
170
212
|
```txt
|
|
171
|
-
|
|
213
|
+
packages/pi-firecrawl/
|
|
172
214
|
├── src/
|
|
173
|
-
│ ├── index.ts
|
|
174
|
-
│ ├── firecrawl.ts
|
|
175
|
-
│
|
|
215
|
+
│ ├── index.ts # Pi package entrypoint
|
|
216
|
+
│ ├── firecrawl.ts # Extension registration and command orchestration
|
|
217
|
+
│ ├── lazy-tools.ts # Deferred capability catalog and loader tool
|
|
218
|
+
│ └── *.ts # Package-local client, settings, selector, and tool modules
|
|
176
219
|
├── README.md
|
|
177
220
|
├── LICENSE
|
|
178
221
|
├── tsconfig.json
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-firecrawl",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.50.0",
|
|
4
4
|
"description": "Pi extension that exposes Firecrawl web scraping and crawling tools.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,6 +23,9 @@
|
|
|
23
23
|
"./src/index.ts"
|
|
24
24
|
]
|
|
25
25
|
},
|
|
26
|
+
"piExtension": {
|
|
27
|
+
"lifecycle": "stable"
|
|
28
|
+
},
|
|
26
29
|
"scripts": {
|
|
27
30
|
"check": "biome check . && npm run typecheck",
|
|
28
31
|
"format": "biome check --write .",
|
|
@@ -33,9 +36,9 @@
|
|
|
33
36
|
"typebox": "*"
|
|
34
37
|
},
|
|
35
38
|
"devDependencies": {
|
|
36
|
-
"@biomejs/biome": "2.5.
|
|
37
|
-
"@earendil-works/pi-coding-agent": "0.
|
|
38
|
-
"typebox": "1.3.
|
|
39
|
+
"@biomejs/biome": "2.5.7",
|
|
40
|
+
"@earendil-works/pi-coding-agent": "0.84.1",
|
|
41
|
+
"typebox": "1.3.11",
|
|
39
42
|
"typescript": "7.0.2"
|
|
40
43
|
},
|
|
41
44
|
"dependencies": {
|
|
@@ -44,6 +47,6 @@
|
|
|
44
47
|
"repository": {
|
|
45
48
|
"type": "git",
|
|
46
49
|
"url": "https://github.com/narumiruna/pi-extensions",
|
|
47
|
-
"directory": "
|
|
50
|
+
"directory": "packages/pi-firecrawl"
|
|
48
51
|
}
|
|
49
52
|
}
|
package/src/firecrawl.ts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { hasApiKey } from "./client.js";
|
|
3
|
+
import {
|
|
4
|
+
availableFirecrawlTools,
|
|
5
|
+
configureLazyFirecrawlTools,
|
|
6
|
+
createFirecrawlLoadTool,
|
|
7
|
+
initializeAvailableFirecrawlTools,
|
|
8
|
+
loadedFirecrawlToolsFromBranch,
|
|
9
|
+
} from "./lazy-tools.js";
|
|
3
10
|
import { cleanupResponseArtifacts, openResponseArtifacts } from "./response-format.js";
|
|
4
11
|
import { loadSettings } from "./settings.js";
|
|
5
12
|
import {
|
|
6
13
|
advanceFirecrawlSessionGeneration,
|
|
7
14
|
allFirecrawlTools,
|
|
8
|
-
applyFirecrawlTools,
|
|
9
15
|
buildCommandGuide,
|
|
10
16
|
buildConfigMessage,
|
|
11
17
|
buildStatusMessage,
|
|
@@ -14,6 +20,7 @@ import {
|
|
|
14
20
|
currentFirecrawlSessionSignal,
|
|
15
21
|
isCurrentFirecrawlSession,
|
|
16
22
|
recordSettingsNotice,
|
|
23
|
+
sanitizeFirecrawlDisplay,
|
|
17
24
|
showToolSelector,
|
|
18
25
|
updateFirecrawlTools,
|
|
19
26
|
waitForFirecrawlSettings,
|
|
@@ -26,18 +33,18 @@ const COMMAND_COMPLETIONS = [
|
|
|
26
33
|
{ value: "config", label: "config", description: "Show configuration quick start" },
|
|
27
34
|
{ value: "quickstart", label: "quickstart", description: "Show configuration quick start" },
|
|
28
35
|
{ value: "status", label: "status", description: "Show tool and settings status" },
|
|
29
|
-
{ value: "tools", label: "tools", description: "
|
|
30
|
-
{ value: "toggle", label: "toggle", description: "
|
|
31
|
-
{ value: "enable", label: "enable", description: "
|
|
32
|
-
{ value: "disable", label: "disable", description: "
|
|
36
|
+
{ value: "tools", label: "tools", description: "Choose lazy-loadable Firecrawl tools" },
|
|
37
|
+
{ value: "toggle", label: "toggle", description: "Choose lazy-loadable Firecrawl tools" },
|
|
38
|
+
{ value: "enable", label: "enable", description: "Make all Firecrawl tools available" },
|
|
39
|
+
{ value: "disable", label: "disable", description: "Make all Firecrawl tools unavailable" },
|
|
33
40
|
];
|
|
34
41
|
const MENU_OPTIONS = {
|
|
35
42
|
config: "Configuration quick start",
|
|
36
43
|
help: "Command usage guide",
|
|
37
44
|
status: "Show tool status",
|
|
38
|
-
tools: "
|
|
39
|
-
enable: "
|
|
40
|
-
disable: "
|
|
45
|
+
tools: "Choose available Firecrawl tools",
|
|
46
|
+
enable: "Make all Firecrawl tools available",
|
|
47
|
+
disable: "Make all Firecrawl tools unavailable",
|
|
41
48
|
} as const;
|
|
42
49
|
type CommandAction =
|
|
43
50
|
| "menu"
|
|
@@ -55,11 +62,13 @@ export default function firecrawl(pi: ExtensionAPI) {
|
|
|
55
62
|
pi.registerTool(crawlStatusTool);
|
|
56
63
|
pi.registerTool(mapTool);
|
|
57
64
|
pi.registerTool(searchTool);
|
|
65
|
+
pi.registerTool(createFirecrawlLoadTool(pi));
|
|
58
66
|
|
|
59
67
|
pi.registerCommand("firecrawl", {
|
|
60
68
|
description: "Open Firecrawl help and tool controls",
|
|
61
69
|
getArgumentCompletions: (prefix) => commandCompletions(prefix),
|
|
62
70
|
handler: async (args, ctx) => {
|
|
71
|
+
initializeAvailableFirecrawlTools(pi, ctx.sessionManager);
|
|
63
72
|
const generation = currentFirecrawlSessionGeneration();
|
|
64
73
|
await handleFirecrawlCommand(pi, args, ctx, generation);
|
|
65
74
|
},
|
|
@@ -67,19 +76,26 @@ export default function firecrawl(pi: ExtensionAPI) {
|
|
|
67
76
|
|
|
68
77
|
pi.on("session_start", async (_event, ctx) => {
|
|
69
78
|
const generation = advanceFirecrawlSessionGeneration();
|
|
79
|
+
initializeAvailableFirecrawlTools(pi, ctx.sessionManager);
|
|
70
80
|
openResponseArtifacts(ctx.sessionManager);
|
|
71
81
|
clearSettingsNotice();
|
|
72
82
|
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
73
83
|
const settings = await loadSettings();
|
|
74
84
|
if (!isCurrentFirecrawlSession(generation)) return;
|
|
75
85
|
recordSettingsNotice(settings);
|
|
76
|
-
if (settings.notice) ctx.ui.notify(settings.notice, "warning");
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
86
|
+
if (settings.notice) ctx.ui.notify(sanitizeFirecrawlDisplay(settings.notice), "warning");
|
|
87
|
+
const availableTools =
|
|
88
|
+
settings.kind === "loaded" ? settings.settings.tools : availableFirecrawlTools(pi);
|
|
89
|
+
const loadedTools = loadedFirecrawlToolsFromBranch(
|
|
90
|
+
ctx.sessionManager.getBranch(),
|
|
91
|
+
availableTools,
|
|
92
|
+
);
|
|
93
|
+
configureLazyFirecrawlTools(pi, availableTools, loadedTools, ctx.sessionManager);
|
|
81
94
|
if (settings.kind === "invalid") {
|
|
82
|
-
ctx.ui.notify(
|
|
95
|
+
ctx.ui.notify(
|
|
96
|
+
sanitizeFirecrawlDisplay(`Firecrawl settings ignored: ${settings.reason}`),
|
|
97
|
+
"warning",
|
|
98
|
+
);
|
|
83
99
|
}
|
|
84
100
|
});
|
|
85
101
|
|
|
@@ -104,39 +120,46 @@ async function handleFirecrawlCommand(
|
|
|
104
120
|
await showMenu(pi, ctx, generation);
|
|
105
121
|
return;
|
|
106
122
|
case "help":
|
|
123
|
+
requireObservableUi(ctx, "help");
|
|
107
124
|
ctx.ui.notify(buildCommandGuide(), "info");
|
|
108
125
|
return;
|
|
109
126
|
case "config":
|
|
110
127
|
case "quickstart":
|
|
128
|
+
requireObservableUi(ctx, command);
|
|
111
129
|
ctx.ui.notify(buildConfigMessage(), hasApiKey() ? "info" : "warning");
|
|
112
130
|
return;
|
|
113
131
|
case "status": {
|
|
132
|
+
requireObservableUi(ctx, "status");
|
|
114
133
|
const status = await buildStatusMessage(pi);
|
|
115
134
|
if (!isCurrentFirecrawlSession(generation)) return;
|
|
116
135
|
ctx.ui.notify(status, hasApiKey() ? "info" : "warning");
|
|
117
136
|
return;
|
|
118
137
|
}
|
|
119
138
|
case "tools":
|
|
139
|
+
requireObservableUi(ctx, "tools");
|
|
120
140
|
await showToolSelector(pi, ctx);
|
|
121
141
|
return;
|
|
122
142
|
case "enable":
|
|
123
|
-
await updateFirecrawlTools(pi, ctx, allFirecrawlTools(), "
|
|
143
|
+
await updateFirecrawlTools(pi, ctx, allFirecrawlTools(), "made all available");
|
|
124
144
|
return;
|
|
125
145
|
case "disable":
|
|
126
|
-
await updateFirecrawlTools(pi, ctx, [], "
|
|
146
|
+
await updateFirecrawlTools(pi, ctx, [], "made all unavailable");
|
|
127
147
|
return;
|
|
128
148
|
}
|
|
129
149
|
|
|
130
|
-
ctx.
|
|
150
|
+
if (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc")) {
|
|
151
|
+
throw new Error(sanitizeFirecrawlDisplay(`Unknown /firecrawl command: ${args.trim()}`));
|
|
152
|
+
}
|
|
153
|
+
ctx.ui.notify(
|
|
154
|
+
sanitizeFirecrawlDisplay(
|
|
155
|
+
`Unknown /firecrawl command: ${args.trim()}\n\n${buildCommandGuide()}`,
|
|
156
|
+
),
|
|
157
|
+
"warning",
|
|
158
|
+
);
|
|
131
159
|
}
|
|
132
160
|
|
|
133
161
|
async function showMenu(pi: ExtensionAPI, ctx: CommandContext, generation: number) {
|
|
134
|
-
|
|
135
|
-
const status = await buildStatusMessage(pi);
|
|
136
|
-
if (!isCurrentFirecrawlSession(generation)) return;
|
|
137
|
-
ctx.ui.notify(`${buildCommandGuide()}\n\n${status}`, hasApiKey() ? "info" : "warning");
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
162
|
+
requireObservableUi(ctx, "menu");
|
|
140
163
|
const menuSignal = currentFirecrawlSessionSignal();
|
|
141
164
|
const isCurrent = () => isCurrentFirecrawlSession(generation) && !menuSignal.aborted;
|
|
142
165
|
const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
|
|
@@ -150,6 +173,7 @@ async function showMenu(pi: ExtensionAPI, ctx: CommandContext, generation: numbe
|
|
|
150
173
|
main: () => ({
|
|
151
174
|
kind: "actions",
|
|
152
175
|
title: "Firecrawl",
|
|
176
|
+
lines: mainMenuLines(pi),
|
|
153
177
|
items: Object.entries(MENU_OPTIONS).map(([id, label]) => ({
|
|
154
178
|
id,
|
|
155
179
|
label,
|
|
@@ -179,11 +203,11 @@ async function showMenu(pi: ExtensionAPI, ctx: CommandContext, generation: numbe
|
|
|
179
203
|
return { kind: "close" };
|
|
180
204
|
},
|
|
181
205
|
enable: async () => {
|
|
182
|
-
await updateFirecrawlTools(pi, ctx, allFirecrawlTools(), "
|
|
206
|
+
await updateFirecrawlTools(pi, ctx, allFirecrawlTools(), "made all available");
|
|
183
207
|
return { kind: "close" };
|
|
184
208
|
},
|
|
185
209
|
disable: async () => {
|
|
186
|
-
await updateFirecrawlTools(pi, ctx, [], "
|
|
210
|
+
await updateFirecrawlTools(pi, ctx, [], "made all unavailable");
|
|
187
211
|
return { kind: "close" };
|
|
188
212
|
},
|
|
189
213
|
},
|
|
@@ -195,6 +219,23 @@ async function showMenu(pi: ExtensionAPI, ctx: CommandContext, generation: numbe
|
|
|
195
219
|
});
|
|
196
220
|
}
|
|
197
221
|
|
|
222
|
+
function mainMenuLines(pi: ExtensionAPI) {
|
|
223
|
+
const active = new Set(pi.getActiveTools());
|
|
224
|
+
const capabilityNames = allFirecrawlTools();
|
|
225
|
+
const loadedCount = capabilityNames.filter((name) => active.has(name)).length;
|
|
226
|
+
return [
|
|
227
|
+
`Lazy catalog: ${availableFirecrawlTools(pi).length}/${capabilityNames.length} available`,
|
|
228
|
+
`Loaded this session: ${loadedCount}/${capabilityNames.length}`,
|
|
229
|
+
`API key: ${hasApiKey() ? "present" : "missing"}`,
|
|
230
|
+
];
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function requireObservableUi(ctx: CommandContext, route: string) {
|
|
234
|
+
if (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc")) {
|
|
235
|
+
throw new Error(`/firecrawl ${route} requires TUI or RPC mode`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
198
239
|
export function parseCommand(args: string): CommandAction | "unknown" {
|
|
199
240
|
const command = args.trim().toLowerCase();
|
|
200
241
|
if (!command) return "menu";
|
|
@@ -228,4 +269,8 @@ export {
|
|
|
228
269
|
} from "./client.js";
|
|
229
270
|
export { cleanupResponseArtifacts } from "./response-format.js";
|
|
230
271
|
export { normalizeFirecrawlSettings } from "./settings.js";
|
|
231
|
-
export {
|
|
272
|
+
export {
|
|
273
|
+
formatPersistedSelection,
|
|
274
|
+
orderedFirecrawlTools,
|
|
275
|
+
sanitizeFirecrawlDisplay,
|
|
276
|
+
} from "./tool-selector.js";
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tool-names.js";
|
|
4
|
+
|
|
5
|
+
export const FIRECRAWL_LOAD_TOOL_NAME = "firecrawl_load";
|
|
6
|
+
|
|
7
|
+
const AVAILABLE_TOOLS_STORE = Symbol.for("@narumitw/pi-firecrawl.available-tools-store");
|
|
8
|
+
const SESSION_AVAILABLE_TOOLS_STORE = Symbol.for(
|
|
9
|
+
"@narumitw/pi-firecrawl.session-available-tools-store",
|
|
10
|
+
);
|
|
11
|
+
type FirecrawlGlobal = typeof globalThis & {
|
|
12
|
+
[AVAILABLE_TOOLS_STORE]?: WeakMap<ExtensionAPI, Set<FirecrawlToolName>>;
|
|
13
|
+
[SESSION_AVAILABLE_TOOLS_STORE]?: WeakMap<object, Set<FirecrawlToolName>>;
|
|
14
|
+
};
|
|
15
|
+
const sharedGlobal = globalThis as FirecrawlGlobal;
|
|
16
|
+
const existingAvailableToolsStore = sharedGlobal[AVAILABLE_TOOLS_STORE];
|
|
17
|
+
const availableToolsByApi =
|
|
18
|
+
existingAvailableToolsStore ?? new WeakMap<ExtensionAPI, Set<FirecrawlToolName>>();
|
|
19
|
+
if (!existingAvailableToolsStore) sharedGlobal[AVAILABLE_TOOLS_STORE] = availableToolsByApi;
|
|
20
|
+
const existingSessionAvailableToolsStore = sharedGlobal[SESSION_AVAILABLE_TOOLS_STORE];
|
|
21
|
+
const availableToolsBySession =
|
|
22
|
+
existingSessionAvailableToolsStore ?? new WeakMap<object, Set<FirecrawlToolName>>();
|
|
23
|
+
if (!existingSessionAvailableToolsStore) {
|
|
24
|
+
sharedGlobal[SESSION_AVAILABLE_TOOLS_STORE] = availableToolsBySession;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const CRAWL_CREATION_TERMS = new Set(["begin", "create", "launch", "start"]);
|
|
28
|
+
|
|
29
|
+
const SEARCH_TEXT: Record<FirecrawlToolName, string> = {
|
|
30
|
+
firecrawl_scrape:
|
|
31
|
+
"scrape scraping extract extraction single url page pages markdown html raw links screenshot json structured content",
|
|
32
|
+
firecrawl_crawl: "crawl crawling website site start pages depth paths sitemap batch",
|
|
33
|
+
firecrawl_crawl_status:
|
|
34
|
+
"crawl crawling status job monitor check retrieve completed progress results",
|
|
35
|
+
firecrawl_map: "map mapping discover discovery url urls links sitemap site inventory",
|
|
36
|
+
firecrawl_search:
|
|
37
|
+
"search searching web internet query results research discover discovery optionally scrape",
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export function initializeAvailableFirecrawlTools(pi: ExtensionAPI, sessionOwner?: object) {
|
|
41
|
+
if (sessionOwner) {
|
|
42
|
+
const sessionTools = availableToolsBySession.get(sessionOwner);
|
|
43
|
+
if (sessionTools) {
|
|
44
|
+
setAvailableTools(pi, sessionTools, sessionOwner);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const apiTools = availableToolsByApi.get(pi);
|
|
49
|
+
if (apiTools) {
|
|
50
|
+
if (sessionOwner) setAvailableTools(pi, apiTools, sessionOwner);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const activeTools = new Set(pi.getActiveTools());
|
|
54
|
+
setAvailableTools(
|
|
55
|
+
pi,
|
|
56
|
+
FIRECRAWL_TOOL_NAMES.filter((name) => activeTools.has(name)),
|
|
57
|
+
sessionOwner,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function configureLazyFirecrawlTools(
|
|
62
|
+
pi: ExtensionAPI,
|
|
63
|
+
availableTools: readonly FirecrawlToolName[],
|
|
64
|
+
loadedTools: readonly FirecrawlToolName[] = [],
|
|
65
|
+
sessionOwner?: object,
|
|
66
|
+
) {
|
|
67
|
+
const available = setAvailableTools(pi, availableTools, sessionOwner);
|
|
68
|
+
const loaded = new Set(loadedTools);
|
|
69
|
+
const restoredTools = FIRECRAWL_TOOL_NAMES.filter(
|
|
70
|
+
(name) => available.has(name) && loaded.has(name),
|
|
71
|
+
);
|
|
72
|
+
const nonCapabilityTools = pi
|
|
73
|
+
.getActiveTools()
|
|
74
|
+
.filter((name) => !FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName));
|
|
75
|
+
pi.setActiveTools(unique([...nonCapabilityTools, FIRECRAWL_LOAD_TOOL_NAME, ...restoredTools]));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function applyAvailableFirecrawlTools(
|
|
79
|
+
pi: ExtensionAPI,
|
|
80
|
+
availableTools: readonly FirecrawlToolName[],
|
|
81
|
+
sessionOwner?: object,
|
|
82
|
+
) {
|
|
83
|
+
const available = setAvailableTools(pi, availableTools, sessionOwner);
|
|
84
|
+
const active = pi
|
|
85
|
+
.getActiveTools()
|
|
86
|
+
.filter(
|
|
87
|
+
(name) =>
|
|
88
|
+
!FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName) ||
|
|
89
|
+
available.has(name as FirecrawlToolName),
|
|
90
|
+
);
|
|
91
|
+
pi.setActiveTools(unique([...active, FIRECRAWL_LOAD_TOOL_NAME]));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function availableFirecrawlTools(pi: ExtensionAPI) {
|
|
95
|
+
const available = availableToolsByApi.get(pi) ?? new Set();
|
|
96
|
+
return FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function createFirecrawlLoadTool(pi: ExtensionAPI) {
|
|
100
|
+
return defineTool({
|
|
101
|
+
name: FIRECRAWL_LOAD_TOOL_NAME,
|
|
102
|
+
label: "Firecrawl: Load Tools",
|
|
103
|
+
description:
|
|
104
|
+
"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.",
|
|
105
|
+
promptSnippet: "Load Firecrawl web research capabilities on demand",
|
|
106
|
+
promptGuidelines: [
|
|
107
|
+
"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.",
|
|
108
|
+
"If FIRECRAWL_API_KEY is missing, report the configuration error instead of retrying repeatedly.",
|
|
109
|
+
],
|
|
110
|
+
parameters: Type.Object({
|
|
111
|
+
query: Type.String({
|
|
112
|
+
description: "Firecrawl capability or web research task to find tools for.",
|
|
113
|
+
maxLength: 500,
|
|
114
|
+
}),
|
|
115
|
+
limit: Type.Optional(
|
|
116
|
+
Type.Integer({
|
|
117
|
+
description: "Maximum tools to load. Defaults to 3.",
|
|
118
|
+
minimum: 1,
|
|
119
|
+
maximum: 5,
|
|
120
|
+
}),
|
|
121
|
+
),
|
|
122
|
+
}),
|
|
123
|
+
async execute(_toolCallId, params, signal) {
|
|
124
|
+
signal?.throwIfAborted();
|
|
125
|
+
const available = new Set(availableFirecrawlTools(pi));
|
|
126
|
+
const matches = matchFirecrawlTools(params.query, params.limit ?? 3, available);
|
|
127
|
+
const active = pi.getActiveTools();
|
|
128
|
+
const activeSet = new Set(active);
|
|
129
|
+
const added = matches.filter((name) => !activeSet.has(name));
|
|
130
|
+
if (added.length > 0) pi.setActiveTools(unique([...active, ...added]));
|
|
131
|
+
|
|
132
|
+
const text =
|
|
133
|
+
matches.length === 0
|
|
134
|
+
? "No available Firecrawl tools matched the query."
|
|
135
|
+
: added.length > 0
|
|
136
|
+
? `Loaded Firecrawl tools: ${added.join(", ")}`
|
|
137
|
+
: `Matching Firecrawl tools are already loaded: ${matches.join(", ")}`;
|
|
138
|
+
return {
|
|
139
|
+
content: [{ type: "text" as const, text }],
|
|
140
|
+
details: { matches, added },
|
|
141
|
+
};
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function matchFirecrawlTools(
|
|
147
|
+
query: string,
|
|
148
|
+
limit: number,
|
|
149
|
+
available: ReadonlySet<FirecrawlToolName>,
|
|
150
|
+
) {
|
|
151
|
+
const terms = [
|
|
152
|
+
...new Set(
|
|
153
|
+
query
|
|
154
|
+
.toLowerCase()
|
|
155
|
+
.split(/[^a-z0-9]+/)
|
|
156
|
+
.filter((term) => term.length >= 2),
|
|
157
|
+
),
|
|
158
|
+
];
|
|
159
|
+
if (terms.length === 0) return [];
|
|
160
|
+
const ranked = FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name))
|
|
161
|
+
.map((name, index) => ({
|
|
162
|
+
name,
|
|
163
|
+
index,
|
|
164
|
+
score: terms.reduce(
|
|
165
|
+
(score, term) => score + (SEARCH_TEXT[name].split(" ").includes(term) ? 1 : 0),
|
|
166
|
+
0,
|
|
167
|
+
),
|
|
168
|
+
}))
|
|
169
|
+
.filter((match) => match.score > 0)
|
|
170
|
+
.sort((left, right) => right.score - left.score || left.index - right.index);
|
|
171
|
+
const bestScore = ranked[0]?.score;
|
|
172
|
+
if (bestScore === undefined) return [];
|
|
173
|
+
const matches = ranked
|
|
174
|
+
.filter((match) => match.score === bestScore)
|
|
175
|
+
.slice(0, limit)
|
|
176
|
+
.map((match) => match.name);
|
|
177
|
+
if (
|
|
178
|
+
matches.includes("firecrawl_crawl") &&
|
|
179
|
+
available.has("firecrawl_crawl_status") &&
|
|
180
|
+
!matches.includes("firecrawl_crawl_status") &&
|
|
181
|
+
matches.length < limit
|
|
182
|
+
) {
|
|
183
|
+
matches.push("firecrawl_crawl_status");
|
|
184
|
+
}
|
|
185
|
+
if (
|
|
186
|
+
matches.includes("firecrawl_crawl_status") &&
|
|
187
|
+
available.has("firecrawl_crawl") &&
|
|
188
|
+
!matches.includes("firecrawl_crawl") &&
|
|
189
|
+
terms.some((term) => CRAWL_CREATION_TERMS.has(term)) &&
|
|
190
|
+
matches.length < limit
|
|
191
|
+
) {
|
|
192
|
+
matches.unshift("firecrawl_crawl");
|
|
193
|
+
}
|
|
194
|
+
return matches;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function loadedFirecrawlToolsFromBranch(
|
|
198
|
+
entries: readonly unknown[],
|
|
199
|
+
availableTools: readonly FirecrawlToolName[],
|
|
200
|
+
) {
|
|
201
|
+
const available = new Set(availableTools);
|
|
202
|
+
const loaded = new Set<FirecrawlToolName>();
|
|
203
|
+
for (const entry of entries) {
|
|
204
|
+
if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) continue;
|
|
205
|
+
const message = entry.message;
|
|
206
|
+
if (
|
|
207
|
+
message.role !== "toolResult" ||
|
|
208
|
+
message.toolName !== FIRECRAWL_LOAD_TOOL_NAME ||
|
|
209
|
+
message.isError === true
|
|
210
|
+
) {
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const details = isRecord(message.details) ? message.details : undefined;
|
|
214
|
+
const recordedNames = [
|
|
215
|
+
...(Array.isArray(message.addedToolNames) ? message.addedToolNames : []),
|
|
216
|
+
...(details && Array.isArray(details.added) ? details.added : []),
|
|
217
|
+
];
|
|
218
|
+
for (const name of recordedNames) {
|
|
219
|
+
if (isFirecrawlToolName(name) && available.has(name)) loaded.add(name);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return FIRECRAWL_TOOL_NAMES.filter((name) => loaded.has(name));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function setAvailableTools(
|
|
226
|
+
pi: ExtensionAPI,
|
|
227
|
+
availableTools: readonly FirecrawlToolName[] | ReadonlySet<FirecrawlToolName>,
|
|
228
|
+
sessionOwner?: object,
|
|
229
|
+
) {
|
|
230
|
+
const available = new Set(availableTools);
|
|
231
|
+
availableToolsByApi.set(pi, available);
|
|
232
|
+
if (sessionOwner) availableToolsBySession.set(sessionOwner, new Set(available));
|
|
233
|
+
return available;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function isFirecrawlToolName(value: unknown): value is FirecrawlToolName {
|
|
237
|
+
return typeof value === "string" && FIRECRAWL_TOOL_NAMES.includes(value as FirecrawlToolName);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
241
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function unique(values: readonly string[]) {
|
|
245
|
+
return [...new Set(values)];
|
|
246
|
+
}
|
package/src/settings.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { constants } from "node:fs";
|
|
|
3
3
|
import { access, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
-
import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./
|
|
6
|
+
import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tool-names.js";
|
|
7
7
|
|
|
8
8
|
const NEW_SETTINGS_FILE = "pi-firecrawl.json";
|
|
9
9
|
const LEGACY_SETTINGS_FILE = "pi-firecrawl-settings.json";
|
|
@@ -119,7 +119,9 @@ async function pathEntryExists(filePath: string) {
|
|
|
119
119
|
export function normalizeFirecrawlSettings(value: unknown): FirecrawlSettings | undefined {
|
|
120
120
|
if (!value || typeof value !== "object") return undefined;
|
|
121
121
|
const settings = value as { tools?: unknown; updatedAt?: unknown };
|
|
122
|
-
if (typeof settings.updatedAt !== "number")
|
|
122
|
+
if (typeof settings.updatedAt !== "number" || !Number.isFinite(settings.updatedAt)) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
123
125
|
if (!Array.isArray(settings.tools)) return undefined;
|
|
124
126
|
if (!settings.tools.every(isFirecrawlToolName)) return undefined;
|
|
125
127
|
return { tools: orderedUniqueFirecrawlTools(settings.tools), updatedAt: settings.updatedAt };
|
|
@@ -140,7 +142,11 @@ export function saveSettings(
|
|
|
140
142
|
settings: FirecrawlSettings,
|
|
141
143
|
operations: Partial<SettingsFileOperations> = {},
|
|
142
144
|
): Promise<void> {
|
|
143
|
-
const
|
|
145
|
+
const normalizedSettings = normalizeFirecrawlSettings(settings);
|
|
146
|
+
if (!normalizedSettings) {
|
|
147
|
+
return Promise.reject(new Error("Cannot save invalid Firecrawl settings"));
|
|
148
|
+
}
|
|
149
|
+
const operation = settingsSaveQueue.then(() => saveSettingsNow(normalizedSettings, operations));
|
|
144
150
|
settingsSaveQueue = operation.catch(() => undefined);
|
|
145
151
|
return operation;
|
|
146
152
|
}
|
package/src/tool-selector.ts
CHANGED
|
@@ -1,23 +1,32 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from "node:util";
|
|
1
2
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
3
|
import { configuredApiUrl, hasApiKey } from "./client.js";
|
|
4
|
+
import {
|
|
5
|
+
applyAvailableFirecrawlTools,
|
|
6
|
+
availableFirecrawlTools,
|
|
7
|
+
FIRECRAWL_LOAD_TOOL_NAME,
|
|
8
|
+
} from "./lazy-tools.js";
|
|
3
9
|
import {
|
|
4
10
|
loadSettings,
|
|
5
11
|
type SettingsLoadResult,
|
|
6
12
|
saveSettings,
|
|
7
13
|
settingsFilePath,
|
|
8
14
|
} from "./settings.js";
|
|
9
|
-
import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./
|
|
15
|
+
import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tool-names.js";
|
|
10
16
|
|
|
11
17
|
type CommandContext = ExtensionCommandContext;
|
|
12
|
-
type
|
|
18
|
+
type ToolAvailabilityStatus = "enabled" | "disabled" | "partial";
|
|
13
19
|
type ToolSelectorScreen = "tools";
|
|
14
20
|
type ToolSelectorAction = "toggle" | "enableAll" | "disableAll";
|
|
15
21
|
interface ToolStatusSummary {
|
|
16
|
-
|
|
17
|
-
|
|
22
|
+
availabilityStatus: ToolAvailabilityStatus;
|
|
23
|
+
availableFirecrawlToolCount: number;
|
|
24
|
+
loadedFirecrawlToolCount: number;
|
|
18
25
|
activeNonFirecrawlToolCount: number;
|
|
19
26
|
}
|
|
20
27
|
|
|
28
|
+
type ToolSelectionSaveResult = "saved" | "available-tools-changed" | "failed";
|
|
29
|
+
|
|
21
30
|
let settingsNotice: string | undefined;
|
|
22
31
|
let sessionGeneration = 0;
|
|
23
32
|
let sessionController = new AbortController();
|
|
@@ -45,12 +54,14 @@ export function clearSettingsNotice() {
|
|
|
45
54
|
}
|
|
46
55
|
|
|
47
56
|
export function recordSettingsNotice(settings: SettingsLoadResult) {
|
|
48
|
-
|
|
57
|
+
settingsNotice = settings.notice;
|
|
49
58
|
}
|
|
50
59
|
|
|
51
60
|
export async function showToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
|
|
52
61
|
const generation = sessionGeneration;
|
|
53
|
-
if (!ctx.hasUI)
|
|
62
|
+
if (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc")) {
|
|
63
|
+
throw new Error("/firecrawl tools requires TUI or RPC mode");
|
|
64
|
+
}
|
|
54
65
|
const menuSignal = sessionController.signal;
|
|
55
66
|
const isCurrent = () => isCurrentFirecrawlSession(generation) && !menuSignal.aborted;
|
|
56
67
|
const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
|
|
@@ -59,7 +70,7 @@ export async function showToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
|
|
|
59
70
|
start: "tools",
|
|
60
71
|
screens: {
|
|
61
72
|
tools: () => {
|
|
62
|
-
const selectedTools = new Set(
|
|
73
|
+
const selectedTools = new Set(availableFirecrawlTools(pi));
|
|
63
74
|
return {
|
|
64
75
|
kind: "multiSelect",
|
|
65
76
|
title: toolSelectorTitle(selectedTools),
|
|
@@ -72,12 +83,12 @@ export async function showToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
|
|
|
72
83
|
actions: [
|
|
73
84
|
{
|
|
74
85
|
id: "enable-all",
|
|
75
|
-
label: "
|
|
86
|
+
label: "Make all Firecrawl tools available",
|
|
76
87
|
action: "enableAll",
|
|
77
88
|
},
|
|
78
89
|
{
|
|
79
90
|
id: "disable-all",
|
|
80
|
-
label: "
|
|
91
|
+
label: "Make all Firecrawl tools unavailable",
|
|
81
92
|
action: "disableAll",
|
|
82
93
|
},
|
|
83
94
|
{ id: "done", label: "Done", close: true },
|
|
@@ -90,24 +101,34 @@ export async function showToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
|
|
|
90
101
|
actions: {
|
|
91
102
|
toggle: async ({ itemId, selected }) => {
|
|
92
103
|
if (!isFirecrawlToolName(itemId)) return { kind: "rejected" };
|
|
93
|
-
const
|
|
104
|
+
const acceptedTools = availableFirecrawlTools(pi);
|
|
105
|
+
const selectedTools = new Set(acceptedTools);
|
|
94
106
|
if (selected) selectedTools.add(itemId);
|
|
95
107
|
else selectedTools.delete(itemId);
|
|
96
|
-
const
|
|
108
|
+
const result = await transactSelectedTools(
|
|
97
109
|
pi,
|
|
98
110
|
ctx,
|
|
99
111
|
orderedFirecrawlTools(selectedTools),
|
|
100
112
|
generation,
|
|
113
|
+
acceptedTools,
|
|
101
114
|
);
|
|
102
|
-
return saved ? { kind: "stay" } : { kind: "rejected" };
|
|
115
|
+
return result === "saved" ? { kind: "stay" } : { kind: "rejected" };
|
|
103
116
|
},
|
|
104
117
|
enableAll: async () => {
|
|
105
|
-
const
|
|
106
|
-
|
|
118
|
+
const acceptedTools = availableFirecrawlTools(pi);
|
|
119
|
+
const result = await transactSelectedTools(
|
|
120
|
+
pi,
|
|
121
|
+
ctx,
|
|
122
|
+
allFirecrawlTools(),
|
|
123
|
+
generation,
|
|
124
|
+
acceptedTools,
|
|
125
|
+
);
|
|
126
|
+
return result === "saved" ? { kind: "stay" } : { kind: "rejected" };
|
|
107
127
|
},
|
|
108
128
|
disableAll: async () => {
|
|
109
|
-
const
|
|
110
|
-
|
|
129
|
+
const acceptedTools = availableFirecrawlTools(pi);
|
|
130
|
+
const result = await transactSelectedTools(pi, ctx, [], generation, acceptedTools);
|
|
131
|
+
return result === "saved" ? { kind: "stay" } : { kind: "rejected" };
|
|
111
132
|
},
|
|
112
133
|
},
|
|
113
134
|
});
|
|
@@ -129,11 +150,14 @@ export async function updateFirecrawlTools(
|
|
|
129
150
|
action: string,
|
|
130
151
|
) {
|
|
131
152
|
const generation = sessionGeneration;
|
|
132
|
-
const
|
|
133
|
-
if (
|
|
153
|
+
const result = await transactSelectedTools(pi, ctx, selectedTools, generation);
|
|
154
|
+
if (result !== "saved" || !isCurrentFirecrawlSession(generation)) return;
|
|
134
155
|
const status = await buildStatusMessage(pi);
|
|
135
156
|
if (!isCurrentFirecrawlSession(generation)) return;
|
|
136
|
-
ctx.ui.notify(
|
|
157
|
+
ctx.ui.notify(
|
|
158
|
+
sanitizeFirecrawlDisplay(`Firecrawl lazy catalog ${action}.\n\n${status}`),
|
|
159
|
+
hasApiKey() ? "info" : "warning",
|
|
160
|
+
);
|
|
137
161
|
}
|
|
138
162
|
|
|
139
163
|
export async function setSelectedFirecrawlTools(
|
|
@@ -141,7 +165,7 @@ export async function setSelectedFirecrawlTools(
|
|
|
141
165
|
ctx: CommandContext,
|
|
142
166
|
selectedTools: readonly FirecrawlToolName[],
|
|
143
167
|
): Promise<boolean> {
|
|
144
|
-
return transactSelectedTools(pi, ctx, selectedTools, sessionGeneration);
|
|
168
|
+
return (await transactSelectedTools(pi, ctx, selectedTools, sessionGeneration)) === "saved";
|
|
145
169
|
}
|
|
146
170
|
|
|
147
171
|
let toolTransactionQueue = Promise.resolve();
|
|
@@ -155,9 +179,10 @@ function transactSelectedTools(
|
|
|
155
179
|
ctx: CommandContext,
|
|
156
180
|
selectedTools: readonly FirecrawlToolName[],
|
|
157
181
|
expectedGeneration: number,
|
|
158
|
-
|
|
182
|
+
expectedAvailableTools?: readonly FirecrawlToolName[],
|
|
183
|
+
): Promise<ToolSelectionSaveResult> {
|
|
159
184
|
const operation = toolTransactionQueue.then(() =>
|
|
160
|
-
transactSelectedToolsNow(pi, ctx, selectedTools, expectedGeneration),
|
|
185
|
+
transactSelectedToolsNow(pi, ctx, selectedTools, expectedGeneration, expectedAvailableTools),
|
|
161
186
|
);
|
|
162
187
|
toolTransactionQueue = operation.then(
|
|
163
188
|
() => undefined,
|
|
@@ -171,84 +196,118 @@ async function transactSelectedToolsNow(
|
|
|
171
196
|
ctx: CommandContext,
|
|
172
197
|
selectedTools: readonly FirecrawlToolName[],
|
|
173
198
|
expectedGeneration: number,
|
|
174
|
-
|
|
175
|
-
|
|
199
|
+
expectedAvailableTools?: readonly FirecrawlToolName[],
|
|
200
|
+
): Promise<ToolSelectionSaveResult> {
|
|
201
|
+
if (!isCurrentFirecrawlSession(expectedGeneration)) return "failed";
|
|
202
|
+
if (expectedAvailableTools && !arraysEqual(availableFirecrawlTools(pi), expectedAvailableTools)) {
|
|
203
|
+
ctx.ui.notify(
|
|
204
|
+
"Firecrawl tool availability changed while the selector was open. Review the current state and try again.",
|
|
205
|
+
"warning",
|
|
206
|
+
);
|
|
207
|
+
return "available-tools-changed";
|
|
208
|
+
}
|
|
176
209
|
const previousActiveTools = pi.getActiveTools();
|
|
210
|
+
const previousAvailableTools = availableFirecrawlTools(pi);
|
|
177
211
|
try {
|
|
178
|
-
applyFirecrawlTools(pi, selectedTools);
|
|
212
|
+
applyFirecrawlTools(pi, selectedTools, ctx.sessionManager);
|
|
179
213
|
await persistSettings(selectedTools);
|
|
180
|
-
return isCurrentFirecrawlSession(expectedGeneration);
|
|
214
|
+
return isCurrentFirecrawlSession(expectedGeneration) ? "saved" : "failed";
|
|
181
215
|
} catch (error) {
|
|
182
216
|
let rollbackError: unknown;
|
|
183
217
|
try {
|
|
184
|
-
|
|
218
|
+
applyAvailableFirecrawlTools(pi, previousAvailableTools, ctx.sessionManager);
|
|
219
|
+
const currentNonCapabilityTools = pi
|
|
220
|
+
.getActiveTools()
|
|
221
|
+
.filter((name) => !FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName));
|
|
222
|
+
const previousLoadedTools = previousActiveTools.filter((name) =>
|
|
185
223
|
FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName),
|
|
186
|
-
)
|
|
187
|
-
|
|
224
|
+
);
|
|
225
|
+
pi.setActiveTools(unique([...currentNonCapabilityTools, ...previousLoadedTools]));
|
|
188
226
|
} catch (caught) {
|
|
189
227
|
rollbackError = caught;
|
|
190
228
|
}
|
|
191
|
-
if (!isCurrentFirecrawlSession(expectedGeneration)) return
|
|
229
|
+
if (!isCurrentFirecrawlSession(expectedGeneration)) return "failed";
|
|
192
230
|
ctx.ui.notify(
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
231
|
+
sanitizeFirecrawlDisplay(
|
|
232
|
+
rollbackError
|
|
233
|
+
? `Firecrawl settings save failed: ${formatError(error)}; active-tool rollback failed: ${formatError(rollbackError)}`
|
|
234
|
+
: `Firecrawl settings save failed; active tools restored: ${formatError(error)}`,
|
|
235
|
+
),
|
|
196
236
|
"warning",
|
|
197
237
|
);
|
|
198
|
-
return
|
|
238
|
+
return "failed";
|
|
199
239
|
}
|
|
200
240
|
}
|
|
201
241
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
242
|
+
function arraysEqual<T>(left: readonly T[], right: readonly T[]) {
|
|
243
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function applyFirecrawlTools(
|
|
247
|
+
pi: ExtensionAPI,
|
|
248
|
+
selectedTools: readonly FirecrawlToolName[],
|
|
249
|
+
sessionOwner?: object,
|
|
250
|
+
) {
|
|
251
|
+
applyAvailableFirecrawlTools(pi, selectedTools, sessionOwner);
|
|
209
252
|
}
|
|
210
253
|
|
|
211
254
|
function getToolStatusSummary(pi: ExtensionAPI): ToolStatusSummary {
|
|
212
255
|
const firecrawlToolNames = new Set<string>(FIRECRAWL_TOOL_NAMES);
|
|
213
256
|
const activeToolNames = new Set(pi.getActiveTools());
|
|
214
|
-
const
|
|
257
|
+
const loadedFirecrawlToolCount = FIRECRAWL_TOOL_NAMES.filter((name) =>
|
|
215
258
|
activeToolNames.has(name),
|
|
216
259
|
).length;
|
|
260
|
+
const availableFirecrawlToolCount = availableFirecrawlTools(pi).length;
|
|
217
261
|
const activeNonFirecrawlToolCount = Array.from(activeToolNames).filter(
|
|
218
|
-
(name) => !firecrawlToolNames.has(name),
|
|
262
|
+
(name) => !firecrawlToolNames.has(name) && name !== FIRECRAWL_LOAD_TOOL_NAME,
|
|
219
263
|
).length;
|
|
220
|
-
const
|
|
221
|
-
|
|
264
|
+
const availabilityStatus =
|
|
265
|
+
availableFirecrawlToolCount === FIRECRAWL_TOOL_NAMES.length
|
|
222
266
|
? "enabled"
|
|
223
|
-
:
|
|
267
|
+
: availableFirecrawlToolCount === 0
|
|
224
268
|
? "disabled"
|
|
225
269
|
: "partial";
|
|
226
270
|
|
|
227
|
-
return {
|
|
271
|
+
return {
|
|
272
|
+
availabilityStatus,
|
|
273
|
+
availableFirecrawlToolCount,
|
|
274
|
+
loadedFirecrawlToolCount,
|
|
275
|
+
activeNonFirecrawlToolCount,
|
|
276
|
+
};
|
|
228
277
|
}
|
|
229
278
|
|
|
230
279
|
export async function buildStatusMessage(pi: ExtensionAPI) {
|
|
280
|
+
const generation = sessionGeneration;
|
|
281
|
+
const settings = await loadSettings();
|
|
282
|
+
if (!isCurrentFirecrawlSession(generation)) return "";
|
|
283
|
+
recordSettingsNotice(settings);
|
|
231
284
|
const summary = getToolStatusSummary(pi);
|
|
232
|
-
const persistedSetting =
|
|
233
|
-
return
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
285
|
+
const persistedSetting = persistedSettingLabel(settings);
|
|
286
|
+
return sanitizeFirecrawlDisplay(
|
|
287
|
+
[
|
|
288
|
+
`Firecrawl tools available to lazy-load: ${formatRuntimeStatus(summary)}`,
|
|
289
|
+
`Loaded capability tools this session: ${summary.loadedFirecrawlToolCount}/${FIRECRAWL_TOOL_NAMES.length}`,
|
|
290
|
+
`Loader: ${pi.getActiveTools().includes(FIRECRAWL_LOAD_TOOL_NAME) ? "active" : "inactive"}`,
|
|
291
|
+
`Persisted lazy catalog: ${persistedSetting}`,
|
|
292
|
+
`Settings file: ${settingsFilePath()}`,
|
|
293
|
+
...(settingsNotice ? [`Settings note: ${settingsNotice}`] : []),
|
|
294
|
+
`Other active tools preserved: ${summary.activeNonFirecrawlToolCount}`,
|
|
295
|
+
`API key: ${hasApiKey() ? "present" : "missing"} (FIRECRAWL_API_KEY)`,
|
|
296
|
+
`API URL: ${configuredApiUrl()}`,
|
|
297
|
+
].join("\n"),
|
|
298
|
+
);
|
|
242
299
|
}
|
|
243
300
|
|
|
244
301
|
export function buildConfigMessage() {
|
|
245
|
-
return
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
302
|
+
return sanitizeFirecrawlDisplay(
|
|
303
|
+
[
|
|
304
|
+
"Firecrawl configuration:",
|
|
305
|
+
`API key: ${hasApiKey() ? "present" : "missing"} (FIRECRAWL_API_KEY)`,
|
|
306
|
+
`API URL: ${configuredApiUrl()}`,
|
|
307
|
+
"Override API URL with FIRECRAWL_API_URL or FIRECRAWL_BASE_URL.",
|
|
308
|
+
"This extension never logs, displays, or stores your Firecrawl API key.",
|
|
309
|
+
].join("\n"),
|
|
310
|
+
);
|
|
252
311
|
}
|
|
253
312
|
|
|
254
313
|
export function buildCommandGuide() {
|
|
@@ -259,26 +318,21 @@ export function buildCommandGuide() {
|
|
|
259
318
|
"/firecrawl config — show API key presence and API URL",
|
|
260
319
|
"/firecrawl quickstart — alias for /firecrawl config",
|
|
261
320
|
"/firecrawl status — show tool and settings status",
|
|
262
|
-
"/firecrawl tools —
|
|
321
|
+
"/firecrawl tools — choose tools available to lazy-load",
|
|
263
322
|
"/firecrawl toggle — alias for /firecrawl tools",
|
|
264
|
-
"/firecrawl enable —
|
|
265
|
-
"/firecrawl disable —
|
|
323
|
+
"/firecrawl enable — make all Firecrawl tools available to lazy-load",
|
|
324
|
+
"/firecrawl disable — make all Firecrawl capability tools unavailable",
|
|
266
325
|
].join("\n");
|
|
267
326
|
}
|
|
268
327
|
|
|
269
328
|
function toolSelectorTitle(selectedTools: ReadonlySet<FirecrawlToolName>) {
|
|
270
|
-
return `Firecrawl tools (${selectedTools.size}/${FIRECRAWL_TOOL_NAMES.length}). Non-built-in tools run at user risk.`;
|
|
329
|
+
return `Firecrawl tools available to lazy-load (${selectedTools.size}/${FIRECRAWL_TOOL_NAMES.length}). Non-built-in tools run at user risk.`;
|
|
271
330
|
}
|
|
272
331
|
|
|
273
332
|
function isFirecrawlToolName(value: string): value is FirecrawlToolName {
|
|
274
333
|
return FIRECRAWL_TOOL_NAMES.includes(value as FirecrawlToolName);
|
|
275
334
|
}
|
|
276
335
|
|
|
277
|
-
function getActiveFirecrawlTools(pi: ExtensionAPI) {
|
|
278
|
-
const activeToolNames = new Set(pi.getActiveTools());
|
|
279
|
-
return FIRECRAWL_TOOL_NAMES.filter((toolName) => activeToolNames.has(toolName));
|
|
280
|
-
}
|
|
281
|
-
|
|
282
336
|
export function allFirecrawlTools() {
|
|
283
337
|
return [...FIRECRAWL_TOOL_NAMES];
|
|
284
338
|
}
|
|
@@ -292,27 +346,40 @@ export function orderedFirecrawlTools(selectedTools: ReadonlySet<FirecrawlToolNa
|
|
|
292
346
|
}
|
|
293
347
|
|
|
294
348
|
function formatRuntimeStatus(summary: ToolStatusSummary) {
|
|
295
|
-
return `${summary.
|
|
349
|
+
return `${summary.availabilityStatus} (${summary.availableFirecrawlToolCount}/${FIRECRAWL_TOOL_NAMES.length} available)`;
|
|
296
350
|
}
|
|
297
351
|
|
|
298
|
-
|
|
299
|
-
const settings = await loadSettings();
|
|
300
|
-
recordSettingsNotice(settings);
|
|
352
|
+
function persistedSettingLabel(settings: SettingsLoadResult) {
|
|
301
353
|
if (settings.kind === "loaded") return formatPersistedSelection(settings.settings.tools);
|
|
302
354
|
if (settings.kind === "invalid") {
|
|
303
|
-
return `none; current
|
|
355
|
+
return `none; current availability policy preserved (invalid settings ignored: ${settings.reason})`;
|
|
304
356
|
}
|
|
305
|
-
return "none; current
|
|
357
|
+
return "none; current availability policy preserved";
|
|
306
358
|
}
|
|
307
359
|
|
|
308
360
|
export function formatPersistedSelection(tools: readonly FirecrawlToolName[]) {
|
|
309
361
|
if (tools.length === FIRECRAWL_TOOL_NAMES.length) {
|
|
310
|
-
return `all
|
|
362
|
+
return `all available (${tools.length}/${FIRECRAWL_TOOL_NAMES.length} selected)`;
|
|
311
363
|
}
|
|
312
|
-
if (tools.length === 0) return `all
|
|
364
|
+
if (tools.length === 0) return `all unavailable (0/${FIRECRAWL_TOOL_NAMES.length} selected)`;
|
|
313
365
|
return `${tools.length}/${FIRECRAWL_TOOL_NAMES.length} selected: ${tools.join(", ")}`;
|
|
314
366
|
}
|
|
315
367
|
|
|
368
|
+
export function sanitizeFirecrawlDisplay(value: string, maxCharacters = 50_000) {
|
|
369
|
+
const characters = Array.from(stripVTControlCharacters(value), (character) => {
|
|
370
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
371
|
+
const unsafeControl =
|
|
372
|
+
(codePoint >= 0 && codePoint <= 8) ||
|
|
373
|
+
(codePoint >= 11 && codePoint <= 31) ||
|
|
374
|
+
(codePoint >= 127 && codePoint <= 159);
|
|
375
|
+
return unsafeControl ? "�" : character;
|
|
376
|
+
});
|
|
377
|
+
const limit = Number.isFinite(maxCharacters) ? Math.max(0, Math.floor(maxCharacters)) : 0;
|
|
378
|
+
if (characters.length <= limit) return characters.join("");
|
|
379
|
+
if (limit === 0) return "";
|
|
380
|
+
return `${characters.slice(0, limit - 1).join("")}…`;
|
|
381
|
+
}
|
|
382
|
+
|
|
316
383
|
function formatError(error: unknown) {
|
|
317
384
|
return error instanceof Error ? error.message : String(error);
|
|
318
385
|
}
|
package/src/tools.ts
CHANGED
|
@@ -6,15 +6,7 @@ import {
|
|
|
6
6
|
} from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { Type } from "typebox";
|
|
8
8
|
import { cleanObject, firecrawlRequest, jsonResult, withStatus } from "./client.js";
|
|
9
|
-
|
|
10
|
-
export const FIRECRAWL_TOOL_NAMES = [
|
|
11
|
-
"firecrawl_scrape",
|
|
12
|
-
"firecrawl_crawl",
|
|
13
|
-
"firecrawl_crawl_status",
|
|
14
|
-
"firecrawl_map",
|
|
15
|
-
"firecrawl_search",
|
|
16
|
-
] as const;
|
|
17
|
-
export type FirecrawlToolName = (typeof FIRECRAWL_TOOL_NAMES)[number];
|
|
9
|
+
import { FIRECRAWL_TOOL_NAMES } from "./tool-names.js";
|
|
18
10
|
|
|
19
11
|
const StringArray = Type.Array(Type.String());
|
|
20
12
|
const OUTPUT_LIMIT_DESCRIPTION = `Output is truncated to ${DEFAULT_MAX_LINES} lines or ${formatSize(DEFAULT_MAX_BYTES)}; complete truncated responses are saved temporarily and their path is returned.`;
|
|
@@ -23,11 +15,6 @@ export const scrapeTool = defineTool({
|
|
|
23
15
|
name: FIRECRAWL_TOOL_NAMES[0],
|
|
24
16
|
label: "Firecrawl: Scrape",
|
|
25
17
|
description: `Scrape a single URL through Firecrawl and return requested formats. ${OUTPUT_LIMIT_DESCRIPTION}`,
|
|
26
|
-
promptSnippet: "Scrape a URL through Firecrawl",
|
|
27
|
-
promptGuidelines: [
|
|
28
|
-
"Use firecrawl_scrape when you need clean markdown, HTML, links, screenshots, or structured extraction for one URL.",
|
|
29
|
-
"If FIRECRAWL_API_KEY is missing, report the configuration error instead of retrying repeatedly.",
|
|
30
|
-
],
|
|
31
18
|
parameters: Type.Object({
|
|
32
19
|
url: Type.String({ description: "URL to scrape." }),
|
|
33
20
|
formats: Type.Optional(
|
|
@@ -91,7 +78,6 @@ export const crawlTool = defineTool({
|
|
|
91
78
|
name: FIRECRAWL_TOOL_NAMES[1],
|
|
92
79
|
label: "Firecrawl: Crawl",
|
|
93
80
|
description: `Start a Firecrawl crawl job for a website. ${OUTPUT_LIMIT_DESCRIPTION}`,
|
|
94
|
-
promptSnippet: "Start a Firecrawl site crawl job",
|
|
95
81
|
parameters: Type.Object({
|
|
96
82
|
url: Type.String({ description: "Starting URL for the crawl." }),
|
|
97
83
|
limit: Type.Optional(Type.Number({ description: "Maximum number of pages to crawl." })),
|
|
@@ -135,7 +121,6 @@ export const crawlStatusTool = defineTool({
|
|
|
135
121
|
name: FIRECRAWL_TOOL_NAMES[2],
|
|
136
122
|
label: "Firecrawl: Crawl Status",
|
|
137
123
|
description: `Check a Firecrawl crawl job status and retrieve completed crawl data. ${OUTPUT_LIMIT_DESCRIPTION}`,
|
|
138
|
-
promptSnippet: "Check a Firecrawl crawl job status",
|
|
139
124
|
parameters: Type.Object({
|
|
140
125
|
id: Type.String({ description: "Crawl job id returned by firecrawl_crawl." }),
|
|
141
126
|
}),
|
|
@@ -157,7 +142,6 @@ export const mapTool = defineTool({
|
|
|
157
142
|
name: FIRECRAWL_TOOL_NAMES[3],
|
|
158
143
|
label: "Firecrawl: Map",
|
|
159
144
|
description: `Discover URLs for a site through Firecrawl's map endpoint. ${OUTPUT_LIMIT_DESCRIPTION}`,
|
|
160
|
-
promptSnippet: "Map/discover URLs for a site through Firecrawl",
|
|
161
145
|
parameters: Type.Object({
|
|
162
146
|
url: Type.String({ description: "Website URL to map." }),
|
|
163
147
|
search: Type.Optional(
|
|
@@ -190,7 +174,6 @@ export const searchTool = defineTool({
|
|
|
190
174
|
name: FIRECRAWL_TOOL_NAMES[4],
|
|
191
175
|
label: "Firecrawl: Search",
|
|
192
176
|
description: `Search the web through Firecrawl and optionally scrape search results. ${OUTPUT_LIMIT_DESCRIPTION}`,
|
|
193
|
-
promptSnippet: "Search the web through Firecrawl",
|
|
194
177
|
parameters: Type.Object({
|
|
195
178
|
query: Type.String({ description: "Search query." }),
|
|
196
179
|
limit: Type.Optional(Type.Number({ description: "Maximum number of search results." })),
|