A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-browser.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-browser.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-browser.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 site icons (favicons) in tabs, address bar suggestions and the bookmarks panel 7249579 15 hours, 50 minutes ago History
omnibox.ts · 17.6 KB · 352 lines
1/**
2 * The address bar's suggestions: what to show under it as you type, and which site to complete inline.
3 *
4 * Everything here is local (open tabs, your saved links, the copy of your history, your kept copies). Search suggestions from the search site are
5 * fetched separately, and only for text that is not an address (see `remoteAllowed`), so a typed address never leaves the
6 * machine before you press Enter. Electron-free so it is unit-tested.
7 */
8
9export interface OmniItem {
10 url: string;
11 title: string;
12}
13export interface OmniTab extends OmniItem {
14 id: number;
15}
16
17export type OmniRow =
18 | { kind: "go"; url: string; title: string }
19 | { kind: "search"; text: string }
20 | { kind: "tab"; id: number; url: string; title: string }
21 | { kind: "bookmark"; url: string; title: string }
22 | { kind: "history"; url: string; title: string }
23 | { kind: "kept"; url: string; title: string; original: string }
24 | { kind: "suggest"; text: string }
25 | { kind: "ask"; text: string }
26 | { kind: "cmd"; name: string; line: string; description: string; arg?: string; preview?: string; ready: boolean; problem?: string; readOnly: boolean; destructive: boolean }
27 | { kind: "notice"; text: string; connect?: boolean };
28
29const LIMITS = { tab: 3, bookmark: 5, history: 5, kept: 3 };
30
31const hostOf = (u: string): string => {
32 try {
33 const x = new URL(u);
34 return /^https?:$/.test(x.protocol) ? x.hostname.replace(/^www\./, "").toLowerCase() : "";
35 } catch {
36 return "";
37 }
38};
39
40/** The site part of an address as it is typed: host and port, without "www." ("localhost:8899", "slashdot.org"). */
41const siteOf = (u: string): string => {
42 try {
43 const x = new URL(u);
44 return /^https?:$/.test(x.protocol) ? x.host.replace(/^www\./, "").toLowerCase() : "";
45 } catch {
46 return "";
47 }
48};
49
50const isLocalHost = (host: string) =>
51 host === "localhost" || host.endsWith(".local") || /^127(\.\d+){3}$/.test(host) || /^10(\.\d+){3}$/.test(host) || /^192\.168(\.\d+){2}$/.test(host) || /^172\.(1[6-9]|2\d|3[01])(\.\d+){2}$/.test(host);
52
53/** True when Enter would open this text as an address rather than search for it (the same rule as the address bar's). */
54export function looksLikeAddress(raw: string): boolean {
55 const u = raw.trim();
56 if (!u) return false;
57 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(u) || /^(about|file|data|view-source):/i.test(u)) return true;
58 const host = u.split(/[/?#]/)[0]?.split(":")[0] ?? "";
59 return !/\s/.test(u) && (isLocalHost(host) || /^[^\s.]+(\.[^\s.]+)+$/.test(host));
60}
61
62/**
63 * Whether the text may be sent for search suggestions: never an address or anything that looks like part of one (a path,
64 * a port, an @), never very short or very long text.
65 */
66export function remoteAllowed(raw: string): boolean {
67 const t = raw.trim();
68 if (t.length < 2 || t.length > 100) return false;
69 if (t.startsWith("/")) return false; // a command, never a search
70 if (looksLikeAddress(t)) return false;
71 if (!/\s/.test(t) && /[/:@\\]/.test(t)) return false;
72 return true;
73}
74
75/**
76 * The site to complete inline as you type: the first site you have saved, kept or open whose name starts with what you typed
77 * ("slash" → "slashdot.org"). Only while the text could be the start of a site name; the most used site wins.
78 */
79export function autofillHost(raw: string, urls: string[]): string | null {
80 const t = raw.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/^www\./, "");
81 if (t.length < 2 || /[\s/?#:@]/.test(t)) return null;
82 const count = new Map<string, number>();
83 for (const u of urls) {
84 const h = siteOf(u);
85 if (h && h.startsWith(t) && h !== t) count.set(h, (count.get(h) ?? 0) + 1);
86 }
87 let best: string | null = null;
88 let n = 0;
89 for (const [h, c] of count) if (c > n || (c === n && best && h.length < best.length)) (best = h), (n = c);
90 return best;
91}
92
93const norm = (u: string) => u.replace(/^https?:\/\/(www\.)?/i, "").replace(/\/$/, "").toLowerCase();
94
95/** Rank: the site name starts with the text, then a word of the title starts with it, then it is anywhere. */
96function score(words: string[], it: OmniItem): number {
97 const hay = `${it.title}\n${it.url}`.toLowerCase();
98 if (!words.every((w) => hay.includes(w))) return -1;
99 const first = words[0] as string;
100 const host = hostOf(it.url);
101 if (host.startsWith(first)) return 3;
102 if (new RegExp(`(^|[^a-z0-9])${first.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(it.title.toLowerCase())) return 2;
103 return 1;
104}
105
106function pick<T extends OmniItem>(words: string[], items: T[], limit: number, seen: Set<string>): T[] {
107 return items
108 .map((it, i) => ({ it, s: score(words, it), i }))
109 .filter((x) => x.s > 0)
110 .sort((a, b) => b.s - a.s || a.i - b.i)
111 .map((x) => x.it)
112 .filter((it) => {
113 const k = norm(it.url);
114 if (seen.has(k)) return false;
115 seen.add(k);
116 return true;
117 })
118 .slice(0, limit);
119}
120
121/**
122 * The rows under the address bar. The first row is what Enter does with the text as typed (or completed): open it, or search
123 * for it. Then open tabs (switch to them), saved links, pages from your history, kept copies; search suggestions are added by
124 * the caller when they arrive; the last row hands the text to the assistant. `history` comes most visited and most recent
125 * first (see history-copy.ts), and a page already shown as a tab or a saved link is not shown again.
126 */
127export function suggest(p: { text: string; tabs: OmniTab[]; activeTab?: number; bookmarks: OmniItem[]; history?: OmniItem[]; kept: Array<OmniItem & { id: string; view: string }>; askable?: boolean; autofill?: boolean }): { autofill: string | null; rows: OmniRow[] } {
128 const text = p.text.trim();
129 if (!text) return { autofill: null, rows: [] };
130 const history = p.history ?? [];
131 const autofill = p.autofill === false ? null : autofillHost(text, [...p.tabs.map((t) => t.url), ...p.bookmarks.map((b) => b.url), ...history.map((h) => h.url), ...p.kept.map((k) => k.url)]);
132 const rows: OmniRow[] = [];
133 if (autofill) {
134 // where to go: the scheme of an address you used on that site (a local site is usually plain http)
135 const used = [...p.tabs, ...p.bookmarks, ...history, ...p.kept].map((x) => x.url).find((u) => siteOf(u) === autofill) ?? "";
136 rows.push({ kind: "go", url: `${/^http:/i.test(used) ? "http" : "https"}://${autofill}/`, title: autofill });
137 }
138 else if (looksLikeAddress(text)) rows.push({ kind: "go", url: text, title: text });
139 else rows.push({ kind: "search", text });
140 const words = text.toLowerCase().split(/\s+/).filter(Boolean);
141 const seen = new Set<string>();
142 for (const t of pick(words, p.tabs.filter((t) => t.id !== p.activeTab && /^https?:/i.test(t.url)), LIMITS.tab, seen)) rows.push({ kind: "tab", id: t.id, url: t.url, title: t.title || t.url });
143 for (const b of pick(words, p.bookmarks, LIMITS.bookmark, seen)) rows.push({ kind: "bookmark", url: b.url, title: b.title || b.url });
144 for (const h of pick(words, history, LIMITS.history, seen)) rows.push({ kind: "history", url: h.url, title: h.title || h.url });
145 for (const k of pick(words, p.kept, LIMITS.kept, new Set())) rows.push({ kind: "kept", url: k.view, title: k.title || k.url, original: k.url });
146 if (p.askable !== false && !looksLikeAddress(text)) rows.push({ kind: "ask", text });
147 return { autofill, rows };
148}
149
150/** The search site's suggestions (OpenSearch suggestions JSON: ["text", ["one", "two", …]]), without the text itself. */
151export function parseSuggestions(body: string, text: string, max = 5): string[] {
152 let j: unknown;
153 try {
154 j = JSON.parse(body);
155 } catch {
156 return [];
157 }
158 const list = Array.isArray(j) && Array.isArray(j[1]) ? (j[1] as unknown[]) : [];
159 const t = text.trim().toLowerCase();
160 const out: string[] = [];
161 for (const s of list) {
162 if (typeof s !== "string") continue;
163 const v = s.trim().slice(0, 120);
164 if (!v || v.toLowerCase() === t || out.some((o) => o.toLowerCase() === v.toLowerCase())) continue;
165 out.push(v);
166 if (out.length >= max) break;
167 }
168 return out;
169}
170
171// ---- "/" commands: the tools of a connected service, typed ----------------------------------------------------------
172
173/** A tool as a command you can type: its argument is the rest of the line. */
174export interface CommandInfo {
175 name: string;
176 description: string;
177 /** The argument the rest of the line fills (the first required one, else the first), and its type. */
178 arg?: string;
179 argType?: string;
180 /** Whether that argument must be given. */
181 argRequired: boolean;
182 /** Other required arguments, which a single line cannot give. */
183 needs: string[];
184 readOnly: boolean;
185 /** Asks before it runs (the MCP default for a tool that changes things, unless the server says it does not destroy anything). */
186 destructive: boolean;
187}
188
189/** Short names the service's own box uses, for the same tools. */
190export const COMMAND_ALIASES: Record<string, string> = { note: "create_note", task: "create_task", search: "global_search", websearch: "web_search" };
191
192/** `fixed`: arguments the browser always sets itself (the entry's fixed arguments), so they are never asked for. */
193export function toCommand(t: { name: string; description?: string; inputSchema?: Record<string, unknown>; annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean } }, fixed: string[] = []): CommandInfo {
194 const all = t.inputSchema && typeof t.inputSchema.properties === "object" && t.inputSchema.properties ? (t.inputSchema.properties as Record<string, { type?: unknown }>) : {};
195 const props = Object.fromEntries(Object.entries(all).filter(([k]) => !fixed.includes(k)));
196 const required = (Array.isArray(t.inputSchema?.required) ? (t.inputSchema?.required as unknown[]).filter((x): x is string => typeof x === "string") : []).filter((r) => !fixed.includes(r));
197 const arg = required[0] ?? Object.keys(props)[0];
198 const type = arg ? props[arg]?.type : undefined;
199 const readOnly = t.annotations?.readOnlyHint === true;
200 return {
201 name: t.name,
202 description: (t.description ?? "").split(/\n/)[0]?.slice(0, 160) ?? "",
203 ...(arg ? { arg } : {}),
204 ...(typeof type === "string" ? { argType: type } : {}),
205 argRequired: !!arg && required.includes(arg),
206 needs: required.filter((r) => r !== arg),
207 readOnly,
208 destructive: !readOnly && t.annotations?.destructiveHint !== false,
209 };
210}
211
212/** "/create_task buy milk" → { name: "create_task", rest: "buy milk" }; aliases resolved. Null for anything else. */
213export function parseCommand(text: string): { name: string; typed: string; rest: string } | null {
214 const m = /^\/([A-Za-z_][\w-]*)?(?:\s+([\s\S]*))?$/.exec(text.trim());
215 if (!m) return null;
216 const typed = (m[1] ?? "").toLowerCase();
217 return { name: COMMAND_ALIASES[typed] ?? typed, typed, rest: (m[2] ?? "").trim() };
218}
219
220/** The arguments for a command line, or what is missing. */
221export function commandArgs(c: CommandInfo, rest: string): { args: Record<string, unknown> } | { problem: string } {
222 if (c.needs.length) return { problem: `needs ${c.needs.join(", ")} too, which a single line cannot give` };
223 if (!c.arg) return rest ? { problem: "takes nothing after its name" } : { args: {} };
224 if (!rest) return c.argRequired ? { problem: `type the ${c.arg.replace(/_/g, " ")}` } : { args: {} };
225 let v: unknown = rest;
226 if (c.argType === "integer" || c.argType === "number") {
227 v = Number(rest);
228 if (!Number.isFinite(v as number) || (c.argType === "integer" && !Number.isInteger(v))) return { problem: `${c.arg} must be a number` };
229 } else if (c.argType === "boolean") {
230 if (!/^(true|false|yes|no)$/i.test(rest)) return { problem: `${c.arg} must be yes or no` };
231 v = /^(true|yes)$/i.test(rest);
232 } else if (c.argType === "array") v = rest.split(",").map((x) => x.trim()).filter(Boolean);
233 return { args: { [c.arg]: v } };
234}
235
236/**
237 * The rows for a "/" line. While the name is being typed: the commands that start with it (then those that contain it). Once
238 * there is a space: that one command, with what will be sent.
239 */
240export function commandRows(text: string, cmds: CommandInfo[], max = 8): OmniRow[] {
241 const p = parseCommand(text);
242 if (!p) return [];
243 const row = (c: CommandInfo, line: string, rest: string | null): OmniRow => {
244 const a = rest === null ? null : commandArgs(c, rest);
245 const ready = !!a && "args" in a;
246 return {
247 kind: "cmd",
248 name: c.name,
249 line,
250 description: c.description,
251 ...(c.arg ? { arg: c.arg } : {}),
252 ...(a && "args" in a && c.arg && rest ? { preview: `${c.arg}: ${rest}` } : {}),
253 ready,
254 ...(a && "problem" in a ? { problem: a.problem } : {}),
255 readOnly: c.readOnly,
256 destructive: c.destructive,
257 };
258 };
259 const hasRest = /\s/.test(text.trim()) || text.endsWith(" ");
260 if (hasRest) {
261 const c = cmds.find((x) => x.name === p.name);
262 return c ? [row(c, text.trim(), p.rest)] : [];
263 }
264 const t = p.typed;
265 const aliasHits = Object.entries(COMMAND_ALIASES).filter(([a]) => t && a.startsWith(t)).map(([, n]) => n);
266 const starts = cmds.filter((c) => c.name.startsWith(t) || aliasHits.includes(c.name));
267 const contains = t ? cmds.filter((c) => !starts.includes(c) && c.name.includes(t)) : [];
268 return [...starts, ...contains].slice(0, max).map((c) => row(c, `/${c.name}`, c.argRequired ? null : ""));
269}
270
271/** What a command's answer means, in words: the browser writes the sentence (the server answers in data, in no language). */
272export interface CommandResult {
273 sentence: string;
274 /** The page of the thing made, on the service's own site (only an address on the service's own origin is kept). */
275 page?: string;
276 /** For lists and searches: the things found, with their pages when the service gives them. */
277 items?: Array<{ title: string; page?: string; group?: string }>;
278 /** The answer as data, laid out to read (or the text as it came). */
279 details: string;
280}
281
282const VERBS: Record<string, string> = { note: "Saved note", link: "Saved link", contact: "Added contact", organization: "Added organization", file: "Uploaded file" };
283const clip = (s: string, n = 90) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
284const titleOf = (o: Record<string, unknown>): string => {
285 for (const k of ["title", "name", "filename", "original_file_name", "subject", "content", "content_preview", "text", "url"]) {
286 const v = o[k];
287 if (typeof v === "string" && v.trim()) return v.trim().replace(/\s+/g, " ");
288 }
289 const fn = [o.first_name, o.last_name].filter((x) => typeof x === "string" && x).join(" ");
290 return fn;
291};
292
293/**
294 * Describe the answer to "/tool args". `origin` is the service's own origin: a "page" elsewhere is not shown as a link.
295 * Writes: "Saved note: buy milk (private)". Lists and searches: how many were found, and each one's title and page.
296 * Anything else: "Done" (or the answer itself, when it is short plain text).
297 */
298export function describeResult(tool: string, args: Record<string, unknown>, text: string, origin: string, readOnly: boolean): CommandResult {
299 let data: unknown;
300 try {
301 data = JSON.parse(text);
302 } catch {
303 data = undefined;
304 }
305 const details = data === undefined ? text : JSON.stringify(data, null, 2);
306 const pageOf = (o: unknown): string | undefined => {
307 if (!o || typeof o !== "object") return undefined;
308 const p = (o as Record<string, unknown>).page;
309 if (typeof p !== "string") return undefined;
310 try {
311 const u = new URL(p);
312 return u.origin === origin && /^https?:$/.test(u.protocol) ? u.href : undefined;
313 } catch {
314 return undefined;
315 }
316 };
317 const obj = data && typeof data === "object" && !Array.isArray(data) ? (data as Record<string, unknown>) : null;
318 // a list: the answer itself, or every list of things in it, each named by its group (a search answers in groups:
319 // projects, tasks, notes…)
320 const isList = (v: unknown): v is unknown[] => Array.isArray(v) && (v.length === 0 || v.some((x) => x && typeof x === "object"));
321 const groups: Array<[string | undefined, unknown[]]> = Array.isArray(data) ? [[undefined, data]] : obj ? Object.entries(obj).filter((e): e is [string, unknown[]] => isList(e[1])) : [];
322 // a single thing with an empty list in it (tags: []) is not a list; a search whose groups are all empty is
323 const listy = Array.isArray(data) || groups.some(([, l]) => l.length) || (!!obj && Object.values(obj).every((v) => Array.isArray(v) || typeof v === "number"));
324 if (readOnly && groups.length && listy) {
325 const named = groups.length > 1;
326 const rows = groups.flatMap(([g, list]) =>
327 list
328 .filter((x): x is Record<string, unknown> => !!x && typeof x === "object")
329 .map((x) => {
330 const page = pageOf(x);
331 return { title: clip(titleOf(x) || "(untitled)", 120), ...(page ? { page } : {}), ...(named && g ? { group: g.replace(/_/g, " ") } : {}) };
332 }),
333 );
334 const items = rows.slice(0, 50);
335 const what = typeof args.query === "string" ? ` for “${clip(args.query, 60)}”` : "";
336 const n = rows.length;
337 return { sentence: `/${tool}: ${n === 0 ? "nothing found" : n === 1 ? "1 found" : `${n} found`}${what}`, items, details };
338 }
339 const typed = Object.values(args).find((v): v is string => typeof v === "string" && !!v.trim());
340 const m = /^(create|add|upload|save)_(.+)$/.exec(tool);
341 if (!readOnly && m && obj) {
342 const noun = (m[2] as string).replace(/_/g, " ");
343 const verb = VERBS[m[2] as string] ?? `${m[1] === "upload" ? "Uploaded" : "Created"} ${noun}`;
344 const what = clip(typed?.replace(/\s+/g, " ") || titleOf(obj));
345 const page = pageOf(obj);
346 return { sentence: `${verb}${what ? `: ${what}` : ""}${obj.is_public === false ? " (private)" : ""}`, ...(page ? { page } : {}), details };
347 }
348 if (readOnly) return { sentence: `/${tool}: the answer is below`, details };
349 if (data === undefined && text.trim() && text.length <= 120) return { sentence: `/${tool}: ${text.trim().replace(/\s+/g, " ")}`, details };
350 const page = pageOf(obj);
351 return { sentence: `Done: /${tool}`, ...(page ? { page } : {}), details };
352}