@narumitw/pi-firecrawl 0.50.5 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lazy-tools.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  import { defineTool, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
+ import { DEFAULT_TOOL_MODE, type FirecrawlToolMode } from "./settings.js";
3
4
  import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tool-names.js";
5
+ import { crawlStatusTool, crawlTool, mapTool, scrapeTool, searchTool } from "./tools.js";
4
6
 
5
7
  export const FIRECRAWL_LOAD_TOOL_NAME = "firecrawl_load";
6
8
 
7
9
  const AVAILABLE_TOOLS_STORE = Symbol.for("@narumitw/pi-firecrawl.available-tools-store");
8
10
  const SESSION_AVAILABLE_TOOLS_STORE = Symbol.for("@narumitw/pi-firecrawl.session-available-tools-store");
11
+ const ACTIVATION_OWNERSHIP_STORE = Symbol.for("@narumitw/pi-firecrawl.activation-ownership-store");
12
+ type ActivationOwnership = { explicit: Set<string>; owned: Set<string> };
9
13
  type FirecrawlGlobal = typeof globalThis & {
10
14
  [AVAILABLE_TOOLS_STORE]?: WeakMap<ExtensionAPI, Set<FirecrawlToolName>>;
11
15
  [SESSION_AVAILABLE_TOOLS_STORE]?: WeakMap<object, Set<FirecrawlToolName>>;
16
+ [ACTIVATION_OWNERSHIP_STORE]?: WeakMap<object, ActivationOwnership>;
12
17
  };
13
18
  const sharedGlobal = globalThis as FirecrawlGlobal;
14
19
  const existingAvailableToolsStore = sharedGlobal[AVAILABLE_TOOLS_STORE];
@@ -19,7 +24,85 @@ const availableToolsBySession = existingSessionAvailableToolsStore ?? new WeakMa
19
24
  if (!existingSessionAvailableToolsStore) {
20
25
  sharedGlobal[SESSION_AVAILABLE_TOOLS_STORE] = availableToolsBySession;
21
26
  }
27
+ // Reload rebuilds the extension API, but keeps its public sessionManager identity.
28
+ const activationOwnershipBySession =
29
+ sharedGlobal[ACTIVATION_OWNERSHIP_STORE] ?? new WeakMap<object, ActivationOwnership>();
30
+ sharedGlobal[ACTIVATION_OWNERSHIP_STORE] = activationOwnershipBySession;
31
+ const activationOwnershipByApi = new WeakMap<ExtensionAPI, ActivationOwnership>();
32
+
33
+ function observeActivationOwnership(pi: ExtensionAPI, active: readonly string[], sessionOwner?: object) {
34
+ const ownership = (sessionOwner ? activationOwnershipBySession.get(sessionOwner) : undefined) ??
35
+ activationOwnershipByApi.get(pi) ?? {
36
+ explicit: new Set<string>(),
37
+ owned: new Set<string>(),
38
+ };
39
+ // A redundant host selection of an already-owned active name has no public signal.
40
+ // Keep known ownership rather than reclassifying carryover as explicit intent.
41
+ for (const name of active) {
42
+ if (FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName) && !ownership.owned.has(name))
43
+ ownership.explicit.add(name);
44
+ }
45
+ activationOwnershipByApi.set(pi, ownership);
46
+ if (sessionOwner) activationOwnershipBySession.set(sessionOwner, ownership);
47
+ return ownership;
48
+ }
49
+
50
+ function recordOwnedActivations(pi: ExtensionAPI, names: readonly string[]) {
51
+ const ownership = activationOwnershipByApi.get(pi);
52
+ if (!ownership) return;
53
+ for (const name of names) {
54
+ if (!ownership.explicit.has(name)) ownership.owned.add(name);
55
+ }
56
+ }
57
+
22
58
  const lazyExposureByApi = new WeakMap<ExtensionAPI, boolean>();
59
+ const modeByApi = new WeakMap<ExtensionAPI, FirecrawlToolMode>();
60
+ const exposuresByApi = new WeakMap<ExtensionAPI, Map<string, string>>();
61
+ const loaderRegistrations = new WeakSet<ExtensionAPI>();
62
+ const capabilityTools = [scrapeTool, crawlTool, crawlStatusTool, mapTool, searchTool];
63
+
64
+ export function firecrawlToolMode(pi: ExtensionAPI): FirecrawlToolMode {
65
+ return modeByApi.get(pi) ?? DEFAULT_TOOL_MODE;
66
+ }
67
+
68
+ // Factory registration is action-free. Startup applies persisted availability and mode.
69
+ export function registerFirecrawlTools(pi: ExtensionAPI) {
70
+ registerExposure(pi, FIRECRAWL_TOOL_NAMES, DEFAULT_TOOL_MODE);
71
+ }
72
+
73
+ function registerExposure(pi: ExtensionAPI, availableTools: readonly FirecrawlToolName[], mode: FirecrawlToolMode) {
74
+ const available = new Set(availableTools);
75
+ const exposures = exposuresByApi.get(pi) ?? new Map<string, string>();
76
+ exposuresByApi.set(pi, exposures);
77
+ for (const tool of capabilityTools) {
78
+ const exposure = !available.has(tool.name as FirecrawlToolName)
79
+ ? "hidden"
80
+ : mode === "codemode"
81
+ ? "codemode"
82
+ : "direct";
83
+ if (exposures.get(tool.name) === exposure) continue;
84
+ try {
85
+ pi.registerTool({ ...tool, exposure, defaultActive: false });
86
+ exposures.set(tool.name, exposure);
87
+ } catch (error) {
88
+ // Refresh may throw after replacing the registration; rollback must re-register it.
89
+ exposures.delete(tool.name);
90
+ throw error;
91
+ }
92
+ }
93
+ const loaderExposure = mode === "lazy" ? "direct" : "hidden";
94
+ if (mode !== "lazy" && !loaderRegistrations.has(pi)) return;
95
+ if (exposures.get(FIRECRAWL_LOAD_TOOL_NAME) !== loaderExposure) {
96
+ loaderRegistrations.add(pi);
97
+ try {
98
+ pi.registerTool({ ...createFirecrawlLoadTool(pi), exposure: loaderExposure, defaultActive: false });
99
+ exposures.set(FIRECRAWL_LOAD_TOOL_NAME, loaderExposure);
100
+ } catch (error) {
101
+ exposures.delete(FIRECRAWL_LOAD_TOOL_NAME);
102
+ throw error;
103
+ }
104
+ }
105
+ }
23
106
 
24
107
  const CRAWL_CREATION_TERMS = new Set(["begin", "create", "launch", "start"]);
25
108
 
@@ -45,12 +128,7 @@ export function initializeAvailableFirecrawlTools(pi: ExtensionAPI, sessionOwner
45
128
  if (sessionOwner) setAvailableTools(pi, apiTools, sessionOwner);
46
129
  return;
47
130
  }
48
- const activeTools = new Set(pi.getActiveTools());
49
- setAvailableTools(
50
- pi,
51
- FIRECRAWL_TOOL_NAMES.filter((name) => activeTools.has(name)),
52
- sessionOwner,
53
- );
131
+ setAvailableTools(pi, FIRECRAWL_TOOL_NAMES, sessionOwner);
54
132
  }
55
133
 
56
134
  export function configureFirecrawlToolExposure(
@@ -59,25 +137,48 @@ export function configureFirecrawlToolExposure(
59
137
  loadedTools: readonly FirecrawlToolName[] = [],
60
138
  sessionOwner?: object,
61
139
  model?: ExtensionContext["model"],
140
+ mode: FirecrawlToolMode = DEFAULT_TOOL_MODE,
62
141
  ) {
142
+ const previouslyActive = new Set(pi.getActiveTools());
143
+ const ownership = observeActivationOwnership(pi, [...previouslyActive], sessionOwner);
144
+ modeByApi.set(pi, mode);
145
+ registerExposure(pi, availableTools, mode);
63
146
  const available = setAvailableTools(pi, availableTools, sessionOwner);
64
- const lazyExposure = supportsNativeDeferredToolLoading(model);
147
+ const lazyExposure = mode === "lazy" && supportsNativeDeferredToolLoading(model);
65
148
  lazyExposureByApi.set(pi, lazyExposure);
66
149
  const loaded = new Set(loadedTools);
67
- const exposedTools = lazyExposure
68
- ? FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name) && loaded.has(name))
69
- : FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
70
- const nonCapabilityTools = pi
150
+ const exposedTools =
151
+ mode === "codemode"
152
+ ? []
153
+ : lazyExposure
154
+ ? FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name) && loaded.has(name))
155
+ : FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
156
+ const preservedTools = pi
71
157
  .getActiveTools()
72
- .filter((name) => !FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName));
73
- pi.setActiveTools(unique([...nonCapabilityTools, FIRECRAWL_LOAD_TOOL_NAME, ...exposedTools]));
158
+ .filter(
159
+ (name) =>
160
+ name !== FIRECRAWL_LOAD_TOOL_NAME &&
161
+ (!FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName) ||
162
+ (mode === "codemode" &&
163
+ previouslyActive.has(name) &&
164
+ !ownership.owned.has(name) &&
165
+ available.has(name as FirecrawlToolName))),
166
+ );
167
+ pi.setActiveTools(
168
+ unique([...preservedTools, ...(mode === "lazy" ? [FIRECRAWL_LOAD_TOOL_NAME] : []), ...exposedTools]),
169
+ );
170
+ if (mode === "codemode") ownership.owned.clear();
171
+ else recordOwnedActivations(pi, exposedTools);
74
172
  }
75
173
 
76
174
  export function requireEagerFirecrawlToolExposure(pi: ExtensionAPI) {
175
+ if (firecrawlToolMode(pi) !== "lazy") return;
77
176
  lazyExposureByApi.set(pi, false);
78
177
  const active = pi.getActiveTools();
79
178
  const available = availableFirecrawlTools(pi);
179
+ observeActivationOwnership(pi, active);
80
180
  pi.setActiveTools(unique([...active, FIRECRAWL_LOAD_TOOL_NAME, ...available]));
181
+ recordOwnedActivations(pi, available);
81
182
  }
82
183
 
83
184
  export function applyAvailableFirecrawlTools(
@@ -85,21 +186,35 @@ export function applyAvailableFirecrawlTools(
85
186
  availableTools: readonly FirecrawlToolName[],
86
187
  sessionOwner?: object,
87
188
  ) {
189
+ const mode = firecrawlToolMode(pi);
190
+ // Host allowlists can activate direct tools during registration despite defaultActive:false.
191
+ const previouslyActive = new Set(pi.getActiveTools());
192
+ observeActivationOwnership(pi, [...previouslyActive], sessionOwner);
193
+ registerExposure(pi, availableTools, mode);
88
194
  const available = setAvailableTools(pi, availableTools, sessionOwner);
89
195
  const lazyExposure = lazyExposureByApi.get(pi) === true;
90
196
  const active = pi
91
197
  .getActiveTools()
92
198
  .filter(
93
199
  (name) =>
94
- !FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName) ||
95
- (lazyExposure && available.has(name as FirecrawlToolName)),
200
+ (name !== FIRECRAWL_LOAD_TOOL_NAME || mode === "lazy") &&
201
+ (!FIRECRAWL_TOOL_NAMES.includes(name as FirecrawlToolName) ||
202
+ ((mode === "codemode" || lazyExposure) &&
203
+ previouslyActive.has(name) &&
204
+ available.has(name as FirecrawlToolName))),
96
205
  );
97
- const eagerTools = lazyExposure ? [] : FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
98
- pi.setActiveTools(unique([...active, FIRECRAWL_LOAD_TOOL_NAME, ...eagerTools]));
206
+ const eagerTools =
207
+ mode === "codemode" || lazyExposure ? [] : FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
208
+ pi.setActiveTools(unique([...active, ...(mode === "lazy" ? [FIRECRAWL_LOAD_TOOL_NAME] : []), ...eagerTools]));
209
+ recordOwnedActivations(pi, eagerTools);
99
210
  }
100
211
 
101
212
  export function firecrawlToolExposureMode(pi: ExtensionAPI) {
102
- return lazyExposureByApi.get(pi) === true ? "native deferred" : "eager";
213
+ return firecrawlToolMode(pi) === "codemode"
214
+ ? "codemode"
215
+ : lazyExposureByApi.get(pi) === true
216
+ ? "native deferred"
217
+ : "eager";
103
218
  }
104
219
 
105
220
  export function supportsNativeDeferredToolLoading(model: ExtensionContext["model"]): boolean {
@@ -129,6 +244,16 @@ export function supportsNativeDeferredToolLoading(model: ExtensionContext["model
129
244
  return false;
130
245
  }
131
246
 
247
+ // Restore an uncommitted policy without touching a replaced session's active tools.
248
+ // Session startup waits for the settings transaction queue before reading this store.
249
+ export function restoreAvailableFirecrawlPolicy(
250
+ pi: ExtensionAPI,
251
+ tools: readonly FirecrawlToolName[],
252
+ sessionOwner: object,
253
+ ) {
254
+ setAvailableTools(pi, tools, sessionOwner);
255
+ }
256
+
132
257
  export function availableFirecrawlTools(pi: ExtensionAPI) {
133
258
  const available = availableToolsByApi.get(pi) ?? new Set();
134
259
  return FIRECRAWL_TOOL_NAMES.filter((name) => available.has(name));
@@ -165,7 +290,11 @@ export function createFirecrawlLoadTool(pi: ExtensionAPI) {
165
290
  const active = pi.getActiveTools();
166
291
  const activeSet = new Set(active);
167
292
  const added = matches.filter((name) => !activeSet.has(name));
168
- if (added.length > 0) pi.setActiveTools(unique([...active, ...added]));
293
+ observeActivationOwnership(pi, active);
294
+ if (added.length > 0) {
295
+ pi.setActiveTools(unique([...active, ...added]));
296
+ recordOwnedActivations(pi, added);
297
+ }
169
298
 
170
299
  const text =
171
300
  matches.length === 0
@@ -0,0 +1,100 @@
1
+ import type { KeybindingsManager } from "@earendil-works/pi-coding-agent";
2
+ import { isKittyProtocolActive, Key, type KeyId, matchesKey, type TUI } from "@earendil-works/pi-tui";
3
+ import { sanitizeFirecrawlDisplay } from "./tool-selector.js";
4
+
5
+ const actions = ["tui.select.up", "tui.select.down", "tui.select.confirm", "tui.select.cancel"] as const;
6
+ type Action = (typeof actions)[number];
7
+
8
+ /** Show the first usable configured key, following the wrapper and SettingsList's input order. */
9
+ export function settingsKeyHints(keybindings: Pick<KeybindingsManager, "getKeys" | "matches">, tui: TUI): string {
10
+ const terminal = tui.terminal as typeof tui.terminal & { modifyOtherKeysActive?: boolean };
11
+ const extended = isKittyProtocolActive() || terminal.kittyProtocolActive || terminal.modifyOtherKeysActive === true;
12
+ const actionFor = (input: string): Action | undefined => {
13
+ if (matchesKey(input, Key.ctrl("c"))) return "tui.select.cancel";
14
+ if (keybindings.matches(input, "tui.select.up")) return "tui.select.up";
15
+ if (keybindings.matches(input, "tui.select.down")) return "tui.select.down";
16
+ if (keybindings.matches(input, "tui.select.confirm") || input === " ") return "tui.select.confirm";
17
+ if (keybindings.matches(input, "tui.select.cancel")) return "tui.select.cancel";
18
+ return undefined;
19
+ };
20
+ const usable = (key: string, action: Action) =>
21
+ sanitizeFirecrawlDisplay(key) === key &&
22
+ inputsFor(key, extended).some((input) => matchesKey(input, key as KeyId) && actionFor(input) === action);
23
+ const hint = (action: Action, label: string, extra: string[] = []) => {
24
+ const first = keybindings.getKeys(action).find((key) => usable(key, action));
25
+ const keys = [first, ...extra.filter((key) => usable(key, action))].filter((key): key is string => !!key);
26
+ const displayed = [...new Set(keys.map(displayKey))];
27
+ return displayed.length ? `${displayed.join("/")} ${label}` : "";
28
+ };
29
+ return [
30
+ hint("tui.select.up", "up"),
31
+ hint("tui.select.down", "down"),
32
+ hint("tui.select.confirm", "change", ["space"]),
33
+ hint("tui.select.cancel", "close", ["ctrl+c"]),
34
+ "Changes save immediately.",
35
+ ]
36
+ .filter(Boolean)
37
+ .join(" · ");
38
+ }
39
+
40
+ function displayKey(key: string): string {
41
+ const parts = key.toLowerCase().split("+");
42
+ const base = parts.pop() ?? "";
43
+ const modifiers = [...new Set(parts.filter((part) => ["shift", "ctrl", "alt", "super"].includes(part)))];
44
+ const aliases: Record<string, string> = { up: "↑", down: "↓", escape: "esc", esc: "esc", return: "enter" };
45
+ return [...modifiers, aliases[base] ?? base].join("+");
46
+ }
47
+
48
+ function inputsFor(key: string, extended: boolean): string[] {
49
+ const parts = key.toLowerCase().split("+");
50
+ const base = parts.pop() ?? "";
51
+ const masks: Record<string, number> = { shift: 1, alt: 2, ctrl: 4, super: 8 };
52
+ const modifier = parts.reduce((mask, part) => mask | (masks[part] ?? 0), 0) + 1;
53
+ const codepoint = codepoints[base] ?? (base.length === 1 ? base.charCodeAt(0) : undefined);
54
+ // Ask Pi's live matcher rather than inferring aliases, legacy collisions, or modifier support.
55
+ // CSI-u and modifyOtherKeys are only candidates when the terminal supports disambiguation.
56
+ return extended && codepoint !== undefined
57
+ ? [...legacyInputs, `\x1b[${codepoint};${modifier}u`, `\x1b[27;${modifier};${codepoint}~`]
58
+ : legacyInputs;
59
+ }
60
+
61
+ const codepoints: Record<string, number> = {
62
+ escape: 27,
63
+ esc: 27,
64
+ enter: 13,
65
+ return: 13,
66
+ tab: 9,
67
+ space: 32,
68
+ backspace: 127,
69
+ left: 57417,
70
+ right: 57418,
71
+ up: 57419,
72
+ down: 57420,
73
+ pageup: 57421,
74
+ pagedown: 57422,
75
+ home: 57423,
76
+ end: 57424,
77
+ insert: 57425,
78
+ delete: 57426,
79
+ };
80
+ // Cover ASCII/Ctrl/Alt legacy identities, arrows, functional keys, and xterm modifiers.
81
+ // Lock bits and keypad/shifted identities have the same normalized action as these probes.
82
+ const legacyInputs = [
83
+ ...Array.from({ length: 128 }, (_, code) => String.fromCharCode(code)),
84
+ ...Array.from({ length: 128 }, (_, code) => `\x1b${String.fromCharCode(code)}`),
85
+ "\x1b[Z",
86
+ "\x1bOM",
87
+ "\x1b[E",
88
+ "\x1b[e",
89
+ "\x1bOe",
90
+ ...["OP", "OQ", "OR", "OS", "OH", "OF"].map((suffix) => `\x1b${suffix}`),
91
+ ...[1, 2, 3, 4, 5, 6, 7, 8, 15, 17, 18, 19, 20, 21, 23, 24].flatMap((code) => [
92
+ `\x1b[${code}~`,
93
+ ...Array.from({ length: 16 }, (_, modifier) => `\x1b[${code};${modifier + 1}~`),
94
+ ]),
95
+ ...["A", "B", "C", "D", "E", "H", "F"].flatMap((suffix) => [
96
+ `\x1b[${suffix}`,
97
+ `\x1bO${suffix}`,
98
+ ...Array.from({ length: 16 }, (_, modifier) => `\x1b[1;${modifier + 1}${suffix}`),
99
+ ]),
100
+ ];
@@ -0,0 +1,186 @@
1
+ import { type ExtensionAPI, type ExtensionCommandContext, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Key,
4
+ matchesKey,
5
+ type SettingItem,
6
+ SettingsList,
7
+ type TuiMouseEvent,
8
+ truncateToWidth,
9
+ } from "@earendil-works/pi-tui";
10
+ import { availableFirecrawlTools, firecrawlToolMode } from "./lazy-tools.js";
11
+ import {
12
+ DEFAULT_TOOL_MODE,
13
+ FIRECRAWL_TOOL_MODES,
14
+ isFirecrawlToolMode,
15
+ loadSettings,
16
+ settingsFilePath,
17
+ } from "./settings.js";
18
+ import { settingsKeyHints } from "./settings-key-hints.js";
19
+ import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tool-names.js";
20
+ import {
21
+ currentFirecrawlSessionGeneration,
22
+ currentFirecrawlSessionSignal,
23
+ isCurrentFirecrawlSession,
24
+ sanitizeFirecrawlDisplay,
25
+ setFirecrawlCapabilityEnabled,
26
+ setFirecrawlToolMode,
27
+ waitForFirecrawlSettings,
28
+ } from "./tool-selector.js";
29
+
30
+ export async function showFirecrawlSettings(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
31
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
32
+ if (ctx.mode === "rpc" && ctx.hasUI) {
33
+ ctx.ui.notify(
34
+ sanitizeFirecrawlDisplay(
35
+ `Edit Firecrawl settings: ${settingsFilePath()}\nSet toolMode to codemode, lazy, or direct; run /reload to apply manual edits.`,
36
+ ),
37
+ "info",
38
+ );
39
+ return;
40
+ }
41
+ throw new Error("/firecrawl settings requires TUI or RPC mode");
42
+ }
43
+ const generation = currentFirecrawlSessionGeneration(pi);
44
+ const sessionSignal = currentFirecrawlSessionSignal(pi);
45
+ const isCurrent = () => isCurrentFirecrawlSession(pi, generation) && !sessionSignal.aborted;
46
+ await waitForFirecrawlSettings();
47
+ if (!isCurrent()) return;
48
+ const settings = await loadSettings();
49
+ if (!isCurrent()) return;
50
+ if (settings.kind === "invalid") {
51
+ ctx.ui.notify(
52
+ sanitizeFirecrawlDisplay(`Firecrawl settings ignored: ${settings.reason}; repair the file before saving.`),
53
+ "warning",
54
+ );
55
+ }
56
+ let savedMode = settings.kind === "loaded" ? (settings.settings.toolMode ?? DEFAULT_TOOL_MODE) : DEFAULT_TOOL_MODE;
57
+ let drain = Promise.resolve();
58
+ let disposeComponent = () => {};
59
+ try {
60
+ await ctx.ui.custom<void>((tui, theme, keybindings, done) => {
61
+ if (!isCurrent()) {
62
+ done(undefined);
63
+ return { render: () => [], invalidate() {} };
64
+ }
65
+ const controller = new AbortController();
66
+ let pending = 0;
67
+ let queue = Promise.resolve();
68
+ let listOffset = 2;
69
+ let listHeight = 0;
70
+ const live = () => isCurrent() && !controller.signal.aborted;
71
+ const dispose = () => {
72
+ controller.abort();
73
+ sessionSignal.removeEventListener("abort", close);
74
+ };
75
+ const close = () => {
76
+ if (controller.signal.aborted) return;
77
+ dispose();
78
+ done(undefined);
79
+ };
80
+ disposeComponent = dispose;
81
+ const selected = new Set(availableFirecrawlTools(pi));
82
+ const items: SettingItem[] = [
83
+ {
84
+ id: "toolMode",
85
+ label: "Tool mode",
86
+ description:
87
+ "Codemode: five callable tools, no loader. Lazy: loader first (eager on unsupported models). Direct: five declared tools. Saved immediately; applies after /reload.",
88
+ currentValue: savedMode,
89
+ values: [...FIRECRAWL_TOOL_MODES],
90
+ },
91
+ ...FIRECRAWL_TOOL_NAMES.map((name) => ({
92
+ id: name,
93
+ label: name,
94
+ description:
95
+ "Allow this capability. Changes apply and save immediately; closing does not undo saved changes.",
96
+ currentValue: selected.has(name) ? "enabled" : "disabled",
97
+ values: ["enabled", "disabled"],
98
+ })),
99
+ ];
100
+ const list = new SettingsList(
101
+ items,
102
+ items.length,
103
+ {
104
+ ...getSettingsListTheme(),
105
+ description: (text) => theme.fg("muted", text),
106
+ // Six fixed, non-searchable rows have only the stock control hint, not scroll/result hints.
107
+ hint: () => theme.fg("muted", settingsKeyHints(keybindings, tui)),
108
+ },
109
+ (id, value) => {
110
+ if (!live()) return;
111
+ pending += 1;
112
+ // Register persistence at acceptance so replacement/shutdown can await it, even
113
+ // before this screen's observer queue runs. Only runtime/UI work is session-owned.
114
+ const modeEdit = id === "toolMode" && isFirecrawlToolMode(value);
115
+ const save = modeEdit
116
+ ? setFirecrawlToolMode(pi, ctx, value, sessionSignal)
117
+ : FIRECRAWL_TOOL_NAMES.includes(id as FirecrawlToolName)
118
+ ? setFirecrawlCapabilityEnabled(pi, ctx, id as FirecrawlToolName, value === "enabled", sessionSignal)
119
+ : undefined;
120
+ queue = queue
121
+ .then(async () => {
122
+ if (save && (await save) && isCurrent() && modeEdit && isFirecrawlToolMode(value)) savedMode = value;
123
+ })
124
+ .catch((error: unknown) => {
125
+ if (isCurrent())
126
+ ctx.ui.notify(sanitizeFirecrawlDisplay(`Firecrawl settings failed: ${String(error)}`), "warning");
127
+ })
128
+ .finally(() => {
129
+ pending -= 1;
130
+ if (!live()) return;
131
+ if (pending === 0) {
132
+ list.updateValue("toolMode", savedMode);
133
+ const available = new Set(availableFirecrawlTools(pi));
134
+ for (const name of FIRECRAWL_TOOL_NAMES)
135
+ list.updateValue(name, available.has(name) ? "enabled" : "disabled");
136
+ }
137
+ tui.requestRender();
138
+ });
139
+ drain = queue;
140
+ },
141
+ close,
142
+ );
143
+ // Six bounded rows need no search input; SettingsList owns navigation and value cycling.
144
+ // Submitted settings changes drain in order even after close; disposal releases UI ownership.
145
+ // Session replacement suppresses stale runtime/UI work, not accepted persistence.
146
+ sessionSignal.addEventListener("abort", close, { once: true });
147
+ return {
148
+ render(width: number) {
149
+ const heading = theme.fg("accent", theme.bold("Firecrawl Settings"));
150
+ const mode = `Running: ${firecrawlToolMode(pi)}; saved: ${savedMode}${savedMode !== firecrawlToolMode(pi) ? " — /reload required" : ""}`;
151
+ const listLines = list.render(Math.max(width, 5));
152
+ // Mouse coordinates must follow the last rendered layout, not unpainted pending state.
153
+ listOffset = pending > 0 ? 3 : 2;
154
+ listHeight = listLines.length;
155
+ return [
156
+ heading,
157
+ theme.fg("muted", mode),
158
+ ...(pending > 0 ? [theme.fg("muted", "Saving changes…")] : []),
159
+ ...listLines,
160
+ ].map((line) => truncateToWidth(line, width));
161
+ },
162
+ invalidate() {
163
+ list.invalidate();
164
+ },
165
+ handleInput(data: string) {
166
+ if (!live()) return;
167
+ if (matchesKey(data, Key.ctrl("c"))) close();
168
+ else list.handleInput(data);
169
+ if (live()) tui.requestRender();
170
+ },
171
+ handleMouse(event: TuiMouseEvent) {
172
+ if (!live() || event.y < listOffset || event.y >= listOffset + listHeight) return undefined;
173
+ const result = list.handleMouse({ ...event, y: event.y - listOffset, height: listHeight });
174
+ if (live() && result && result.render !== false) tui.requestRender();
175
+ return result;
176
+ },
177
+ dispose,
178
+ waitForPending: () => queue,
179
+ };
180
+ });
181
+ } finally {
182
+ // Release UI ownership even when the custom host fails; submitted saves still drain.
183
+ disposeComponent();
184
+ await drain;
185
+ }
186
+ }
package/src/settings.ts CHANGED
@@ -8,7 +8,16 @@ import { FIRECRAWL_TOOL_NAMES, type FirecrawlToolName } from "./tool-names.js";
8
8
  const NEW_SETTINGS_FILE = "pi-firecrawl.json";
9
9
  const LEGACY_SETTINGS_FILE = "pi-firecrawl-settings.json";
10
10
 
11
+ export const FIRECRAWL_TOOL_MODES = ["codemode", "lazy", "direct"] as const;
12
+ export type FirecrawlToolMode = (typeof FIRECRAWL_TOOL_MODES)[number];
13
+ export const DEFAULT_TOOL_MODE: FirecrawlToolMode = "codemode";
14
+
15
+ export function isFirecrawlToolMode(value: unknown): value is FirecrawlToolMode {
16
+ return FIRECRAWL_TOOL_MODES.includes(value as FirecrawlToolMode);
17
+ }
18
+
11
19
  export interface FirecrawlSettings {
20
+ toolMode?: FirecrawlToolMode;
12
21
  tools: FirecrawlToolName[];
13
22
  updatedAt: number;
14
23
  }
@@ -77,7 +86,7 @@ async function readSettingsDocument(filePath: string): Promise<SettingsDocumentR
77
86
  return {
78
87
  result: {
79
88
  kind: "invalid",
80
- reason: `${filePath}: expected tools to be an array of Firecrawl tool names`,
89
+ reason: `${filePath}: expected valid tools, a finite updatedAt, and toolMode (codemode, lazy, or direct) when present`,
81
90
  },
82
91
  };
83
92
  } catch (error) {
@@ -117,14 +126,19 @@ async function pathEntryExists(filePath: string) {
117
126
  }
118
127
 
119
128
  export function normalizeFirecrawlSettings(value: unknown): FirecrawlSettings | undefined {
120
- if (!value || typeof value !== "object") return undefined;
121
- const settings = value as { tools?: unknown; updatedAt?: unknown };
129
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
130
+ const settings = value as { tools?: unknown; updatedAt?: unknown; toolMode?: unknown };
131
+ if (settings.toolMode !== undefined && !isFirecrawlToolMode(settings.toolMode)) return undefined;
122
132
  if (typeof settings.updatedAt !== "number" || !Number.isFinite(settings.updatedAt)) {
123
133
  return undefined;
124
134
  }
125
135
  if (!Array.isArray(settings.tools)) return undefined;
126
136
  if (!settings.tools.every(isFirecrawlToolName)) return undefined;
127
- return { tools: orderedUniqueFirecrawlTools(settings.tools), updatedAt: settings.updatedAt };
137
+ return {
138
+ toolMode: settings.toolMode ?? DEFAULT_TOOL_MODE,
139
+ tools: orderedUniqueFirecrawlTools(settings.tools),
140
+ updatedAt: settings.updatedAt,
141
+ };
128
142
  }
129
143
 
130
144
  function isFirecrawlToolName(value: unknown): value is FirecrawlToolName {
@@ -146,26 +160,52 @@ export function saveSettings(
146
160
  if (!normalizedSettings) {
147
161
  return Promise.reject(new Error("Cannot save invalid Firecrawl settings"));
148
162
  }
149
- const operation = settingsSaveQueue.then(() => saveSettingsNow(normalizedSettings, operations));
163
+ return queueSettingsSave({ ...normalizedSettings, toolMode: settings.toolMode }, operations);
164
+ }
165
+
166
+ export function saveToolMode(
167
+ toolMode: FirecrawlToolMode,
168
+ fallbackTools: readonly FirecrawlToolName[],
169
+ operations: Partial<SettingsFileOperations> = {},
170
+ ): Promise<void> {
171
+ if (!isFirecrawlToolMode(toolMode) || !fallbackTools.every(isFirecrawlToolName)) {
172
+ return Promise.reject(new Error("Cannot save invalid Firecrawl settings"));
173
+ }
174
+ return queueSettingsSave({ toolMode, updatedAt: Date.now() }, operations, fallbackTools);
175
+ }
176
+
177
+ function queueSettingsSave(
178
+ patch: Partial<FirecrawlSettings> & { updatedAt: number },
179
+ operations: Partial<SettingsFileOperations>,
180
+ fallbackTools: readonly FirecrawlToolName[] = FIRECRAWL_TOOL_NAMES,
181
+ ): Promise<void> {
182
+ const filePath = settingsFilePath();
183
+ const legacyPath = legacySettingsFilePath();
184
+ const fallback = [...fallbackTools];
185
+ const operation = settingsSaveQueue.then(() => saveSettingsNow(filePath, legacyPath, patch, operations, fallback));
150
186
  settingsSaveQueue = operation.catch(() => undefined);
151
187
  return operation;
152
188
  }
153
189
 
154
190
  async function saveSettingsNow(
155
- settings: FirecrawlSettings,
191
+ filePath: string,
192
+ legacyPath: string,
193
+ patch: Partial<FirecrawlSettings> & { updatedAt: number },
156
194
  operations: Partial<SettingsFileOperations>,
195
+ fallbackTools: readonly FirecrawlToolName[],
157
196
  ): Promise<void> {
158
- const filePath = settingsFilePath();
159
197
  let current = await readSettingsDocument(filePath);
160
198
  const replaceCanonical = current.result.kind !== "missing";
161
- if (!replaceCanonical) current = await readSettingsDocument(legacySettingsFilePath());
199
+ if (!replaceCanonical) current = await readSettingsDocument(legacyPath);
162
200
  if (current.result.kind === "invalid") {
163
201
  throw new Error(`Cannot save Firecrawl settings until you repair ${current.result.reason}`);
164
202
  }
165
203
  const nextDocument = {
166
204
  ...(current.document ?? {}),
167
- tools: [...settings.tools],
168
- updatedAt: settings.updatedAt,
205
+ toolMode:
206
+ patch.toolMode ?? (current.result.kind === "loaded" ? current.result.settings.toolMode : DEFAULT_TOOL_MODE),
207
+ tools: [...(patch.tools ?? (current.result.kind === "loaded" ? current.result.settings.tools : fallbackTools))],
208
+ updatedAt: patch.updatedAt,
169
209
  };
170
210
  await mkdir(dirname(filePath), { recursive: true });
171
211
  const tempFile = `${filePath}.${process.pid}.${randomUUID()}.tmp`;