@x-tech-laboratories/x-app 0.108.0 → 0.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ // An API endpoint a user points an app at, such as a model server's: whether it answers on the user's own machine or
2
+ // network, and its failures put in plain words that say what happened and what to do, with the raw detail kept for a
3
+ // Details disclosure. No message names a key, and the endpoint is named by host and port alone.
4
+ // ── Hosting ──────────────────────────────────────────────────────────────────
5
+ // The four numbers of an IPv4 address, or null for anything else.
6
+ function ipv4_parts(host) {
7
+ const parts = host.split(".");
8
+ if (parts.length !== 4 || !parts.every((part) => /^\d{1,3}$/.test(part)))
9
+ return null;
10
+ const numbers = parts.map(Number);
11
+ return numbers.every((number) => number <= 255) ? numbers : null;
12
+ }
13
+ // Loopback (127/8), private (10/8, 172.16/12, 192.168/16) or link-local (169.254/16).
14
+ function is_local_ipv4([first, second]) {
15
+ return first === 127 || first === 10 || (first === 172 && second >= 16 && second <= 31) || (first === 192 && second === 168) || (first === 169 && second === 254);
16
+ }
17
+ // The IPv4 address mapped into an IPv6 one, written either way or as URL writes it (::ffff:c0a8:102 for 192.168.1.2),
18
+ // or null for any other.
19
+ function mapped_ipv4(bare) {
20
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(bare);
21
+ if (mapped)
22
+ return ipv4_parts(mapped[1]);
23
+ const mapped_hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(bare);
24
+ if (!mapped_hex)
25
+ return null;
26
+ const [high, low] = [parseInt(mapped_hex[1], 16), parseInt(mapped_hex[2], 16)];
27
+ return [high >> 8, high & 255, low >> 8, low & 255];
28
+ }
29
+ // Loopback (::1), unique local (fc00::/7), link-local (fe80::/10) or an IPv4 address mapped into IPv6.
30
+ function is_local_ipv6(bare) {
31
+ if (bare === "::1")
32
+ return true;
33
+ const mapped = mapped_ipv4(bare);
34
+ if (mapped)
35
+ return is_local_ipv4(mapped);
36
+ return /^f[cd][0-9a-f]{0,2}:/.test(bare) || /^fe[89ab][0-9a-f]?:/.test(bare);
37
+ }
38
+ // An address's host, lower case and without the brackets around IPv6, or null when it is no whole address.
39
+ function host_of_address(address) {
40
+ try {
41
+ return new URL(address.trim()).hostname.replace(/^\[|\]$/g, "").toLowerCase();
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ // Whether the endpoint's host is loopback or a private-network address; an empty or unreadable endpoint is not.
48
+ export function is_local_endpoint(endpoint) {
49
+ const host = host_of_address(endpoint);
50
+ if (host === null)
51
+ return false;
52
+ if (host === "localhost" || host.endsWith(".localhost"))
53
+ return true;
54
+ const parts = ipv4_parts(host);
55
+ if (parts)
56
+ return is_local_ipv4(parts);
57
+ return host.includes(":") && is_local_ipv6(host);
58
+ }
59
+ // Whether an address is this machine's own: localhost, a name under .localhost, or a loopback address (127/8, ::1, or
60
+ // 127/8 mapped into IPv6); one on the local network is not.
61
+ export function is_loopback_address(address) {
62
+ const host = host_of_address(address);
63
+ if (host === null)
64
+ return false;
65
+ if (host === "localhost" || host.endsWith(".localhost") || host === "::1")
66
+ return true;
67
+ const parts = ipv4_parts(host) ?? (host.includes(":") ? mapped_ipv4(host) : null);
68
+ return parts !== null && parts[0] === 127;
69
+ }
70
+ // The endpoint's host and port, never its path, user or password; the default endpoint when it is empty.
71
+ export function host_of(endpoint, default_endpoint = "") {
72
+ try {
73
+ const url = new URL(endpoint.trim() || default_endpoint);
74
+ const port = url.port || (url.protocol === "https:" ? "443" : url.protocol === "http:" ? "80" : "");
75
+ return port ? `${url.hostname}:${port}` : url.hostname;
76
+ }
77
+ catch {
78
+ return "the address in its settings";
79
+ }
80
+ }
81
+ export class PlainFailure extends Error {
82
+ detail;
83
+ constructor(message, detail) {
84
+ super(message);
85
+ this.name = "PlainFailure";
86
+ this.detail = detail;
87
+ }
88
+ }
89
+ // A request the endpoint refused as larger than its model's context, with the tokens it counted when it said.
90
+ export class ContextOverflow extends Error {
91
+ prompt_tokens;
92
+ constructor(message, prompt_tokens = null) {
93
+ super(message);
94
+ this.name = "ContextOverflow";
95
+ this.prompt_tokens = prompt_tokens;
96
+ }
97
+ }
98
+ // Anything shaped like an API key, which some providers quote back in part, is hidden.
99
+ export function hide_keys(text) {
100
+ return text.replace(/\b(?:sk|pk|rk)[-_][A-Za-z0-9*_.-]{5,}[A-Za-z0-9*_-]/gi, "[hidden]");
101
+ }
102
+ function status_of(error) {
103
+ const status = error?.status;
104
+ return typeof status === "number" ? status : null;
105
+ }
106
+ function message_of(error) {
107
+ return error instanceof Error ? error.message : String(error);
108
+ }
109
+ function codes_of(error) {
110
+ const codes = [];
111
+ for (let at = error, depth = 0; at && typeof at === "object" && depth < 5; at = at.cause, depth += 1) {
112
+ const code = at.code;
113
+ if (typeof code === "string")
114
+ codes.push(code);
115
+ }
116
+ return codes;
117
+ }
118
+ const overflow_words = /context (?:length|size|window)|exceeds the available context|prompt is too long|too many tokens|maximum context|context_length_exceeded|input is too long/i;
119
+ // The endpoint refused a request as larger than its context, with the size it counted when it said; null for another failure.
120
+ export function overflow_of(error) {
121
+ if (error instanceof ContextOverflow)
122
+ return error;
123
+ const status = status_of(error);
124
+ const message = message_of(error);
125
+ if (status !== 413 && !(status === 400 && overflow_words.test(message)))
126
+ return null;
127
+ const counted = /request \((\d+) tokens\)|resulted in (\d+) tokens|too long: (\d+) tokens|prompt has (\d+) tokens/i.exec(message);
128
+ const tokens = counted ? Number(counted.slice(1).find(Boolean)) : null;
129
+ return new ContextOverflow(hide_keys(message), tokens);
130
+ }
131
+ const connection_codes = new Set(["ECONNREFUSED", "ENOTFOUND", "EHOSTUNREACH", "ENETUNREACH", "ECONNRESET", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"]);
132
+ // The SDKs' error classes keep the name "Error", so their class is told by its constructor too.
133
+ function is_named(error, name) {
134
+ const given = error;
135
+ return given?.name === name || given?.constructor?.name === name;
136
+ }
137
+ function is_timeout(error) {
138
+ return is_named(error, "APIConnectionTimeoutError") || codes_of(error).includes("ETIMEDOUT") || /^Request timed out\.?$/i.test(message_of(error));
139
+ }
140
+ function is_unreachable(error) {
141
+ return is_named(error, "APIConnectionError") || codes_of(error).some((code) => connection_codes.has(code)) || /^(Connection error\.|fetch failed)$/i.test(message_of(error));
142
+ }
143
+ // A failure reaching or asking the endpoint in plain words, with the raw text, its keys hidden, as its detail.
144
+ export function explain_endpoint_failure(error, where) {
145
+ const at = `The ${where.label ?? "service"} at ${host_of(where.endpoint, where.default_endpoint)}`;
146
+ const under = where.settings ? ` under ${where.settings}` : "";
147
+ const status = status_of(error);
148
+ const raw = hide_keys(message_of(error));
149
+ const codes = codes_of(error).filter((code) => !raw.includes(code));
150
+ const detail = codes.length > 0 ? `${raw} (${codes.join(", ")})` : raw;
151
+ const plain = (message) => ({ message, detail });
152
+ if (is_timeout(error))
153
+ return plain(`${at} did not answer in time. Check that its server is running and not overloaded${where.retry ? `, then ${where.retry}` : ""}.`);
154
+ if (status === null && is_unreachable(error))
155
+ return plain(`${at} cannot be reached. Check that its server is running and that its endpoint${under} is right.`);
156
+ if (overflow_of(error))
157
+ return plain(`The request was too large for the model's context.${where.overflow_advice ? ` ${where.overflow_advice}` : ""}`);
158
+ if (status === 401 || status === 403)
159
+ return plain(`${at} refused the API key. Check its ${where.key_name ?? "API key"}${under}.`);
160
+ if (status === 404 && /model/i.test(raw))
161
+ return plain(`${at} does not know the model “${where.model ?? ""}”. Check the model's name${under}.`);
162
+ if (status === 404)
163
+ return plain(`${at} has no ${where.serves ?? "API"} at that address. Check its endpoint${under}; it usually ends in /v1.`);
164
+ if (status === 429)
165
+ return plain(`${at} is limiting how often it is asked. ${where.rate_limit_advice ?? "Wait a minute and try again."}`);
166
+ if (status === null && where.keep_unknown)
167
+ return { message: raw };
168
+ return plain(`${at} could not answer.`);
169
+ }
@@ -0,0 +1,9 @@
1
+ export declare function unescape_html(text: string): string;
2
+ export interface PageText {
3
+ title: string;
4
+ text: string;
5
+ }
6
+ export interface HtmlTextOptions {
7
+ blank_lines?: boolean;
8
+ }
9
+ export declare function html_to_text(html: string, base?: string, options?: HtmlTextOptions): PageText;
@@ -0,0 +1,122 @@
1
+ // A web page's readable text: its title, then its words a block to a line, scripts, styles and drawings left out, and
2
+ // each link kept as plain text with its address after it. It needs nothing of Node or a page, so it runs anywhere.
3
+ // ── Entities ─────────────────────────────────────────────────────────────────
4
+ const named_entities = {
5
+ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", copy: "©", reg: "®", trade: "™", hellip: "…",
6
+ mdash: "—", ndash: "–", lsquo: "‘", rsquo: "’", ldquo: "“", rdquo: "”", laquo: "«", raquo: "»", bull: "•",
7
+ middot: "·", euro: "€", pound: "£", yen: "¥", cent: "¢", sect: "§", deg: "°", times: "×", divide: "÷", minus: "−",
8
+ };
9
+ // Character references such as &amp; and &#8217; as the characters they name.
10
+ export function unescape_html(text) {
11
+ return text.replace(/&(#[0-9]+|#[xX][0-9a-fA-F]+|[A-Za-z][A-Za-z0-9]*);?/g, (whole, name) => {
12
+ if (name.startsWith("#")) {
13
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
14
+ return code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff) ? String.fromCodePoint(code) : "�";
15
+ }
16
+ return named_entities[name] ?? named_entities[name.toLowerCase()] ?? whole;
17
+ });
18
+ }
19
+ // ── Text ─────────────────────────────────────────────────────────────────────
20
+ const block_tags = new Set(["address", "article", "aside", "blockquote", "br", "dd", "div", "dl", "dt", "figcaption", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "ol", "p", "pre", "section", "table", "td", "th", "tr", "ul"]);
21
+ const hidden_tags = new Set(["script", "style", "noscript", "svg", "template", "iframe", "object", "canvas"]);
22
+ // Read as they are up to their closing tag, since what is inside is not markup.
23
+ const raw_text_tags = new Set(["script", "style"]);
24
+ function attribute(attributes, name) {
25
+ const found = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(attributes);
26
+ return found ? unescape_html(found[1] ?? found[2] ?? found[3] ?? "") : null;
27
+ }
28
+ // A link's address made whole against the page's, when it leads to another web page.
29
+ function link_address(href, base) {
30
+ if (!href)
31
+ return null;
32
+ try {
33
+ const address = new URL(href, base || undefined);
34
+ return address.protocol === "http:" || address.protocol === "https:" ? address.href : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ // The page's title and readable text; `base` is the page's address, which makes its relative links whole.
41
+ export function html_to_text(html, base = "", options = {}) {
42
+ const parts = [];
43
+ const title_parts = [];
44
+ let hidden = 0;
45
+ let in_title = false;
46
+ // Each open link: its address, and where its text starts among the parts.
47
+ const links = [];
48
+ const data = (raw, unescape = true) => {
49
+ if (!raw || hidden)
50
+ return;
51
+ const text = unescape ? unescape_html(raw) : raw;
52
+ if (in_title)
53
+ title_parts.push(text);
54
+ else
55
+ parts.push(text);
56
+ };
57
+ const start_tag = (name, attributes) => {
58
+ if (hidden_tags.has(name))
59
+ hidden += 1;
60
+ if (hidden)
61
+ return;
62
+ if (name === "title")
63
+ in_title = true;
64
+ if (block_tags.has(name))
65
+ parts.push("\n");
66
+ if (name === "a")
67
+ links.push({ address: link_address(attribute(attributes, "href"), base), start: parts.length });
68
+ };
69
+ const end_tag = (name) => {
70
+ if (hidden_tags.has(name) && hidden) {
71
+ hidden -= 1;
72
+ return;
73
+ }
74
+ if (hidden)
75
+ return;
76
+ if (name === "title")
77
+ in_title = false;
78
+ if (name === "a") {
79
+ const link = links.pop();
80
+ const said = link ? parts.slice(link.start).join("").replace(/\s+/g, " ").trim() : "";
81
+ if (link?.address && said !== link.address)
82
+ parts.push(said ? ` (${link.address})` : link.address);
83
+ }
84
+ if (block_tags.has(name))
85
+ parts.push("\n");
86
+ };
87
+ const tag = /<(\/?)([A-Za-z][^\s/>]*)((?:[^>"']|"[^"]*"|'[^']*')*)>|<!--[\s\S]*?(?:-->|$)|<![^>]*>|<\?[^>]*>/g;
88
+ let position = 0;
89
+ for (let match = tag.exec(html); match !== null; match = tag.exec(html)) {
90
+ data(html.slice(position, match.index));
91
+ position = tag.lastIndex;
92
+ if (match[2] === undefined)
93
+ continue;
94
+ const name = match[2].toLowerCase();
95
+ const attributes = match[3] ?? "";
96
+ if (match[1]) {
97
+ end_tag(name);
98
+ continue;
99
+ }
100
+ start_tag(name, attributes);
101
+ if (attributes.trimEnd().endsWith("/"))
102
+ end_tag(name);
103
+ else if (raw_text_tags.has(name)) {
104
+ const close = new RegExp(`</${name}\\s*>`, "ig");
105
+ close.lastIndex = position;
106
+ const end = close.exec(html);
107
+ data(html.slice(position, end ? end.index : html.length), false);
108
+ if (end) {
109
+ end_tag(name);
110
+ position = close.lastIndex;
111
+ }
112
+ else
113
+ position = html.length;
114
+ tag.lastIndex = position;
115
+ }
116
+ }
117
+ data(html.slice(position));
118
+ const words = (text) => text.split(/\s+/).filter(Boolean).join(" ");
119
+ const title = words(title_parts.join(" "));
120
+ const lines = parts.join("").split(/\r\n|\r|\n/).map(words).filter(Boolean);
121
+ return { title: Array.from(title).slice(0, 500).join(""), text: lines.join(options.blank_lines ? "\n\n" : "\n") };
122
+ }
@@ -0,0 +1,23 @@
1
+ import type { JsonSchema } from "./api_spec.ts";
2
+ export type McpTransport = "http" | "stdio";
3
+ export interface McpServerTarget {
4
+ id: string;
5
+ name: string;
6
+ transport: McpTransport;
7
+ address?: string;
8
+ token?: string;
9
+ command?: string;
10
+ args?: string[];
11
+ variables?: string[];
12
+ }
13
+ export interface McpToolRecord {
14
+ name: string;
15
+ description: string;
16
+ read_only: boolean;
17
+ input_schema: JsonSchema;
18
+ }
19
+ export interface McpListing {
20
+ tools: McpToolRecord[];
21
+ instructions: string;
22
+ }
23
+ export declare function sends_outside(server: Pick<McpServerTarget, "transport" | "address">): boolean;
@@ -0,0 +1,10 @@
1
+ // The MCP servers a user adds, as a page and a server both see them: each server, reached over streamable HTTP or
2
+ // started as a local command over stdio, the tools it lists, and whether its tools stay on this machine. It needs
3
+ // nothing of Node or a page, so it runs anywhere; `server/mcp_client` reaches the servers.
4
+ import { is_loopback_address } from "./endpoints.js";
5
+ // ── Where it runs ────────────────────────────────────────────────────────────
6
+ // A server's tools stay on this machine only when it is a local command or answers on a loopback address
7
+ // (`endpoints` `is_loopback_address`).
8
+ export function sends_outside(server) {
9
+ return server.transport === "http" && !is_loopback_address(server.address ?? "");
10
+ }
@@ -0,0 +1,4 @@
1
+ export declare const repeat_window_chars = 1200;
2
+ export declare const repeat_check_chars = 200;
3
+ export declare function is_repeating(text: string): boolean;
4
+ export declare function repetition_watch(): (text: string) => boolean;
@@ -0,0 +1,26 @@
1
+ // Notices text going round in circles, such as a model's reply stuck in a loop: looping text packs far smaller than
2
+ // prose, code or data does. On fflate, so it runs in a page as on Node.
3
+ // ── Imports ──────────────────────────────────────────────────────────────────
4
+ import { deflateSync, strToU8 } from "fflate";
5
+ // ── Repetition ───────────────────────────────────────────────────────────────
6
+ export const repeat_window_chars = 1200;
7
+ // How much new text arrives between checks.
8
+ export const repeat_check_chars = 200;
9
+ const repeat_ratio = 0.2;
10
+ // Whether the last repeat_window_chars of the text pack to under a fifth of their size.
11
+ export function is_repeating(text) {
12
+ if (text.length < repeat_window_chars)
13
+ return false;
14
+ const tail = strToU8(text.slice(-repeat_window_chars));
15
+ return deflateSync(tail).length / tail.length < repeat_ratio;
16
+ }
17
+ // Says, as text streams in, whether it has started repeating; checks every repeat_check_chars.
18
+ export function repetition_watch() {
19
+ let checked = 0;
20
+ return (text) => {
21
+ if (text.length - checked < repeat_check_chars)
22
+ return false;
23
+ checked = text.length;
24
+ return is_repeating(text);
25
+ };
26
+ }
@@ -0,0 +1,13 @@
1
+ import { type LookupFunction } from "node:net";
2
+ export declare function is_public_address(address: string): boolean;
3
+ export type Resolver = (hostname: string) => Promise<string[]>;
4
+ export interface GuardOptions {
5
+ resolve?: Resolver;
6
+ allowed_ports?: ReadonlySet<number>;
7
+ ports_hint?: string;
8
+ allow_address?: (address: string) => boolean;
9
+ }
10
+ export declare function ports_of(setting: unknown): Set<number>;
11
+ export declare function checked_web_address(url: string, options?: GuardOptions): URL;
12
+ export declare function public_addresses(hostname: string, options?: GuardOptions): Promise<string[]>;
13
+ export declare function guarded_lookup(options?: GuardOptions): LookupFunction;
@@ -0,0 +1,129 @@
1
+ // Which web addresses a server may fetch for its user or a program: plain http or https, no credentials in the
2
+ // address, the usual port unless the app allows another, and a host that resolves only to public addresses, checked
3
+ // again as the connection is made, so a name that changes its answer cannot lead to this computer or its network.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { lookup } from "node:dns/promises";
6
+ import { BlockList, isIP } from "node:net";
7
+ // ── Public addresses ─────────────────────────────────────────────────────────
8
+ const non_public_ipv4 = new BlockList();
9
+ for (const [network, prefix] of [
10
+ ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12],
11
+ ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.88.99.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15],
12
+ ["198.51.100.0", 24], ["203.0.113.0", 24], ["224.0.0.0", 4], ["240.0.0.0", 4],
13
+ ]) {
14
+ non_public_ipv4.addSubnet(network, prefix, "ipv4");
15
+ }
16
+ const non_public_ipv6 = new BlockList();
17
+ for (const [network, prefix] of [
18
+ ["64:ff9b:1::", 48], ["100::", 64], ["2001::", 23], ["2001:db8::", 32], ["2002::", 16], ["3fff::", 20], ["5f00::", 16],
19
+ ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8],
20
+ ]) {
21
+ non_public_ipv6.addSubnet(network, prefix, "ipv6");
22
+ }
23
+ // An IPv6 address as its sixteen bytes, or null when it is not one.
24
+ function ipv6_bytes(address) {
25
+ if (isIP(address) !== 6)
26
+ return null;
27
+ let text = address.split("%")[0].toLowerCase();
28
+ const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
29
+ if (dotted) {
30
+ const quad = dotted[1].split(".").map(Number);
31
+ text = `${text.slice(0, dotted.index)}${((quad[0] << 8) | quad[1]).toString(16)}:${((quad[2] << 8) | quad[3]).toString(16)}`;
32
+ }
33
+ const [head, tail] = text.split("::");
34
+ const groups_of = (part) => (part ? part.split(":").filter(Boolean) : []);
35
+ const front = groups_of(head);
36
+ const back = groups_of(tail);
37
+ const groups = tail === undefined ? front : [...front, ...Array(8 - front.length - back.length).fill("0"), ...back];
38
+ if (groups.length !== 8)
39
+ return null;
40
+ return groups.flatMap((group) => {
41
+ const value = parseInt(group, 16);
42
+ return [value >> 8, value & 255];
43
+ });
44
+ }
45
+ // Whether an address is reachable on the public internet; an IPv4 address carried inside IPv6, mapped or through the
46
+ // NAT64 prefix, is judged as itself.
47
+ export function is_public_address(address) {
48
+ const family = isIP(address);
49
+ if (family === 4)
50
+ return !non_public_ipv4.check(address, "ipv4");
51
+ const bytes = ipv6_bytes(address);
52
+ if (!bytes)
53
+ return false;
54
+ const embedded = bytes.slice(12).join(".");
55
+ const zero_until = (end) => bytes.slice(0, end).every((byte) => byte === 0);
56
+ // ::ffff:a.b.c.d, mapped.
57
+ if (zero_until(10) && bytes[10] === 255 && bytes[11] === 255)
58
+ return is_public_address(embedded);
59
+ // ::a.b.c.d and every address under ::/96, :: and ::1 among them.
60
+ if (zero_until(12))
61
+ return false;
62
+ // 64:ff9b::a.b.c.d, the NAT64 prefix.
63
+ if (bytes[0] === 0 && bytes[1] === 0x64 && bytes[2] === 0xff && bytes[3] === 0x9b && bytes.slice(4, 12).every((byte) => byte === 0))
64
+ return is_public_address(embedded);
65
+ return !non_public_ipv6.check(address.split("%")[0], "ipv6");
66
+ }
67
+ async function system_resolver(hostname) {
68
+ return (await lookup(hostname, { all: true, verbatim: true })).map((found) => found.address);
69
+ }
70
+ // The ports a setting such as "8080, 8443" lists; anything else in it is left out.
71
+ export function ports_of(setting) {
72
+ return new Set(String(setting ?? "")
73
+ .split(/[\s,;]+/)
74
+ .map(Number)
75
+ .filter((port) => Number.isInteger(port) && port > 0 && port < 65536));
76
+ }
77
+ // The address as a URL when its form may be fetched: http or https, no name or password, and its port the usual one
78
+ // or one the app allows, without its #fragment. Throws a plain error saying why not.
79
+ export function checked_web_address(url, options = {}) {
80
+ let parsed;
81
+ try {
82
+ parsed = new URL(String(url).trim());
83
+ }
84
+ catch {
85
+ throw new Error("Give a whole web address, starting with http:// or https://.");
86
+ }
87
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
88
+ throw new Error(`Only http and https addresses can be read, not ${parsed.protocol.replace(/:$/, "")}.`);
89
+ if (!parsed.hostname)
90
+ throw new Error("Give a whole web address, with its host.");
91
+ if (parsed.username || parsed.password)
92
+ throw new Error("An address with a name or password in it is not read.");
93
+ if (parsed.port && !options.allowed_ports?.has(Number(parsed.port)))
94
+ throw new Error(`Port ${parsed.port} is not allowed; only 80 and 443 are${options.ports_hint ? `, ${options.ports_hint}` : ""}.`);
95
+ parsed.hash = "";
96
+ return parsed;
97
+ }
98
+ // The host's addresses, when every one of them is public (or a test lets it through); throws a plain error otherwise.
99
+ export async function public_addresses(hostname, options = {}) {
100
+ const host = hostname.replace(/^\[|\]$/g, "").replace(/\.+$/, "");
101
+ if (!host)
102
+ throw new Error("Give a whole web address, with its host.");
103
+ let addresses;
104
+ try {
105
+ addresses = isIP(host) ? [host] : await (options.resolve ?? system_resolver)(host);
106
+ }
107
+ catch {
108
+ throw new Error(`The host ${host} could not be found.`);
109
+ }
110
+ if (addresses.length === 0)
111
+ throw new Error(`The host ${host} could not be found.`);
112
+ const refused = addresses.find((address) => !is_public_address(address) && options.allow_address?.(address) !== true);
113
+ if (refused !== undefined)
114
+ throw new Error(`${host} is not a public address (it leads to ${refused}), so it is not read: only pages on the public web are.`);
115
+ return addresses;
116
+ }
117
+ // The lookup a connection is made with, as node:http's `lookup` option, so it reaches only the addresses just checked,
118
+ // however the name answers.
119
+ export function guarded_lookup(options = {}) {
120
+ const guarded = (hostname, given, callback) => {
121
+ public_addresses(hostname, options).then((addresses) => {
122
+ if (typeof given === "object" && given?.all)
123
+ callback(null, addresses.map((address) => ({ address, family: isIP(address) })));
124
+ else
125
+ callback(null, addresses[0], isIP(addresses[0]));
126
+ }, (error) => callback(error));
127
+ };
128
+ return guarded;
129
+ }
@@ -35,5 +35,15 @@ export declare class HelpRequested extends Error {
35
35
  export declare const loopback_hosts: string[];
36
36
  export declare function is_loopback(host: string): boolean;
37
37
  export declare function read_secret_file(path: string): string;
38
+ export declare const max_secret_chars = 1024;
39
+ export type SecretReader = (command: string[]) => Promise<string>;
40
+ export interface SecretCommandWords {
41
+ what?: string;
42
+ secret?: string;
43
+ }
44
+ export declare function command_words(line: string, words_for?: SecretCommandWords): string[];
45
+ export declare function secret_command_reader(words_for?: SecretCommandWords): SecretReader;
46
+ export declare const read_secret_command: SecretReader;
47
+ export declare function secret_from_command(command_line: string, read?: SecretReader, words_for?: SecretCommandWords): Promise<string>;
38
48
  export declare function read_server_config<Name extends string = never>(spec: ServerConfigSpec<Name>): ServerConfig<Name>;
39
49
  export {};
@@ -1,7 +1,9 @@
1
1
  // A server's settings from the command line and the environment: the address and port, the web folder, the app's own
2
2
  // options, and the secret browsers sign in with, read from a file or a variable. Without a secret the server may only
3
- // listen on this machine.
3
+ // listen on this machine. A secret may also be printed by a command, such as a password manager's, so a setting names
4
+ // the program and never holds the secret.
4
5
  // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { execFile } from "node:child_process";
5
7
  import { readFileSync } from "node:fs";
6
8
  import { parseArgs } from "node:util";
7
9
  export class HelpRequested extends Error {
@@ -30,6 +32,78 @@ export function read_secret_file(path) {
30
32
  throw new Error(`The secret at ${path} is empty`);
31
33
  return secret.trim();
32
34
  }
35
+ // ── Secret commands ──────────────────────────────────────────────────────────
36
+ const secret_timeout_ms = 10_000;
37
+ export const max_secret_chars = 1024;
38
+ // A command line split into words as a shell would, with single and double quotes and backslashes, but nothing expanded.
39
+ export function command_words(line, words_for = {}) {
40
+ const words = [];
41
+ let word = "";
42
+ let has_word = false;
43
+ let quote = null;
44
+ for (let index = 0; index < line.length; index += 1) {
45
+ const char = line[index];
46
+ if (quote === "'") {
47
+ if (char === "'")
48
+ quote = null;
49
+ else
50
+ word += char;
51
+ }
52
+ else if (char === "\\" && index + 1 < line.length && (quote === null || /["\\$`]/.test(line[index + 1]))) {
53
+ word += line[(index += 1)];
54
+ has_word = true;
55
+ }
56
+ else if (quote === '"') {
57
+ if (char === '"')
58
+ quote = null;
59
+ else
60
+ word += char;
61
+ }
62
+ else if (char === "'" || char === '"') {
63
+ quote = char;
64
+ has_word = true;
65
+ }
66
+ else if (/\s/.test(char)) {
67
+ if (has_word)
68
+ words.push(word);
69
+ word = "";
70
+ has_word = false;
71
+ }
72
+ else {
73
+ word += char;
74
+ has_word = true;
75
+ }
76
+ }
77
+ if (quote)
78
+ throw new Error(`The ${words_for.what ?? "secret command"} has a quote that is never closed.`);
79
+ if (has_word)
80
+ words.push(word);
81
+ return words;
82
+ }
83
+ // A reader of the first line a program prints, run without a shell; a failure, an empty line or an overlong one is
84
+ // refused in words that never hold what it printed.
85
+ export function secret_command_reader(words_for = {}) {
86
+ const what = words_for.what ?? "secret command";
87
+ const secret_word = words_for.secret ?? "secret";
88
+ return ([program, ...args]) => new Promise((resolve, reject) => {
89
+ if (!program)
90
+ return reject(new Error(`The ${what} is empty.`));
91
+ execFile(program, args, { timeout: secret_timeout_ms, maxBuffer: max_secret_chars * 4, encoding: "utf8" }, (error, stdout) => {
92
+ if (error)
93
+ return reject(new Error(`The ${what} ${program} failed${typeof error.code === "number" ? ` with exit code ${error.code}` : ""}.`));
94
+ const secret = stdout.split("\n")[0].replace(/\r$/, "");
95
+ if (!secret || secret.length > max_secret_chars)
96
+ return reject(new Error(`The ${what} ${program} printed no usable ${secret_word}.`));
97
+ resolve(secret);
98
+ });
99
+ });
100
+ }
101
+ export const read_secret_command = secret_command_reader();
102
+ // The secret a setting's command line prints, or "" when no command is set.
103
+ export async function secret_from_command(command_line, read = read_secret_command, words_for = {}) {
104
+ const words = command_words(command_line.trim(), words_for);
105
+ return words.length === 0 ? "" : read(words);
106
+ }
33
107
  // ── Reading ──────────────────────────────────────────────────────────────────
34
108
  function capitals(name) {
35
109
  return name.replaceAll("-", "_").toUpperCase();
@@ -0,0 +1,29 @@
1
+ import { type CallToolResult } from "@modelcontextprotocol/client";
2
+ import type { McpListing, McpServerTarget } from "../mcp_servers.ts";
3
+ export type { McpListing, McpServerTarget, McpToolRecord, McpTransport } from "../mcp_servers.ts";
4
+ export interface McpLimits {
5
+ connect_ms: number;
6
+ call_ms: number;
7
+ idle_ms: number;
8
+ max_tools: number;
9
+ max_description: number;
10
+ max_instructions: number;
11
+ stderr_chars: number;
12
+ }
13
+ export declare const default_mcp_limits: McpLimits;
14
+ export interface McpClientOptions {
15
+ name: string;
16
+ version: string;
17
+ limits?: Partial<McpLimits>;
18
+ }
19
+ export interface McpClient {
20
+ limits: McpLimits;
21
+ list_tools(server: McpServerTarget): Promise<McpListing>;
22
+ call_tool(server: McpServerTarget, name: string, args: Record<string, unknown>, signal: AbortSignal): Promise<string>;
23
+ forget(server_id?: string): Promise<void>;
24
+ open_connections(): number;
25
+ }
26
+ export declare function result_text(result: CallToolResult): string;
27
+ export declare function instructions_of(said: string | undefined, max?: number): string;
28
+ export declare function passed_variables(names: string[], from?: Record<string, string | undefined>): Record<string, string>;
29
+ export declare function create_mcp_client(options: McpClientOptions): McpClient;