ceulen 0.5.1 → 0.7.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/CHANGELOG.md +317 -12
- package/README.md +87 -91
- package/extensions/lib/advisor-marker.ts +33 -0
- package/extensions/lib/panel.ts +25 -2
- package/extensions/lib/rate.ts +24 -0
- package/extensions/lib/registry.ts +93 -7
- package/extensions/lib/tools.ts +47 -0
- package/extensions/lib/usage-store.ts +33 -0
- package/extensions/modules/advisor/commands/advisor.ts +244 -0
- package/extensions/modules/advisor/configPanel.ts +194 -0
- package/extensions/modules/advisor/index.ts +217 -0
- package/extensions/modules/advisor/lib/config.ts +248 -0
- package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
- package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
- package/extensions/modules/advisor/lib/model-picker.ts +47 -0
- package/extensions/modules/advisor/lib/watcher.ts +286 -0
- package/extensions/modules/advisor/test/compliance.test.ts +125 -0
- package/extensions/modules/advisor/test/config.test.ts +202 -0
- package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
- package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
- package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
- package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
- package/extensions/modules/advisor/test/module.test.ts +586 -0
- package/extensions/modules/advisor/test/watcher.test.ts +478 -0
- package/extensions/modules/classifier/configPanel.ts +104 -0
- package/extensions/modules/classifier/index.ts +297 -0
- package/extensions/modules/classifier/lib/settings.ts +95 -0
- package/extensions/modules/classifier/test/classifier.test.ts +475 -0
- package/extensions/modules/composer/index.ts +152 -3
- package/extensions/modules/composer/lib/footer.ts +119 -0
- package/extensions/modules/composer/lib/shapes.ts +265 -26
- package/extensions/modules/composer/test/editor.test.ts +1 -1
- package/extensions/modules/composer/test/footer.test.ts +96 -0
- package/extensions/modules/composer/test/module.test.ts +113 -11
- package/extensions/modules/composer/test/screen.test.ts +29 -1
- package/extensions/modules/composer/test/shapes.test.ts +224 -8
- package/extensions/modules/config/defaultTools.ts +96 -0
- package/extensions/modules/config/index.ts +147 -7
- package/extensions/modules/config/piSettings.ts +254 -69
- package/extensions/modules/config/test/defaultTools.test.ts +122 -0
- package/extensions/modules/config/test/menu.test.ts +64 -0
- package/extensions/modules/config/test/panel.test.ts +38 -23
- package/extensions/modules/config/test/piSettings.test.ts +130 -3
- package/extensions/modules/config/test/renderTools.test.ts +71 -0
- package/extensions/modules/config/test/tools.test.ts +146 -0
- package/extensions/modules/fff/index.ts +2094 -0
- package/extensions/modules/fff/lib/query.ts +129 -0
- package/extensions/modules/fff/test/index.test.ts +607 -0
- package/extensions/modules/fff/test/query.test.ts +71 -0
- package/extensions/modules/munin/configPanel.ts +105 -0
- package/extensions/modules/munin/index.ts +641 -0
- package/extensions/modules/munin/lib/helpers.ts +471 -0
- package/extensions/modules/munin/lib/retry.ts +20 -0
- package/extensions/modules/munin/lib/sdk.ts +218 -0
- package/extensions/modules/munin/test/config.test.ts +168 -0
- package/extensions/modules/munin/test/configPanel.test.ts +161 -0
- package/extensions/modules/munin/test/extension.test.ts +224 -0
- package/extensions/modules/munin/test/helpers.test.ts +523 -0
- package/extensions/modules/munin/test/retry.test.ts +145 -0
- package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
- package/extensions/modules/plan/configPanel.ts +152 -0
- package/extensions/modules/plan/index.ts +917 -0
- package/extensions/modules/plan/lib/plan-tools.ts +72 -0
- package/extensions/modules/plan/lib/prompt.ts +65 -0
- package/extensions/modules/plan/lib/settings.ts +166 -0
- package/extensions/modules/plan/lib/shell-gate.ts +200 -0
- package/extensions/modules/plan/test/configPanel.test.ts +96 -0
- package/extensions/modules/plan/test/harness.ts +133 -0
- package/extensions/modules/plan/test/module.test.ts +305 -0
- package/extensions/modules/plan/test/settings.test.ts +114 -0
- package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
- package/extensions/modules/ponytail/index.ts +23 -73
- package/extensions/modules/ponytail/lib/config.ts +1 -6
- package/extensions/modules/ponytail/test/extension.test.ts +1 -85
- package/extensions/modules/repair/configPanel.ts +96 -0
- package/extensions/modules/repair/index.ts +414 -0
- package/extensions/modules/repair/lib/auto-bg.ts +333 -0
- package/extensions/modules/repair/lib/edit-repair.ts +155 -0
- package/extensions/modules/repair/lib/editor.ts +251 -0
- package/extensions/modules/repair/lib/guards.ts +34 -0
- package/extensions/modules/repair/lib/input-repair.ts +324 -0
- package/extensions/modules/repair/lib/patch.ts +481 -0
- package/extensions/modules/repair/lib/settings.ts +114 -0
- package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
- package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
- package/extensions/modules/repair/test/editor.test.ts +141 -0
- package/extensions/modules/repair/test/guards.test.ts +64 -0
- package/extensions/modules/repair/test/input-repair.test.ts +231 -0
- package/extensions/modules/repair/test/patch.test.ts +563 -0
- package/extensions/modules/repair/test/settings.test.ts +167 -0
- package/extensions/modules/repair/test/wrapper.test.ts +210 -0
- package/extensions/modules/router/commands/commands.ts +4 -0
- package/extensions/modules/router/lib/client.ts +61 -0
- package/extensions/modules/router/lib/provider.ts +34 -13
- package/extensions/modules/router/lib/systemone.ts +152 -0
- package/extensions/modules/router/test/unit.test.ts +179 -0
- package/extensions/modules/rtk/findFallback.js +68 -0
- package/extensions/modules/rtk/index.ts +248 -0
- package/extensions/modules/rtk/safe-rewrite.js +74 -0
- package/extensions/modules/rtk/test/findFallback.test.js +66 -0
- package/extensions/modules/rtk/test/index.test.js +131 -0
- package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
- package/extensions/modules/rtk/version-gate.js +34 -0
- package/extensions/modules/serena/index.ts +629 -0
- package/extensions/modules/serena/lib/detect.ts +73 -0
- package/extensions/modules/serena/lib/env.ts +76 -0
- package/extensions/modules/serena/lib/guidance.ts +26 -0
- package/extensions/modules/serena/lib/normalize.ts +27 -0
- package/extensions/modules/serena/lib/symbol-key.ts +20 -0
- package/extensions/modules/serena/lib/truncate.ts +20 -0
- package/extensions/modules/serena/test/env.test.ts +122 -0
- package/extensions/modules/serena/test/index.test.ts +347 -0
- package/extensions/modules/serena/test/worker.test.ts +562 -0
- package/extensions/modules/serena/worker.ts +858 -0
- package/extensions/modules/steering/configPanel.ts +122 -0
- package/extensions/modules/steering/index.ts +616 -0
- package/extensions/modules/steering/lib/anchor.ts +175 -0
- package/extensions/modules/steering/lib/errors.ts +253 -0
- package/extensions/modules/steering/lib/family.ts +33 -0
- package/extensions/modules/steering/lib/guidance.ts +172 -0
- package/extensions/modules/steering/lib/history.ts +170 -0
- package/extensions/modules/steering/lib/settings.ts +127 -0
- package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
- package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
- package/extensions/modules/steering/test/anchor.test.ts +160 -0
- package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
- package/extensions/modules/steering/test/errors.test.ts +309 -0
- package/extensions/modules/steering/test/family.test.ts +43 -0
- package/extensions/modules/steering/test/guidance.test.ts +357 -0
- package/extensions/modules/steering/test/harness.ts +93 -0
- package/extensions/modules/steering/test/history.test.ts +118 -0
- package/extensions/modules/steering/test/settings.test.ts +182 -0
- package/extensions/modules/steering/test/status.test.ts +71 -0
- package/extensions/modules/steering/test/toolCall.test.ts +99 -0
- package/extensions/modules/subagent/agents/planner.md +14 -0
- package/extensions/modules/subagent/agents/reviewer.md +42 -0
- package/extensions/modules/subagent/agents/scout.md +47 -0
- package/extensions/modules/subagent/agents/tester.md +12 -0
- package/extensions/modules/subagent/agents/worker.md +18 -0
- package/extensions/modules/subagent/configPanel.ts +219 -0
- package/extensions/modules/subagent/index.ts +2451 -0
- package/extensions/modules/subagent/lib/agents.ts +408 -0
- package/extensions/modules/subagent/lib/background.ts +383 -0
- package/extensions/modules/subagent/lib/herdr.ts +1019 -0
- package/extensions/modules/subagent/lib/history.ts +126 -0
- package/extensions/modules/subagent/lib/model.ts +156 -0
- package/extensions/modules/subagent/lib/render.ts +335 -0
- package/extensions/modules/subagent/lib/result.ts +110 -0
- package/extensions/modules/subagent/lib/roles.ts +296 -0
- package/extensions/modules/subagent/lib/routing.ts +223 -0
- package/extensions/modules/subagent/lib/runner.ts +559 -0
- package/extensions/modules/subagent/lib/schema.ts +21 -0
- package/extensions/modules/subagent/lib/security.ts +752 -0
- package/extensions/modules/subagent/lib/settings.ts +159 -0
- package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
- package/extensions/modules/subagent/lib/threads.ts +135 -0
- package/extensions/modules/subagent/lib/types.ts +18 -0
- package/extensions/modules/subagent/lib/widget.ts +475 -0
- package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
- package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
- package/extensions/modules/subagent/test/routing.test.ts +350 -0
- package/extensions/modules/subagent/test/widget.test.ts +208 -0
- package/extensions/modules/usage/index.ts +59 -16
- package/extensions/modules/usage/test/genrate.test.ts +70 -0
- package/extensions/modules/usage/test/parsers.test.ts +13 -0
- package/extensions/modules/ux/UPSTREAM +24 -0
- package/extensions/modules/ux/index.ts +393 -0
- package/extensions/modules/ux/lib/audit.ts +562 -0
- package/extensions/modules/ux/lib/config.ts +136 -0
- package/extensions/modules/ux/lib/instructions.ts +77 -0
- package/extensions/modules/ux/test/audit.test.ts +756 -0
- package/extensions/modules/ux/test/extension.test.ts +394 -0
- package/extensions/modules/ux/test/instructions.test.ts +19 -0
- package/extensions/modules/web/configPanel.ts +193 -0
- package/extensions/modules/web/index.ts +978 -0
- package/extensions/modules/web/lib/agy.ts +209 -0
- package/extensions/modules/web/lib/brave.ts +42 -0
- package/extensions/modules/web/lib/cdp.ts +686 -0
- package/extensions/modules/web/lib/chatapi.ts +101 -0
- package/extensions/modules/web/lib/chatgpt.ts +796 -0
- package/extensions/modules/web/lib/chrome.ts +328 -0
- package/extensions/modules/web/lib/config.ts +136 -0
- package/extensions/modules/web/lib/content.ts +99 -0
- package/extensions/modules/web/lib/crawl4ai.ts +172 -0
- package/extensions/modules/web/lib/extract.ts +235 -0
- package/extensions/modules/web/lib/firecrawl.ts +56 -0
- package/extensions/modules/web/lib/format.ts +197 -0
- package/extensions/modules/web/lib/gemini-auth.ts +286 -0
- package/extensions/modules/web/lib/gemini-dr.ts +338 -0
- package/extensions/modules/web/lib/gemini.ts +551 -0
- package/extensions/modules/web/lib/imageapi.ts +559 -0
- package/extensions/modules/web/lib/retry.ts +71 -0
- package/extensions/modules/web/lib/search.ts +237 -0
- package/extensions/modules/web/lib/searxng.ts +69 -0
- package/extensions/modules/web/lib/settings.ts +148 -0
- package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
- package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
- package/extensions/modules/web/test/agy.test.ts +383 -0
- package/extensions/modules/web/test/cdp.test.ts +717 -0
- package/extensions/modules/web/test/chat.test.ts +171 -0
- package/extensions/modules/web/test/chatgpt.test.ts +633 -0
- package/extensions/modules/web/test/chrome.test.ts +282 -0
- package/extensions/modules/web/test/config.test.ts +218 -0
- package/extensions/modules/web/test/configPanel.test.ts +132 -0
- package/extensions/modules/web/test/crawl.test.ts +134 -0
- package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
- package/extensions/modules/web/test/extension.test.ts +118 -0
- package/extensions/modules/web/test/extract.test.ts +436 -0
- package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
- package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
- package/extensions/modules/web/test/fixtures/interaction.html +31 -0
- package/extensions/modules/web/test/format.test.ts +230 -0
- package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
- package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
- package/extensions/modules/web/test/gemini.test.ts +472 -0
- package/extensions/modules/web/test/hook.test.ts +101 -0
- package/extensions/modules/web/test/image.test.ts +1089 -0
- package/extensions/modules/web/test/retry.test.ts +119 -0
- package/extensions/modules/web/test/screenshot.test.ts +109 -0
- package/extensions/modules/web/test/search.test.ts +210 -0
- package/extensions/modules/web/test/settings.test.ts +165 -0
- package/extensions/modules/web/test/skill.test.ts +72 -0
- package/extensions/modules/web/types.d.ts +3 -0
- package/extensions/modules/web/vendor/package.json +1 -0
- package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
- package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
- package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
- package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
- package/extensions/modules/web/vendor/readability/index.js +9 -0
- package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
- package/extensions/modules/zai/configPanel.ts +151 -0
- package/extensions/modules/zai/index.ts +186 -0
- package/extensions/modules/zai/lib/anthropic.ts +159 -0
- package/extensions/modules/zai/lib/settings.ts +198 -0
- package/extensions/modules/zai/lib/signing.ts +718 -0
- package/extensions/modules/zai/lib/throttle.ts +198 -0
- package/extensions/modules/zai/test/anthropic.test.ts +132 -0
- package/extensions/modules/zai/test/configPanel.test.ts +207 -0
- package/extensions/modules/zai/test/extension.test.ts +249 -0
- package/extensions/modules/zai/test/settings.test.ts +183 -0
- package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
- package/extensions/modules/zai/test/signing.test.ts +345 -0
- package/extensions/modules/zai/test/throttle.test.ts +329 -0
- package/package.json +19 -4
- package/scripts/validate-themes.mjs +75 -0
- package/skills/munin/SKILL.md +117 -0
- package/skills/ux-capture/SKILL.md +202 -0
- package/skills/ux-design/SKILL.md +279 -0
- package/skills/ux-presets/SKILL.md +484 -0
- package/skills/ux-routing/SKILL.md +46 -0
- package/skills/web/SKILL.md +153 -0
- package/themes/alabaster.json +93 -0
- package/themes/amethyst.json +96 -0
- package/themes/anthracite.json +93 -0
- package/themes/basalt.json +91 -0
- package/themes/birch.json +95 -0
- package/themes/catppuccin-mocha.json +91 -0
- package/themes/dark-abyss.json +91 -0
- package/themes/dark-arctic.json +104 -0
- package/themes/dark-aurora.json +95 -0
- package/themes/dark-catppuccin.json +107 -0
- package/themes/dark-cavern.json +91 -0
- package/themes/dark-celestial.json +106 -0
- package/themes/dark-copper.json +95 -0
- package/themes/dark-cosmos.json +90 -0
- package/themes/dark-cyberpunk.json +102 -0
- package/themes/dark-dracula.json +98 -0
- package/themes/dark-eclipse.json +91 -0
- package/themes/dark-ember.json +95 -0
- package/themes/dark-equinox.json +90 -0
- package/themes/dark-forest.json +96 -0
- package/themes/dark-github.json +105 -0
- package/themes/dark-gruvbox.json +112 -0
- package/themes/dark-lavender.json +95 -0
- package/themes/dark-lunar.json +89 -0
- package/themes/dark-midnight.json +95 -0
- package/themes/dark-monochrome.json +94 -0
- package/themes/dark-monokai.json +98 -0
- package/themes/dark-nebula.json +90 -0
- package/themes/dark-neon-noir.json +100 -0
- package/themes/dark-nord.json +98 -0
- package/themes/dark-ocean.json +101 -0
- package/themes/dark-one.json +100 -0
- package/themes/dark-poimandres.json +115 -0
- package/themes/dark-rainforest.json +91 -0
- package/themes/dark-reef.json +91 -0
- package/themes/dark-retro.json +92 -0
- package/themes/dark-rose-pine.json +96 -0
- package/themes/dark-sakura.json +95 -0
- package/themes/dark-slate.json +95 -0
- package/themes/dark-solarized.json +97 -0
- package/themes/dark-solstice.json +90 -0
- package/themes/dark-starfall.json +91 -0
- package/themes/dark-sunset.json +99 -0
- package/themes/dark-swamp.json +90 -0
- package/themes/dark-synthwave.json +103 -0
- package/themes/dark-taiga.json +91 -0
- package/themes/dark-terminal.json +95 -0
- package/themes/dark-tokyo-night.json +101 -0
- package/themes/dark-tundra.json +91 -0
- package/themes/dark-twilight.json +91 -0
- package/themes/dark-volcanic.json +91 -0
- package/themes/dark.json +80 -0
- package/themes/graphite.json +92 -0
- package/themes/light-arctic.json +107 -0
- package/themes/light-aurora-day.json +91 -0
- package/themes/light-canyon.json +91 -0
- package/themes/light-catppuccin.json +106 -0
- package/themes/light-cirrus.json +90 -0
- package/themes/light-coral.json +95 -0
- package/themes/light-cyberpunk.json +96 -0
- package/themes/light-dawn.json +90 -0
- package/themes/light-dunes.json +91 -0
- package/themes/light-eucalyptus.json +95 -0
- package/themes/light-forest.json +100 -0
- package/themes/light-frost.json +95 -0
- package/themes/light-github.json +115 -0
- package/themes/light-glacier.json +91 -0
- package/themes/light-gruvbox.json +108 -0
- package/themes/light-haze.json +90 -0
- package/themes/light-honeycomb.json +95 -0
- package/themes/light-lagoon.json +91 -0
- package/themes/light-lavender.json +95 -0
- package/themes/light-meadow.json +91 -0
- package/themes/light-mint.json +95 -0
- package/themes/light-monochrome.json +101 -0
- package/themes/light-ocean.json +99 -0
- package/themes/light-one.json +99 -0
- package/themes/light-opal.json +91 -0
- package/themes/light-orchard.json +91 -0
- package/themes/light-paper.json +95 -0
- package/themes/light-poimandres.json +115 -0
- package/themes/light-prism.json +90 -0
- package/themes/light-retro.json +98 -0
- package/themes/light-sand.json +95 -0
- package/themes/light-savanna.json +91 -0
- package/themes/light-solarized.json +102 -0
- package/themes/light-soleil.json +90 -0
- package/themes/light-sunset.json +99 -0
- package/themes/light-synthwave.json +98 -0
- package/themes/light-tokyo-night.json +111 -0
- package/themes/light-wetland.json +91 -0
- package/themes/light-zenith.json +89 -0
- package/themes/light.json +80 -0
- package/themes/limestone.json +94 -0
- package/themes/mahogany.json +97 -0
- package/themes/marble.json +93 -0
- package/themes/mirage.json +79 -0
- package/themes/obsidian.json +91 -0
- package/themes/onyx.json +91 -0
- package/themes/pearl.json +93 -0
- package/themes/porcelain.json +91 -0
- package/themes/quartz.json +96 -0
- package/themes/sandstone.json +95 -0
- package/themes/titanium.json +90 -0
|
@@ -0,0 +1,978 @@
|
|
|
1
|
+
// ponytail: ported from @bacnh85/pi-web 0.17.8 extensions/index.ts — the 11
|
|
2
|
+
// unified web tools + the conditional WEB_ROUTING_GUIDANCE injection, wrapped
|
|
3
|
+
// in ceulen's module conventions: per-tool kill-switch (ceulen.disabledTools →
|
|
4
|
+
// defaultActive:false, /config re-activates live), and the pi-web skill
|
|
5
|
+
// contributed via resources_discover (kill-switch gated, NOT the package.json
|
|
6
|
+
// manifest). No slash command — web_status covers status.
|
|
7
|
+
|
|
8
|
+
/// <reference path="./types.d.ts" />
|
|
9
|
+
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
|
|
14
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { Type } from "typebox";
|
|
16
|
+
|
|
17
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
findEnvValue,
|
|
21
|
+
cwdFromContext,
|
|
22
|
+
includeProjectEnv,
|
|
23
|
+
normalizeSearxngBaseUrl,
|
|
24
|
+
normalizeFirecrawlBaseUrl,
|
|
25
|
+
normalizeCrawl4aiApiUrl,
|
|
26
|
+
loadFirecrawlConfig,
|
|
27
|
+
loadCrawl4aiConfig,
|
|
28
|
+
HOSTED_FIRECRAWL_BASE_URL,
|
|
29
|
+
} from "./lib/config";
|
|
30
|
+
import {
|
|
31
|
+
truncateText,
|
|
32
|
+
formatFirecrawlScrape,
|
|
33
|
+
formatCrawl4aiResult,
|
|
34
|
+
formatUnifiedSearchResults,
|
|
35
|
+
} from "./lib/format";
|
|
36
|
+
import { searchWithDiagnostics } from "./lib/search";
|
|
37
|
+
import {
|
|
38
|
+
loadGeminiWebConfig,
|
|
39
|
+
geminiAsk,
|
|
40
|
+
geminiResearch,
|
|
41
|
+
describeGeminiError,
|
|
42
|
+
} from "./lib/gemini";
|
|
43
|
+
import { cookieStoreSnapshot } from "./lib/gemini-auth";
|
|
44
|
+
import {
|
|
45
|
+
generateImageWithFallback,
|
|
46
|
+
loadImageApiConfig,
|
|
47
|
+
loadImageRateConfig,
|
|
48
|
+
imageRateSnapshot,
|
|
49
|
+
type ImageProvider,
|
|
50
|
+
} from "./lib/imageapi";
|
|
51
|
+
import {
|
|
52
|
+
chatgptChat,
|
|
53
|
+
describeChatApiError,
|
|
54
|
+
loadChatConfig,
|
|
55
|
+
} from "./lib/chatapi";
|
|
56
|
+
import {
|
|
57
|
+
chatgptAuthSnapshot,
|
|
58
|
+
chatgptWebChat,
|
|
59
|
+
describeChatGptError,
|
|
60
|
+
loadChatGptAuth,
|
|
61
|
+
} from "./lib/chatgpt";
|
|
62
|
+
import { extractWithDiagnostics, type ExtractMode } from "./lib/extract";
|
|
63
|
+
import { firecrawlRequest, type FirecrawlResult } from "./lib/firecrawl";
|
|
64
|
+
import {
|
|
65
|
+
fetchCrawl4aiCrawl,
|
|
66
|
+
fetchCrawl4aiScreenshot,
|
|
67
|
+
fetchCrawl4aiPdf,
|
|
68
|
+
fetchCrawl4aiHealth,
|
|
69
|
+
} from "./lib/crawl4ai";
|
|
70
|
+
import {
|
|
71
|
+
capturePdf as captureLocalPdf,
|
|
72
|
+
captureScreenshot as captureLocalScreenshot,
|
|
73
|
+
findChromeBinary,
|
|
74
|
+
isSsrfBlocked,
|
|
75
|
+
resolveEngine,
|
|
76
|
+
FULL_PAGE_HEIGHT,
|
|
77
|
+
} from "./lib/chrome";
|
|
78
|
+
import {
|
|
79
|
+
runInteraction,
|
|
80
|
+
type InteractStep,
|
|
81
|
+
} from "./lib/cdp";
|
|
82
|
+
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// Shared schema fragment
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
const sharedControlSchema = {
|
|
88
|
+
timeout_ms: Type.Optional(Type.Number({ description: "Request timeout in milliseconds." })),
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const firecrawlControlSchema = {
|
|
92
|
+
firecrawl_api_key: Type.Optional(Type.String({ description: "Override $FIRECRAWL_API_KEY." })),
|
|
93
|
+
firecrawl_api_url: Type.Optional(Type.String({ description: "Override $FIRECRAWL_API_URL." })),
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const crawl4aiControlSchema = {
|
|
97
|
+
crawl4ai_api_url: Type.Optional(Type.String({ description: "Override $CRAWL4AI_API_URL." })),
|
|
98
|
+
crawl4ai_api_token: Type.Optional(Type.String({ description: "Override $CRAWL4AI_API_TOKEN." })),
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const engineSchema = {
|
|
102
|
+
engine: Type.Optional(Type.Union([
|
|
103
|
+
Type.Literal("auto"),
|
|
104
|
+
Type.Literal("local"),
|
|
105
|
+
Type.Literal("daemon"),
|
|
106
|
+
], { default: "auto", description: "auto routes localhost/private/file URLs to local Chrome, the rest to the Crawl4AI daemon; local/daemon force one." })),
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// Saved image file → inline image block (the 0.6.2 vision-loop lesson: the
|
|
110
|
+
// generating model should see its own output).
|
|
111
|
+
export async function toImageBlock(file: string): Promise<{ type: "image"; data: string; mimeType: string }> {
|
|
112
|
+
const data = (await fs.promises.readFile(file)).toString("base64");
|
|
113
|
+
const lower = file.toLowerCase();
|
|
114
|
+
const mimeType = lower.endsWith(".jpg") || lower.endsWith(".jpeg")
|
|
115
|
+
? "image/jpeg"
|
|
116
|
+
: lower.endsWith(".webp")
|
|
117
|
+
? "image/webp"
|
|
118
|
+
: lower.endsWith(".gif")
|
|
119
|
+
? "image/gif"
|
|
120
|
+
: "image/png";
|
|
121
|
+
return { type: "image" as const, data, mimeType };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
// Always-on routing guidance (injected only when a web_* tool is active)
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
// Portable home for the pi-web backend-selection protocol. Previously forced
|
|
129
|
+
// always-on via ~/.pi/agent/AGENTS.md; now self-injected by this extension so
|
|
130
|
+
// the guidance travels with the package and disappears when pi-web is absent.
|
|
131
|
+
const WEB_ROUTING_GUIDANCE = `## Web Tool Routing (pi-web)
|
|
132
|
+
|
|
133
|
+
- **web_search** — web search (auto: SearXNG → Brave → Firecrawl; force via \`backend\`, tune via \`engines\`).
|
|
134
|
+
- **web_extract** — URL → markdown (auto: static JSDOM → dynamic Firecrawl → full Crawl4AI → agy; force via \`mode\`; prompt+schema for JSON extraction).
|
|
135
|
+
- **web_map** — discover site URLs (Firecrawl Map).
|
|
136
|
+
- **web_crawl** — multi-page crawl: \`mode: "light"\` (Firecrawl, url) or \`mode: "full"\` (Crawl4AI, urls[]).
|
|
137
|
+
- **web_screenshot** / **web_pdf** — page capture (Crawl4AI).
|
|
138
|
+
- **web_interact** — drive a real headless Chrome session: trusted click/type/press, JS evaluate, wait_for, screenshots + scrollWidth probe (use to verify UI behavior, not just looks).
|
|
139
|
+
- **web_research** — AI-synthesized research via Gemini web (mode "ask" = grounded answer, guest OK; mode "research" = Deep Research report — plan, autonomous web browsing, cited report; takes minutes when available).
|
|
140
|
+
- **web_image** — text→image generation (auto: Gemini web → ChatGPT web via CHATGPT_WEB_AUTH_KEY / codex login → Z.ai GLM-Image → custom OpenAI-images endpoint; \`model\`/\`n\`/\`size\` params).
|
|
141
|
+
- **web_chat** — one-off chat completion — ChatGPT web (CHATGPT_WEB_AUTH_KEY / codex login; default when configured) or an OpenAI-compatible gateway (\`WEB_CHAT_API_BASE_URL\`; non-streaming).
|
|
142
|
+
- **web_status** — provider config + health.
|
|
143
|
+
|
|
144
|
+
Rules: Firecrawl Search is weak on domain-specific queries — prefer SearXNG/Brave; Firecrawl Scrape fails on bot-protected sites — use Crawl4AI (\`mode: "full"\`) then agy (\`mode: "agy"\`); cite source URLs.`;
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
// ---------------------------------------------------------------------------
|
|
148
|
+
// Extension entry point
|
|
149
|
+
// ---------------------------------------------------------------------------
|
|
150
|
+
|
|
151
|
+
/** Validate a requested image size: WxH, 3-4 digits each. Present-but-invalid throws (never silently generates a square). */
|
|
152
|
+
export function parseSizeParam(value: unknown): string | undefined {
|
|
153
|
+
if (value === undefined) return undefined;
|
|
154
|
+
const s = String(value);
|
|
155
|
+
if (!/^\d{3,4}x\d{3,4}$/.test(s)) throw new Error(`invalid size "${s}": expected WxH with 3-4 digits each, e.g. 960x1728`);
|
|
156
|
+
return s;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export default function piWebExtension(pi: ExtensionAPI) {
|
|
160
|
+
// Skill ships in-package (../../../skills/web, 3 levels up from the module
|
|
161
|
+
// dir) and is contributed through resources_discover — NOT via the
|
|
162
|
+
// package.json `pi.skills` manifest — so the kill-switch gates it too:
|
|
163
|
+
// disabled module ⇒ factory never runs ⇒ no web skill registered.
|
|
164
|
+
const skillsRoot = new URL("../../../skills/", import.meta.url).pathname;
|
|
165
|
+
pi.on("resources_discover", () => ({
|
|
166
|
+
skillPaths: [path.join(fs.realpathSync(skillsRoot), "web")],
|
|
167
|
+
}));
|
|
168
|
+
|
|
169
|
+
// Per-tool kill-switch (ceulen.disabledTools): listed tools register
|
|
170
|
+
// inactive — /config re-activates them live via setActiveTools. Wrapping
|
|
171
|
+
// registerTool keeps the 11 definitions below untouched (munin pattern).
|
|
172
|
+
const disabledTools = readDisabledTools();
|
|
173
|
+
const registerTool = pi.registerTool.bind(pi);
|
|
174
|
+
pi.registerTool = ((tool: Parameters<typeof pi.registerTool>[0]) =>
|
|
175
|
+
registerTool({ ...tool, defaultActive: !disabledTools.has((tool as { name: string }).name) })) as typeof pi.registerTool;
|
|
176
|
+
|
|
177
|
+
// ── web_search ────────────────────────────────────────────────────────
|
|
178
|
+
pi.registerTool({
|
|
179
|
+
name: "web_search",
|
|
180
|
+
label: "Web Search",
|
|
181
|
+
description:
|
|
182
|
+
"Search the web. Auto-selects backends: SearXNG, Brave, Firecrawl.",
|
|
183
|
+
promptSnippet: "Search current web results",
|
|
184
|
+
promptGuidelines: ["Source discovery, docs, facts. Precision/site/docs → Brave via backend:'brave'; tune SearXNG via engines.", "Cite source URLs."],
|
|
185
|
+
parameters: Type.Object({
|
|
186
|
+
query: Type.String(),
|
|
187
|
+
count: Type.Optional(Type.Number({ default: 5 })),
|
|
188
|
+
freshness: Type.Optional(Type.String({ description: "Time filter: pw/pm/py or YYYY-MM-DDtoYYYY-MM-DD." })),
|
|
189
|
+
country: Type.Optional(Type.String({ default: "US" })),
|
|
190
|
+
backend: Type.Optional(Type.Union(
|
|
191
|
+
[Type.Literal("auto"), Type.Literal("searxng"), Type.Literal("brave"), Type.Literal("firecrawl")],
|
|
192
|
+
{ default: "auto", description: "auto, searxng, brave, firecrawl." },
|
|
193
|
+
)),
|
|
194
|
+
engines: Type.Optional(Type.String({ description: "SearXNG engine list (google,github). Only for searxng/auto backend." })),
|
|
195
|
+
include_content: Type.Optional(Type.Boolean({ default: false, description: "Fetch inline page content (slower)." })),
|
|
196
|
+
content_chars: Type.Optional(Type.Number({ default: 5000 })),
|
|
197
|
+
...sharedControlSchema,
|
|
198
|
+
}),
|
|
199
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
200
|
+
const diagnostics = await searchWithDiagnostics({
|
|
201
|
+
query: params.query as string,
|
|
202
|
+
count: params.count as number | undefined,
|
|
203
|
+
freshness: params.freshness as string | undefined,
|
|
204
|
+
country: params.country as string | undefined,
|
|
205
|
+
backend: params.backend as "auto" | "searxng" | "brave" | "firecrawl" | undefined,
|
|
206
|
+
engines: params.engines as string | undefined,
|
|
207
|
+
include_content: params.include_content as boolean | undefined,
|
|
208
|
+
content_chars: params.content_chars as number | undefined,
|
|
209
|
+
timeout_ms: params.timeout_ms as number | undefined,
|
|
210
|
+
signal,
|
|
211
|
+
_ctx: ctx,
|
|
212
|
+
});
|
|
213
|
+
const attempts = diagnostics.attempts.map((a) => `${a.backend}: ${a.status}${a.message ? ` (${a.message})` : ""}`).join("\n");
|
|
214
|
+
const text = `${formatUnifiedSearchResults(diagnostics.results)}\n\n--- Search diagnostics ---\nSelected backend: ${diagnostics.selectedBackend}\n${attempts}`;
|
|
215
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: diagnostics };
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
// ── web_extract ──────────────────────────────────────────────────────
|
|
220
|
+
pi.registerTool({
|
|
221
|
+
name: "web_extract",
|
|
222
|
+
label: "Web Content Extraction",
|
|
223
|
+
description:
|
|
224
|
+
"Extract readable content from a URL. Auto mode: static\u2192dynamic\u2192full\u2192agy.",
|
|
225
|
+
promptSnippet: "Extract readable webpage content as markdown",
|
|
226
|
+
promptGuidelines: ["Markdown from a known URL; prompt+schema for structured JSON extraction.", "Cite the source URL."],
|
|
227
|
+
parameters: Type.Object({
|
|
228
|
+
url: Type.String(),
|
|
229
|
+
mode: Type.Optional(Type.Union(
|
|
230
|
+
[Type.Literal("auto"), Type.Literal("static"), Type.Literal("dynamic"), Type.Literal("full"), Type.Literal("agy")],
|
|
231
|
+
{ default: "auto", description: "auto, static, dynamic, full, agy." },
|
|
232
|
+
)),
|
|
233
|
+
prompt: Type.Optional(Type.String({ description: "Prompt for structured JSON extraction (dynamic/agy modes)." })),
|
|
234
|
+
schema: Type.Optional(Type.Any({ description: "JSON schema for structured extraction (dynamic/agy modes)." })),
|
|
235
|
+
content_chars: Type.Optional(Type.Number({ default: 20000 })),
|
|
236
|
+
wait_for: Type.Optional(Type.Number({ description: "Ms to wait for Firecrawl render before extraction." })),
|
|
237
|
+
mobile: Type.Optional(Type.Boolean({ default: false, description: "Mobile viewport (dynamic mode only)." })),
|
|
238
|
+
...crawl4aiControlSchema,
|
|
239
|
+
...sharedControlSchema,
|
|
240
|
+
}),
|
|
241
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
242
|
+
const diagnostics = await extractWithDiagnostics({
|
|
243
|
+
url: params.url as string,
|
|
244
|
+
mode: params.mode as ExtractMode | undefined,
|
|
245
|
+
prompt: params.prompt as string | undefined,
|
|
246
|
+
schema: params.schema,
|
|
247
|
+
content_chars: params.content_chars as number | undefined,
|
|
248
|
+
timeout_ms: params.timeout_ms as number | undefined,
|
|
249
|
+
wait_for: params.wait_for as number | undefined,
|
|
250
|
+
mobile: params.mobile as boolean | undefined,
|
|
251
|
+
crawl4ai_api_token: params.crawl4ai_api_token as string | undefined,
|
|
252
|
+
crawl4ai_api_url: params.crawl4ai_api_url as string | undefined,
|
|
253
|
+
signal,
|
|
254
|
+
_ctx: ctx,
|
|
255
|
+
});
|
|
256
|
+
const result = diagnostics.result;
|
|
257
|
+
const attempts = diagnostics.attempts.map((a) => `${a.mode}: ${a.status}${a.message ? ` (${a.message})` : ""}`).join("\n");
|
|
258
|
+
const text = `${result.title ? `# ${result.title}\n\n` : ""}${result.markdown}\n\n--- Extraction diagnostics ---\nSelected mode: ${diagnostics.selectedMode}\nFallback used: ${diagnostics.fallbackUsed}\n${attempts}`;
|
|
259
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: { url: params.url, ...diagnostics } };
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
// ── web_map ──────────────────────────────────────────────────────────
|
|
264
|
+
pi.registerTool({
|
|
265
|
+
name: "web_map",
|
|
266
|
+
label: "Site URL Discovery",
|
|
267
|
+
description:
|
|
268
|
+
"Discover site URLs via Firecrawl Map.",
|
|
269
|
+
promptSnippet: "Map site URLs",
|
|
270
|
+
promptGuidelines: ["URL discovery before crawling; prefer web_extract for small jobs."],
|
|
271
|
+
parameters: Type.Object({
|
|
272
|
+
url: Type.String(),
|
|
273
|
+
limit: Type.Optional(Type.Number({ default: 100 })),
|
|
274
|
+
include_subdomains: Type.Optional(Type.Boolean({ default: false })),
|
|
275
|
+
search: Type.Optional(Type.String({ description: "Search query to guide URL discovery (semantic map)." })),
|
|
276
|
+
sitemap: Type.Optional(Type.Union([Type.Literal("only"), Type.Literal("include"), Type.Literal("skip")], { description: "only, include(default), skip." })),
|
|
277
|
+
use_index: Type.Optional(Type.Boolean({ default: true, description: "Use Firecrawl index for discovery." })),
|
|
278
|
+
ignore_cache: Type.Optional(Type.Boolean({ default: false, description: "Ignore cached results." })),
|
|
279
|
+
...firecrawlControlSchema,
|
|
280
|
+
...sharedControlSchema,
|
|
281
|
+
}),
|
|
282
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
283
|
+
const body: Record<string, unknown> = {
|
|
284
|
+
url: params.url,
|
|
285
|
+
limit: (params.limit as number) ?? 100,
|
|
286
|
+
includeSubdomains: Boolean(params.include_subdomains),
|
|
287
|
+
};
|
|
288
|
+
if (params.search !== undefined) body.search = params.search;
|
|
289
|
+
if (params.sitemap !== undefined) body.sitemap = params.sitemap;
|
|
290
|
+
if (params.use_index !== undefined) body.useIndex = params.use_index;
|
|
291
|
+
if (params.ignore_cache !== undefined) body.ignoreCache = params.ignore_cache;
|
|
292
|
+
const config = loadFirecrawlConfig(params as Record<string, unknown>, cwdFromContext(ctx), includeProjectEnv(ctx));
|
|
293
|
+
const result = await firecrawlRequest(config, "POST", "/map", body, signal);
|
|
294
|
+
const urls = result.data || result.links || result.urls || [];
|
|
295
|
+
const text = Array.isArray(urls) && urls.length > 0
|
|
296
|
+
? (urls as Array<Record<string, unknown> | string>).map((u: any) => u.url || u).join("\n")
|
|
297
|
+
: JSON.stringify(result, null, 2);
|
|
298
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: result };
|
|
299
|
+
},
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
// ── web_crawl ────────────────────────────────────────────────────────
|
|
303
|
+
pi.registerTool({
|
|
304
|
+
name: "web_crawl",
|
|
305
|
+
label: "Site Crawl",
|
|
306
|
+
description:
|
|
307
|
+
"Crawl pages. Firecrawl 'light' or Crawl4AI 'full' headless mode.",
|
|
308
|
+
promptSnippet: "Crawl a small site section",
|
|
309
|
+
promptGuidelines: ["'light'=Firecrawl (url), 'full'=Crawl4AI (urls[]). Prefer web_map + web_extract for small jobs."],
|
|
310
|
+
parameters: Type.Object({
|
|
311
|
+
url: Type.Optional(Type.String({ description: "URL for mode:'light' (Firecrawl)." })),
|
|
312
|
+
urls: Type.Optional(Type.Array(Type.String(), { description: "URLs for mode:'full' (Crawl4AI), up to 100." })),
|
|
313
|
+
mode: Type.Optional(Type.Union([Type.Literal("light"), Type.Literal("full")], { default: "light", description: "'light'(Firecrawl) or 'full'(Crawl4AI)." })),
|
|
314
|
+
limit: Type.Optional(Type.Number({ default: 10 })),
|
|
315
|
+
include_paths: Type.Optional(Type.String({ description: "Comma-separated include paths (light mode)." })),
|
|
316
|
+
exclude_paths: Type.Optional(Type.String({ description: "Comma-separated exclude paths (light mode)." })),
|
|
317
|
+
poll: Type.Optional(Type.Boolean({ default: false, description: "Poll until completion (light mode)." })),
|
|
318
|
+
browser_config: Type.Optional(Type.Any({ description: "BrowserConfig JSON (full mode)." })),
|
|
319
|
+
crawler_config: Type.Optional(Type.Any({ description: "CrawlerRunConfig JSON (full mode)." })),
|
|
320
|
+
content_chars: Type.Optional(Type.Number({ default: 20000 })),
|
|
321
|
+
...firecrawlControlSchema,
|
|
322
|
+
...crawl4aiControlSchema,
|
|
323
|
+
...sharedControlSchema,
|
|
324
|
+
}),
|
|
325
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
326
|
+
const mode = (params.mode as string) || "light";
|
|
327
|
+
const cwd = cwdFromContext(ctx);
|
|
328
|
+
const trusted = includeProjectEnv(ctx);
|
|
329
|
+
const maxChars = (params.content_chars as number) ?? 20000;
|
|
330
|
+
|
|
331
|
+
if (mode === "full") {
|
|
332
|
+
// Crawl4AI mode
|
|
333
|
+
const rawUrls = (params.urls as string[]) || (params.url ? [params.url as string] : []);
|
|
334
|
+
if (!rawUrls.length) throw new Error("Either url or urls parameter is required for crawl.");
|
|
335
|
+
const urls = rawUrls.slice(0, 100); // documented cap
|
|
336
|
+
const truncated = rawUrls.length > urls.length ? ` (truncated from ${rawUrls.length} to the 100-URL cap)` : "";
|
|
337
|
+
const config = loadCrawl4aiConfig(params as Record<string, unknown>, cwd, trusted);
|
|
338
|
+
const browserConfig = params.browser_config as Record<string, unknown> | undefined;
|
|
339
|
+
const crawlerConfig = params.crawler_config as Record<string, unknown> | undefined;
|
|
340
|
+
const result = await fetchCrawl4aiCrawl(config, urls, browserConfig, crawlerConfig, signal);
|
|
341
|
+
// Note BEFORE the body: truncateText cuts from the front, so a tail-appended
|
|
342
|
+
// note is exactly what a maxed-out crawl would lose.
|
|
343
|
+
const text = truncated + formatCrawl4aiResult(result as unknown as Record<string, unknown>, maxChars);
|
|
344
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: result };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Firecrawl mode ("light")
|
|
348
|
+
if (!params.url) throw new Error("The url parameter is required for Firecrawl mode ('light').");
|
|
349
|
+
const fcConfig = loadFirecrawlConfig(params as Record<string, unknown>, cwd, trusted);
|
|
350
|
+
let result = await firecrawlRequest(
|
|
351
|
+
fcConfig,
|
|
352
|
+
"POST",
|
|
353
|
+
"/crawl",
|
|
354
|
+
{
|
|
355
|
+
url: params.url as string,
|
|
356
|
+
limit: Math.min(10000, Math.max(1, (params.limit as number) ?? 10)),
|
|
357
|
+
includePaths: params.include_paths
|
|
358
|
+
? String(params.include_paths).split(",").map((s: string) => s.trim()).filter(Boolean)
|
|
359
|
+
: [],
|
|
360
|
+
excludePaths: params.exclude_paths
|
|
361
|
+
? String(params.exclude_paths).split(",").map((s: string) => s.trim()).filter(Boolean)
|
|
362
|
+
: [],
|
|
363
|
+
scrapeOptions: { formats: ["markdown"], onlyMainContent: true },
|
|
364
|
+
},
|
|
365
|
+
signal,
|
|
366
|
+
1, // ponytail: crawl submission is non-idempotent — never retried
|
|
367
|
+
);
|
|
368
|
+
const id = result.id || (result.data as Record<string, unknown> | undefined)?.id;
|
|
369
|
+
let pollTimedOut = false;
|
|
370
|
+
if (params.poll && id && !Array.isArray(result.data)) {
|
|
371
|
+
const { abortableSleep } = await import("./lib/retry");
|
|
372
|
+
// Honor timeout_ms for the whole poll loop (same clamp as web_interact
|
|
373
|
+
// step budgets); absent → legacy behavior (iteration cap only).
|
|
374
|
+
const deadline =
|
|
375
|
+
typeof params.timeout_ms === "number" ? Date.now() + Math.min(Math.max(params.timeout_ms, 1_000), 600_000) : 0;
|
|
376
|
+
for (let i = 0; i < 60; i++) {
|
|
377
|
+
result = await firecrawlRequest(fcConfig, "GET", `/crawl/${id}`, undefined, signal);
|
|
378
|
+
if (["completed", "failed", "cancelled"].includes(
|
|
379
|
+
String(result.status || (result.data as Record<string, unknown> | undefined)?.status || ""),
|
|
380
|
+
))
|
|
381
|
+
break;
|
|
382
|
+
if (deadline && Date.now() + 2000 > deadline) {
|
|
383
|
+
pollTimedOut = true;
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
await abortableSleep(2000, signal);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const pages = Array.isArray(result.data)
|
|
390
|
+
? (result.data as Record<string, unknown>[])
|
|
391
|
+
: ((result.data as Record<string, unknown>)?.data as Record<string, unknown>[]) || [];
|
|
392
|
+
let text = pages.length
|
|
393
|
+
? pages.map((p: Record<string, unknown>) => formatFirecrawlScrape({ data: p } as Record<string, unknown>, maxChars)).join("\n\n---\n\n")
|
|
394
|
+
: id
|
|
395
|
+
? `Crawl started: ${id}\nUse poll=true or check Firecrawl status/dashboard.`
|
|
396
|
+
: JSON.stringify(result, null, 2);
|
|
397
|
+
if (pollTimedOut) {
|
|
398
|
+
const status = String(result.status || (result.data as Record<string, unknown> | undefined)?.status || "unknown");
|
|
399
|
+
text += `\n\n⚠ Polling stopped at timeout_ms before the crawl finished (status: ${status}); this is the current incomplete state.`;
|
|
400
|
+
}
|
|
401
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: result };
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// ── web_screenshot ───────────────────────────────────────────────────
|
|
406
|
+
pi.registerTool({
|
|
407
|
+
name: "web_screenshot",
|
|
408
|
+
label: "Web Page Screenshot",
|
|
409
|
+
description:
|
|
410
|
+
"Full-page PNG screenshot via the Crawl4AI daemon, or via local headless Chrome for localhost/private/file URLs (auto-detected, engine overridable). The PNG is returned inline as an image block.",
|
|
411
|
+
promptSnippet: "Screenshot a webpage",
|
|
412
|
+
promptGuidelines: ["PNG returned inline (multimodal models see it); use when web_extract fails on JS-heavy pages, or to visually inspect a built UI. Local dev servers (localhost/LAN/file://) capture automatically via local Chrome."],
|
|
413
|
+
parameters: Type.Object({
|
|
414
|
+
url: Type.String(),
|
|
415
|
+
wait_for: Type.Optional(Type.Number({ default: 2, description: "Seconds to wait before capture." })),
|
|
416
|
+
wait_for_images: Type.Optional(Type.Boolean({ default: false })),
|
|
417
|
+
engine: Type.Optional(engineSchema.engine),
|
|
418
|
+
width: Type.Optional(Type.Number({ default: 1280, description: "Local engine: viewport width." })),
|
|
419
|
+
height: Type.Optional(Type.Number({ default: 800, description: "Local engine: viewport height (full_page uses 8000)." })),
|
|
420
|
+
full_page: Type.Optional(Type.Boolean({ default: false, description: "Local engine: capture a tall 8000px window to approximate full page." })),
|
|
421
|
+
reduced_motion: Type.Optional(Type.Boolean({ default: false, description: "Local engine: force prefers-reduced-motion. Staggered page-load reveals screenshot as blank sections otherwise; also doubles as a reduced-motion audit." })),
|
|
422
|
+
...crawl4aiControlSchema,
|
|
423
|
+
...sharedControlSchema,
|
|
424
|
+
}),
|
|
425
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
426
|
+
const url = params.url as string;
|
|
427
|
+
// Local capture with honest sub-500px handling: headless Chrome clamps
|
|
428
|
+
// --window-size to 500px (a "390 capture" renders 500 and crops), so
|
|
429
|
+
// widths below the clamp go through CDP device-metrics emulation and
|
|
430
|
+
// report a scrollWidth/innerWidth probe beside the PNG.
|
|
431
|
+
const captureLocalShot = async () => {
|
|
432
|
+
const width = (params.width as number | undefined) ?? 1280;
|
|
433
|
+
const reducedMotion = params.reduced_motion as boolean | undefined;
|
|
434
|
+
const waitForSec = params.wait_for as number | undefined;
|
|
435
|
+
const fullPage = params.full_page as boolean | undefined;
|
|
436
|
+
if (width < 500) {
|
|
437
|
+
const r = await runInteraction({
|
|
438
|
+
url,
|
|
439
|
+
viewport: { width, height: fullPage ? FULL_PAGE_HEIGHT : ((params.height as number | undefined) ?? 844) },
|
|
440
|
+
reducedMotion,
|
|
441
|
+
waitForSec,
|
|
442
|
+
signal,
|
|
443
|
+
});
|
|
444
|
+
const base64 = r.screenshot ?? "";
|
|
445
|
+
return { base64, mime: "image/png", size: Math.round((base64.length * 3) / 4), probe: r.probe, emulated: true, height: fullPage ? FULL_PAGE_HEIGHT : ((params.height as number | undefined) ?? 844) };
|
|
446
|
+
}
|
|
447
|
+
const cap = await captureLocalScreenshot({
|
|
448
|
+
url,
|
|
449
|
+
width,
|
|
450
|
+
height: params.height as number | undefined,
|
|
451
|
+
fullPage: params.full_page as boolean | undefined,
|
|
452
|
+
reducedMotion,
|
|
453
|
+
waitForSec,
|
|
454
|
+
signal,
|
|
455
|
+
});
|
|
456
|
+
return { ...cap, probe: undefined as { scrollWidth?: number; innerWidth?: number } | undefined, emulated: false };
|
|
457
|
+
};
|
|
458
|
+
let engine = resolveEngine(params.engine as string | undefined, url);
|
|
459
|
+
let screenshot: string | undefined;
|
|
460
|
+
let mime: string | undefined;
|
|
461
|
+
let size: number | undefined;
|
|
462
|
+
let artifactUrl: string | undefined;
|
|
463
|
+
let details: Record<string, unknown> = {};
|
|
464
|
+
|
|
465
|
+
if (engine === "local") {
|
|
466
|
+
const cap = await captureLocalShot();
|
|
467
|
+
screenshot = cap.base64;
|
|
468
|
+
mime = cap.mime;
|
|
469
|
+
size = cap.size;
|
|
470
|
+
details = { mime: cap.mime, size: cap.size, ...(cap.probe ? { probe: cap.probe, emulated: true, emulatedHeight: (cap as { height?: number }).height } : {}) };
|
|
471
|
+
} else {
|
|
472
|
+
const config = loadCrawl4aiConfig(params as Record<string, unknown>, cwdFromContext(ctx), includeProjectEnv(ctx));
|
|
473
|
+
try {
|
|
474
|
+
const result = await fetchCrawl4aiScreenshot(
|
|
475
|
+
config,
|
|
476
|
+
url,
|
|
477
|
+
params.wait_for as number | undefined,
|
|
478
|
+
params.wait_for_images as boolean | undefined,
|
|
479
|
+
signal,
|
|
480
|
+
);
|
|
481
|
+
if (result.success === false) {
|
|
482
|
+
throw new Error(String(result.error_message ?? "Crawl4AI screenshot failed"));
|
|
483
|
+
}
|
|
484
|
+
screenshot = result.screenshot as string | undefined;
|
|
485
|
+
artifactUrl = result.url as string | undefined;
|
|
486
|
+
mime = result.mime as string | undefined;
|
|
487
|
+
size = result.size as number | undefined;
|
|
488
|
+
details = { ...result };
|
|
489
|
+
} catch (err) {
|
|
490
|
+
// Daemon can't render this URL (SSRF-blocked); retry via local Chrome.
|
|
491
|
+
if (!isSsrfBlocked(err) || !findChromeBinary()) throw err;
|
|
492
|
+
engine = "local";
|
|
493
|
+
const cap = await captureLocalShot();
|
|
494
|
+
screenshot = cap.base64;
|
|
495
|
+
mime = cap.mime;
|
|
496
|
+
size = cap.size;
|
|
497
|
+
details = { mime: cap.mime, size: cap.size, ...(cap.probe ? { probe: cap.probe, emulated: true, emulatedHeight: (cap as { height?: number }).height } : {}), fallback: "daemon SSRF-blocked this URL" };
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
let text = `Screenshot: ${url}\nEngine: ${engine === "local" ? "local-chrome" : "crawl4ai"}\n`;
|
|
502
|
+
if (details.probe) {
|
|
503
|
+
const probe = details.probe as { scrollWidth?: number; innerWidth?: number };
|
|
504
|
+
const emuHeight = (details.emulatedHeight as number | undefined) ?? (params.height as number | undefined) ?? 844;
|
|
505
|
+
text += `Viewport: ${params.width}x${emuHeight} (device-emulated${params.full_page ? ", full page" : ""})\n`;
|
|
506
|
+
text += `Probe: scrollWidth ${probe.scrollWidth ?? "?"} / innerWidth ${probe.innerWidth ?? "?"}${typeof probe.scrollWidth === "number" && typeof params.width === "number" && probe.scrollWidth > params.width ? " — CONTENT OVERFLOWS" : ""}\n`;
|
|
507
|
+
}
|
|
508
|
+
if (artifactUrl) text += `Artifact: ${artifactUrl}\n`;
|
|
509
|
+
if (mime) text += `MIME: ${mime}\n`;
|
|
510
|
+
if (size) text += `Size: ${size} bytes\n`;
|
|
511
|
+
// Return the PNG as a real image block so multimodal models see it.
|
|
512
|
+
const content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }> = [
|
|
513
|
+
{ type: "text", text: truncateText(text) },
|
|
514
|
+
];
|
|
515
|
+
if (screenshot) content.push({ type: "image", data: screenshot, mimeType: mime || "image/png" });
|
|
516
|
+
return { content, details: { ...details, url, engine } };
|
|
517
|
+
},
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
// ── web_pdf ──────────────────────────────────────────────────────────
|
|
521
|
+
pi.registerTool({
|
|
522
|
+
name: "web_pdf",
|
|
523
|
+
label: "Web Page PDF",
|
|
524
|
+
description:
|
|
525
|
+
"PDF document via the Crawl4AI daemon, or via local headless Chrome for localhost/private/file URLs (auto-detected, engine overridable).",
|
|
526
|
+
promptSnippet: "PDF a webpage",
|
|
527
|
+
promptGuidelines: ["Printable/archivable page snapshot; returns base64 PDF. Local dev servers capture automatically via local Chrome."],
|
|
528
|
+
parameters: Type.Object({
|
|
529
|
+
url: Type.String(),
|
|
530
|
+
engine: Type.Optional(engineSchema.engine),
|
|
531
|
+
reduced_motion: Type.Optional(Type.Boolean({ default: false, description: "Local engine: force prefers-reduced-motion before printing." })),
|
|
532
|
+
...crawl4aiControlSchema,
|
|
533
|
+
...sharedControlSchema,
|
|
534
|
+
}),
|
|
535
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
536
|
+
const url = params.url as string;
|
|
537
|
+
let engine = resolveEngine(params.engine as string | undefined, url);
|
|
538
|
+
let pdf: string | undefined;
|
|
539
|
+
let artifactUrl: string | undefined;
|
|
540
|
+
let size: number | undefined;
|
|
541
|
+
let details: Record<string, unknown> = {};
|
|
542
|
+
|
|
543
|
+
if (engine === "local") {
|
|
544
|
+
const cap = await captureLocalPdf({ url, reducedMotion: params.reduced_motion as boolean | undefined, signal });
|
|
545
|
+
pdf = cap.base64;
|
|
546
|
+
size = cap.size;
|
|
547
|
+
details = { mime: cap.mime, size: cap.size };
|
|
548
|
+
} else {
|
|
549
|
+
const config = loadCrawl4aiConfig(params as Record<string, unknown>, cwdFromContext(ctx), includeProjectEnv(ctx));
|
|
550
|
+
try {
|
|
551
|
+
const result = await fetchCrawl4aiPdf(config, url, signal);
|
|
552
|
+
pdf = result.pdf as string | undefined;
|
|
553
|
+
artifactUrl = result.url as string | undefined;
|
|
554
|
+
size = result.size as number | undefined;
|
|
555
|
+
details = { ...result };
|
|
556
|
+
} catch (err) {
|
|
557
|
+
if (!isSsrfBlocked(err) || !findChromeBinary()) throw err;
|
|
558
|
+
engine = "local";
|
|
559
|
+
const cap = await captureLocalPdf({ url, reducedMotion: params.reduced_motion as boolean | undefined, signal });
|
|
560
|
+
pdf = cap.base64;
|
|
561
|
+
size = cap.size;
|
|
562
|
+
details = { mime: cap.mime, size: cap.size, fallback: "daemon SSRF-blocked this URL" };
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
let text = `PDF: ${url}\nEngine: ${engine === "local" ? "local-chrome" : "crawl4ai"}\n`;
|
|
567
|
+
if (pdf) text += `Data: base64 PDF (${pdf.length} chars)\n`;
|
|
568
|
+
if (artifactUrl) text += `Artifact: ${artifactUrl}\n`;
|
|
569
|
+
if (size) text += `Size: ${size} bytes\n`;
|
|
570
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: { ...details, url, engine } };
|
|
571
|
+
},
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
// ── web_interact ────────────────────────────────────────────────
|
|
575
|
+
pi.registerTool({
|
|
576
|
+
name: "web_interact",
|
|
577
|
+
label: "Web Page Interaction",
|
|
578
|
+
description:
|
|
579
|
+
"Drive a real headless Chrome session: open a URL and run steps in one call — trusted clicks (CDP mouse events, so user activation works: clipboard, login), typing, key presses, JS evaluate (value correctly unwrapped), wait_for selector/milliseconds, native dialog answer (dialog step), screenshots. Native confirm()/alert()/prompt()/beforeunload are auto-DISMISSED and reported per step; each step has a timeout_ms budget (default 60s, clamped 1s–600s) that fails loudly instead of hanging. Returns per-step results, a final inline PNG, and a scrollWidth/innerWidth probe. Local Chrome only (any http/https/file URL the local machine can reach). One call = one browser lifecycle; re-call with adjusted steps for exploratory flows.",
|
|
580
|
+
promptSnippet: "Interact with a webpage (click/type/evaluate) in headless Chrome",
|
|
581
|
+
promptGuidelines: [
|
|
582
|
+
"Use to VERIFY your own UI builds in the UX render-inspect loop: click the primary CTA, submit the form, read back state with evaluate — a screenshot alone proves nothing about behavior.",
|
|
583
|
+
"click/type go through CDP trusted input (user activation), so clipboard writes and gated APIs work — document.execCommand('copy') under a trusted click returns true.",
|
|
584
|
+
"Native confirm()/alert() dialogs are auto-DISMISSED (destructive actions stay blocked) and reported on the step result; to ACCEPT one, arm {\"dialog\":\"accept\"} before the triggering click.",
|
|
585
|
+
"A step stuck longer than timeout_ms (default 60s) fails with the reason instead of hanging the call — raise timeout_ms for legitimately slow evaluate steps.",
|
|
586
|
+
"Set viewport {width:390,height:844} for mobile briefs — honest device-metrics emulation (the CLI --window-size path clamps at 500px); the probe's scrollWidth reveals overflow (scrollWidth > width means broken CSS).",
|
|
587
|
+
"Steps run in order and stop at the first failure, so a broken selector surfaces loudly instead of silently no-op'ing later steps.",
|
|
588
|
+
],
|
|
589
|
+
parameters: Type.Object({
|
|
590
|
+
url: Type.String({ description: "Page to open (http://, https://, or file://)." }),
|
|
591
|
+
// Wire format is a FLAT object with optional action fields, not a union of
|
|
592
|
+
// object variants: Z.ai's anthropic-compatible endpoint rejects anyOf nested
|
|
593
|
+
// inside anyOf with 400/1210, and the wait_for string|number union inside the
|
|
594
|
+
// step union is exactly that. Runtime still accepts the union shape.
|
|
595
|
+
steps: Type.Optional(
|
|
596
|
+
Type.Array(
|
|
597
|
+
Type.Object({
|
|
598
|
+
click: Type.Optional(Type.String({ description: "Selector to trusted-click (scrolled into view, clicked at center via CDP mouse events)." })),
|
|
599
|
+
type: Type.Optional(Type.Object({ selector: Type.String(), text: Type.String() }, { description: "Focus selector, then insert text." })),
|
|
600
|
+
press: Type.Optional(Type.String({ description: "Key to press: Enter, Tab, Escape, Backspace, Delete, ArrowUp/Down/Left/Right, Space, or a single character." })),
|
|
601
|
+
evaluate: Type.Optional(Type.String({ description: "JS expression to evaluate; resolved value returned (awaitPromise on)." })),
|
|
602
|
+
wait_for: Type.Optional(Type.String({ description: "Selector to wait for (5s budget)." })),
|
|
603
|
+
wait_ms: Type.Optional(Type.Number({ description: "Milliseconds to sleep." })),
|
|
604
|
+
screenshot: Type.Optional(Type.Boolean({ description: "Capture a PNG now; the last screenshot is returned inline. false = no-op here (the automatic final screenshot still runs)." })),
|
|
605
|
+
dialog: Type.Optional(Type.String({ description: '"accept" or "dismiss" — the answer for the NEXT native dialog (confirm/alert/prompt/beforeunload); default auto-dismiss.' })),
|
|
606
|
+
label: Type.Optional(Type.String({ description: "Optional label shown on the step's result line." })),
|
|
607
|
+
}, { description: "One action per step object — set exactly one action field (click OR type OR press OR evaluate OR wait_for OR wait_ms OR screenshot OR dialog); extra action fields are auto-split into separate steps. Omit for open + screenshot + probe only." })),
|
|
608
|
+
),
|
|
609
|
+
viewport: Type.Optional(
|
|
610
|
+
Type.Object({
|
|
611
|
+
width: Type.Number({ description: "Viewport width in CSS px (e.g. 390 for a phone)." }),
|
|
612
|
+
height: Type.Optional(Type.Number({ description: "Viewport height (default 800)." })),
|
|
613
|
+
device_scale_factor: Type.Optional(Type.Number({ description: "Device scale factor (default 1; 2 for retina-style captures)." })),
|
|
614
|
+
}),
|
|
615
|
+
),
|
|
616
|
+
reduced_motion: Type.Optional(Type.Boolean({ default: false, description: "Emulate prefers-reduced-motion: reduce so staggered load reveals don't screenshot as blank sections." })),
|
|
617
|
+
grant: Type.Optional(Type.Array(Type.String(), { description: "Browser permissions to grant, e.g. [\"clipboardReadWrite\", \"clipboardSanitizedWrite\"] (CDP names). Friendly aliases \"clipboard-read\"/\"clipboard-write\" are mapped automatically." })),
|
|
618
|
+
wait_for: Type.Optional(Type.Number({ default: 2, description: "Seconds to settle after load before steps run." })),
|
|
619
|
+
...sharedControlSchema,
|
|
620
|
+
}),
|
|
621
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, _ctx: any) {
|
|
622
|
+
const url = params.url as string;
|
|
623
|
+
// Flatten wait_ms back onto the union shape runInteraction validates
|
|
624
|
+
// ({ wait_for: number }); the schema is flat only because of the
|
|
625
|
+
// Z.ai anyOf-in-anyOf limit (see schema comment above).
|
|
626
|
+
const steps = ((params.steps ?? []) as Record<string, unknown>[]).map((s) => {
|
|
627
|
+
if (!("wait_ms" in s)) return s as InteractStep;
|
|
628
|
+
const { wait_ms, ...rest } = s;
|
|
629
|
+
return { ...rest, wait_for: wait_ms } as InteractStep;
|
|
630
|
+
});
|
|
631
|
+
const result = await runInteraction({
|
|
632
|
+
url,
|
|
633
|
+
steps,
|
|
634
|
+
viewport: params.viewport as { width: number; height?: number; device_scale_factor?: number } | undefined,
|
|
635
|
+
reducedMotion: params.reduced_motion as boolean | undefined,
|
|
636
|
+
grant: params.grant as string[] | undefined,
|
|
637
|
+
waitForSec: params.wait_for as number | undefined,
|
|
638
|
+
// Per-step budget, clamped to a sane range — 0/negative would fail every step.
|
|
639
|
+
stepTimeoutMs:
|
|
640
|
+
typeof params.timeout_ms === "number" ? Math.min(Math.max(params.timeout_ms, 1_000), 600_000) : undefined,
|
|
641
|
+
signal,
|
|
642
|
+
});
|
|
643
|
+
const lines = [`Interaction: ${url}`];
|
|
644
|
+
if (result.splitSteps) {
|
|
645
|
+
lines.push(`Note: ${result.splitSteps} multi-action step(s) were auto-split into one-step-per-action (order preserved).`);
|
|
646
|
+
}
|
|
647
|
+
result.outcomes.forEach((o, i) => {
|
|
648
|
+
const value = o.ok && o.value !== undefined ? ` = ${JSON.stringify(o.value)}` : "";
|
|
649
|
+
lines.push(`${i + 1}. ${o.label} → ${o.ok ? `ok${value}` : `FAILED: ${o.error}`}${o.dialogs ? ` [${o.dialogs.join("; ")}]` : ""}`);
|
|
650
|
+
});
|
|
651
|
+
if (result.outcomes.some((o) => !o.ok)) lines.push("Stopped at the first failed step.");
|
|
652
|
+
if (result.navigatedTo) {
|
|
653
|
+
lines.push(`⚠ A step navigated the page to ${result.navigatedTo} — later steps ran against the NEW document.`);
|
|
654
|
+
}
|
|
655
|
+
if (result.dialogs?.length) lines.push(`Native dialogs: ${result.dialogs.join("; ")}`);
|
|
656
|
+
const p = result.probe;
|
|
657
|
+
const overflow =
|
|
658
|
+
typeof p.scrollWidth === "number" && typeof params.viewport === "object" && params.viewport !== null
|
|
659
|
+
? p.scrollWidth > (params.viewport as { width: number }).width
|
|
660
|
+
: false;
|
|
661
|
+
lines.push(
|
|
662
|
+
`Probe: scrollWidth ${p.scrollWidth ?? "?"} / innerWidth ${p.innerWidth ?? "?"}${overflow ? " — CONTENT OVERFLOWS the viewport" : ""}`,
|
|
663
|
+
);
|
|
664
|
+
const content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }> = [
|
|
665
|
+
{ type: "text", text: truncateText(lines.join("\n")) },
|
|
666
|
+
];
|
|
667
|
+
if (result.screenshot) content.push({ type: "image", data: result.screenshot, mimeType: "image/png" });
|
|
668
|
+
return {
|
|
669
|
+
content,
|
|
670
|
+
details: {
|
|
671
|
+
url,
|
|
672
|
+
probe: result.probe,
|
|
673
|
+
...(result.navigatedTo ? { navigatedTo: result.navigatedTo } : {}),
|
|
674
|
+
...(result.dialogs?.length ? { dialogs: result.dialogs } : {}),
|
|
675
|
+
outcomes: result.outcomes.map(({ label, ok, value, error, dialogs }) => ({ label, ok, value, error, dialogs })),
|
|
676
|
+
},
|
|
677
|
+
};
|
|
678
|
+
},
|
|
679
|
+
});
|
|
680
|
+
|
|
681
|
+
// ── web_research ─────────────────────────────────────────────────────
|
|
682
|
+
pi.registerTool({
|
|
683
|
+
name: "web_research",
|
|
684
|
+
label: "Web Research (Gemini)",
|
|
685
|
+
description:
|
|
686
|
+
"AI-synthesized web research via Gemini (gemini.google.com web tier, cookie auth). Mode 'ask' returns a quick grounded answer with source links (works guest-mode, Flash only). Mode 'research' runs Gemini Deep Research — plan turn, 'Start research' confirm, then polls until the cited report lands. Requires GEMINI_WEB_SECURE_1PSID (+ fresh __Secure-1PSIDTS); the plan turn runs over plain Node, but confirm (execution start) and report polling are gated server-side and may refuse from this transport (verified 2026-09-14: confirm needs a browser-grade TLS fingerprint) — refusals return an honest partial result (plan + transcript + note) instead of the report. Takes minutes when available.",
|
|
687
|
+
promptSnippet: "AI-synthesized research with citations",
|
|
688
|
+
promptGuidelines: [
|
|
689
|
+
"Use for AI-synthesized research with sources (mode ask = quick grounded answer; mode research = multi-minute Deep Research report). NOT for URL-list searches (web_search) or single-URL extraction (web_extract). Cite the returned source URLs.",
|
|
690
|
+
],
|
|
691
|
+
parameters: Type.Object({
|
|
692
|
+
query: Type.String({ description: "Research question or topic." }),
|
|
693
|
+
mode: Type.Optional(Type.Union(
|
|
694
|
+
[Type.Literal("ask"), Type.Literal("research")],
|
|
695
|
+
{ default: "ask", description: "ask = quick grounded answer (guest OK); research = full Deep Research report (cookie required; runs the pure-Node DR client — plan/confirm execute on live sessions, degraded sessions return an honest partial result)." },
|
|
696
|
+
)),
|
|
697
|
+
model: Type.Optional(Type.String({ description: "Gemini model for ask mode (e.g. gemini-3-flash). Discovered from the account by default." })),
|
|
698
|
+
...sharedControlSchema,
|
|
699
|
+
}),
|
|
700
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
701
|
+
const config = loadGeminiWebConfig(cwdFromContext(ctx), includeProjectEnv(ctx));
|
|
702
|
+
const mode = (params.mode as string) || "ask";
|
|
703
|
+
const query = params.query as string;
|
|
704
|
+
try {
|
|
705
|
+
if (mode === "research") {
|
|
706
|
+
const timeoutMs = Math.min(Math.max((params.timeout_ms as number) ?? 600_000, 30_000), 1_800_000);
|
|
707
|
+
const result = await geminiResearch(query, { config, timeoutMs, signal });
|
|
708
|
+
const meta = [
|
|
709
|
+
"Mode: research (Gemini Deep Research)",
|
|
710
|
+
result.title ? `Title: ${result.title}` : null,
|
|
711
|
+
result.eta ? `ETA: ${result.eta}` : null,
|
|
712
|
+
].filter(Boolean).join("\n");
|
|
713
|
+
const sources = result.sources.length ? result.sources.map((s, i) => `${i + 1}. ${s}`).join("\n") : "(none found in report text)";
|
|
714
|
+
const text = `${meta}\n\n${result.text}\n\n--- Sources (extracted from report) ---\n${sources}`;
|
|
715
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: { mode, ...result } };
|
|
716
|
+
}
|
|
717
|
+
const askTimeoutMs = Math.min(Math.max((params.timeout_ms as number) ?? 120_000, 30_000), 600_000);
|
|
718
|
+
const result = await geminiAsk(query, { config, model: params.model as string | undefined, timeoutMs: askTimeoutMs, signal });
|
|
719
|
+
const meta = [
|
|
720
|
+
"Mode: ask",
|
|
721
|
+
`Model: ${result.model ?? "unknown"}`,
|
|
722
|
+
result.guest ? "Guest mode (no cookie — Flash only; set GEMINI_WEB_SECURE_1PSID for full access)" : "Cookie auth",
|
|
723
|
+
].join("\n");
|
|
724
|
+
const sources = result.sources.length ? result.sources.map((s, i) => `${i + 1}. ${s}`).join("\n") : "(none found in answer text)";
|
|
725
|
+
const text = `${meta}\n\n${result.text}\n\n--- Sources (extracted from answer) ---\n${sources}`;
|
|
726
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: { mode, ...result } };
|
|
727
|
+
} catch (err) {
|
|
728
|
+
throw new Error(describeGeminiError(err));
|
|
729
|
+
}
|
|
730
|
+
},
|
|
731
|
+
});
|
|
732
|
+
|
|
733
|
+
// ── web_image ────────────────────────────────────────────────────────
|
|
734
|
+
pi.registerTool({
|
|
735
|
+
name: "web_image",
|
|
736
|
+
label: "Web Image Generation",
|
|
737
|
+
description:
|
|
738
|
+
"Generate images from text via free upstream providers, with fallback: Gemini web (gemini.google.com, guest or cookie auth), ChatGPT web (subscription via CHATGPT_WEB_AUTH_KEY / codex login, image_generation tool), Z.ai official API (GLM-Image via ZAI_API_KEY), or any custom OpenAI-compatible images endpoint (WEB_IMAGE_API_BASE_URL). Optional size=WxH for zai/custom (glm-image enums incl. 960x1728 portrait; omit = server default, usually square). Returns saved file paths plus the images inline.",
|
|
739
|
+
promptSnippet: "Generate images via free upstreams (Gemini web, ChatGPT web, Z.ai GLM-Image)",
|
|
740
|
+
promptGuidelines: [
|
|
741
|
+
"Use for image GENERATION from a text prompt. provider auto falls back gemini → chatgpt → zai → custom. Portrait/aspect-sensitive prompts: pass size (zai/custom), e.g. 960x1728 — default is square. Capturing an EXISTING page is web_screenshot, not this.",
|
|
742
|
+
],
|
|
743
|
+
parameters: Type.Object({
|
|
744
|
+
prompt: Type.String({ description: "Image description." }),
|
|
745
|
+
provider: Type.Optional(Type.Union(
|
|
746
|
+
[Type.Literal("auto"), Type.Literal("gemini"), Type.Literal("chatgpt"), Type.Literal("zai"), Type.Literal("custom")],
|
|
747
|
+
{ default: "auto", description: "auto = gemini → chatgpt (if CHATGPT_WEB_AUTH_KEY/codex login) → zai (if ZAI_API_KEY) → custom (if WEB_IMAGE_API_BASE_URL); pin one to skip fallback." },
|
|
748
|
+
)),
|
|
749
|
+
model: Type.Optional(Type.String({ description: "Provider-specific model (e.g. glm-image, or a Gemini image-capable model id). Omit for the provider default." })),
|
|
750
|
+
n: Type.Optional(Type.Number({ default: 1, description: "Number of images, 1-4 (applies to zai/custom; the gemini web tier returns its own count)." })),
|
|
751
|
+
size: Type.Optional(Type.String({ pattern: "^\\d{3,4}x\\d{3,4}$", description: "Image size as WxH (zai/custom only). glm-image enums: 1280x1280 (default), 1568x1056, 1056x1568, 1472x1088, 1088x1472, 1728x960, 960x1728. Omit for the provider default." })),
|
|
752
|
+
out_dir: Type.Optional(Type.String({ description: "Directory for saved images (default: fresh temp dir)." })),
|
|
753
|
+
...sharedControlSchema,
|
|
754
|
+
}),
|
|
755
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
756
|
+
const cwd = cwdFromContext(ctx);
|
|
757
|
+
const trusted = includeProjectEnv(ctx);
|
|
758
|
+
const prompt = params.prompt as string;
|
|
759
|
+
const n = Math.min(Math.max(Math.trunc((params.n as number) ?? 1) || 1, 1), 4);
|
|
760
|
+
const timeoutMs = Math.min(Math.max((params.timeout_ms as number) ?? 180_000, 10_000), 600_000);
|
|
761
|
+
const outDir = params.out_dir
|
|
762
|
+
? path.resolve(cwd, String(params.out_dir))
|
|
763
|
+
: await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-web-image-"));
|
|
764
|
+
const result = await generateImageWithFallback({
|
|
765
|
+
prompt,
|
|
766
|
+
model: params.model as string | undefined,
|
|
767
|
+
n,
|
|
768
|
+
size: parseSizeParam(params.size),
|
|
769
|
+
outDir,
|
|
770
|
+
provider: (params.provider as "auto" | ImageProvider) ?? "auto",
|
|
771
|
+
geminiConfig: loadGeminiWebConfig(cwd, trusted),
|
|
772
|
+
apiConfig: loadImageApiConfig(cwd, trusted),
|
|
773
|
+
rateConfig: loadImageRateConfig(cwd, trusted),
|
|
774
|
+
...(() => {
|
|
775
|
+
const cgpt = loadChatGptAuth(cwd, trusted);
|
|
776
|
+
return { chatgptAuth: cgpt.auth, ...(cgpt.problem ? { chatgptProblem: cgpt.problem } : {}) };
|
|
777
|
+
})(),
|
|
778
|
+
timeoutMs,
|
|
779
|
+
signal,
|
|
780
|
+
});
|
|
781
|
+
const blocks = await Promise.all(result.paths.map(toImageBlock));
|
|
782
|
+
const text = [
|
|
783
|
+
`Provider: ${result.provider}${result.model ? ` (${result.model})` : ""}`,
|
|
784
|
+
`Saved: ${result.paths.length} image(s)`,
|
|
785
|
+
...result.paths.map((p) => ` ${p}`),
|
|
786
|
+
...(result.urls.length
|
|
787
|
+
? [
|
|
788
|
+
"Not saved (download failed — URL openable directly):",
|
|
789
|
+
...result.urls.map((u, i) => ` ${u}${result.downloadErrors?.[i] ? ` (${result.downloadErrors[i]})` : ""}`),
|
|
790
|
+
]
|
|
791
|
+
: []),
|
|
792
|
+
result.attempts.length ? `Provider notes: ${result.attempts.join(" | ")}` : null,
|
|
793
|
+
result.note ?? null,
|
|
794
|
+
].filter(Boolean).join("\n");
|
|
795
|
+
const content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }> = [
|
|
796
|
+
{ type: "text" as const, text },
|
|
797
|
+
...blocks,
|
|
798
|
+
];
|
|
799
|
+
return { content, details: { provider: result.provider, model: result.model, paths: result.paths, urls: result.urls, downloadErrors: result.downloadErrors, attempts: result.attempts } };
|
|
800
|
+
},
|
|
801
|
+
});
|
|
802
|
+
|
|
803
|
+
// ── web_chat ─────────────────────────────────────────────────────────
|
|
804
|
+
pi.registerTool({
|
|
805
|
+
name: "web_chat",
|
|
806
|
+
label: "Web Chat (ChatGPT web / gateway)",
|
|
807
|
+
description:
|
|
808
|
+
"One-off chat completion — ChatGPT web tier (subscription, via CHATGPT_WEB_AUTH_KEY / codex login; default when configured) or any OpenAI-compatible gateway (WEB_CHAT_API_BASE_URL). Non-streaming Q&A; not a provider — use /model to switch your main model.",
|
|
809
|
+
promptSnippet: "One-off chat via ChatGPT web or an OpenAI-compatible gateway",
|
|
810
|
+
promptGuidelines: [
|
|
811
|
+
"Use for a quick one-off second opinion, classification, or short generation call. Grounded research with sources → web_research; switching your main chat model → /model.",
|
|
812
|
+
],
|
|
813
|
+
parameters: Type.Object({
|
|
814
|
+
prompt: Type.String({ description: "The question or instruction." }),
|
|
815
|
+
provider: Type.Optional(Type.Union(
|
|
816
|
+
[Type.Literal("chatgpt"), Type.Literal("gateway")],
|
|
817
|
+
{ description: "chatgpt = ChatGPT web (CHATGPT_WEB_AUTH_KEY / codex login); gateway = WEB_CHAT_API_BASE_URL. Default: chatgpt when configured, else gateway." },
|
|
818
|
+
)),
|
|
819
|
+
model: Type.Optional(Type.String({ description: "Model id (chatgpt: e.g. gpt-5.5; gateway: e.g. gpt-5.3-mini). Omit for the provider default." })),
|
|
820
|
+
system: Type.Optional(Type.String({ description: "Optional system prompt." })),
|
|
821
|
+
...sharedControlSchema,
|
|
822
|
+
}),
|
|
823
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
824
|
+
const cwd = cwdFromContext(ctx);
|
|
825
|
+
const trusted = includeProjectEnv(ctx);
|
|
826
|
+
const wantChatGpt = params.provider === "chatgpt" || (params.provider === undefined && Boolean(loadChatGptAuth(cwd, trusted).auth));
|
|
827
|
+
if (wantChatGpt) {
|
|
828
|
+
const cgpt = loadChatGptAuth(cwd, trusted);
|
|
829
|
+
if (!cgpt.auth) {
|
|
830
|
+
throw new Error(
|
|
831
|
+
`ChatGPT web chat is not configured. ${cgpt.problem ?? "Set CHATGPT_WEB_AUTH_KEY (the tokens JSON from ~/.codex/auth.json after `codex login`, or a bare access-token JWT) in ~/.pi/agent/.env.local"} — or run codex login — then restart pi. provider=gateway uses WEB_CHAT_API_BASE_URL instead.`,
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
const timeoutMs = Math.min(Math.max((params.timeout_ms as number) ?? 120_000, 10_000), 300_000);
|
|
835
|
+
try {
|
|
836
|
+
const result = await chatgptWebChat({
|
|
837
|
+
auth: cgpt.auth,
|
|
838
|
+
prompt: params.prompt as string,
|
|
839
|
+
system: params.system as string | undefined,
|
|
840
|
+
model: params.model as string | undefined,
|
|
841
|
+
cwd,
|
|
842
|
+
includeCwdEnv: trusted,
|
|
843
|
+
timeoutMs,
|
|
844
|
+
signal,
|
|
845
|
+
});
|
|
846
|
+
const text = `Model: ${result.model ?? "chatgpt default"}\n\n${result.text}`;
|
|
847
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: { model: result.model, usage: result.usage } };
|
|
848
|
+
} catch (err) {
|
|
849
|
+
if ((err as Error)?.name === "AbortError") throw err;
|
|
850
|
+
throw new Error(describeChatGptError(err));
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
const config = loadChatConfig(cwd, trusted);
|
|
854
|
+
if (!config) {
|
|
855
|
+
throw new Error(
|
|
856
|
+
"web_chat is not configured. Set WEB_CHAT_API_BASE_URL (and optional WEB_CHAT_API_KEY) in ~/.pi/agent/.env.local — any OpenAI-compatible /chat/completions gateway works (a ChatGPT web bridge, https://api.openai.com/v1, …) — then restart pi.",
|
|
857
|
+
);
|
|
858
|
+
}
|
|
859
|
+
const timeoutMs = Math.min(Math.max((params.timeout_ms as number) ?? 120_000, 10_000), 300_000);
|
|
860
|
+
try {
|
|
861
|
+
const result = await chatgptChat({
|
|
862
|
+
baseUrl: config.baseUrl,
|
|
863
|
+
apiKey: config.apiKey,
|
|
864
|
+
prompt: params.prompt as string,
|
|
865
|
+
model: params.model as string | undefined,
|
|
866
|
+
system: params.system as string | undefined,
|
|
867
|
+
timeoutMs,
|
|
868
|
+
signal,
|
|
869
|
+
});
|
|
870
|
+
const text = `Model: ${result.model ?? "gateway default"}\n\n${result.text}`;
|
|
871
|
+
return { content: [{ type: "text" as const, text: truncateText(text) }], details: { model: result.model, usage: undefined } };
|
|
872
|
+
} catch (err) {
|
|
873
|
+
if ((err as Error)?.name === "AbortError") throw err;
|
|
874
|
+
throw new Error(describeChatApiError(err));
|
|
875
|
+
}
|
|
876
|
+
},
|
|
877
|
+
});
|
|
878
|
+
|
|
879
|
+
// ── web_status ───────────────────────────────────────────────────────
|
|
880
|
+
pi.registerTool({
|
|
881
|
+
name: "web_status",
|
|
882
|
+
label: "Web Provider Status",
|
|
883
|
+
description:
|
|
884
|
+
"Show web provider config status without printing secrets.",
|
|
885
|
+
promptSnippet: "Check web provider config and server status",
|
|
886
|
+
promptGuidelines: ["Reports backend presence/health; never prints secrets."],
|
|
887
|
+
parameters: Type.Object({}),
|
|
888
|
+
async execute(_id: string, _params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
889
|
+
const cwd = cwdFromContext(ctx);
|
|
890
|
+
const trusted = includeProjectEnv(ctx);
|
|
891
|
+
|
|
892
|
+
// Provider config status
|
|
893
|
+
const braveKey = findEnvValue("BRAVE_API_KEY", cwd, trusted);
|
|
894
|
+
const searxngUrl = findEnvValue("SEARXNG_BASE_URL", cwd, trusted);
|
|
895
|
+
const fireKey = findEnvValue("FIRECRAWL_API_KEY", cwd, trusted);
|
|
896
|
+
const fireUrl = findEnvValue("FIRECRAWL_API_URL", cwd, trusted);
|
|
897
|
+
const c4aiUrl = findEnvValue("CRAWL4AI_API_URL", cwd, trusted);
|
|
898
|
+
const c4aiToken = findEnvValue("CRAWL4AI_API_TOKEN", cwd, trusted);
|
|
899
|
+
const geminiCfg = loadGeminiWebConfig(cwd, trusted);
|
|
900
|
+
const imageApiCfg = loadImageApiConfig(cwd, trusted);
|
|
901
|
+
const chatgptCfg = loadChatGptAuth(cwd, trusted);
|
|
902
|
+
|
|
903
|
+
const { isAgyInstalled } = await import("./lib/agy");
|
|
904
|
+
|
|
905
|
+
const fcBaseUrl = normalizeFirecrawlBaseUrl(fireUrl.value);
|
|
906
|
+
const fcHosted = !fireUrl.value || fcBaseUrl.startsWith(HOSTED_FIRECRAWL_BASE_URL);
|
|
907
|
+
|
|
908
|
+
const status: Record<string, unknown> = {
|
|
909
|
+
brave: { apiKeyFound: Boolean(braveKey.value), apiKeySource: braveKey.value ? braveKey.source : "not set" },
|
|
910
|
+
searxng: { baseUrl: normalizeSearxngBaseUrl(searxngUrl.value), baseUrlSource: searxngUrl.source || "default local" },
|
|
911
|
+
firecrawl: {
|
|
912
|
+
baseUrl: fcBaseUrl,
|
|
913
|
+
apiUrlSource: fireUrl.source || "default hosted",
|
|
914
|
+
apiKeyFound: Boolean(fireKey.value),
|
|
915
|
+
apiKeySource: fireKey.value ? fireKey.source : "not set",
|
|
916
|
+
hostedMode: fcHosted,
|
|
917
|
+
ready: fcHosted ? Boolean(fireKey.value) : Boolean(fireUrl.value?.trim()),
|
|
918
|
+
},
|
|
919
|
+
crawl4ai: {
|
|
920
|
+
baseUrl: normalizeCrawl4aiApiUrl(c4aiUrl.value),
|
|
921
|
+
baseUrlSource: c4aiUrl.source || "default",
|
|
922
|
+
apiTokenFound: Boolean(c4aiToken.value),
|
|
923
|
+
apiTokenSource: c4aiToken.value ? c4aiToken.source : "not set",
|
|
924
|
+
},
|
|
925
|
+
agy: { installed: isAgyInstalled() },
|
|
926
|
+
geminiWeb: {
|
|
927
|
+
configured: Boolean(geminiCfg.psid),
|
|
928
|
+
cookieSource: geminiCfg.psidSource,
|
|
929
|
+
proxy: Boolean(geminiCfg.proxy),
|
|
930
|
+
cookieStore: cookieStoreSnapshot(),
|
|
931
|
+
},
|
|
932
|
+
imageProviders: {
|
|
933
|
+
gemini: { configured: Boolean(geminiCfg.psid), guestPossible: true },
|
|
934
|
+
chatgpt: { configured: Boolean(chatgptCfg.auth) },
|
|
935
|
+
zai: { configured: Boolean(imageApiCfg.zai) },
|
|
936
|
+
custom: imageApiCfg.custom
|
|
937
|
+
? { configured: true, label: imageApiCfg.custom.label }
|
|
938
|
+
: { configured: false },
|
|
939
|
+
rate: imageRateSnapshot(),
|
|
940
|
+
},
|
|
941
|
+
webChat: (() => {
|
|
942
|
+
const cfg = loadChatConfig(cwd, trusted);
|
|
943
|
+
return {
|
|
944
|
+
configured: Boolean(cfg),
|
|
945
|
+
baseUrl: cfg?.baseUrl,
|
|
946
|
+
keyFound: Boolean(cfg?.apiKey),
|
|
947
|
+
source: cfg?.source ?? "not set",
|
|
948
|
+
defaultProvider: loadChatGptAuth(cwd, trusted).auth ? "chatgpt" : "gateway",
|
|
949
|
+
};
|
|
950
|
+
})(),
|
|
951
|
+
chatgptWeb: chatgptAuthSnapshot(chatgptCfg),
|
|
952
|
+
localChrome: { path: findChromeBinary() ?? "not found" },
|
|
953
|
+
};
|
|
954
|
+
|
|
955
|
+
// Crawl4AI health check
|
|
956
|
+
let c4aiHealth: Record<string, unknown> | undefined;
|
|
957
|
+
try {
|
|
958
|
+
const c4aiCfg = loadCrawl4aiConfig({}, cwd, trusted);
|
|
959
|
+
c4aiHealth = await fetchCrawl4aiHealth(c4aiCfg, signal);
|
|
960
|
+
} catch (e: any) {
|
|
961
|
+
c4aiHealth = { status: "unreachable", error: e?.message ?? String(e) };
|
|
962
|
+
}
|
|
963
|
+
status.crawl4ai = { ...(status.crawl4ai as Record<string, unknown>), health: c4aiHealth };
|
|
964
|
+
|
|
965
|
+
return { content: [{ type: "text" as const, text: JSON.stringify(status, null, 2) }], details: status };
|
|
966
|
+
},
|
|
967
|
+
});
|
|
968
|
+
|
|
969
|
+
// ── Always-on routing guidance ──────────────────────────────────────────
|
|
970
|
+
// Inject the backend-selection protocol only when a web_* tool is actually
|
|
971
|
+
// active, so recon agents / sessions without pi-web carry zero overhead.
|
|
972
|
+
pi.on("before_agent_start", async (event) => {
|
|
973
|
+
const active = event.systemPromptOptions?.selectedTools ?? pi.getActiveTools();
|
|
974
|
+
if (!active.some((t) => t.startsWith("web_"))) return;
|
|
975
|
+
return { systemPrompt: `${event.systemPrompt}\n\n${WEB_ROUTING_GUIDANCE}` };
|
|
976
|
+
});
|
|
977
|
+
|
|
978
|
+
}
|