Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(tools): keep an approved toolkit as a named tool for its site

Shahriar9327283d0100
diff --git a/docs/guide/approvals.md b/docs/guide/approvals.md
index fc07784..b698f25 100644
--- a/docs/guide/approvals.md
+++ b/docs/guide/approvals.md
@@ -125,6 +125,18 @@ someone allowlists the browsentic tools to stop being asked.
waives them instead, going back to "the client's permissions are the only gate".
+### Tools the user kept
+
+A toolkit the user saved from the keep prompt runs from `/` with no approval at all. That is the
+whole point of saving one: the code was read and approved when it was kept, so asking again would
+be asking about something already answered. What holds it in place is not a prompt but the record
+itself, which pins the origin and the path segment it was approved on and re-checks both before it
+installs anything.
+
+The daemon is not in that loop. The code lives in extension storage, the run goes from the side
+panel straight to the tab, and the daemon holds only a markdown note that the tool exists. There
+is no action for it, so no MCP client can reach it, with or without `unattended`.
+
It does not waive a `deny`. That is why the two live-tool rules deny rather than confirm: a
client allowlisting the Browsentic tools is exactly the setup where `unattended: allow` gets
turned on, and writing code into your logged-in page is not something a client's own prompt is
diff --git a/scripts/check-toolkit.mjs b/scripts/check-toolkit.mjs
index 048f40b..c311407 100644
--- a/scripts/check-toolkit.mjs
+++ b/scripts/check-toolkit.mjs
@@ -71,7 +71,18 @@ const names = install('kit-1', `
tools.cyclic = () => { const o = {}; o.self = o; return o; };
const helper = 1;
`);
-check('install reports only the functions', names.sort(), ['add', 'boom', 'cyclic', 'echo', 'nothing', 'slow']);
+check(
+ 'install reports only the functions',
+ names.map((entry) => entry.name).sort(),
+ ['add', 'boom', 'cyclic', 'echo', 'nothing', 'slow'],
+);
+// Arity is what decides whether a function can become a saved tool: `/` passes no
+// arguments, so only a zero-argument entry point is ever offered.
+check(
+ 'install reports each arity',
+ Object.fromEntries(names.map((entry) => [entry.name, entry.arity])),
+ { echo: 1, add: 2, slow: 1, boom: 0, nothing: 0, cyclic: 0 },
+);
check('install stamps the attribute', world.attributes.get('data-browsentic-toolkit'), 'kit-1');
// ── calling across the bridge ────────────────────────────────────────────────
@@ -98,7 +109,7 @@ check('the abandoned call did not corrupt the next one', await toolkit.callToolk
// ── re-installing over a live toolkit ────────────────────────────────────────
const second = install('kit-2', `tools.echo = () => 'replaced';`);
-check('re-install swaps the toolkit', second, ['echo']);
+check('re-install swaps the toolkit', second.map((entry) => entry.name), ['echo']);
check('re-install restamps the id', world.attributes.get('data-browsentic-toolkit'), 'kit-2');
check('the new function answers', await toolkit.callToolkit('echo', [], 1000), 'replaced');
const gone = await toolkit.callToolkit('add', [1, 1], 1000).catch((e) => e);
@@ -159,5 +170,49 @@ check('with the switch on it rides along as an overlay', route({ liveTools: true
check('it never replaces the base skill it advises against', route({ liveTools: true }).base.name, 'browser-control');
check('no context at all means off', routeSkill(library, 'create 20 tags').overlays.map((s) => s.name), []);
+// ── saved tools: naming and scope ────────────────────────────────────────────────
+//
+// Scope is host plus the first path segment, and the display name is never a filename.
+// Both matter: the first decides where a tool is offered, the second keeps a user-shaped
+// string out of `join(skillsDir, name + '.md')`.
+
+const savedOut = join(root, 'node_modules/.cache/browsentic-toolkit/saved-tool.mjs');
+await build({
+ entryPoints: [join(root, 'src/lib/skills/saved-tool.ts')],
+ outfile: savedOut,
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ logLevel: 'warning',
+ alias: { '@': join(root, 'src') },
+});
+const saved = await import(pathToFileURL(savedOut).href);
+
+const watch = saved.scopeOf('https://www.youtube.com/watch?v=abc');
+check('scope takes host and first segment', watch, { host: 'youtube.com', segment: 'watch' });
+check('www is not part of the host', saved.scopeOf('https://www.github.com/pulls').host, 'github.com');
+check('a bare origin scopes to root', saved.scopeOf('https://example.com/').segment, 'root');
+check('a non-http url has no scope', saved.scopeOf('file:///etc/passwd'), null);
+check('a chrome page has no scope', saved.scopeOf('chrome://extensions'), null);
+
+check('the display name reads host first', saved.displayName(watch, 'darken-page'), 'youtube.com:watch:darken-page');
+
+check('another id under the same segment matches', saved.toolMatchesUrl(watch, 'https://youtube.com/watch?v=zzz'), true);
+check('a deeper path under the segment matches', saved.toolMatchesUrl(watch, 'https://youtube.com/watch/live'), true);
+check('a different segment does not', saved.toolMatchesUrl(watch, 'https://youtube.com/results?q=cats'), false);
+check('the site root does not', saved.toolMatchesUrl(watch, 'https://youtube.com/'), false);
+check('a subdomain does not', saved.toolMatchesUrl(watch, 'https://music.youtube.com/watch?v=abc'), false);
+
+// The daemon half becomes a path, so it goes through SKILL_NAME_RE like every other skill.
+const skillName = saved.skillNameFor(watch, 'darken-page-except-video-player');
+check('the skill name is path-safe', /^[a-z0-9][a-z0-9-]{0,47}$/.test(skillName), true);
+check('the skill name is recognisable as a tool', saved.isSavedToolSkill(skillName), true);
+const hostile = saved.skillNameFor({ host: '../../etc', segment: '..' }, 'x/../../y');
+check('traversal cannot survive into a skill name', /^[a-z0-9][a-z0-9-]{0,47}$/.test(hostile), true);
+check('and it carries no separators', /[/.]/.test(hostile), false);
+
+check('a purpose becomes a slug', saved.slugFromPurpose('Darken the page except the video player', 'fn'), 'darken-page-except-video-player');
+check('a purpose of only stop words falls back', saved.slugFromPurpose('the a of', 'darkenPage'), 'darkenpage');
+
console.log(failed ? `\n${failed} of ${ran} failed` : `\n${ran}/${ran} toolkit checks passed`);
process.exit(failed ? 1 : 0);
diff --git a/src/daemon/skills/page-scripting.md b/src/daemon/skills/page-scripting.md
index cab7240..d521e0a 100644
--- a/src/daemon/skills/page-scripting.md
+++ b/src/daemon/skills/page-scripting.md
@@ -48,3 +48,21 @@ Rules that keep it working:
If the approval comes back declined, that is an answer, not an obstacle: fall back to the ordinary tools or ask, never re-submit the same code hoping for a different click. A `CODE_ERROR` result carries the page-side exception — fix the code and inject the corrected version, which is a new approval, so get it right in as few revisions as you can.
`LIVE_TOOLS_OFF` means the switch went off between messages. Only the user can turn it back on; say what you would use it for and why, and carry on with the ordinary tools meanwhile.
+
+## When the user keeps it
+
+A second after an install lands, the panel offers to keep it as a named tool for that site,
+scoped to the host and the first path segment: `youtube.com:watch:darken-page-except-video-player`.
+Only a zero-argument entry point can be kept, since the user runs it by name with nothing to
+pass, so a function that takes arguments is a one-off by design.
+
+Two things follow for you.
+
+- **Write one zero-argument entry point when the job is a whole action.** "Darken this page" is
+ worth keeping and needs no input. "Create a tag called X" is not, and should take its name as
+ an argument. Shape the toolkit around which of the two you are doing rather than adding
+ parameters that only exist to look general.
+- **A kept tool is not yours to call.** It lives in the extension, it is not a page action, and
+ no `page_*` tool reaches it. If the user asks for the same effect again on that site, tell them
+ to run `/<name>` rather than writing the same code a second time. You will see a skill note for
+ each one they kept, which is how you know it exists.
diff --git a/src/extension/components/composer.tsx b/src/extension/components/composer.tsx
index eb84236..0792c72 100644
--- a/src/extension/components/composer.tsx
+++ b/src/extension/components/composer.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState, type MouseEvent } from 'react';
import { Code2, FileText, FileUp, Loader2, Mic, MicOff, Paperclip, ScanEye, Send, Sparkles, Square, X } from 'lucide-react';
import { SkillMenu, skillMenuItems, type SkillMenuItem } from '@/extension/components/skill-menu';
+import type { SavedToolMeta } from '@/lib/bridge/saved-tools';
import { Button } from '@/extension/components/ui/button';
import { Textarea } from '@/extension/components/ui/textarea';
import type { FocusedElement, SkillCatalog } from '@/lib/actions/protocol';
@@ -33,6 +34,8 @@ export function Composer({
onToggleLiveTools,
onAttachSkill,
onCommand,
+ tools,
+ onRunTool,
onSend,
onStop,
onToggleVoice,
@@ -57,6 +60,8 @@ export function Composer({
onToggleLiveTools: () => void;
onAttachSkill: (skill: AttachedSkill | null) => void;
onCommand: (command: string) => void;
+ tools: SavedToolMeta[];
+ onRunTool: (id: string) => void;
onSend: () => void;
onStop: () => void;
onToggleVoice: () => void;
@@ -73,8 +78,8 @@ export function Composer({
const menuOpen = slash !== null && connected;
const [highlight, setHighlight] = useState(0);
const menuItems = useMemo(
- () => (menuOpen ? skillMenuItems(catalog, tabUrl, slash ?? '') : []),
- [menuOpen, catalog, tabUrl, slash],
+ () => (menuOpen ? skillMenuItems(catalog, tabUrl, slash ?? '', tools) : []),
+ [menuOpen, catalog, tabUrl, slash, tools],
);
useEffect(() => setHighlight(0), [slash]);
@@ -85,7 +90,10 @@ export function Composer({
}, [menuOpen, cancelPending]);
function choose(item: SkillMenuItem) {
- if (item.command) {
+ if (item.savedToolId) {
+ voice.setInput('');
+ onRunTool(item.savedToolId);
+ } else if (item.command) {
voice.setInput('');
onCommand(item.command);
} else if (item.agentSkillId) {
diff --git a/src/extension/components/saved-tools.tsx b/src/extension/components/saved-tools.tsx
new file mode 100644
index 0000000..47b8e8c
--- /dev/null
+++ b/src/extension/components/saved-tools.tsx
@@ -0,0 +1,138 @@
+import { useEffect, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { Check, Trash2, X, Zap } from 'lucide-react';
+
+import { Button } from '@/extension/components/ui/button';
+import type { ToolOffer } from '@/lib/bridge/code-toolkit';
+import type { SavedToolMeta } from '@/lib/bridge/saved-tools';
+import { displayName, slugify } from '@/lib/skills/saved-tool';
+
+/**
+ * The offer, a second after an approved toolkit lands. It shows the name it would take
+ * rather than asking for one, because the answer is usually yes and the name is usually
+ * right — but the last segment stays editable, since that is the part the user will type.
+ */
+export function KeepToolPrompt({
+ offer,
+ onKeep,
+ onDismiss,
+}: {
+ offer: ToolOffer;
+ onKeep: (slug: string) => void;
+ onDismiss: () => void;
+}) {
+ const [slug, setSlug] = useState(offer.suggestedSlug);
+ useEffect(() => setSlug(offer.suggestedSlug), [offer.suggestedSlug]);
+
+ const clean = slugify(slug) || offer.suggestedSlug;
+ const where = offer.segment === 'root' ? offer.host : `${offer.host}/${offer.segment}`;
+
+ return (
+ <div className="enters mb-2 rounded-xl border border-lime/30 bg-lime/8 px-3 py-2.5">
+ <div className="flex items-start gap-2">
+ <Zap className="mt-0.5 size-3.5 shrink-0 text-lime" />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs font-medium text-ink">Keep this as a tool for {where}?</p>
+ <p className="mt-0.5 text-[11px] leading-relaxed text-ink-dim">{offer.purpose}</p>
+ </div>
+ </div>
+
+ <label className="mt-2.5 block">
+ <span className="sr-only">Tool name</span>
+ <span className="flex items-center rounded-lg border border-line bg-ground/60 px-2 py-1 font-mono text-[10px]">
+ <span className="shrink-0 text-ink-faint">{offer.host}:{offer.segment}:</span>
+ <input
+ value={slug}
+ onChange={(event) => setSlug(event.target.value)}
+ spellCheck={false}
+ aria-label="Tool name"
+ className="min-w-0 flex-1 bg-transparent text-ink outline-none"
+ />
+ </span>
+ </label>
+ <p className="mt-1 font-mono text-[10px] text-ink-faint">
+ runs with /{displayName({ host: offer.host, segment: offer.segment }, clean)}
+ </p>
+
+ <div className="mt-2.5 flex gap-1.5">
+ <Button variant="ghost" size="sm" className="flex-1" onClick={onDismiss}>
+ <X className="size-3" /> No
+ </Button>
+ <Button size="sm" className="flex-1" onClick={() => onKeep(clean)}>
+ <Check className="size-3" /> Yes, keep it
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/** `/remove-tools`: everything saved, with a cross on each. */
+export function SavedToolList({
+ tools,
+ onForget,
+ onClose,
+}: {
+ tools: SavedToolMeta[];
+ onForget: (id: string) => void;
+ onClose: () => void;
+}) {
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [onClose]);
+
+ return createPortal(
+ <div className="enters fixed inset-0 z-50 flex flex-col bg-ground/96 backdrop-blur">
+ <div className="flex items-start gap-2 border-b border-line px-3 py-2.5">
+ <Zap className="mt-0.5 size-3.5 shrink-0 text-lime" />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs font-medium text-ink">Your tools</p>
+ <p className="mt-0.5 text-[11px] leading-relaxed text-ink-dim">
+ Removing one deletes its code from the browser and its note from the daemon.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ title="Close"
+ className="mt-0.5 shrink-0 rounded p-0.5 text-ink-faint transition-colors hover:text-ink"
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-auto">
+ {tools.length === 0 ? (
+ <p className="px-3 py-4 text-[11px] leading-relaxed text-ink-faint">
+ Nothing saved yet. Turn the Live tool switch on, ask for something the ordinary tools cannot do, and
+ you will be offered the result to keep.
+ </p>
+ ) : (
+ <ul className="divide-y divide-line">
+ {tools.map((tool) => (
+ <li key={tool.id} className="flex items-start gap-2 px-3 py-2.5">
+ <div className="min-w-0 flex-1">
+ <p className="truncate font-mono text-[11px] text-ink">{tool.name}</p>
+ <p className="mt-0.5 text-[11px] leading-relaxed text-ink-dim">{tool.description}</p>
+ </div>
+ <button
+ type="button"
+ onClick={() => onForget(tool.id)}
+ title={`Remove ${tool.name}`}
+ aria-label={`Remove ${tool.name}`}
+ className="mt-0.5 shrink-0 rounded p-1 text-ink-faint transition-colors hover:bg-ember/10 hover:text-ember"
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/src/extension/components/skill-menu.tsx b/src/extension/components/skill-menu.tsx
index b721bc4..008f8b7 100644
--- a/src/extension/components/skill-menu.tsx
+++ b/src/extension/components/skill-menu.tsx
@@ -1,31 +1,52 @@
-import { BookOpen, Globe, Sparkles, SquareSlash } from 'lucide-react';
+import { BookOpen, Globe, Sparkles, SquareSlash, Zap } from 'lucide-react';
import type { SkillCatalog } from '@/lib/actions/protocol';
import { AGENTS } from '@/lib/agents/catalog';
-import { CONTEXT_COMMAND, CONTEXT_COMMAND_DESCRIPTION } from '@/lib/bridge/commands';
+import {
+ CONTEXT_COMMAND,
+ CONTEXT_COMMAND_DESCRIPTION,
+ REMOVE_TOOLS_COMMAND,
+ REMOVE_TOOLS_DESCRIPTION,
+} from '@/lib/bridge/commands';
+import type { SavedToolMeta } from '@/lib/bridge/saved-tools';
import { hostMatchesDomains, hostnameOf } from '@/lib/skills/format';
+import { toolMatchesUrl } from '@/lib/skills/saved-tool';
import { cn } from '@/lib/utils';
export interface SkillMenuItem {
key: string;
- group: 'command' | 'site' | 'general' | 'agent' | 'other-site';
+ group: 'tool' | 'command' | 'site' | 'general' | 'agent' | 'other-site';
name: string;
description: string;
/** Set on agent skills — choosing one attaches this id to the message instead of a text prefix. */
agentSkillId?: string;
/** Set on typed commands — choosing one sends this text right away instead of inserting a prefix. */
command?: string;
+ /**
+ * Set on a tool the user saved. Choosing one runs its approved code in the tab there and
+ * then: no agent, no daemon, no prompt, because all three already had their say when it
+ * was saved.
+ */
+ savedToolId?: string;
}
+// Saved tools sort first: they are the only entries that do something on their own, and
+// the user named them, so they are the ones being looked for.
const GROUP_ORDER: Record<SkillMenuItem['group'], number> = {
- command: 0,
- site: 1,
- general: 2,
- agent: 3,
- 'other-site': 4,
+ tool: 0,
+ command: 1,
+ site: 2,
+ general: 3,
+ agent: 4,
+ 'other-site': 5,
};
-export function skillMenuItems(catalog: SkillCatalog | undefined, tabUrl: string, query: string): SkillMenuItem[] {
+export function skillMenuItems(
+ catalog: SkillCatalog | undefined,
+ tabUrl: string,
+ query: string,
+ tools: readonly SavedToolMeta[] = [],
+): SkillMenuItem[] {
const host = hostnameOf(tabUrl);
const items: SkillMenuItem[] = [
{
@@ -36,6 +57,27 @@ export function skillMenuItems(catalog: SkillCatalog | undefined, tabUrl: string
command: CONTEXT_COMMAND,
},
];
+ if (tools.length) {
+ items.push({
+ key: 'command:remove-tools',
+ group: 'command',
+ name: 'remove-tools',
+ description: REMOVE_TOOLS_DESCRIPTION,
+ command: REMOVE_TOOLS_COMMAND,
+ });
+ }
+ // Only the ones that belong on this page. A tool saved for youtube.com/watch is noise
+ // on the homepage, and offering it there would only produce a scope refusal.
+ for (const tool of tools) {
+ if (!toolMatchesUrl(tool.scope, tabUrl)) continue;
+ items.push({
+ key: `tool:${tool.id}`,
+ group: 'tool',
+ name: tool.name,
+ description: tool.description,
+ savedToolId: tool.id,
+ });
+ }
for (const skill of catalog?.skills ?? []) {
const group =
skill.category !== 'site-exploration'
@@ -71,6 +113,7 @@ export function SkillMenu({
onSelect: (item: SkillMenuItem) => void;
}) {
const labels: Record<SkillMenuItem['group'], string> = {
+ tool: 'Your tools',
command: 'Commands',
site: 'On this site',
general: 'Browsentic skills',
@@ -108,7 +151,9 @@ export function SkillMenu({
index === highlight ? 'bg-brand/12' : 'hover:bg-ground/40',
)}
>
- {item.group === 'command' ? (
+ {item.group === 'tool' ? (
+ <Zap className="mt-0.5 size-3 shrink-0 text-lime" />
+ ) : item.group === 'command' ? (
<SquareSlash className="mt-0.5 size-3 shrink-0 text-amber" />
) : item.group === 'agent' ? (
<Sparkles className="mt-0.5 size-3 shrink-0 text-brand" />
diff --git a/src/extension/entrypoints/sidepanel/App.tsx b/src/extension/entrypoints/sidepanel/App.tsx
index c140637..3d64fe7 100644
--- a/src/extension/entrypoints/sidepanel/App.tsx
+++ b/src/extension/entrypoints/sidepanel/App.tsx
@@ -3,6 +3,7 @@ import { ArrowDown, PanelRightClose, SquarePen } from 'lucide-react';
import { browser } from 'wxt/browser';
import { invokeInActiveTab } from '@/lib/actions/client';
+import { isRemoveToolsCommand } from '@/lib/bridge/commands';
import { getPageInfo } from '@/lib/actions/page/get-page-info';
import { BRIDGE_CHANNEL, type FocusedElement } from '@/lib/actions/protocol';
import { Wordmark } from '@/extension/components/brand';
@@ -14,6 +15,7 @@ import { PanelNav, type PanelTab } from '@/extension/components/panel-nav';
import { RecordingBar } from '@/extension/components/recording-bar';
import { RecordingPanel } from '@/extension/components/recording-panel';
import { RunTimeline } from '@/extension/components/run-timeline';
+import { KeepToolPrompt, SavedToolList } from '@/extension/components/saved-tools';
import { SessionList } from '@/extension/components/session-list';
import { SessionRail } from '@/extension/components/session-rail';
import { SettingsPanel } from '@/extension/components/settings-panel';
@@ -53,6 +55,7 @@ export default function App() {
const [attachError, setAttachError] = useState<string | null>(null);
const [attachedSkill, setAttachedSkill] = useState<AttachedSkill | null>(null);
const [focus, setFocus] = useState<FocusedElement | null>(null);
+ const [showTools, setShowTools] = useState(false);
const [picking, setPicking] = useState(false);
const [liveTools, setLiveTools] = useState(false);
const [tab, setTab] = usePanelTab();
@@ -329,8 +332,15 @@ export default function App() {
)}
</div>
+ {showTools && (
+ <SavedToolList tools={run.tools} onForget={run.forgetTool} onClose={() => setShowTools(false)} />
+ )}
+
{tab === 'chat' && (
<footer className="shrink-0 border-t border-line p-3">
+ {run.toolOffer && (
+ <KeepToolPrompt offer={run.toolOffer} onKeep={run.keepTool} onDismiss={run.dismissTool} />
+ )}
<Composer
voice={voice}
voiceEnabled={voiceEnabled}
@@ -347,9 +357,18 @@ export default function App() {
onToggleLiveTools={() => setLiveTools((on) => !on)}
onAttachSkill={setAttachedSkill}
onCommand={(command) => {
+ if (isRemoveToolsCommand(command)) {
+ setShowTools(true);
+ return;
+ }
open('chat');
run.send(command);
}}
+ tools={run.tools}
+ onRunTool={(id) => {
+ open('chat');
+ run.runTool(id);
+ }}
onSend={handleSend}
onStop={run.cancel}
onToggleVoice={toggleVoice}
diff --git a/src/lib/actions/page/toolkit.ts b/src/lib/actions/page/toolkit.ts
index a9aca7b..6231749 100644
--- a/src/lib/actions/page/toolkit.ts
+++ b/src/lib/actions/page/toolkit.ts
@@ -33,6 +33,16 @@ interface ToolkitReply {
error?: string;
}
+/**
+ * What the installer reports back. Arity comes from `Function.length`, which is what
+ * decides whether a function can become a saved tool: `/` invocation passes no arguments,
+ * so only a zero-argument entry point can be offered for saving.
+ */
+export interface ToolkitEntry {
+ name: string;
+ arity: number;
+}
+
export function installerSource(toolkitId: string, code: string): string {
const key = JSON.stringify(TOOLKIT_GLOBAL);
const attribute = JSON.stringify(TOOLKIT_ATTRIBUTE);
@@ -45,8 +55,10 @@ export function installerSource(toolkitId: string, code: string): string {
${code}
})(tools);
- const names = Object.keys(tools).filter((name) => typeof tools[name] === 'function');
- if (!names.length) {
+ const entries = Object.keys(tools)
+ .filter((name) => typeof tools[name] === 'function')
+ .map((name) => ({ name: name, arity: tools[name].length }));
+ if (!entries.length) {
throw new Error('The code defined no functions on "tools" — assign each entry point, e.g. tools.addTag = (name) => {…}.');
}
@@ -89,7 +101,7 @@ ${code}
store.tools = tools;
store.id = ${JSON.stringify(toolkitId)};
document.documentElement.setAttribute(${attribute}, ${JSON.stringify(toolkitId)});
- return names;
+ return entries;
})()`;
}
diff --git a/src/lib/bridge/code-toolkit.ts b/src/lib/bridge/code-toolkit.ts
index 1583bce..8e9d425 100644
--- a/src/lib/bridge/code-toolkit.ts
+++ b/src/lib/bridge/code-toolkit.ts
@@ -14,9 +14,11 @@ import { z } from 'zod';
import { invokeInTab } from '@/lib/actions/client';
import { injectCode } from '@/lib/actions/page/inject-code';
import { runCode } from '@/lib/actions/page/run-code';
-import { installerSource, TOOLKIT_MISSING } from '@/lib/actions/page/toolkit';
+import { installerSource, TOOLKIT_MISSING, type ToolkitEntry } from '@/lib/actions/page/toolkit';
import { failure, success, type ActionResult } from '@/lib/actions/protocol';
+import { scopeOf, slugFromPurpose } from '@/lib/skills/saved-tool';
import { send, withDebugger, type DebuggerSession } from './cdp';
+import { getSavedTool, scopeMatches } from './saved-tools';
const TOOLKITS_KEY = 'browsentic/codeToolkits';
@@ -30,10 +32,34 @@ interface StoredToolkit {
origin: string;
purpose: string;
code: string;
- functions: string[];
+ entries: ToolkitEntry[];
installedAt: number;
}
+/**
+ * What the panel is asked about a second after an install lands. Metadata only: the code
+ * stays here, and the panel already has it from the approval it just answered.
+ */
+export interface ToolOffer {
+ toolkitId: string;
+ /** The zero-argument entry point a saved tool would call. */
+ fn: string;
+ purpose: string;
+ suggestedSlug: string;
+ host: string;
+ segment: string;
+ origin: string;
+}
+
+/** How long after an install the offer appears. Long enough to see the effect land first. */
+const OFFER_DELAY_MS = 1_000;
+
+const offerListeners = new Set<(offer: ToolOffer) => void>();
+
+export function onToolOffer(listener: (offer: ToolOffer) => void): void {
+ offerListeners.add(listener);
+}
+
type ToolkitMap = Record<string, StoredToolkit>;
interface EvaluateReply {
@@ -86,30 +112,99 @@ export async function installToolkit(tabId: number, url: string | undefined, inp
origin,
purpose,
code,
- functions: [],
+ entries: [],
installedAt: Date.now(),
};
const installed = await evaluateInstaller(tabId, toolkit);
if (!installed.ok) return installed;
- toolkit.functions = installed.data as string[];
+ toolkit.entries = installed.data as ToolkitEntry[];
await writeToolkit(tabId, toolkit);
const summary = {
toolkitId: toolkit.id,
origin,
purpose,
- functions: toolkit.functions,
+ functions: toolkit.entries.map((entry) => entry.name),
};
- if (!call) return success(summary);
- const called = await runToolkit(tabId, url, { function: call.function, args: call.args });
+ const called = call ? await runToolkit(tabId, url, { function: call.function, args: call.args }) : null;
+ offerToKeep(toolkit, url, call?.function);
+
+ if (!called) return success(summary);
return called.ok
? success({ ...summary, called: called.data })
: success({ ...summary, callFailed: called.error });
}
+/**
+ * Ask, once, whether this is worth keeping. Only a zero-argument entry point can be
+ * offered, because `/` invocation passes nothing: prefer the one just called, since that
+ * is the effect the user watched happen, and otherwise take a lone zero-argument function.
+ * Anything else stays a one-off, which is the honest answer for a toolkit that needs input.
+ */
+function offerToKeep(toolkit: StoredToolkit, url: string | undefined, called: string | undefined): void {
+ const zeroArg = toolkit.entries.filter((entry) => entry.arity === 0);
+ const entry = zeroArg.find((candidate) => candidate.name === called) ?? (zeroArg.length === 1 ? zeroArg[0] : null);
+ const scope = url ? scopeOf(url) : null;
+ if (!entry || !scope) return;
+
+ setTimeout(() => {
+ const offer: ToolOffer = {
+ toolkitId: toolkit.id,
+ fn: entry.name,
+ purpose: toolkit.purpose,
+ suggestedSlug: slugFromPurpose(toolkit.purpose, entry.name),
+ host: scope.host,
+ segment: scope.segment,
+ origin: toolkit.origin,
+ };
+ for (const listener of offerListeners) listener(offer);
+ }, OFFER_DELAY_MS);
+}
+
+/**
+ * The `/` path. No guardrail runs here and none should: this code was read and approved
+ * when it was saved, the user asked for it by name just now, and the daemon is not in the
+ * loop at all — which is also what keeps it out of reach of an MCP client.
+ */
+export async function runSavedTool(tabId: number, url: string | undefined, toolId: string): Promise<ActionResult> {
+ const tool = await getSavedTool(toolId);
+ if (!tool) return failure('UNKNOWN_TOOL', 'That tool is no longer saved.');
+ if (!scopeMatches(tool, url)) {
+ return failure(
+ 'TOOLKIT_SCOPE',
+ `“${tool.name}” was saved for ${tool.origin}/${tool.scope.segment}, and this tab is somewhere else.`,
+ );
+ }
+
+ const staged: StoredToolkit = {
+ id: tool.id,
+ origin: tool.origin,
+ purpose: tool.description,
+ code: tool.code,
+ entries: [],
+ installedAt: Date.now(),
+ };
+ const installed = await evaluateInstaller(tabId, staged);
+ if (!installed.ok) return installed;
+
+ staged.entries = installed.data as ToolkitEntry[];
+ await writeToolkit(tabId, staged);
+ return invokeInTab(tabId, runCode.name, { function: tool.fn, args: [], timeoutMs: 10_000 });
+}
+
+/**
+ * The approved source for a toolkit still installed in this tab, by the id the offer
+ * carried. Saving reads it from here rather than from the panel, so the code makes one
+ * fewer hop and the panel never has to hold it to hand it back.
+ */
+export async function toolkitCode(tabId: number, toolkitId: string): Promise<string | null> {
+ const toolkit = (await readToolkits())[String(tabId)];
+ return toolkit && toolkit.id === toolkitId ? toolkit.code : null;
+}
+
export async function runToolkit(tabId: number, url: string | undefined, input: unknown): Promise<ActionResult> {
const parsed = runCode.input.safeParse(input ?? {});
if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
@@ -131,10 +226,10 @@ export async function runToolkit(tabId: number, url: string | undefined, input:
);
}
- if (!toolkit.functions.includes(parsed.data.function)) {
+ if (!toolkit.entries.some((entry) => entry.name === parsed.data.function)) {
return failure(
'UNKNOWN_FUNCTION',
- `This toolkit has no function named “${parsed.data.function}”. It defines: ${toolkit.functions.join(', ')}.`,
+ `This toolkit has no function named “${parsed.data.function}”. It defines: ${toolkit.entries.map((entry) => entry.name).join(', ')}.`,
);
}
@@ -153,11 +248,11 @@ function evaluateInstaller(tabId: number, toolkit: StoredToolkit): Promise<Actio
if (thrown) {
return failure('CODE_ERROR', `The code failed while installing: ${describeThrow(thrown)}`);
}
- const names = reply.result?.value;
- if (!Array.isArray(names)) {
+ const entries = reply.result?.value;
+ if (!Array.isArray(entries)) {
return failure('CODE_ERROR', 'The code installed but reported no functions.');
}
- return success(names as string[]);
+ return success(entries as ToolkitEntry[]);
});
}
diff --git a/src/lib/bridge/commands.ts b/src/lib/bridge/commands.ts
index 4fbf319..bfbe27c 100644
--- a/src/lib/bridge/commands.ts
+++ b/src/lib/bridge/commands.ts
@@ -4,6 +4,13 @@ import type { FileStatus } from './file-store';
export const CONTEXT_COMMAND = '/context';
+export const REMOVE_TOOLS_COMMAND = '/remove-tools';
+
+export const REMOVE_TOOLS_DESCRIPTION = 'Review the tools you saved, and delete any you are done with.';
+
+export const isRemoveToolsCommand = (text: string): boolean =>
+ text.trim().toLowerCase() === REMOVE_TOOLS_COMMAND;
+
export const CONTEXT_COMMAND_DESCRIPTION =
'See what this conversation carries — messages, files, recordings, tabs.';
diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.ts
index 24efb56..7f29e5c 100644
--- a/src/lib/bridge/run-port.ts
+++ b/src/lib/bridge/run-port.ts
@@ -10,7 +10,10 @@ import type { MonitorState } from '@/lib/monitor/events';
import type { RecordingState } from '@/lib/recordings/events';
import type { SiteMapDraft } from '@/lib/skills/site-map';
import { navigate } from '@/lib/actions/page/navigate';
+import { onToolOffer, runSavedTool, toolkitCode, type ToolOffer } from './code-toolkit';
import { CONTEXT_COMMAND, isContextCommand, type ContextBreakdown } from './commands';
+import { listSavedTools, withoutCode, type SavedToolMeta } from './saved-tools';
+import { dropTool, keepTool } from './tool-registry';
import { tryFastPath } from './fast-path';
import { dropDiagnosticsForSession } from './diagnostics';
import { listMeta } from './file-store';
@@ -84,7 +87,12 @@ export type RunCommand =
| { op: 'discardMap'; stagingId: string }
| { op: 'startRecording'; captureValues: boolean }
| { op: 'stopRecording' }
- | { op: 'stopMonitor'; monitorId: string };
+ | { op: 'stopMonitor'; monitorId: string }
+ | { op: 'keepTool'; toolkitId: string; tabId: number; slug?: string }
+ | { op: 'dismissTool'; toolkitId: string }
+ | { op: 'forgetTool'; id: string }
+ | { op: 'runTool'; id: string; tab: TabAnchor }
+ | { op: 'listTools' };
export type RunMessage =
| { op: 'event'; sessionId?: string; runId: string; event: RunEvent }
@@ -95,6 +103,9 @@ export type RunMessage =
| { op: 'recording'; state: RecordingState | null }
| { op: 'preview'; sessionId?: string; preview: ScreenshotPreview }
| { op: 'monitor'; state: MonitorState }
+ | { op: 'toolOffer'; offer: ToolOffer }
+ | { op: 'toolOfferSettled'; toolkitId: string }
+ | { op: 'tools'; tools: SavedToolMeta[] }
| { op: 'close' };
const ports = new Set<Browser.runtime.Port>();
@@ -106,6 +117,8 @@ const persistTimers = new Map<string, ReturnType<typeof setTimeout>>();
const cancelTimers = new Map<string, ReturnType<typeof setTimeout>>();
let externalItems: RunItem[] = [];
const pendingDrafts = new Map<string, { sessionId?: string; draft: SiteMapDraft }>();
+/** Offers raised but not yet answered, so a stale panel cannot save a toolkit twice. */
+const pendingOffers = new Map<string, ToolOffer>();
let queue: Promise<unknown> = Promise.resolve();
function serialized<T>(task: () => Promise<T>): Promise<T> {
@@ -130,6 +143,11 @@ export function serveRunPorts(): void {
});
});
+ onToolOffer((offer) => {
+ pendingOffers.set(offer.toolkitId, offer);
+ broadcast({ op: 'toolOffer', offer });
+ });
+
onMonitorState((state) => {
broadcast({ op: 'monitor', state });
if (state.phase !== 'watching') {
@@ -196,6 +214,7 @@ export function serveRunPorts(): void {
post(port, { op: 'mapDraft', sessionId: held.sessionId, draft: held.draft });
}
void currentRecording().then((state) => post(port, { op: 'recording', state }));
+ void listSavedTools().then((tools) => post(port, { op: 'tools', tools: tools.map(withoutCode) }));
void activeMonitorStates().then((states) => {
for (const state of states) post(port, { op: 'monitor', state });
});
@@ -289,9 +308,49 @@ function handle(command: RunCommand): void {
case 'stopMonitor':
void stopTabMonitor(command.monitorId);
return;
+ case 'keepTool':
+ void serialized(async () => {
+ const offer = pendingOffers.get(command.toolkitId);
+ const code = offer ? await toolkitCode(command.tabId, command.toolkitId) : null;
+ if (offer && code) await keepTool({ offer, code, slug: command.slug }).catch(() => undefined);
+ pendingOffers.delete(command.toolkitId);
+ broadcast({ op: 'toolOfferSettled', toolkitId: command.toolkitId });
+ await publishTools();
+ });
+ return;
+ case 'dismissTool':
+ pendingOffers.delete(command.toolkitId);
+ broadcast({ op: 'toolOfferSettled', toolkitId: command.toolkitId });
+ return;
+ case 'forgetTool':
+ void serialized(async () => {
+ await dropTool(command.id);
+ await publishTools();
+ });
+ return;
+ case 'runTool':
+ void serialized(async () => {
+ const result = await runSavedTool(command.tab.tabId, command.tab.url, command.id);
+ broadcast({ op: 'item', item: toolRunItem(command.id, result) });
+ });
+ return;
+ case 'listTools':
+ void publishTools();
+ return;
}
}
+/** A saved-tool run shows on the timeline like any other step, marked local since it was. */
+function toolRunItem(id: string, result: { ok: boolean; error?: { code: string; message: string } }): RunItem {
+ return result.ok
+ ? { kind: 'tool', id: nextId(), action: 'savedTool', input: { tool: id }, ok: true, source: 'local' }
+ : notice('error', `${result.error?.code}: ${result.error?.message}`);
+}
+
+async function publishTools(): Promise<void> {
+ broadcast({ op: 'tools', tools: (await listSavedTools()).map(withoutCode) });
+}
+
async function absorb(runId: string, event: RunEvent): Promise<void> {
if (runId === EXTERNAL_RUN_ID) {
externalItems = reduce(externalItems, event).slice(-MAX_EXTERNAL_ITEMS);
diff --git a/src/lib/bridge/saved-tools.ts b/src/lib/bridge/saved-tools.ts
new file mode 100644
index 0000000..6ef0fda
--- /dev/null
+++ b/src/lib/bridge/saved-tools.ts
@@ -0,0 +1,104 @@
+/**
+ * Tools the user kept: the JavaScript half.
+ *
+ * This is the only place an approved toolkit's source lives once it is saved, and it is
+ * deliberately `storage.local` in the extension — not the daemon, not the page, not the
+ * skills directory. The daemon gets a markdown note that such a tool exists so the agent
+ * can mention it; it never gets the code, so nothing an MCP client can reach ever holds a
+ * line of it.
+ *
+ * A saved tool runs without a guardrail prompt. That exemption is the point (the code was
+ * read and approved at save time) and it is why the record pins both the origin it was
+ * approved on and the scope it may be offered in: the run path re-checks both before it
+ * installs anything.
+ */
+
+import { browser } from 'wxt/browser';
+import { displayName, scopeOf, toolMatchesUrl, type ToolScope } from '@/lib/skills/saved-tool';
+
+const TOOLS_KEY = 'browsentic/savedTools';
+
+/** A guard on the store, not a product limit — a slash menu stops being a menu long before this. */
+export const MAX_SAVED_TOOLS = 100;
+
+export interface SavedTool {
+ id: string;
+ /** `youtube.com:watch:darken-page-except-video-player`. Shown, typed, never made a path. */
+ name: string;
+ /** The daemon's skill file for this tool, so removal can unlink the right one. */
+ skillName: string;
+ description: string;
+ scope: ToolScope;
+ /** The full origin the code was approved on. Re-checked before every run. */
+ origin: string;
+ /** The approved source. Never leaves the extension. */
+ code: string;
+ /** The zero-argument entry point `/` invokes. */
+ fn: string;
+ createdAt: number;
+}
+
+/** Everything but the code: what the panel renders and what may cross a message boundary. */
+export type SavedToolMeta = Omit<SavedTool, 'code'>;
+
+export const withoutCode = ({ code: _code, ...meta }: SavedTool): SavedToolMeta => meta;
+
+export async function listSavedTools(): Promise<SavedTool[]> {
+ const stored = await browser.storage.local.get(TOOLS_KEY);
+ const held = stored[TOOLS_KEY];
+ return Array.isArray(held) ? (held as SavedTool[]) : [];
+}
+
+export async function savedToolsFor(url: string): Promise<SavedToolMeta[]> {
+ const tools = await listSavedTools();
+ return tools.filter((tool) => toolMatchesUrl(tool.scope, url)).map(withoutCode);
+}
+
+export async function getSavedTool(id: string): Promise<SavedTool | null> {
+ return (await listSavedTools()).find((tool) => tool.id === id) ?? null;
+}
+
+export async function saveTool(tool: SavedTool): Promise<void> {
+ const tools = await listSavedTools();
+ // Same name on the same scope replaces rather than accumulates: saving twice from the
+ // same page is a correction, not a second tool.
+ const kept = tools.filter((held) => held.name !== tool.name);
+ await browser.storage.local.set({ [TOOLS_KEY]: [tool, ...kept].slice(0, MAX_SAVED_TOOLS) });
+}
+
+export async function forgetSavedTool(id: string): Promise<SavedToolMeta | null> {
+ const tools = await listSavedTools();
+ const going = tools.find((tool) => tool.id === id);
+ if (!going) return null;
+ await browser.storage.local.set({ [TOOLS_KEY]: tools.filter((tool) => tool.id !== id) });
+ return withoutCode(going);
+}
+
+/**
+ * A name that does not collide with what is already saved on this scope. The suffix is
+ * numeric rather than a uuid because the whole point of the name is that it can be typed.
+ */
+export async function uniqueName(scope: ToolScope, slug: string): Promise<string> {
+ const taken = new Set((await listSavedTools()).map((tool) => tool.name));
+ const base = displayName(scope, slug);
+ if (!taken.has(base)) return base;
+ for (let n = 2; n < 100; n++) {
+ const candidate = `${base}-${n}`;
+ if (!taken.has(candidate)) return candidate;
+ }
+ return `${base}-${Date.now()}`;
+}
+
+/** The origin a tool may run on, recomputed from the live tab rather than trusted from the record. */
+export function scopeMatches(tool: SavedTool, url: string | undefined): boolean {
+ if (!url) return false;
+ const here = scopeOf(url);
+ if (!here) return false;
+ let origin: string;
+ try {
+ origin = new URL(url).origin;
+ } catch {
+ return false;
+ }
+ return origin === tool.origin && toolMatchesUrl(tool.scope, url);
+}
diff --git a/src/lib/bridge/tool-registry.ts b/src/lib/bridge/tool-registry.ts
new file mode 100644
index 0000000..44b2d13
--- /dev/null
+++ b/src/lib/bridge/tool-registry.ts
@@ -0,0 +1,103 @@
+/**
+ * Keeping a tool, and letting it go again.
+ *
+ * Two halves that must move together and are deliberately kept apart:
+ *
+ * the code → `storage.local`, extension only. Never sent anywhere.
+ * a description → a markdown skill on the daemon, so the agent knows the tool exists
+ * and can tell the user to reach for it.
+ *
+ * The daemon half carries no JavaScript at all. That is what keeps a saved tool out of an
+ * MCP client's reach: the skill it can theoretically read is prose, and the only thing that
+ * can execute the tool is the side panel, over a port no external caller is on.
+ */
+
+import type { SkillDraft } from '@/lib/skills/format';
+import { skillNameFor, slugify } from '@/lib/skills/saved-tool';
+import type { ToolOffer } from './code-toolkit';
+import { deleteSkill, saveSkill } from './socket';
+import {
+ forgetSavedTool,
+ saveTool,
+ uniqueName,
+ withoutCode,
+ type SavedTool,
+ type SavedToolMeta,
+} from './saved-tools';
+
+/** The code the panel approved, read back out of the tab's live toolkit record. */
+export interface KeepRequest {
+ offer: ToolOffer;
+ /** The toolkit source, supplied by whatever still holds it. */
+ code: string;
+ /** User-editable last name segment; falls back to the suggestion on the offer. */
+ slug?: string;
+}
+
+export async function keepTool(request: KeepRequest): Promise<SavedToolMeta> {
+ const { offer, code } = request;
+ const scope = { host: offer.host, segment: offer.segment };
+ const slug = slugify(request.slug ?? '') || offer.suggestedSlug;
+ const name = await uniqueName(scope, slug);
+
+ const tool: SavedTool = {
+ id: crypto.randomUUID(),
+ name,
+ skillName: skillNameFor(scope, slug),
+ description: offer.purpose,
+ scope,
+ origin: offer.origin,
+ code,
+ fn: offer.fn,
+ createdAt: Date.now(),
+ };
+
+ await saveTool(tool);
+ // Best effort: the tool works from `/` whether or not the daemon is up to hear about it.
+ await saveSkill(skillFor(tool)).catch(() => undefined);
+ return withoutCode(tool);
+}
+
+export async function dropTool(id: string): Promise<SavedToolMeta | null> {
+ const gone = await forgetSavedTool(id);
+ if (gone) await deleteSkill(gone.skillName).catch(() => undefined);
+ return gone;
+}
+
+/**
+ * The markdown the daemon gets. It describes the tool and says who may run it, because an
+ * agent that tried would only find there is no action for it — better to say so plainly
+ * than to let it discover that by failing.
+ */
+function skillFor(tool: SavedTool): SkillDraft {
+ const where = tool.scope.segment === 'root' ? tool.scope.host : `${tool.scope.host}/${tool.scope.segment}`;
+ return {
+ name: tool.skillName,
+ description: `Saved tool on ${where}: ${tool.description}`,
+ category: 'site-exploration',
+ domains: [tool.scope.host],
+ triggers: [tool.name, tool.scope.host],
+ body: [
+ `# ${tool.name}`,
+ '',
+ `The user saved a tool for **${where}**, out of page code they read and approved:`,
+ '',
+ `> ${tool.description}`,
+ '',
+ '## How it runs',
+ '',
+ `It runs from the side panel, by typing \`/${tool.name}\`. It is already approved, so it`,
+ 'needs no further permission and costs no round trip.',
+ '',
+ '## What you should do',
+ '',
+ 'You cannot call it yourself: it is not a page action, and its code lives in the extension',
+ 'rather than here. If the user asks for this on this page, tell them the tool exists and to',
+ `run \`/${tool.name}\`, rather than writing the same thing again with page.injectCode.`,
+ '',
+ 'If they want it changed, write fresh code with page.injectCode as usual and let them save',
+ 'that over the old one.',
+ ].join('\n'),
+ };
+}
+
diff --git a/src/lib/bridge/use-run.ts b/src/lib/bridge/use-run.ts
index 494c167..9cab5f1 100644
--- a/src/lib/bridge/use-run.ts
+++ b/src/lib/bridge/use-run.ts
@@ -4,6 +4,8 @@ import type { FocusedElement } from '@/lib/actions/protocol';
import type { MonitorState } from '@/lib/monitor/events';
import type { RecordingState } from '@/lib/recordings/events';
import { SITE_MAPPER_SKILL, type SiteMapDraft } from '@/lib/skills/site-map';
+import type { ToolOffer } from './code-toolkit';
+import type { SavedToolMeta } from './saved-tools';
import { attachPreview, notice, reduce, type RunItem } from './run-items';
import { RUN_PORT, type RunCommand, type RunMessage } from './run-port';
import { useActiveTab } from './use-active-tab';
@@ -43,12 +45,22 @@ export interface Run {
stopRecording: () => void;
monitors: MonitorState[];
stopMonitor: (monitorId: string) => void;
+ /** Tools the user kept, for the `/` menu and `/remove-tools`. Metadata only, never code. */
+ tools: SavedToolMeta[];
+ /** Raised a second after an approved toolkit lands, asking whether to keep it. */
+ toolOffer: ToolOffer | null;
+ keepTool: (slug?: string) => void;
+ dismissTool: () => void;
+ forgetTool: (id: string) => void;
+ runTool: (id: string) => void;
}
export function useRun(): Run {
const [drafts, setDrafts] = useState<Record<string, SiteMapDraft>>({});
const [recording, setRecording] = useState<RecordingState | null>(null);
const [monitors, setMonitors] = useState<MonitorState[]>([]);
+ const [offer, setOffer] = useState<ToolOffer | null>(null);
+ const [tools, setTools] = useState<SavedToolMeta[]>([]);
const [bySession, setBySession] = useState<Record<string, RunItem[]>>({});
const port = useRef<Browser.runtime.Port | null>(null);
@@ -111,6 +123,12 @@ export function useRun(): Run {
write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => [...items, runMessage.item]);
} else if (runMessage.op === 'preview') {
write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => attachPreview(items, runMessage.preview));
+ } else if (runMessage.op === 'toolOffer') {
+ setOffer(runMessage.offer);
+ } else if (runMessage.op === 'toolOfferSettled') {
+ setOffer((held) => (held?.toolkitId === runMessage.toolkitId ? null : held));
+ } else if (runMessage.op === 'tools') {
+ setTools(runMessage.tools);
} else if (runMessage.op === 'close') {
window.close();
} else {
@@ -224,6 +242,31 @@ export function useRun(): Run {
stopRecording: useCallback(() => {
post({ op: 'stopRecording' });
}, [post]),
+ tools,
+ toolOffer: offer,
+ keepTool: useCallback(
+ (slug?: string) => {
+ if (offer && tab.tabId != null) post({ op: 'keepTool', toolkitId: offer.toolkitId, tabId: tab.tabId, slug });
+ },
+ [offer, post, tab.tabId],
+ ),
+ dismissTool: useCallback(() => {
+ if (offer) post({ op: 'dismissTool', toolkitId: offer.toolkitId });
+ }, [offer, post]),
+ forgetTool: useCallback(
+ (id: string) => {
+ post({ op: 'forgetTool', id });
+ },
+ [post],
+ ),
+ runTool: useCallback(
+ (id: string) => {
+ if (tab.tabId != null) {
+ post({ op: 'runTool', id, tab: { tabId: tab.tabId, url: tab.url, windowId: tab.windowId, title: tab.title } });
+ }
+ },
+ [post, tab],
+ ),
monitors,
stopMonitor: useCallback(
(monitorId: string) => {
diff --git a/src/lib/skills/saved-tool.ts b/src/lib/skills/saved-tool.ts
new file mode 100644
index 0000000..bc9ce3f
--- /dev/null
+++ b/src/lib/skills/saved-tool.ts
@@ -0,0 +1,92 @@
+/**
+ * Naming and matching for tools the user saved out of an approved live toolkit.
+ *
+ * Two names, deliberately. The display name is what the user typed `/` to find and reads
+ * in a list: `youtube.com:watch:darken-page-except-video-player`, host first because that
+ * is how you remember where a tool belongs. The daemon's copy is a skill file, and a skill
+ * name reaches `join(skillsDir, name + '.md')`, so it goes through SKILL_NAME_RE like every
+ * other one rather than carrying a user-shaped string into a path.
+ *
+ * Scope is host plus the first path segment. A tool made on /watch offers itself on every
+ * /watch page and nowhere else on the host, which is the granularity real sites are built
+ * at: the segment names the kind of page, and everything after it names which one.
+ */
+
+import { SKILL_NAME_RE } from './format';
+
+export const ROOT_SEGMENT = 'root';
+
+/** Long enough for three readable parts, short enough to sit in a menu row. */
+const MAX_SLUG = 48;
+
+export interface ToolScope {
+ /** Hostname, lowercased, without a leading `www.`. */
+ host: string;
+ /** First path segment, or ROOT_SEGMENT for `/`. */
+ segment: string;
+}
+
+export function scopeOf(url: string): ToolScope | null {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
+ const host = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ if (!host) return null;
+ const [first = ''] = parsed.pathname.split('/').filter(Boolean);
+ return { host, segment: slugify(first) || ROOT_SEGMENT };
+}
+
+/** `youtube.com:watch:darken-page-except-video-player`. */
+export function displayName(scope: ToolScope, slug: string): string {
+ return `${scope.host}:${scope.segment}:${slug}`;
+}
+
+/**
+ * A tool is offered when the tab is on the same host and the same first path segment.
+ * Everything deeper varies per record (`/orders/1234`) and must not narrow the match.
+ */
+export function toolMatchesUrl(scope: ToolScope, url: string): boolean {
+ const here = scopeOf(url);
+ return !!here && here.host === scope.host && here.segment === scope.segment;
+}
+
+export function slugify(text: string): string {
+ return text
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, MAX_SLUG)
+ .replace(/-+$/, '');
+}
+
+/**
+ * Turn a purpose sentence into the last name segment. Stop words go first so
+ * "Darken the page except the video player" reads as the thing it does.
+ */
+const STOP = new Set(['a', 'an', 'and', 'for', 'from', 'in', 'of', 'on', 'the', 'this', 'to', 'with']);
+
+export function slugFromPurpose(purpose: string, fallback: string): string {
+ const words = purpose
+ .toLowerCase()
+ .replace(/[^a-z0-9\s-]+/g, ' ')
+ .split(/[\s-]+/)
+ .filter((word) => word && !STOP.has(word));
+ return slugify(words.join('-')) || slugify(fallback) || 'tool';
+}
+
+/**
+ * The daemon-side skill name. Derived, sanitised and length-capped, because this one
+ * becomes a filename. Never build a path from `displayName`.
+ */
+export function skillNameFor(scope: ToolScope, slug: string): string {
+ const base = slugify(`tool-${scope.host}-${scope.segment}-${slug}`).slice(0, 48).replace(/-+$/, '');
+ return SKILL_NAME_RE.test(base) ? base : `tool-${slugify(slug).slice(0, 42)}`;
+}
+
+export function isSavedToolSkill(name: string): boolean {
+ return name.startsWith('tool-') && SKILL_NAME_RE.test(name);
+}