@diffra-ai/cli 0.1.1 → 0.1.3
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 +38 -0
- package/dist/bundle/chunks/{anthropic-messages-M3HXJPTI.js → anthropic-messages-5EMOURYI.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-GIFO2563.js → azure-openai-responses-N67KWG2X.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-CVEPACZO.js → chunk-3UNTEQ65.js} +1 -1
- package/dist/bundle/chunks/{chunk-VJQ6ZYW4.js → chunk-4NMBWIZG.js} +5 -5
- package/dist/bundle/chunks/{chunk-INTHKDF2.js → chunk-65DC2T66.js} +1 -1
- package/dist/bundle/chunks/chunk-6ZD23B2R.js +2 -0
- package/dist/bundle/chunks/{chunk-WEJVQTLI.js → chunk-BF423NQ7.js} +1 -1
- package/dist/bundle/chunks/{chunk-262RLABF.js → chunk-CES65UJH.js} +1 -1
- package/dist/bundle/chunks/{chunk-RJRIMI6M.js → chunk-GRYHVZSI.js} +1 -1
- package/dist/bundle/chunks/{chunk-WAH3PGZX.js → chunk-HFTZ6OJJ.js} +2 -2
- package/dist/bundle/chunks/{chunk-N6Q2WLPG.js → chunk-NEFH2K3C.js} +1 -1
- package/dist/bundle/chunks/{chunk-OQFRYL4U.js → chunk-PISJX26Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-VSFRR6IC.js → chunk-QQ6NVGNW.js} +1 -1
- package/dist/bundle/chunks/{chunk-N6QWAQ6I.js → chunk-QYYUGS66.js} +1 -1
- package/dist/bundle/chunks/{chunk-GT3WTHFU.js → chunk-RLMZZV4Q.js} +1 -1
- package/dist/bundle/chunks/chunk-RTPG7C5I.js +2003 -0
- package/dist/bundle/chunks/{chunk-6S2AQWGR.js → chunk-SI7T4LPD.js} +4 -4
- package/dist/bundle/chunks/{chunk-CCH74R6M.js → chunk-VOKUVFV4.js} +1 -1
- package/dist/bundle/chunks/{chunk-OOE7BGUD.js → chunk-VWWMBH3G.js} +1 -1
- package/dist/bundle/chunks/{chunk-B3FUE2LF.js → chunk-XAA355T2.js} +1 -1
- package/dist/bundle/chunks/{cli-EC3ZETTA.js → cli-55VO5MAJ.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-YW7YYPAC.js → cloudflare-workers-ai-system-one-HB5U67WC.js} +1 -1
- package/dist/bundle/chunks/{easter-egg-3d-QN5RJMZR.js → easter-egg-3d-VAZ2JWDP.js} +1 -1
- package/dist/bundle/chunks/{execute-3J63CQJG.js → execute-OEFRHFHI.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-F6DN2LQU.js → google-generative-ai-XRHE7R52.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-MDWFDVAW.js → google-vertex-75CQOPKC.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-XO72TVVH.js → llama-cpp-classify-LKIRB7ZR.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-KYVGR5VN.js → mistral-conversations-KLGIHK73.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-SIQN5LUE.js → openai-codex-responses-7L5VV67U.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-B22DYT4F.js → openai-completions-RBF6UXDW.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-4GVNTR54.js → openai-decisions-W3PJQIOF.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-5DVNSQCE.js → openai-responses-W5ZMLOTR.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-SQMQNKJU.js → openrouter-images-4FW6VFV4.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-GZ4HZRKJ.js → pi-messages-RT7FVQ4G.js} +1 -1
- package/dist/bundle/chunks/{runtime-KEVIZBAR.js → runtime-SI4R3AXJ.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-GMPGMPLA.js → typesafe-system-one-DSJ7OYVL.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-M75O3ECA.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +13 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/sandbox-command.d.ts +8 -0
- package/dist/cli/sandbox-command.d.ts.map +1 -0
- package/dist/cli/sandbox-command.js +52 -0
- package/dist/cli/sandbox-command.js.map +1 -0
- package/dist/config.d.ts +7 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +14 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +20 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +72 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/approval-mode.d.ts +28 -0
- package/dist/core/approval-mode.d.ts.map +1 -0
- package/dist/core/approval-mode.js +34 -0
- package/dist/core/approval-mode.js.map +1 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +15 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +3 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +30 -3
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/fast-model.d.ts +10 -0
- package/dist/core/fast-model.d.ts.map +1 -0
- package/dist/core/fast-model.js +13 -0
- package/dist/core/fast-model.js.map +1 -0
- package/dist/core/keybindings.d.ts +8 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +4 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/sandbox/escalation.d.ts +32 -0
- package/dist/core/sandbox/escalation.d.ts.map +1 -0
- package/dist/core/sandbox/escalation.js +70 -0
- package/dist/core/sandbox/escalation.js.map +1 -0
- package/dist/core/sandbox/launch.d.ts +14 -0
- package/dist/core/sandbox/launch.d.ts.map +1 -0
- package/dist/core/sandbox/launch.js +18 -0
- package/dist/core/sandbox/launch.js.map +1 -0
- package/dist/core/sandbox/policy.d.ts +50 -0
- package/dist/core/sandbox/policy.d.ts.map +1 -0
- package/dist/core/sandbox/policy.js +96 -0
- package/dist/core/sandbox/policy.js.map +1 -0
- package/dist/core/sandbox/seatbelt.d.ts +17 -0
- package/dist/core/sandbox/seatbelt.d.ts.map +1 -0
- package/dist/core/sandbox/seatbelt.js +169 -0
- package/dist/core/sandbox/seatbelt.js.map +1 -0
- package/dist/core/sandbox/windows.d.ts +30 -0
- package/dist/core/sandbox/windows.d.ts.map +1 -0
- package/dist/core/sandbox/windows.js +104 -0
- package/dist/core/sandbox/windows.js.map +1 -0
- package/dist/core/settings-defaults.d.ts +28 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +28 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +9 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +58 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +124 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +177 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/tools/bash.d.ts +12 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +27 -7
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts +3 -0
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +2 -0
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/powershell.d.ts +3 -2
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/powershell.js +4 -6
- package/dist/core/tools/powershell.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +2 -2
- package/dist/core/tools/render-utils.js +5 -5
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/renderers/edit.d.ts.map +1 -1
- package/dist/core/tools/renderers/edit.js +16 -19
- package/dist/core/tools/renderers/edit.js.map +1 -1
- package/dist/core/tools/write.d.ts +3 -0
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +2 -0
- package/dist/core/tools/write.js.map +1 -1
- package/dist/extensions/agents/agent-tool.d.ts +61 -0
- package/dist/extensions/agents/agent-tool.d.ts.map +1 -0
- package/dist/extensions/agents/agent-tool.js +277 -0
- package/dist/extensions/agents/agent-tool.js.map +1 -0
- package/dist/extensions/agents/background.d.ts +56 -0
- package/dist/extensions/agents/background.d.ts.map +1 -0
- package/dist/extensions/agents/background.js +142 -0
- package/dist/extensions/agents/background.js.map +1 -0
- package/dist/extensions/agents/builtin-agents.d.ts +8 -0
- package/dist/extensions/agents/builtin-agents.d.ts.map +1 -0
- package/dist/extensions/agents/builtin-agents.js +38 -0
- package/dist/extensions/agents/builtin-agents.js.map +1 -0
- package/dist/extensions/agents/call-scopes.d.ts +34 -0
- package/dist/extensions/agents/call-scopes.d.ts.map +1 -0
- package/dist/extensions/agents/call-scopes.js +36 -0
- package/dist/extensions/agents/call-scopes.js.map +1 -0
- package/dist/extensions/agents/definitions.d.ts +64 -0
- package/dist/extensions/agents/definitions.d.ts.map +1 -0
- package/dist/extensions/agents/definitions.js +216 -0
- package/dist/extensions/agents/definitions.js.map +1 -0
- package/dist/extensions/agents/index.d.ts +15 -0
- package/dist/extensions/agents/index.d.ts.map +1 -0
- package/dist/extensions/agents/index.js +327 -0
- package/dist/extensions/agents/index.js.map +1 -0
- package/dist/extensions/agents/runner.d.ts +63 -0
- package/dist/extensions/agents/runner.d.ts.map +1 -0
- package/dist/extensions/agents/runner.js +156 -0
- package/dist/extensions/agents/runner.js.map +1 -0
- package/dist/extensions/approval/auto-classifier.d.ts +32 -0
- package/dist/extensions/approval/auto-classifier.d.ts.map +1 -0
- package/dist/extensions/approval/auto-classifier.js +116 -0
- package/dist/extensions/approval/auto-classifier.js.map +1 -0
- package/dist/extensions/approval/exit-plan-mode.d.ts +24 -0
- package/dist/extensions/approval/exit-plan-mode.d.ts.map +1 -0
- package/dist/extensions/approval/exit-plan-mode.js +99 -0
- package/dist/extensions/approval/exit-plan-mode.js.map +1 -0
- package/dist/extensions/approval/index.d.ts +15 -0
- package/dist/extensions/approval/index.d.ts.map +1 -0
- package/dist/extensions/approval/index.js +329 -0
- package/dist/extensions/approval/index.js.map +1 -0
- package/dist/extensions/approval/plan-reminders.d.ts +9 -0
- package/dist/extensions/approval/plan-reminders.d.ts.map +1 -0
- package/dist/extensions/approval/plan-reminders.js +42 -0
- package/dist/extensions/approval/plan-reminders.js.map +1 -0
- package/dist/extensions/approval/policy.d.ts +52 -0
- package/dist/extensions/approval/policy.d.ts.map +1 -0
- package/dist/extensions/approval/policy.js +124 -0
- package/dist/extensions/approval/policy.js.map +1 -0
- package/dist/extensions/approval/shell-safety.d.ts +11 -0
- package/dist/extensions/approval/shell-safety.d.ts.map +1 -0
- package/dist/extensions/approval/shell-safety.js +264 -0
- package/dist/extensions/approval/shell-safety.js.map +1 -0
- package/dist/extensions/cron/cron-expression.d.ts +30 -0
- package/dist/extensions/cron/cron-expression.d.ts.map +1 -0
- package/dist/extensions/cron/cron-expression.js +119 -0
- package/dist/extensions/cron/cron-expression.js.map +1 -0
- package/dist/extensions/cron/index.d.ts +19 -0
- package/dist/extensions/cron/index.d.ts.map +1 -0
- package/dist/extensions/cron/index.js +215 -0
- package/dist/extensions/cron/index.js.map +1 -0
- package/dist/extensions/cron/loop-args.d.ts +35 -0
- package/dist/extensions/cron/loop-args.d.ts.map +1 -0
- package/dist/extensions/cron/loop-args.js +95 -0
- package/dist/extensions/cron/loop-args.js.map +1 -0
- package/dist/extensions/cron/loop-texts.d.ts +29 -0
- package/dist/extensions/cron/loop-texts.d.ts.map +1 -0
- package/dist/extensions/cron/loop-texts.js +83 -0
- package/dist/extensions/cron/loop-texts.js.map +1 -0
- package/dist/extensions/cron/scheduler.d.ts +79 -0
- package/dist/extensions/cron/scheduler.d.ts.map +1 -0
- package/dist/extensions/cron/scheduler.js +146 -0
- package/dist/extensions/cron/scheduler.js.map +1 -0
- package/dist/extensions/cron/tools.d.ts +47 -0
- package/dist/extensions/cron/tools.d.ts.map +1 -0
- package/dist/extensions/cron/tools.js +141 -0
- package/dist/extensions/cron/tools.js.map +1 -0
- package/dist/extensions/goals/evidence.d.ts +20 -0
- package/dist/extensions/goals/evidence.d.ts.map +1 -0
- package/dist/extensions/goals/evidence.js +77 -0
- package/dist/extensions/goals/evidence.js.map +1 -0
- package/dist/extensions/goals/index.d.ts +45 -0
- package/dist/extensions/goals/index.d.ts.map +1 -0
- package/dist/extensions/goals/index.js +438 -0
- package/dist/extensions/goals/index.js.map +1 -0
- package/dist/extensions/goals/prompts.d.ts +15 -0
- package/dist/extensions/goals/prompts.d.ts.map +1 -0
- package/dist/extensions/goals/prompts.js +51 -0
- package/dist/extensions/goals/prompts.js.map +1 -0
- package/dist/extensions/goals/state.d.ts +88 -0
- package/dist/extensions/goals/state.d.ts.map +1 -0
- package/dist/extensions/goals/state.js +204 -0
- package/dist/extensions/goals/state.js.map +1 -0
- package/dist/extensions/goals/tools.d.ts +40 -0
- package/dist/extensions/goals/tools.d.ts.map +1 -0
- package/dist/extensions/goals/tools.js +118 -0
- package/dist/extensions/goals/tools.js.map +1 -0
- package/dist/extensions/goals/verifier.d.ts +30 -0
- package/dist/extensions/goals/verifier.d.ts.map +1 -0
- package/dist/extensions/goals/verifier.js +89 -0
- package/dist/extensions/goals/verifier.js.map +1 -0
- package/dist/extensions/hooks/aggregate.d.ts +30 -0
- package/dist/extensions/hooks/aggregate.d.ts.map +1 -0
- package/dist/extensions/hooks/aggregate.js +103 -0
- package/dist/extensions/hooks/aggregate.js.map +1 -0
- package/dist/extensions/hooks/config.d.ts +47 -0
- package/dist/extensions/hooks/config.d.ts.map +1 -0
- package/dist/extensions/hooks/config.js +169 -0
- package/dist/extensions/hooks/config.js.map +1 -0
- package/dist/extensions/hooks/file-watcher.d.ts +31 -0
- package/dist/extensions/hooks/file-watcher.d.ts.map +1 -0
- package/dist/extensions/hooks/file-watcher.js +106 -0
- package/dist/extensions/hooks/file-watcher.js.map +1 -0
- package/dist/extensions/hooks/index.d.ts +17 -0
- package/dist/extensions/hooks/index.d.ts.map +1 -0
- package/dist/extensions/hooks/index.js +349 -0
- package/dist/extensions/hooks/index.js.map +1 -0
- package/dist/extensions/hooks/matcher.d.ts +10 -0
- package/dist/extensions/hooks/matcher.d.ts.map +1 -0
- package/dist/extensions/hooks/matcher.js +85 -0
- package/dist/extensions/hooks/matcher.js.map +1 -0
- package/dist/extensions/hooks/runner.d.ts +54 -0
- package/dist/extensions/hooks/runner.d.ts.map +1 -0
- package/dist/extensions/hooks/runner.js +197 -0
- package/dist/extensions/hooks/runner.js.map +1 -0
- package/dist/extensions/index.d.ts.map +1 -1
- package/dist/extensions/index.js +29 -2
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/lsp/config.d.ts +40 -0
- package/dist/extensions/lsp/config.d.ts.map +1 -0
- package/dist/extensions/lsp/config.js +92 -0
- package/dist/extensions/lsp/config.js.map +1 -0
- package/dist/extensions/lsp/connection.d.ts +32 -0
- package/dist/extensions/lsp/connection.d.ts.map +1 -0
- package/dist/extensions/lsp/connection.js +124 -0
- package/dist/extensions/lsp/connection.js.map +1 -0
- package/dist/extensions/lsp/index.d.ts +15 -0
- package/dist/extensions/lsp/index.d.ts.map +1 -0
- package/dist/extensions/lsp/index.js +103 -0
- package/dist/extensions/lsp/index.js.map +1 -0
- package/dist/extensions/lsp/server.d.ts +68 -0
- package/dist/extensions/lsp/server.d.ts.map +1 -0
- package/dist/extensions/lsp/server.js +373 -0
- package/dist/extensions/lsp/server.js.map +1 -0
- package/dist/extensions/lsp/tool.d.ts +43 -0
- package/dist/extensions/lsp/tool.d.ts.map +1 -0
- package/dist/extensions/lsp/tool.js +534 -0
- package/dist/extensions/lsp/tool.js.map +1 -0
- package/dist/extensions/memory/index.d.ts +15 -0
- package/dist/extensions/memory/index.d.ts.map +1 -0
- package/dist/extensions/memory/index.js +336 -0
- package/dist/extensions/memory/index.js.map +1 -0
- package/dist/extensions/memory/memory-agent.d.ts +29 -0
- package/dist/extensions/memory/memory-agent.d.ts.map +1 -0
- package/dist/extensions/memory/memory-agent.js +102 -0
- package/dist/extensions/memory/memory-agent.js.map +1 -0
- package/dist/extensions/memory/prompts.d.ts +18 -0
- package/dist/extensions/memory/prompts.d.ts.map +1 -0
- package/dist/extensions/memory/prompts.js +124 -0
- package/dist/extensions/memory/prompts.js.map +1 -0
- package/dist/extensions/memory/recall.d.ts +14 -0
- package/dist/extensions/memory/recall.d.ts.map +1 -0
- package/dist/extensions/memory/recall.js +80 -0
- package/dist/extensions/memory/recall.js.map +1 -0
- package/dist/extensions/memory/store.d.ts +48 -0
- package/dist/extensions/memory/store.d.ts.map +1 -0
- package/dist/extensions/memory/store.js +132 -0
- package/dist/extensions/memory/store.js.map +1 -0
- package/dist/extensions/skills/bundled/batch/SKILL.md +74 -0
- package/dist/extensions/skills/bundled/review/SKILL.md +93 -0
- package/dist/extensions/skills/index.d.ts +15 -0
- package/dist/extensions/skills/index.d.ts.map +1 -0
- package/dist/extensions/skills/index.js +68 -0
- package/dist/extensions/skills/index.js.map +1 -0
- package/dist/extensions/skills/learn.d.ts +9 -0
- package/dist/extensions/skills/learn.d.ts.map +1 -0
- package/dist/extensions/skills/learn.js +46 -0
- package/dist/extensions/skills/learn.js.map +1 -0
- package/dist/extensions/todo/index.d.ts +14 -0
- package/dist/extensions/todo/index.d.ts.map +1 -0
- package/dist/extensions/todo/index.js +55 -0
- package/dist/extensions/todo/index.js.map +1 -0
- package/dist/extensions/todo/todos.d.ts +64 -0
- package/dist/extensions/todo/todos.d.ts.map +1 -0
- package/dist/extensions/todo/todos.js +145 -0
- package/dist/extensions/todo/todos.js.map +1 -0
- package/dist/extensions/todo/tool.d.ts +23 -0
- package/dist/extensions/todo/tool.d.ts.map +1 -0
- package/dist/extensions/todo/tool.js +104 -0
- package/dist/extensions/todo/tool.js.map +1 -0
- package/dist/extensions/web-fetch/fetch-tool.d.ts +27 -0
- package/dist/extensions/web-fetch/fetch-tool.d.ts.map +1 -0
- package/dist/extensions/web-fetch/fetch-tool.js +319 -0
- package/dist/extensions/web-fetch/fetch-tool.js.map +1 -0
- package/dist/extensions/web-fetch/html-to-markdown.d.ts +7 -0
- package/dist/extensions/web-fetch/html-to-markdown.d.ts.map +1 -0
- package/dist/extensions/web-fetch/html-to-markdown.js +21 -0
- package/dist/extensions/web-fetch/html-to-markdown.js.map +1 -0
- package/dist/extensions/web-fetch/index.d.ts +10 -0
- package/dist/extensions/web-fetch/index.d.ts.map +1 -0
- package/dist/extensions/web-fetch/index.js +13 -0
- package/dist/extensions/web-fetch/index.js.map +1 -0
- package/dist/extensions/web-fetch/page-fetch.d.ts +45 -0
- package/dist/extensions/web-fetch/page-fetch.d.ts.map +1 -0
- package/dist/extensions/web-fetch/page-fetch.js +117 -0
- package/dist/extensions/web-fetch/page-fetch.js.map +1 -0
- package/dist/extensions/web-fetch/pdf-text.d.ts +29 -0
- package/dist/extensions/web-fetch/pdf-text.d.ts.map +1 -0
- package/dist/extensions/web-fetch/pdf-text.js +71 -0
- package/dist/extensions/web-fetch/pdf-text.js.map +1 -0
- package/dist/extensions/web-fetch/preapproved-hosts.d.ts +7 -0
- package/dist/extensions/web-fetch/preapproved-hosts.d.ts.map +1 -0
- package/dist/extensions/web-fetch/preapproved-hosts.js +110 -0
- package/dist/extensions/web-fetch/preapproved-hosts.js.map +1 -0
- package/dist/extensions/web-search/dashscope-search.d.ts +29 -0
- package/dist/extensions/web-search/dashscope-search.d.ts.map +1 -0
- package/dist/extensions/web-search/dashscope-search.js +279 -0
- package/dist/extensions/web-search/dashscope-search.js.map +1 -0
- package/dist/extensions/web-search/index.d.ts +15 -0
- package/dist/extensions/web-search/index.d.ts.map +1 -0
- package/dist/extensions/web-search/index.js +51 -0
- package/dist/extensions/web-search/index.js.map +1 -0
- package/dist/extensions/web-search/search-config.d.ts +53 -0
- package/dist/extensions/web-search/search-config.d.ts.map +1 -0
- package/dist/extensions/web-search/search-config.js +174 -0
- package/dist/extensions/web-search/search-config.js.map +1 -0
- package/dist/extensions/web-search/search-tool.d.ts +29 -0
- package/dist/extensions/web-search/search-tool.d.ts.map +1 -0
- package/dist/extensions/web-search/search-tool.js +149 -0
- package/dist/extensions/web-search/search-tool.js.map +1 -0
- package/dist/extensions/worktree/git-worktree.d.ts +69 -0
- package/dist/extensions/worktree/git-worktree.d.ts.map +1 -0
- package/dist/extensions/worktree/git-worktree.js +199 -0
- package/dist/extensions/worktree/git-worktree.js.map +1 -0
- package/dist/extensions/worktree/index.d.ts +27 -0
- package/dist/extensions/worktree/index.d.ts.map +1 -0
- package/dist/extensions/worktree/index.js +188 -0
- package/dist/extensions/worktree/index.js.map +1 -0
- package/dist/extensions/worktree/startup.d.ts +17 -0
- package/dist/extensions/worktree/startup.d.ts.map +1 -0
- package/dist/extensions/worktree/startup.js +56 -0
- package/dist/extensions/worktree/startup.js.map +1 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +28 -4
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +18 -0
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +87 -20
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/diffra-logo.d.ts +6 -0
- package/dist/modes/interactive/components/diffra-logo.d.ts.map +1 -1
- package/dist/modes/interactive/components/diffra-logo.js +30 -4
- package/dist/modes/interactive/components/diffra-logo.js.map +1 -1
- package/dist/modes/interactive/components/dynamic-border.d.ts +1 -1
- package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
- package/dist/modes/interactive/components/dynamic-border.js +3 -3
- package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +16 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +84 -46
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +5 -2
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +152 -62
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-status.d.ts +5 -0
- package/dist/modes/interactive/components/tool-status.d.ts.map +1 -0
- package/dist/modes/interactive/components/tool-status.js +15 -0
- package/dist/modes/interactive/components/tool-status.js.map +1 -0
- package/dist/modes/interactive/components/user-message.d.ts +4 -8
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +38 -36
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +24 -8
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +3 -2
- package/dist/modes/interactive/theme/light.json +3 -2
- package/dist/modes/interactive/theme/system-theme.d.ts +1 -0
- package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/system-theme.js +41 -14
- package/dist/modes/interactive/theme/system-theme.js.map +1 -1
- package/dist/utils/shell.d.ts +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +12 -2
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +5 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +48 -0
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/approval-modes.md +99 -0
- package/docs/builtin-skills.md +53 -0
- package/docs/cli.md +25 -1
- package/docs/docs.json +44 -0
- package/docs/environment-variables.md +7 -0
- package/docs/extensions.md +27 -2
- package/docs/goals.md +84 -0
- package/docs/hooks.md +112 -0
- package/docs/keybindings.md +1 -0
- package/docs/lsp.md +71 -0
- package/docs/memory.md +71 -0
- package/docs/sandbox.md +108 -0
- package/docs/scheduled-tasks.md +84 -0
- package/docs/security.md +3 -2
- package/docs/settings.md +28 -3
- package/docs/shell-aliases.md +1 -1
- package/docs/skills.md +4 -0
- package/docs/slash-commands.md +15 -0
- package/docs/subagents.md +102 -0
- package/docs/web-tools.md +83 -0
- package/docs/windows.md +2 -1
- package/docs/worktrees.md +52 -0
- package/examples/extensions/README.md +1 -1
- package/examples/extensions/plan-mode/README.md +2 -2
- package/examples/extensions/plan-mode/index.ts +7 -4
- package/examples/extensions/subagent/README.md +2 -0
- package/examples/extensions/subagent/index.ts +3 -0
- package/examples/extensions/todo.ts +4 -0
- package/package.json +9 -8
- package/schemas/keybindings.schema.json +4 -0
- package/schemas/settings.schema.json +421 -0
- package/dist/bundle/chunks/chunk-GCKVPVMH.js +0 -2
- package/dist/bundle/chunks/chunk-UNQMECQ4.js +0 -1240
- package/dist/bundle/chunks/virtual-modules-TRFD5ZOL.js +0 -2
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `todo_write` tool: the model replaces the whole todo list with each call, and the result shows
|
|
3
|
+
* the list with a status marker per todo.
|
|
4
|
+
*/
|
|
5
|
+
import { Text } from "@diffra-ai/tui";
|
|
6
|
+
import { Type } from "typebox";
|
|
7
|
+
import { StringEnum } from "../../core/extensions/diffra-ai-extension-view.js";
|
|
8
|
+
import { detectTodoChanges, getCurrentTodos, MAX_TODO_ID_LENGTH, preserveTodoDependencies, sameTodos, TODO_WRITE_TOOL_NAME, validateTodos, } from "./todos.js";
|
|
9
|
+
const todoWriteSchema = Type.Object({
|
|
10
|
+
todos: Type.Array(Type.Object({
|
|
11
|
+
content: Type.String({ minLength: 1 }),
|
|
12
|
+
status: StringEnum(["pending", "in_progress", "completed"]),
|
|
13
|
+
id: Type.String({ maxLength: MAX_TODO_ID_LENGTH }),
|
|
14
|
+
blockedBy: Type.Optional(Type.Array(Type.String({ maxLength: MAX_TODO_ID_LENGTH }), {
|
|
15
|
+
description: "Todo IDs that must be completed before this item. Updates of an unfinished list keep the dependencies of todos sent without blockedBy; use [] to remove them.",
|
|
16
|
+
})),
|
|
17
|
+
}, { additionalProperties: false }), { description: "The updated todo list" }),
|
|
18
|
+
});
|
|
19
|
+
const DESCRIPTION = `Use this tool to create and manage a user-visible task list when explicit progress tracking improves clarity.
|
|
20
|
+
|
|
21
|
+
## When to Use This Tool
|
|
22
|
+
Use it for work that is complex, ambiguous, or multi-phase; has several independent outcomes or important dependencies; benefits from checkpoints; or when the user explicitly asks for a todo list.
|
|
23
|
+
|
|
24
|
+
Do not use it for simple or single-step work, purely conversational or informational requests, or tasks you can answer or complete directly, unless the user explicitly asks for a todo list.
|
|
25
|
+
|
|
26
|
+
## Planning with Todos
|
|
27
|
+
Keep the list short and outcome-oriented: a few meaningful, logically ordered, verifiable steps. Do not create a separate todo for every error, file, command, or minor edit.
|
|
28
|
+
|
|
29
|
+
Use blockedBy only for real dependencies. Reference IDs from the same list and keep independent work unblocked.
|
|
30
|
+
|
|
31
|
+
Keep at most one task in_progress. Keep statuses current, mark finished work completed, revise the list when the scope or approach changes, and remove items that are no longer relevant. Do not mark incomplete or blocked work completed.`;
|
|
32
|
+
/** Create the `todo_write` tool. It reads the current list from the session branch of each call. */
|
|
33
|
+
export function createTodoWriteToolDefinition() {
|
|
34
|
+
return {
|
|
35
|
+
name: TODO_WRITE_TOOL_NAME,
|
|
36
|
+
label: "TodoWrite",
|
|
37
|
+
description: DESCRIPTION,
|
|
38
|
+
promptSnippet: "Create and update a user-visible task list for multi-step work",
|
|
39
|
+
promptGuidelines: [
|
|
40
|
+
"Track complex, ambiguous, or multi-step work with todo_write; skip it for simple tasks unless the user explicitly asks for a plan.",
|
|
41
|
+
"Keep at most one todo in_progress; when several todos finish together, update their statuses in one todo_write call.",
|
|
42
|
+
"Do not repeat the full todo list in prose after calling todo_write; briefly mention only important context or the next step.",
|
|
43
|
+
],
|
|
44
|
+
parameters: todoWriteSchema,
|
|
45
|
+
defaultActive: false,
|
|
46
|
+
executionMode: "sequential",
|
|
47
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
48
|
+
const previous = getCurrentTodos(ctx.sessionManager.getBranch());
|
|
49
|
+
const todos = preserveTodoDependencies(params.todos, previous);
|
|
50
|
+
const problem = validateTodos(todos);
|
|
51
|
+
if (problem)
|
|
52
|
+
throw new Error(problem);
|
|
53
|
+
if (sameTodos(previous, todos)) {
|
|
54
|
+
return {
|
|
55
|
+
content: [
|
|
56
|
+
{
|
|
57
|
+
type: "text",
|
|
58
|
+
text: "Todo list is already up to date. No changes were needed.\n\n<system-reminder>\nYour todo list was not modified because it is already current. Continue with your existing tasks.\n</system-reminder>",
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
details: { todos, changes: { created: [], completed: [] }, unchanged: true },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const details = { todos, changes: detectTodoChanges(previous, todos), unchanged: false };
|
|
65
|
+
const text = todos.length === 0
|
|
66
|
+
? "Todo list has been cleared.\n\n<system-reminder>\nYour todo list is now empty. DO NOT mention this explicitly to the user. You have no pending tasks in your todo list.\n</system-reminder>"
|
|
67
|
+
: `Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable\n\n<system-reminder>\nYour todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:\n\n${JSON.stringify(todos)}. Continue on with the tasks at hand if applicable.\n</system-reminder>`;
|
|
68
|
+
return { content: [{ type: "text", text }], details };
|
|
69
|
+
},
|
|
70
|
+
renderCall(args, theme, context) {
|
|
71
|
+
const text = context.lastComponent ?? new Text("", 0, 0);
|
|
72
|
+
const count = args.todos?.length;
|
|
73
|
+
const summary = count === undefined ? "" : ` ${theme.fg("muted", `${count} ${count === 1 ? "todo" : "todos"}`)}`;
|
|
74
|
+
text.setText(`${theme.fg("toolTitle", theme.bold(TODO_WRITE_TOOL_NAME))}${summary}`);
|
|
75
|
+
return text;
|
|
76
|
+
},
|
|
77
|
+
renderResult(result, _options, theme, context) {
|
|
78
|
+
const text = context.lastComponent ?? new Text("", 0, 0);
|
|
79
|
+
const details = result.details;
|
|
80
|
+
if (context.isError || !details) {
|
|
81
|
+
const output = result.content.find((part) => part.type === "text")?.text ?? "";
|
|
82
|
+
text.setText(`\n${theme.fg("error", output)}`);
|
|
83
|
+
}
|
|
84
|
+
else if (details.todos.length === 0) {
|
|
85
|
+
text.setText(`\n${theme.fg("muted", "Todo list cleared")}`);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
text.setText(`\n${details.todos.map((todo) => formatTodoLine(todo, theme)).join("\n")}`);
|
|
89
|
+
}
|
|
90
|
+
return text;
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export const TODO_STATUS_MARKERS = { pending: "○", in_progress: "◐", completed: "●" };
|
|
95
|
+
/** One todo as a styled line: its status marker and content, completed todos struck through. */
|
|
96
|
+
export function formatTodoLine(todo, theme) {
|
|
97
|
+
const marker = TODO_STATUS_MARKERS[todo.status];
|
|
98
|
+
if (todo.status === "completed")
|
|
99
|
+
return theme.fg("muted", `${marker} ${theme.strikethrough(todo.content)}`);
|
|
100
|
+
if (todo.status === "in_progress")
|
|
101
|
+
return theme.fg("success", `${marker} ${todo.content}`);
|
|
102
|
+
return theme.fg("toolOutput", `${marker} ${todo.content}`);
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=tool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/todo/tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IA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mB,CAAC,EAAE,CAAC,CAAC;YAC7D,CAAC;iBAAM,CAAC;gBACP,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YAC1F,CAAC;YACD,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,mBAAmB,GAA+B,EAAE,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;AAElH,gGAAgG;AAChG,MAAM,UAAU,cAAc,CAAC,IAAc,EAAE,KAAY;IAC1D,MAAM,MAAM,GAAG,mBAAmB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAChD,IAAI,IAAI,CAAC,MAAM,KAAK,WAAW;QAAE,OAAO,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC5G,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa;QAAE,OAAO,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IAC3F,OAAO,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,GAAG,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/**\n * The `todo_write` tool: the model replaces the whole todo list with each call, and the result shows\n * the list with a status marker per todo.\n */\n\nimport { Text } from \"@diffra-ai/tui\";\nimport { Type } from \"typebox\";\nimport { StringEnum } from \"../../core/extensions/diffra-ai-extension-view.ts\";\nimport type { ToolDefinition } from \"../../core/extensions/types.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport {\n\tdetectTodoChanges,\n\tgetCurrentTodos,\n\tMAX_TODO_ID_LENGTH,\n\tpreserveTodoDependencies,\n\tsameTodos,\n\tTODO_WRITE_TOOL_NAME,\n\ttype TodoItem,\n\ttype TodoStatus,\n\ttype TodoWriteDetails,\n\tvalidateTodos,\n} from \"./todos.ts\";\n\nconst todoWriteSchema = Type.Object({\n\ttodos: Type.Array(\n\t\tType.Object(\n\t\t\t{\n\t\t\t\tcontent: Type.String({ minLength: 1 }),\n\t\t\t\tstatus: StringEnum([\"pending\", \"in_progress\", \"completed\"] as const),\n\t\t\t\tid: Type.String({ maxLength: MAX_TODO_ID_LENGTH }),\n\t\t\t\tblockedBy: Type.Optional(\n\t\t\t\t\tType.Array(Type.String({ maxLength: MAX_TODO_ID_LENGTH }), {\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Todo IDs that must be completed before this item. Updates of an unfinished list keep the dependencies of todos sent without blockedBy; use [] to remove them.\",\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{ additionalProperties: false },\n\t\t),\n\t\t{ description: \"The updated todo list\" },\n\t),\n});\n\nconst DESCRIPTION = `Use this tool to create and manage a user-visible task list when explicit progress tracking improves clarity.\n\n## When to Use This Tool\nUse it for work that is complex, ambiguous, or multi-phase; has several independent outcomes or important dependencies; benefits from checkpoints; or when the user explicitly asks for a todo list.\n\nDo not use it for simple or single-step work, purely conversational or informational requests, or tasks you can answer or complete directly, unless the user explicitly asks for a todo list.\n\n## Planning with Todos\nKeep the list short and outcome-oriented: a few meaningful, logically ordered, verifiable steps. Do not create a separate todo for every error, file, command, or minor edit.\n\nUse blockedBy only for real dependencies. Reference IDs from the same list and keep independent work unblocked.\n\nKeep at most one task in_progress. Keep statuses current, mark finished work completed, revise the list when the scope or approach changes, and remove items that are no longer relevant. Do not mark incomplete or blocked work completed.`;\n\n/** Create the `todo_write` tool. It reads the current list from the session branch of each call. */\nexport function createTodoWriteToolDefinition(): ToolDefinition<typeof todoWriteSchema, TodoWriteDetails> {\n\treturn {\n\t\tname: TODO_WRITE_TOOL_NAME,\n\t\tlabel: \"TodoWrite\",\n\t\tdescription: DESCRIPTION,\n\t\tpromptSnippet: \"Create and update a user-visible task list for multi-step work\",\n\t\tpromptGuidelines: [\n\t\t\t\"Track complex, ambiguous, or multi-step work with todo_write; skip it for simple tasks unless the user explicitly asks for a plan.\",\n\t\t\t\"Keep at most one todo in_progress; when several todos finish together, update their statuses in one todo_write call.\",\n\t\t\t\"Do not repeat the full todo list in prose after calling todo_write; briefly mention only important context or the next step.\",\n\t\t],\n\t\tparameters: todoWriteSchema,\n\t\tdefaultActive: false,\n\t\texecutionMode: \"sequential\",\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst previous = getCurrentTodos(ctx.sessionManager.getBranch());\n\t\t\tconst todos = preserveTodoDependencies(params.todos, previous);\n\t\t\tconst problem = validateTodos(todos);\n\t\t\tif (problem) throw new Error(problem);\n\t\t\tif (sameTodos(previous, todos)) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Todo list is already up to date. No changes were needed.\\n\\n<system-reminder>\\nYour todo list was not modified because it is already current. Continue with your existing tasks.\\n</system-reminder>\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { todos, changes: { created: [], completed: [] }, unchanged: true },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst details: TodoWriteDetails = { todos, changes: detectTodoChanges(previous, todos), unchanged: false };\n\t\t\tconst text =\n\t\t\t\ttodos.length === 0\n\t\t\t\t\t? \"Todo list has been cleared.\\n\\n<system-reminder>\\nYour todo list is now empty. DO NOT mention this explicitly to the user. You have no pending tasks in your todo list.\\n</system-reminder>\"\n\t\t\t\t\t: `Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable\\n\\n<system-reminder>\\nYour todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:\\n\\n${JSON.stringify(todos)}. Continue on with the tasks at hand if applicable.\\n</system-reminder>`;\n\t\t\treturn { content: [{ type: \"text\", text }], details };\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst count = args.todos?.length;\n\t\t\tconst summary =\n\t\t\t\tcount === undefined ? \"\" : ` ${theme.fg(\"muted\", `${count} ${count === 1 ? \"todo\" : \"todos\"}`)}`;\n\t\t\ttext.setText(`${theme.fg(\"toolTitle\", theme.bold(TODO_WRITE_TOOL_NAME))}${summary}`);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst details = result.details;\n\t\t\tif (context.isError || !details) {\n\t\t\t\tconst output = result.content.find((part) => part.type === \"text\")?.text ?? \"\";\n\t\t\t\ttext.setText(`\\n${theme.fg(\"error\", output)}`);\n\t\t\t} else if (details.todos.length === 0) {\n\t\t\t\ttext.setText(`\\n${theme.fg(\"muted\", \"Todo list cleared\")}`);\n\t\t\t} else {\n\t\t\t\ttext.setText(`\\n${details.todos.map((todo) => formatTodoLine(todo, theme)).join(\"\\n\")}`);\n\t\t\t}\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport const TODO_STATUS_MARKERS: Record<TodoStatus, string> = { pending: \"○\", in_progress: \"◐\", completed: \"●\" };\n\n/** One todo as a styled line: its status marker and content, completed todos struck through. */\nexport function formatTodoLine(todo: TodoItem, theme: Theme): string {\n\tconst marker = TODO_STATUS_MARKERS[todo.status];\n\tif (todo.status === \"completed\") return theme.fg(\"muted\", `${marker} ${theme.strikethrough(todo.content)}`);\n\tif (todo.status === \"in_progress\") return theme.fg(\"success\", `${marker} ${todo.content}`);\n\treturn theme.fg(\"toolOutput\", `${marker} ${todo.content}`);\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `web_fetch` tool: fetch one URL, turn the page into text, and have a model answer the call's
|
|
3
|
+
* prompt from it. Same-site redirects are followed; a redirect to another site is reported instead.
|
|
4
|
+
*/
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import type { ToolDefinition } from "../../core/extensions/types.ts";
|
|
7
|
+
import type { Settings } from "../../core/settings-schema.ts";
|
|
8
|
+
export declare const WEB_FETCH_TOOL_NAME = "web_fetch";
|
|
9
|
+
declare const webFetchSchema: Type.TObject<{
|
|
10
|
+
url: Type.TString;
|
|
11
|
+
prompt: Type.TString;
|
|
12
|
+
format: Type.TOptional<Type.TUnsafe<"auto" | "html" | "markdown" | "text">>;
|
|
13
|
+
}>;
|
|
14
|
+
/** `details` of a `web_fetch` result: the one-line summary the result row shows. */
|
|
15
|
+
export type WebFetchDetails = {
|
|
16
|
+
summary: string;
|
|
17
|
+
};
|
|
18
|
+
/** Create `web_fetch`. Fetched pages are cached per session for 15 minutes. */
|
|
19
|
+
export declare function createWebFetchToolDefinition(options: {
|
|
20
|
+
getSettings(): Settings;
|
|
21
|
+
}): ToolDefinition<typeof webFetchSchema, WebFetchDetails>;
|
|
22
|
+
/** Rewrite `github.com/<owner>/<repo>/blob/...` to the raw file on raw.githubusercontent.com. */
|
|
23
|
+
export declare function rewriteGitHubBlobUrl(url: string): string;
|
|
24
|
+
/** `http://` URLs to public hosts without an explicit port use HTTPS. */
|
|
25
|
+
export declare function upgradeToHttps(url: string): string;
|
|
26
|
+
export {};
|
|
27
|
+
//# sourceMappingURL=fetch-tool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/web-fetch/fetch-tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG/B,OAAO,KAAK,EAAwB,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAE3F,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAS9D,eAAO,MAAM,mBAAmB,cAAc,CAAC;AAE/C,QAAA,MAAM,cAAc;;;;EASlB,CAAC;AAIH,oFAAoF;AACpF,MAAM,MAAM,eAAe,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAsDlD,+EAA+E;AAC/E,wBAAgB,4BAA4B,CAAC,OAAO,EAAE;IACrD,WAAW,IAAI,QAAQ,CAAC;CACxB,GAAG,cAAc,CAAC,OAAO,cAAc,EAAE,eAAe,CAAC,CA+DzD;AAgMD,iGAAiG;AACjG,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAUxD;AAED,yEAAyE;AACzE,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAMlD"}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `web_fetch` tool: fetch one URL, turn the page into text, and have a model answer the call's
|
|
3
|
+
* prompt from it. Same-site redirects are followed; a redirect to another site is reported instead.
|
|
4
|
+
*/
|
|
5
|
+
import { uuidv7 } from "@diffra-ai/ai";
|
|
6
|
+
import { Text } from "@diffra-ai/tui";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
import { VERSION } from "../../config.js";
|
|
9
|
+
import { StringEnum } from "../../core/extensions/diffra-ai-extension-view.js";
|
|
10
|
+
import { resolveFastModel } from "../../core/fast-model.js";
|
|
11
|
+
import { formatSize } from "../../core/tools/truncate.js";
|
|
12
|
+
import { getDiffraUserAgent } from "../../utils/diffra-user-agent.js";
|
|
13
|
+
import { writeOutputFile } from "../../utils/output-files.js";
|
|
14
|
+
import { htmlToMarkdown } from "./html-to-markdown.js";
|
|
15
|
+
import { fetchPage, isConnectionError, isPrivateHost } from "./page-fetch.js";
|
|
16
|
+
import { extractPdfText } from "./pdf-text.js";
|
|
17
|
+
import { isPreapprovedUrl } from "./preapproved-hosts.js";
|
|
18
|
+
export const WEB_FETCH_TOOL_NAME = "web_fetch";
|
|
19
|
+
const webFetchSchema = Type.Object({
|
|
20
|
+
url: Type.String({ description: "The URL to fetch content from" }),
|
|
21
|
+
prompt: Type.String({ description: "The prompt to run on the fetched content" }),
|
|
22
|
+
format: Type.Optional(StringEnum(["auto", "markdown", "html", "text"], {
|
|
23
|
+
description: "Preferred content format (Accept header only): auto (default, prefers markdown), markdown, html, or text. All content is normalized to plain text.",
|
|
24
|
+
})),
|
|
25
|
+
});
|
|
26
|
+
const FETCH_TIMEOUT_MS = 60_000;
|
|
27
|
+
const DEFAULT_PROCESSING_TIMEOUT_MS = 300_000;
|
|
28
|
+
const MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
|
|
29
|
+
const MAX_REDIRECTS = 10;
|
|
30
|
+
const MAX_CONTENT_CHARS = 100_000;
|
|
31
|
+
const CACHE_TTL_MS = 15 * 60 * 1000;
|
|
32
|
+
const CACHE_CAPACITY = 32;
|
|
33
|
+
const MAX_CACHEABLE_CHARS = 2 * 1024 * 1024;
|
|
34
|
+
const ACCEPT_HEADERS = {
|
|
35
|
+
auto: "text/markdown, text/html;q=0.9, text/plain;q=0.8, */*;q=0.1",
|
|
36
|
+
markdown: "text/markdown, */*;q=0.1",
|
|
37
|
+
html: "text/html, */*;q=0.1",
|
|
38
|
+
text: "text/plain, */*;q=0.1",
|
|
39
|
+
};
|
|
40
|
+
const DESCRIPTION = `Fetches content from a specified URL and processes it using an AI model
|
|
41
|
+
- Takes a URL and a prompt as input
|
|
42
|
+
- Supports content negotiation for markdown (reduces tokens by ~80%)
|
|
43
|
+
- Fetches the URL content and converts HTML to Markdown (links preserved)
|
|
44
|
+
- Processes the content with the prompt using an AI model
|
|
45
|
+
- Returns the model's response about the content, prefixed with fetch metadata (HTTP status, content type, size)
|
|
46
|
+
- Use this tool when you need to retrieve and analyze web content
|
|
47
|
+
|
|
48
|
+
Usage notes:
|
|
49
|
+
- IMPORTANT: This tool cannot access authenticated or private URLs (e.g. Google Docs, Confluence, Jira, private GitHub). If an MCP-provided web fetch tool is available, prefer it, as it may have fewer restrictions. MCP tools start with "mcp__".
|
|
50
|
+
- The URL must be a fully-formed valid URL
|
|
51
|
+
- Plain-http URLs to public hosts are upgraded to https automatically; localhost and private hosts are fetched as given
|
|
52
|
+
- When a URL redirects to a different host, the redirect is NOT followed; the tool returns the redirect URL so you can call web_fetch again with it
|
|
53
|
+
- Binary content (PDFs, images, archives) is saved to a local file and the result includes its path; use read on images. The text of a PDF is extracted when pdftotext is installed
|
|
54
|
+
- Repeated fetches of the same URL within 15 minutes are served from a cache
|
|
55
|
+
- The prompt should describe what information you want to extract from the page
|
|
56
|
+
- format (optional) only sets the Accept header: "auto" (default) prefers markdown and accepts HTML, text, or anything else; "markdown", "html", and "text" prefer that type. All content is normalized to text.
|
|
57
|
+
- This tool does not modify files (other than saving fetched binary content)`;
|
|
58
|
+
/** Create `web_fetch`. Fetched pages are cached per session for 15 minutes. */
|
|
59
|
+
export function createWebFetchToolDefinition(options) {
|
|
60
|
+
const cache = new Map();
|
|
61
|
+
return {
|
|
62
|
+
name: WEB_FETCH_TOOL_NAME,
|
|
63
|
+
label: "WebFetch",
|
|
64
|
+
description: DESCRIPTION,
|
|
65
|
+
promptSnippet: "Fetch a URL and extract information from it with a prompt",
|
|
66
|
+
parameters: webFetchSchema,
|
|
67
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
68
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
69
|
+
const abortSignal = signal ?? new AbortController().signal;
|
|
70
|
+
const url = rewriteGitHubBlobUrl(params.url);
|
|
71
|
+
const problem = validateParams(url, params.prompt);
|
|
72
|
+
if (problem)
|
|
73
|
+
throw new Error(problem);
|
|
74
|
+
const startedAt = Date.now();
|
|
75
|
+
const elapsed = () => ` in ${((Date.now() - startedAt) / 1000).toFixed(1)}s`;
|
|
76
|
+
const accept = ACCEPT_HEADERS[params.format ?? "auto"];
|
|
77
|
+
let page;
|
|
78
|
+
try {
|
|
79
|
+
page = await getPage(cache, `${ctx.sessionManager.getSessionId()}|${accept} ${url}`, url, accept, abortSignal);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (abortSignal.aborted)
|
|
83
|
+
throw error;
|
|
84
|
+
throw new Error(`Error during fetch for ${params.url}: ${error instanceof Error ? error.message : String(error)}`);
|
|
85
|
+
}
|
|
86
|
+
if (page.kind === "redirect") {
|
|
87
|
+
const text = `REDIRECT DETECTED: The URL redirects to a different host (or scheme/port), which was not followed automatically.\n\nOriginal URL: ${page.originalUrl}\nRedirect URL: ${page.redirectUrl}\nStatus: ${page.status}\n\nTo fetch the redirected content, call ${WEB_FETCH_TOOL_NAME} again with:\n- url: "${page.redirectUrl}"\n- prompt: "${params.prompt}"`;
|
|
88
|
+
return {
|
|
89
|
+
content: [{ type: "text", text }],
|
|
90
|
+
details: {
|
|
91
|
+
summary: `Redirected to ${hostOf(page.redirectUrl)} (${page.status}), not followed${elapsed()}`,
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
return processPage(page, params.url, params.prompt, ctx, options.getSettings(), abortSignal, elapsed);
|
|
96
|
+
},
|
|
97
|
+
renderCall(args, theme, context) {
|
|
98
|
+
const text = context.lastComponent ?? new Text("", 0, 0);
|
|
99
|
+
const prompt = args.prompt ? theme.fg("muted", ` ${truncate(args.prompt, 80)}`) : "";
|
|
100
|
+
text.setText(`${theme.fg("toolTitle", theme.bold(WEB_FETCH_TOOL_NAME))} ${theme.fg("accent", args.url ?? "")}${prompt}`);
|
|
101
|
+
return text;
|
|
102
|
+
},
|
|
103
|
+
renderResult(result, { expanded }, theme, context) {
|
|
104
|
+
const text = context.lastComponent ?? new Text("", 0, 0);
|
|
105
|
+
const output = result.content.find((part) => part.type === "text")?.text ?? "";
|
|
106
|
+
if (context.isError) {
|
|
107
|
+
text.setText(`\n${theme.fg("error", output)}`);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
const summary = theme.fg("muted", result.details?.summary ?? "");
|
|
111
|
+
text.setText(expanded ? `\n${summary}\n${theme.fg("toolOutput", output)}` : `\n${summary}`);
|
|
112
|
+
}
|
|
113
|
+
return text;
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/** Ask a model for what the prompt wants from the page; the raw text comes back when that fails. */
|
|
118
|
+
async function processPage(page, requestedUrl, prompt, ctx, settings, signal, elapsed) {
|
|
119
|
+
const urlLine = page.finalUrl !== requestedUrl ? `URL: ${requestedUrl} (final: ${page.finalUrl})` : `URL: ${requestedUrl}`;
|
|
120
|
+
const header = `${urlLine}\nStatus: ${page.status} ${page.statusText || "OK"} | Content-Type: ${page.contentType || "unknown"} | Size: ${page.byteLength.toLocaleString("en-US")} bytes${page.fullTextPath ? `\nFull extracted text saved to: ${page.fullTextPath}. Page through it with read using path, offset and limit.` : ""}`;
|
|
121
|
+
const binaryNote = page.binary
|
|
122
|
+
? `\n\n[Binary content (${page.binary.mimeType || "unknown"}, ${formatSize(page.byteLength)}) saved to ${page.binary.path}.${page.binary.mimeType.startsWith("image/") ? " Use read to view it." : ""}]`
|
|
123
|
+
: "";
|
|
124
|
+
const summary = `Received ${formatSize(page.byteLength)} (${page.status} ${page.statusText || "OK"}) from ${hostOf(requestedUrl)}${page.binary ? `, binary saved to ${page.binary.path}` : ""}${elapsed()}`;
|
|
125
|
+
const result = (text, suffix = "") => ({
|
|
126
|
+
content: [{ type: "text", text }],
|
|
127
|
+
details: { summary: `${summary}${suffix}` },
|
|
128
|
+
});
|
|
129
|
+
if (page.binary && !page.content) {
|
|
130
|
+
const why = page.binary.note ? ` ${page.binary.note}` : "";
|
|
131
|
+
return result(`${header}\n\n[No text could be extracted from this binary content.${why}]${binaryNote}`);
|
|
132
|
+
}
|
|
133
|
+
if (isPreapprovedUrl(page.finalUrl) && page.contentType.includes("text/markdown") && !page.fullTextPath) {
|
|
134
|
+
return result(`${header}\n\n${page.content}${binaryNote}`);
|
|
135
|
+
}
|
|
136
|
+
const model = resolveFastModel(settings, ctx.modelRegistry, ctx.model);
|
|
137
|
+
const request = `The user requested the following: "${prompt}".\n\nI have fetched the content from ${requestedUrl}. Fetch metadata:\n${header}\n\nPlease use the following content to answer the user's request.\n\n---\n${page.content}\n---`;
|
|
138
|
+
try {
|
|
139
|
+
if (!model)
|
|
140
|
+
throw new Error("no model is selected");
|
|
141
|
+
const answer = await askModel(model, request, ctx, AbortSignal.any([signal, AbortSignal.timeout(processingTimeoutMs())]));
|
|
142
|
+
return result(`${header}\n\n${answer || "[The processing model returned no content. The fetch itself succeeded; see the metadata above.]"}${binaryNote}`);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (signal.aborted)
|
|
146
|
+
throw error;
|
|
147
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
148
|
+
return result(`${header}\n\n[Content processing failed (${reason}). The raw fetched content follows.]\n\n${page.content}${binaryNote}`, ", processing failed, raw content returned");
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async function askModel(model, request, ctx, signal) {
|
|
152
|
+
const response = await ctx.modelRegistry.complete(model, {
|
|
153
|
+
systemPrompt: "Extract and summarize the requested information from the provided web content. Be concise and accurate. Respond only with the requested information.",
|
|
154
|
+
messages: [{ role: "user", content: [{ type: "text", text: request }], timestamp: Date.now() }],
|
|
155
|
+
}, { signal, cacheRetention: "none", sessionId: uuidv7() });
|
|
156
|
+
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
157
|
+
throw new Error(response.errorMessage ?? `the model request ended with ${response.stopReason}`);
|
|
158
|
+
}
|
|
159
|
+
return response.content
|
|
160
|
+
.filter((part) => part.type === "text")
|
|
161
|
+
.map((part) => part.text)
|
|
162
|
+
.join("")
|
|
163
|
+
.trim();
|
|
164
|
+
}
|
|
165
|
+
/** The page from the cache when fetched within 15 minutes, otherwise fetched and cached. */
|
|
166
|
+
async function getPage(cache, key, url, accept, signal) {
|
|
167
|
+
const cached = cache.get(key);
|
|
168
|
+
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
|
|
169
|
+
// Re-insert so the map's order stays least recently used first.
|
|
170
|
+
cache.delete(key);
|
|
171
|
+
cache.set(key, cached);
|
|
172
|
+
return cached;
|
|
173
|
+
}
|
|
174
|
+
const fetchOptions = {
|
|
175
|
+
headers: { Accept: accept, "User-Agent": getDiffraUserAgent(VERSION) },
|
|
176
|
+
signal,
|
|
177
|
+
timeoutMs: FETCH_TIMEOUT_MS,
|
|
178
|
+
maxBytes: MAX_RESPONSE_BYTES,
|
|
179
|
+
maxRedirects: MAX_REDIRECTS,
|
|
180
|
+
};
|
|
181
|
+
const upgraded = upgradeToHttps(url);
|
|
182
|
+
let response;
|
|
183
|
+
let usedPlainHttp = false;
|
|
184
|
+
try {
|
|
185
|
+
response = await fetchPage(upgraded, fetchOptions);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
// A public host without HTTPS: fall back to the URL as given.
|
|
189
|
+
if (upgraded === url || !isConnectionError(error))
|
|
190
|
+
throw error;
|
|
191
|
+
response = await fetchPage(url, fetchOptions);
|
|
192
|
+
usedPlainHttp = true;
|
|
193
|
+
}
|
|
194
|
+
if (response.kind === "redirect")
|
|
195
|
+
return response;
|
|
196
|
+
if (response.status < 200 || response.status >= 300) {
|
|
197
|
+
throw new Error(`Request failed with status code ${response.status} ${response.statusText}`);
|
|
198
|
+
}
|
|
199
|
+
const page = await toPage(response, signal);
|
|
200
|
+
if (!usedPlainHttp && page.content.length <= MAX_CACHEABLE_CHARS) {
|
|
201
|
+
cache.delete(key);
|
|
202
|
+
cache.set(key, page);
|
|
203
|
+
while (cache.size > CACHE_CAPACITY)
|
|
204
|
+
cache.delete(cache.keys().next().value);
|
|
205
|
+
}
|
|
206
|
+
return page;
|
|
207
|
+
}
|
|
208
|
+
async function toPage(response, signal) {
|
|
209
|
+
const mimeType = (response.contentType.split(";")[0] ?? "").trim().toLowerCase();
|
|
210
|
+
const base = {
|
|
211
|
+
kind: "page",
|
|
212
|
+
fetchedAt: Date.now(),
|
|
213
|
+
status: response.status,
|
|
214
|
+
statusText: response.statusText,
|
|
215
|
+
contentType: response.contentType,
|
|
216
|
+
byteLength: response.body.length,
|
|
217
|
+
finalUrl: response.finalUrl,
|
|
218
|
+
};
|
|
219
|
+
const pdf = mimeType === "application/pdf" || response.body.subarray(0, 5).toString("latin1") === "%PDF-";
|
|
220
|
+
if (pdf || isBinary(mimeType, response.body)) {
|
|
221
|
+
const path = await writeOutputFile("diffra-web-fetch", pdf ? ".pdf" : extensionFor(mimeType), response.body);
|
|
222
|
+
if (!pdf)
|
|
223
|
+
return { ...base, content: "", binary: { path, mimeType } };
|
|
224
|
+
const text = await extractPdfText(path, signal);
|
|
225
|
+
if (text.kind === "none")
|
|
226
|
+
return { ...base, content: "", binary: { path, mimeType, note: text.reason } };
|
|
227
|
+
return { ...base, content: text.text, binary: { path, mimeType } };
|
|
228
|
+
}
|
|
229
|
+
const decoded = response.body.toString("utf-8");
|
|
230
|
+
const content = mimeType === "text/html" || mimeType === "application/xhtml+xml" ? markdownOf(decoded) : decoded;
|
|
231
|
+
if (content.length <= MAX_CONTENT_CHARS)
|
|
232
|
+
return { ...base, content };
|
|
233
|
+
const fullTextPath = await writeOutputFile("diffra-web-fetch", ".txt", content);
|
|
234
|
+
return {
|
|
235
|
+
...base,
|
|
236
|
+
content: `${content.slice(0, MAX_CONTENT_CHARS - 2000)}\n\n[Content truncated to ${MAX_CONTENT_CHARS - 2000} of ${content.length} characters.]`,
|
|
237
|
+
fullTextPath,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
/** Markdown of a page; HTML turndown cannot parse is kept as it came, as in Qwen Code. */
|
|
241
|
+
function markdownOf(html) {
|
|
242
|
+
try {
|
|
243
|
+
return htmlToMarkdown(html);
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
return html;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const TEXT_MIME_PATTERN = /^(text\/|application\/(json|xml|xhtml\+xml|javascript|ecmascript|x-yaml|yaml|toml|ld\+json|rss\+xml|atom\+xml)|image\/svg\+xml)/;
|
|
250
|
+
function isBinary(mimeType, body) {
|
|
251
|
+
if (TEXT_MIME_PATTERN.test(mimeType) || mimeType.endsWith("+json") || mimeType.endsWith("+xml"))
|
|
252
|
+
return false;
|
|
253
|
+
if (mimeType && mimeType !== "application/octet-stream")
|
|
254
|
+
return true;
|
|
255
|
+
// Unknown or generic types: text when the start has no NUL bytes.
|
|
256
|
+
return body.subarray(0, 8192).includes(0);
|
|
257
|
+
}
|
|
258
|
+
const EXTENSIONS = {
|
|
259
|
+
"application/pdf": ".pdf",
|
|
260
|
+
"image/png": ".png",
|
|
261
|
+
"image/jpeg": ".jpg",
|
|
262
|
+
"image/gif": ".gif",
|
|
263
|
+
"image/webp": ".webp",
|
|
264
|
+
"application/zip": ".zip",
|
|
265
|
+
"application/gzip": ".gz",
|
|
266
|
+
};
|
|
267
|
+
function extensionFor(mimeType) {
|
|
268
|
+
return EXTENSIONS[mimeType] ?? ".bin";
|
|
269
|
+
}
|
|
270
|
+
/** Rewrite `github.com/<owner>/<repo>/blob/...` to the raw file on raw.githubusercontent.com. */
|
|
271
|
+
export function rewriteGitHubBlobUrl(url) {
|
|
272
|
+
if (!URL.canParse(url))
|
|
273
|
+
return url;
|
|
274
|
+
const parsed = new URL(url);
|
|
275
|
+
const host = parsed.hostname.toLowerCase();
|
|
276
|
+
if (host !== "github.com" && host !== "www.github.com")
|
|
277
|
+
return url;
|
|
278
|
+
const rawPath = parsed.pathname.replace(/^(\/[^/]+\/[^/]+)\/blob\//, "$1/");
|
|
279
|
+
if (rawPath === parsed.pathname)
|
|
280
|
+
return url;
|
|
281
|
+
parsed.hostname = "raw.githubusercontent.com";
|
|
282
|
+
parsed.pathname = rawPath;
|
|
283
|
+
return parsed.toString();
|
|
284
|
+
}
|
|
285
|
+
/** `http://` URLs to public hosts without an explicit port use HTTPS. */
|
|
286
|
+
export function upgradeToHttps(url) {
|
|
287
|
+
if (!url.toLowerCase().startsWith("http://") || isPrivateHost(url))
|
|
288
|
+
return url;
|
|
289
|
+
const parsed = new URL(url);
|
|
290
|
+
if (parsed.port !== "")
|
|
291
|
+
return url;
|
|
292
|
+
parsed.protocol = "https:";
|
|
293
|
+
return parsed.toString();
|
|
294
|
+
}
|
|
295
|
+
function validateParams(url, prompt) {
|
|
296
|
+
if (url.trim() === "")
|
|
297
|
+
return "The 'url' parameter cannot be empty.";
|
|
298
|
+
if (!/^https?:\/\//i.test(url))
|
|
299
|
+
return "The 'url' must be a valid URL starting with http:// or https://.";
|
|
300
|
+
if (!URL.canParse(url))
|
|
301
|
+
return "The 'url' is malformed and could not be parsed.";
|
|
302
|
+
const parsed = new URL(url);
|
|
303
|
+
if (parsed.username || parsed.password)
|
|
304
|
+
return "The 'url' must not include credentials.";
|
|
305
|
+
if (prompt.trim() === "")
|
|
306
|
+
return "The 'prompt' parameter cannot be empty.";
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
function processingTimeoutMs() {
|
|
310
|
+
const value = Number(process.env.DIFFRA_WEB_FETCH_PROCESSING_TIMEOUT_MS);
|
|
311
|
+
return Number.isSafeInteger(value) && value > 0 && value <= 2_147_483_647 ? value : DEFAULT_PROCESSING_TIMEOUT_MS;
|
|
312
|
+
}
|
|
313
|
+
function hostOf(url) {
|
|
314
|
+
return URL.canParse(url) ? new URL(url).hostname : url;
|
|
315
|
+
}
|
|
316
|
+
function truncate(text, max) {
|
|
317
|
+
return text.length > max ? `${text.slice(0, max - 3)}...` : text;
|
|
318
|
+
}
|
|
319
|
+
//# sourceMappingURL=fetch-tool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-tool.js","sourceRoot":"","sources":["../../../src/extensions/web-fetch/fetch-tool.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;AACnH,CAAC;AAED,SAAS,MAAM,CAAC,GAAW;IAC1B,OAAO,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC;AACxD,CAAC;AAED,SAAS,QAAQ,CAAC,IAAY,EAAE,GAAW;IAC1C,OAAO,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAClE,CAAC","sourcesContent":["/**\n * The `web_fetch` tool: fetch one URL, turn the page into text, and have a model answer the call's\n * prompt from it. Same-site redirects are followed; a redirect to another site is reported instead.\n */\n\nimport type { Api, Model } from \"@diffra-ai/ai\";\nimport { uuidv7 } from \"@diffra-ai/ai\";\nimport { Text } from \"@diffra-ai/tui\";\nimport { Type } from \"typebox\";\nimport { VERSION } from \"../../config.ts\";\nimport { StringEnum } from \"../../core/extensions/diffra-ai-extension-view.ts\";\nimport type { ExtensionToolContext, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport { resolveFastModel } from \"../../core/fast-model.ts\";\nimport type { Settings } from \"../../core/settings-schema.ts\";\nimport { formatSize } from \"../../core/tools/truncate.ts\";\nimport { getDiffraUserAgent } from \"../../utils/diffra-user-agent.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport { htmlToMarkdown } from \"./html-to-markdown.ts\";\nimport { fetchPage, isConnectionError, isPrivateHost, type PageFetchResult } from \"./page-fetch.ts\";\nimport { extractPdfText } from \"./pdf-text.ts\";\nimport { isPreapprovedUrl } from \"./preapproved-hosts.ts\";\n\nexport const WEB_FETCH_TOOL_NAME = \"web_fetch\";\n\nconst webFetchSchema = Type.Object({\n\turl: Type.String({ description: \"The URL to fetch content from\" }),\n\tprompt: Type.String({ description: \"The prompt to run on the fetched content\" }),\n\tformat: Type.Optional(\n\t\tStringEnum([\"auto\", \"markdown\", \"html\", \"text\"] as const, {\n\t\t\tdescription:\n\t\t\t\t\"Preferred content format (Accept header only): auto (default, prefers markdown), markdown, html, or text. All content is normalized to plain text.\",\n\t\t}),\n\t),\n});\n\ntype WebFetchFormat = \"auto\" | \"markdown\" | \"html\" | \"text\";\n\n/** `details` of a `web_fetch` result: the one-line summary the result row shows. */\nexport type WebFetchDetails = { summary: string };\n\nconst FETCH_TIMEOUT_MS = 60_000;\nconst DEFAULT_PROCESSING_TIMEOUT_MS = 300_000;\nconst MAX_RESPONSE_BYTES = 10 * 1024 * 1024;\nconst MAX_REDIRECTS = 10;\nconst MAX_CONTENT_CHARS = 100_000;\nconst CACHE_TTL_MS = 15 * 60 * 1000;\nconst CACHE_CAPACITY = 32;\nconst MAX_CACHEABLE_CHARS = 2 * 1024 * 1024;\n\nconst ACCEPT_HEADERS: Record<WebFetchFormat, string> = {\n\tauto: \"text/markdown, text/html;q=0.9, text/plain;q=0.8, */*;q=0.1\",\n\tmarkdown: \"text/markdown, */*;q=0.1\",\n\thtml: \"text/html, */*;q=0.1\",\n\ttext: \"text/plain, */*;q=0.1\",\n};\n\nconst DESCRIPTION = `Fetches content from a specified URL and processes it using an AI model\n- Takes a URL and a prompt as input\n- Supports content negotiation for markdown (reduces tokens by ~80%)\n- Fetches the URL content and converts HTML to Markdown (links preserved)\n- Processes the content with the prompt using an AI model\n- Returns the model's response about the content, prefixed with fetch metadata (HTTP status, content type, size)\n- Use this tool when you need to retrieve and analyze web content\n\nUsage notes:\n - IMPORTANT: This tool cannot access authenticated or private URLs (e.g. Google Docs, Confluence, Jira, private GitHub). If an MCP-provided web fetch tool is available, prefer it, as it may have fewer restrictions. MCP tools start with \"mcp__\".\n - The URL must be a fully-formed valid URL\n - Plain-http URLs to public hosts are upgraded to https automatically; localhost and private hosts are fetched as given\n - When a URL redirects to a different host, the redirect is NOT followed; the tool returns the redirect URL so you can call web_fetch again with it\n - Binary content (PDFs, images, archives) is saved to a local file and the result includes its path; use read on images. The text of a PDF is extracted when pdftotext is installed\n - Repeated fetches of the same URL within 15 minutes are served from a cache\n - The prompt should describe what information you want to extract from the page\n - format (optional) only sets the Accept header: \"auto\" (default) prefers markdown and accepts HTML, text, or anything else; \"markdown\", \"html\", and \"text\" prefer that type. All content is normalized to text.\n - This tool does not modify files (other than saving fetched binary content)`;\n\ninterface FetchedPage {\n\tkind: \"page\";\n\tfetchedAt: number;\n\tstatus: number;\n\tstatusText: string;\n\tcontentType: string;\n\tbyteLength: number;\n\tfinalUrl: string;\n\tcontent: string;\n\t/** The content was cut to the size limit; the full text is in `fullTextPath`. */\n\tfullTextPath?: string;\n\t/** Binary content saved to a file; `note` says why no text came out of it. */\n\tbinary?: { path: string; mimeType: string; note?: string };\n}\n\ntype PageRedirect = Extract<PageFetchResult, { kind: \"redirect\" }>;\n\n/** Create `web_fetch`. Fetched pages are cached per session for 15 minutes. */\nexport function createWebFetchToolDefinition(options: {\n\tgetSettings(): Settings;\n}): ToolDefinition<typeof webFetchSchema, WebFetchDetails> {\n\tconst cache = new Map<string, FetchedPage>();\n\treturn {\n\t\tname: WEB_FETCH_TOOL_NAME,\n\t\tlabel: \"WebFetch\",\n\t\tdescription: DESCRIPTION,\n\t\tpromptSnippet: \"Fetch a URL and extract information from it with a prompt\",\n\t\tparameters: webFetchSchema,\n\t\tannotations: { readOnlyHint: true, openWorldHint: true },\n\t\tasync execute(_toolCallId, params, signal, _onUpdate, ctx) {\n\t\t\tconst abortSignal = signal ?? new AbortController().signal;\n\t\t\tconst url = rewriteGitHubBlobUrl(params.url);\n\t\t\tconst problem = validateParams(url, params.prompt);\n\t\t\tif (problem) throw new Error(problem);\n\t\t\tconst startedAt = Date.now();\n\t\t\tconst elapsed = () => ` in ${((Date.now() - startedAt) / 1000).toFixed(1)}s`;\n\t\t\tconst accept = ACCEPT_HEADERS[params.format ?? \"auto\"];\n\t\t\tlet page: FetchedPage | PageRedirect;\n\t\t\ttry {\n\t\t\t\tpage = await getPage(\n\t\t\t\t\tcache,\n\t\t\t\t\t`${ctx.sessionManager.getSessionId()}|${accept} ${url}`,\n\t\t\t\t\turl,\n\t\t\t\t\taccept,\n\t\t\t\t\tabortSignal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (abortSignal.aborted) throw error;\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Error during fetch for ${params.url}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (page.kind === \"redirect\") {\n\t\t\t\tconst text = `REDIRECT DETECTED: The URL redirects to a different host (or scheme/port), which was not followed automatically.\\n\\nOriginal URL: ${page.originalUrl}\\nRedirect URL: ${page.redirectUrl}\\nStatus: ${page.status}\\n\\nTo fetch the redirected content, call ${WEB_FETCH_TOOL_NAME} again with:\\n- url: \"${page.redirectUrl}\"\\n- prompt: \"${params.prompt}\"`;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tsummary: `Redirected to ${hostOf(page.redirectUrl)} (${page.status}), not followed${elapsed()}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn processPage(page, params.url, params.prompt, ctx, options.getSettings(), abortSignal, elapsed);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst prompt = args.prompt ? theme.fg(\"muted\", ` ${truncate(args.prompt, 80)}`) : \"\";\n\t\t\ttext.setText(\n\t\t\t\t`${theme.fg(\"toolTitle\", theme.bold(WEB_FETCH_TOOL_NAME))} ${theme.fg(\"accent\", args.url ?? \"\")}${prompt}`,\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, { expanded }, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst output = result.content.find((part) => part.type === \"text\")?.text ?? \"\";\n\t\t\tif (context.isError) {\n\t\t\t\ttext.setText(`\\n${theme.fg(\"error\", output)}`);\n\t\t\t} else {\n\t\t\t\tconst summary = theme.fg(\"muted\", result.details?.summary ?? \"\");\n\t\t\t\ttext.setText(expanded ? `\\n${summary}\\n${theme.fg(\"toolOutput\", output)}` : `\\n${summary}`);\n\t\t\t}\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\n/** Ask a model for what the prompt wants from the page; the raw text comes back when that fails. */\nasync function processPage(\n\tpage: FetchedPage,\n\trequestedUrl: string,\n\tprompt: string,\n\tctx: ExtensionToolContext,\n\tsettings: Settings,\n\tsignal: AbortSignal,\n\telapsed: () => string,\n) {\n\tconst urlLine =\n\t\tpage.finalUrl !== requestedUrl ? `URL: ${requestedUrl} (final: ${page.finalUrl})` : `URL: ${requestedUrl}`;\n\tconst header = `${urlLine}\\nStatus: ${page.status} ${page.statusText || \"OK\"} | Content-Type: ${page.contentType || \"unknown\"} | Size: ${page.byteLength.toLocaleString(\"en-US\")} bytes${page.fullTextPath ? `\\nFull extracted text saved to: ${page.fullTextPath}. Page through it with read using path, offset and limit.` : \"\"}`;\n\tconst binaryNote = page.binary\n\t\t? `\\n\\n[Binary content (${page.binary.mimeType || \"unknown\"}, ${formatSize(page.byteLength)}) saved to ${page.binary.path}.${page.binary.mimeType.startsWith(\"image/\") ? \" Use read to view it.\" : \"\"}]`\n\t\t: \"\";\n\tconst summary = `Received ${formatSize(page.byteLength)} (${page.status} ${page.statusText || \"OK\"}) from ${hostOf(requestedUrl)}${page.binary ? `, binary saved to ${page.binary.path}` : \"\"}${elapsed()}`;\n\tconst result = (text: string, suffix = \"\") => ({\n\t\tcontent: [{ type: \"text\" as const, text }],\n\t\tdetails: { summary: `${summary}${suffix}` },\n\t});\n\n\tif (page.binary && !page.content) {\n\t\tconst why = page.binary.note ? ` ${page.binary.note}` : \"\";\n\t\treturn result(`${header}\\n\\n[No text could be extracted from this binary content.${why}]${binaryNote}`);\n\t}\n\tif (isPreapprovedUrl(page.finalUrl) && page.contentType.includes(\"text/markdown\") && !page.fullTextPath) {\n\t\treturn result(`${header}\\n\\n${page.content}${binaryNote}`);\n\t}\n\n\tconst model = resolveFastModel(settings, ctx.modelRegistry, ctx.model);\n\tconst request = `The user requested the following: \"${prompt}\".\\n\\nI have fetched the content from ${requestedUrl}. Fetch metadata:\\n${header}\\n\\nPlease use the following content to answer the user's request.\\n\\n---\\n${page.content}\\n---`;\n\ttry {\n\t\tif (!model) throw new Error(\"no model is selected\");\n\t\tconst answer = await askModel(\n\t\t\tmodel,\n\t\t\trequest,\n\t\t\tctx,\n\t\t\tAbortSignal.any([signal, AbortSignal.timeout(processingTimeoutMs())]),\n\t\t);\n\t\treturn result(\n\t\t\t`${header}\\n\\n${answer || \"[The processing model returned no content. The fetch itself succeeded; see the metadata above.]\"}${binaryNote}`,\n\t\t);\n\t} catch (error) {\n\t\tif (signal.aborted) throw error;\n\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\treturn result(\n\t\t\t`${header}\\n\\n[Content processing failed (${reason}). The raw fetched content follows.]\\n\\n${page.content}${binaryNote}`,\n\t\t\t\", processing failed, raw content returned\",\n\t\t);\n\t}\n}\n\nasync function askModel(\n\tmodel: Model<Api>,\n\trequest: string,\n\tctx: ExtensionToolContext,\n\tsignal: AbortSignal,\n): Promise<string> {\n\tconst response = await ctx.modelRegistry.complete(\n\t\tmodel,\n\t\t{\n\t\t\tsystemPrompt:\n\t\t\t\t\"Extract and summarize the requested information from the provided web content. Be concise and accurate. Respond only with the requested information.\",\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: request }], timestamp: Date.now() }],\n\t\t},\n\t\t{ signal, cacheRetention: \"none\", sessionId: uuidv7() },\n\t);\n\tif (response.stopReason === \"error\" || response.stopReason === \"aborted\") {\n\t\tthrow new Error(response.errorMessage ?? `the model request ended with ${response.stopReason}`);\n\t}\n\treturn response.content\n\t\t.filter((part) => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\")\n\t\t.trim();\n}\n\n/** The page from the cache when fetched within 15 minutes, otherwise fetched and cached. */\nasync function getPage(\n\tcache: Map<string, FetchedPage>,\n\tkey: string,\n\turl: string,\n\taccept: string,\n\tsignal: AbortSignal,\n): Promise<FetchedPage | PageRedirect> {\n\tconst cached = cache.get(key);\n\tif (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {\n\t\t// Re-insert so the map's order stays least recently used first.\n\t\tcache.delete(key);\n\t\tcache.set(key, cached);\n\t\treturn cached;\n\t}\n\tconst fetchOptions = {\n\t\theaders: { Accept: accept, \"User-Agent\": getDiffraUserAgent(VERSION) },\n\t\tsignal,\n\t\ttimeoutMs: FETCH_TIMEOUT_MS,\n\t\tmaxBytes: MAX_RESPONSE_BYTES,\n\t\tmaxRedirects: MAX_REDIRECTS,\n\t};\n\tconst upgraded = upgradeToHttps(url);\n\tlet response: PageFetchResult;\n\tlet usedPlainHttp = false;\n\ttry {\n\t\tresponse = await fetchPage(upgraded, fetchOptions);\n\t} catch (error) {\n\t\t// A public host without HTTPS: fall back to the URL as given.\n\t\tif (upgraded === url || !isConnectionError(error)) throw error;\n\t\tresponse = await fetchPage(url, fetchOptions);\n\t\tusedPlainHttp = true;\n\t}\n\tif (response.kind === \"redirect\") return response;\n\tif (response.status < 200 || response.status >= 300) {\n\t\tthrow new Error(`Request failed with status code ${response.status} ${response.statusText}`);\n\t}\n\tconst page = await toPage(response, signal);\n\tif (!usedPlainHttp && page.content.length <= MAX_CACHEABLE_CHARS) {\n\t\tcache.delete(key);\n\t\tcache.set(key, page);\n\t\twhile (cache.size > CACHE_CAPACITY) cache.delete(cache.keys().next().value as string);\n\t}\n\treturn page;\n}\n\nasync function toPage(\n\tresponse: Extract<PageFetchResult, { kind: \"response\" }>,\n\tsignal: AbortSignal,\n): Promise<FetchedPage> {\n\tconst mimeType = (response.contentType.split(\";\")[0] ?? \"\").trim().toLowerCase();\n\tconst base = {\n\t\tkind: \"page\" as const,\n\t\tfetchedAt: Date.now(),\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\tcontentType: response.contentType,\n\t\tbyteLength: response.body.length,\n\t\tfinalUrl: response.finalUrl,\n\t};\n\tconst pdf = mimeType === \"application/pdf\" || response.body.subarray(0, 5).toString(\"latin1\") === \"%PDF-\";\n\tif (pdf || isBinary(mimeType, response.body)) {\n\t\tconst path = await writeOutputFile(\"diffra-web-fetch\", pdf ? \".pdf\" : extensionFor(mimeType), response.body);\n\t\tif (!pdf) return { ...base, content: \"\", binary: { path, mimeType } };\n\t\tconst text = await extractPdfText(path, signal);\n\t\tif (text.kind === \"none\") return { ...base, content: \"\", binary: { path, mimeType, note: text.reason } };\n\t\treturn { ...base, content: text.text, binary: { path, mimeType } };\n\t}\n\tconst decoded = response.body.toString(\"utf-8\");\n\tconst content = mimeType === \"text/html\" || mimeType === \"application/xhtml+xml\" ? markdownOf(decoded) : decoded;\n\tif (content.length <= MAX_CONTENT_CHARS) return { ...base, content };\n\tconst fullTextPath = await writeOutputFile(\"diffra-web-fetch\", \".txt\", content);\n\treturn {\n\t\t...base,\n\t\tcontent: `${content.slice(0, MAX_CONTENT_CHARS - 2000)}\\n\\n[Content truncated to ${MAX_CONTENT_CHARS - 2000} of ${content.length} characters.]`,\n\t\tfullTextPath,\n\t};\n}\n\n/** Markdown of a page; HTML turndown cannot parse is kept as it came, as in Qwen Code. */\nfunction markdownOf(html: string): string {\n\ttry {\n\t\treturn htmlToMarkdown(html);\n\t} catch {\n\t\treturn html;\n\t}\n}\n\nconst TEXT_MIME_PATTERN =\n\t/^(text\\/|application\\/(json|xml|xhtml\\+xml|javascript|ecmascript|x-yaml|yaml|toml|ld\\+json|rss\\+xml|atom\\+xml)|image\\/svg\\+xml)/;\n\nfunction isBinary(mimeType: string, body: Buffer): boolean {\n\tif (TEXT_MIME_PATTERN.test(mimeType) || mimeType.endsWith(\"+json\") || mimeType.endsWith(\"+xml\")) return false;\n\tif (mimeType && mimeType !== \"application/octet-stream\") return true;\n\t// Unknown or generic types: text when the start has no NUL bytes.\n\treturn body.subarray(0, 8192).includes(0);\n}\n\nconst EXTENSIONS: Record<string, string> = {\n\t\"application/pdf\": \".pdf\",\n\t\"image/png\": \".png\",\n\t\"image/jpeg\": \".jpg\",\n\t\"image/gif\": \".gif\",\n\t\"image/webp\": \".webp\",\n\t\"application/zip\": \".zip\",\n\t\"application/gzip\": \".gz\",\n};\n\nfunction extensionFor(mimeType: string): string {\n\treturn EXTENSIONS[mimeType] ?? \".bin\";\n}\n\n/** Rewrite `github.com/<owner>/<repo>/blob/...` to the raw file on raw.githubusercontent.com. */\nexport function rewriteGitHubBlobUrl(url: string): string {\n\tif (!URL.canParse(url)) return url;\n\tconst parsed = new URL(url);\n\tconst host = parsed.hostname.toLowerCase();\n\tif (host !== \"github.com\" && host !== \"www.github.com\") return url;\n\tconst rawPath = parsed.pathname.replace(/^(\\/[^/]+\\/[^/]+)\\/blob\\//, \"$1/\");\n\tif (rawPath === parsed.pathname) return url;\n\tparsed.hostname = \"raw.githubusercontent.com\";\n\tparsed.pathname = rawPath;\n\treturn parsed.toString();\n}\n\n/** `http://` URLs to public hosts without an explicit port use HTTPS. */\nexport function upgradeToHttps(url: string): string {\n\tif (!url.toLowerCase().startsWith(\"http://\") || isPrivateHost(url)) return url;\n\tconst parsed = new URL(url);\n\tif (parsed.port !== \"\") return url;\n\tparsed.protocol = \"https:\";\n\treturn parsed.toString();\n}\n\nfunction validateParams(url: string, prompt: string): string | undefined {\n\tif (url.trim() === \"\") return \"The 'url' parameter cannot be empty.\";\n\tif (!/^https?:\\/\\//i.test(url)) return \"The 'url' must be a valid URL starting with http:// or https://.\";\n\tif (!URL.canParse(url)) return \"The 'url' is malformed and could not be parsed.\";\n\tconst parsed = new URL(url);\n\tif (parsed.username || parsed.password) return \"The 'url' must not include credentials.\";\n\tif (prompt.trim() === \"\") return \"The 'prompt' parameter cannot be empty.\";\n\treturn undefined;\n}\n\nfunction processingTimeoutMs(): number {\n\tconst value = Number(process.env.DIFFRA_WEB_FETCH_PROCESSING_TIMEOUT_MS);\n\treturn Number.isSafeInteger(value) && value > 0 && value <= 2_147_483_647 ? value : DEFAULT_PROCESSING_TIMEOUT_MS;\n}\n\nfunction hostOf(url: string): string {\n\treturn URL.canParse(url) ? new URL(url).hostname : url;\n}\n\nfunction truncate(text: string, max: number): string {\n\treturn text.length > max ? `${text.slice(0, max - 3)}...` : text;\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML pages as Markdown for the model, converted the way Qwen Code does: turndown with its default
|
|
3
|
+
* options, without scripts, styles, and images.
|
|
4
|
+
*/
|
|
5
|
+
/** Markdown of an HTML document. */
|
|
6
|
+
export declare function htmlToMarkdown(html: string): string;
|
|
7
|
+
//# sourceMappingURL=html-to-markdown.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"html-to-markdown.d.ts","sourceRoot":"","sources":["../../../src/extensions/web-fetch/html-to-markdown.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,oCAAoC;AACpC,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGnD"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML pages as Markdown for the model, converted the way Qwen Code does: turndown with its default
|
|
3
|
+
* options, without scripts, styles, and images.
|
|
4
|
+
*/
|
|
5
|
+
import TurndownService from "turndown";
|
|
6
|
+
// One converter for the process: building it compiles its rules, and converting keeps no state.
|
|
7
|
+
let converter;
|
|
8
|
+
/** Markdown of an HTML document. */
|
|
9
|
+
export function htmlToMarkdown(html) {
|
|
10
|
+
converter ??= createConverter();
|
|
11
|
+
return converter.turndown(html);
|
|
12
|
+
}
|
|
13
|
+
function createConverter() {
|
|
14
|
+
const service = new TurndownService();
|
|
15
|
+
// Script and style text, such as hydration data and inline CSS, would use up the size limit.
|
|
16
|
+
service.remove(["script", "style", "noscript"]);
|
|
17
|
+
// One data-URI image can be larger than the whole limit; links keep their URLs.
|
|
18
|
+
service.addRule("drop-images", { filter: "img", replacement: () => "" });
|
|
19
|
+
return service;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=html-to-markdown.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"html-to-markdown.js","sourceRoot":"","sources":["../../../src/extensions/web-fetch/html-to-markdown.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,eAAe,MAAM,UAAU,CAAC;AAEvC,gGAAgG;AAChG,IAAI,SAAsC,CAAC;AAE3C,oCAAoC;AACpC,MAAM,UAAU,cAAc,CAAC,IAAY;IAC1C,SAAS,KAAK,eAAe,EAAE,CAAC;IAChC,OAAO,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,eAAe;IACvB,MAAM,OAAO,GAAG,IAAI,eAAe,EAAE,CAAC;IACtC,6FAA6F;IAC7F,OAAO,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC,CAAC;IAChD,gFAAgF;IAChF,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;IACzE,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["/**\n * HTML pages as Markdown for the model, converted the way Qwen Code does: turndown with its default\n * options, without scripts, styles, and images.\n */\n\nimport TurndownService from \"turndown\";\n\n// One converter for the process: building it compiles its rules, and converting keeps no state.\nlet converter: TurndownService | undefined;\n\n/** Markdown of an HTML document. */\nexport function htmlToMarkdown(html: string): string {\n\tconverter ??= createConverter();\n\treturn converter.turndown(html);\n}\n\nfunction createConverter(): TurndownService {\n\tconst service = new TurndownService();\n\t// Script and style text, such as hydration data and inline CSS, would use up the size limit.\n\tservice.remove([\"script\", \"style\", \"noscript\"]);\n\t// One data-URI image can be larger than the whole limit; links keep their URLs.\n\tservice.addRule(\"drop-images\", { filter: \"img\", replacement: () => \"\" });\n\treturn service;\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `web_fetch` tool as an extension. The CLI loads it as a built-in extension; SDK users add
|
|
3
|
+
* `createWebFetchExtension()` to their extension factories. It is active by default.
|
|
4
|
+
*/
|
|
5
|
+
import type { ExtensionFactory } from "../../core/extensions/types.ts";
|
|
6
|
+
/** Create the extension that registers `web_fetch`. */
|
|
7
|
+
export declare function createWebFetchExtension(): ExtensionFactory;
|
|
8
|
+
declare const _default: ExtensionFactory;
|
|
9
|
+
export default _default;
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/web-fetch/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAGvE,uDAAuD;AACvD,wBAAgB,uBAAuB,IAAI,gBAAgB,CAI1D"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `web_fetch` tool as an extension. The CLI loads it as a built-in extension; SDK users add
|
|
3
|
+
* `createWebFetchExtension()` to their extension factories. It is active by default.
|
|
4
|
+
*/
|
|
5
|
+
import { createWebFetchToolDefinition } from "./fetch-tool.js";
|
|
6
|
+
/** Create the extension that registers `web_fetch`. */
|
|
7
|
+
export function createWebFetchExtension() {
|
|
8
|
+
return (diffra) => {
|
|
9
|
+
diffra.registerTool(createWebFetchToolDefinition({ getSettings: () => diffra.getSettings() }));
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export default createWebFetchExtension();
|
|
13
|
+
//# sourceMappingURL=index.js.map
|