@x-tech-laboratories/x-app 0.107.0 → 0.109.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.
@@ -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,48 @@
1
+ import { type CallToolResult } from "@modelcontextprotocol/client";
2
+ import type { JsonSchema } from "../api_spec.ts";
3
+ export interface McpServerTarget {
4
+ id: string;
5
+ name: string;
6
+ transport: "http" | "stdio";
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 interface McpLimits {
24
+ connect_ms: number;
25
+ call_ms: number;
26
+ idle_ms: number;
27
+ max_tools: number;
28
+ max_description: number;
29
+ max_instructions: number;
30
+ stderr_chars: number;
31
+ }
32
+ export declare const default_mcp_limits: McpLimits;
33
+ export interface McpClientOptions {
34
+ name: string;
35
+ version: string;
36
+ limits?: Partial<McpLimits>;
37
+ }
38
+ export interface McpClient {
39
+ limits: McpLimits;
40
+ list_tools(server: McpServerTarget): Promise<McpListing>;
41
+ call_tool(server: McpServerTarget, name: string, args: Record<string, unknown>, signal: AbortSignal): Promise<string>;
42
+ forget(server_id?: string): Promise<void>;
43
+ open_connections(): number;
44
+ }
45
+ export declare function result_text(result: CallToolResult): string;
46
+ export declare function instructions_of(said: string | undefined, max?: number): string;
47
+ export declare function passed_variables(names: string[], from?: Record<string, string | undefined>): Record<string, string>;
48
+ export declare function create_mcp_client(options: McpClientOptions): McpClient;
@@ -0,0 +1,187 @@
1
+ // A client of the MCP servers a user adds, on the official SDK's client: streamable HTTP with an optional bearer token,
2
+ // or a local command started without a shell, with only the SDK's safe variables (HOME, LOGNAME, PATH, SHELL, TERM,
3
+ // USER) and those the user names. One connection per server is kept while used and closed when idle; a server that
4
+ // exits, hangs or answers badly gives a plain error and never takes the app down.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
7
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
8
+ export const default_mcp_limits = {
9
+ connect_ms: 20_000,
10
+ call_ms: 60_000,
11
+ idle_ms: 120_000,
12
+ max_tools: 200,
13
+ max_description: 2000,
14
+ max_instructions: 2000,
15
+ stderr_chars: 600,
16
+ };
17
+ // ── Results ──────────────────────────────────────────────────────────────────
18
+ // A tool's answer as text: its text parts, then what else it gave said in words.
19
+ export function result_text(result) {
20
+ const parts = [];
21
+ for (const part of result.content ?? []) {
22
+ if (part.type === "text")
23
+ parts.push(part.text);
24
+ else if (part.type === "resource" && "text" in part.resource && typeof part.resource.text === "string")
25
+ parts.push(part.resource.text);
26
+ else if (part.type === "resource_link")
27
+ parts.push(`[${part.name}: ${part.uri}]`);
28
+ else
29
+ parts.push(`[${part.type}]`);
30
+ }
31
+ if (parts.length === 0 && result.structuredContent !== undefined)
32
+ parts.push(JSON.stringify(result.structuredContent));
33
+ return parts.join("\n") || "(No answer.)";
34
+ }
35
+ // What the server said of how to use it when it was reached, cut to the limit.
36
+ export function instructions_of(said, max = default_mcp_limits.max_instructions) {
37
+ const text = (said ?? "").trim();
38
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
39
+ }
40
+ // The variables passed to a local server: only those the user named, from the app's own environment; the SDK adds its safe ones.
41
+ export function passed_variables(names, from = process.env) {
42
+ return Object.fromEntries(names.filter((name) => typeof from[name] === "string").map((name) => [name, from[name]]));
43
+ }
44
+ function key_of(server) {
45
+ return JSON.stringify([server.transport, server.address, server.token, server.command, server.args, server.variables]);
46
+ }
47
+ function where(server) {
48
+ if (server.transport === "stdio")
49
+ return `the command ${server.command}`;
50
+ try {
51
+ return new URL(server.address ?? "").host;
52
+ }
53
+ catch {
54
+ return server.address ?? "";
55
+ }
56
+ }
57
+ function within(work, ms, what) {
58
+ let timer;
59
+ const late = new Promise((_, reject) => (timer = setTimeout(() => reject(new Error(`${what} did not answer within ${ms / 1000} seconds.`)), ms)));
60
+ return Promise.race([work, late]).finally(() => clearTimeout(timer));
61
+ }
62
+ // A client keeping its own connections, one per server id.
63
+ export function create_mcp_client(options) {
64
+ const limits = { ...default_mcp_limits, ...options.limits };
65
+ const connections = new Map();
66
+ // What a server's failure means, in plain words, naming the server and never its token.
67
+ const plain = (server, error, connection) => {
68
+ const raw = error instanceof Error ? error.message : String(error);
69
+ const said = connection?.stderr.trim() ? ` It wrote: ${connection.stderr.trim().slice(-limits.stderr_chars)}` : "";
70
+ const message = server.token ? raw.split(server.token).join("[hidden]") : raw;
71
+ if (/ENOENT/.test(message))
72
+ return new Error(`${server.name} could not be started: ${server.command} was not found.`);
73
+ if (/EACCES/.test(message))
74
+ return new Error(`${server.name} could not be started: ${server.command} may not be run.`);
75
+ if (/ECONNREFUSED|fetch failed|ENOTFOUND|EAI_AGAIN/.test(message))
76
+ return new Error(`${server.name} could not be reached at ${where(server)}.`);
77
+ if (/\b401\b|Unauthorized/i.test(message))
78
+ return new Error(`${server.name} refused the token.`);
79
+ if (/closed|EPIPE/i.test(message))
80
+ return new Error(`${server.name} stopped: it exited or closed its connection.${said}`);
81
+ return new Error(`${server.name} failed: ${message}${said}`);
82
+ };
83
+ const close = async (server_id) => {
84
+ const connection = connections.get(server_id);
85
+ if (!connection)
86
+ return;
87
+ connections.delete(server_id);
88
+ connection.closed = true;
89
+ clearTimeout(connection.idle);
90
+ await connection.client.close().catch(() => undefined);
91
+ };
92
+ const keep_alive = (server_id, connection) => {
93
+ clearTimeout(connection.idle);
94
+ connection.idle = setTimeout(() => void close(server_id), limits.idle_ms);
95
+ connection.idle.unref?.();
96
+ };
97
+ const connect = async (server) => {
98
+ const key = key_of(server);
99
+ const existing = connections.get(server.id);
100
+ if (existing && existing.key === key && !existing.closed)
101
+ return existing;
102
+ if (existing)
103
+ await close(server.id);
104
+ const client = new Client({ name: options.name, version: options.version });
105
+ const connection = { key, client, closed: false, stderr: "" };
106
+ let transport;
107
+ if (server.transport === "stdio") {
108
+ const stdio = new StdioClientTransport({ command: server.command ?? "", args: server.args ?? [], env: passed_variables(server.variables ?? []), stderr: "pipe" });
109
+ stdio.stderr?.on("data", (chunk) => (connection.stderr = (connection.stderr + chunk.toString("utf8")).slice(-limits.stderr_chars)));
110
+ transport = stdio;
111
+ }
112
+ else {
113
+ const token = server.token;
114
+ transport = new StreamableHTTPClientTransport(new URL(server.address ?? ""), token ? { authProvider: { token: async () => token } } : {});
115
+ }
116
+ // A failing transport ends the connection here, never the process.
117
+ client.onerror = () => undefined;
118
+ client.onclose = () => {
119
+ connection.closed = true;
120
+ if (connections.get(server.id) === connection)
121
+ connections.delete(server.id);
122
+ };
123
+ try {
124
+ await within(client.connect(transport), limits.connect_ms, server.name);
125
+ }
126
+ catch (error) {
127
+ connection.closed = true;
128
+ await client.close().catch(() => undefined);
129
+ throw plain(server, error, connection);
130
+ }
131
+ connections.set(server.id, connection);
132
+ keep_alive(server.id, connection);
133
+ return connection;
134
+ };
135
+ const list_tools = async (server) => {
136
+ const connection = await connect(server);
137
+ try {
138
+ const tools = [];
139
+ let cursor;
140
+ for (let page = 0; page < 10 && tools.length < limits.max_tools; page += 1) {
141
+ const answer = await connection.client.listTools(cursor ? { cursor } : undefined, { timeout: limits.connect_ms });
142
+ for (const tool of answer.tools) {
143
+ const description = String(tool.description ?? tool.title ?? "");
144
+ tools.push({
145
+ name: tool.name,
146
+ description: description.length > limits.max_description ? `${description.slice(0, limits.max_description - 1)}…` : description,
147
+ read_only: tool.annotations?.readOnlyHint === true,
148
+ input_schema: tool.inputSchema && typeof tool.inputSchema === "object" ? tool.inputSchema : { type: "object", properties: {} },
149
+ });
150
+ }
151
+ cursor = answer.nextCursor;
152
+ if (!cursor)
153
+ break;
154
+ }
155
+ keep_alive(server.id, connection);
156
+ return { tools: tools.slice(0, limits.max_tools), instructions: instructions_of(connection.client.getInstructions(), limits.max_instructions) };
157
+ }
158
+ catch (error) {
159
+ await close(server.id);
160
+ throw plain(server, error, connection);
161
+ }
162
+ };
163
+ const call_tool = async (server, name, args, signal) => {
164
+ const connection = await connect(server);
165
+ let result;
166
+ try {
167
+ result = (await connection.client.callTool({ name, arguments: args }, { signal, timeout: limits.call_ms }));
168
+ }
169
+ catch (error) {
170
+ // A call that hung or broke leaves the server in doubt, so the next call starts afresh.
171
+ await close(server.id);
172
+ if (signal.aborted)
173
+ throw new Error("Stopped.");
174
+ throw plain(server, error, connection);
175
+ }
176
+ keep_alive(server.id, connection);
177
+ const text = result_text(result);
178
+ if (result.isError)
179
+ throw new Error(text);
180
+ return text;
181
+ };
182
+ const forget = async (server_id) => {
183
+ const ids = server_id === undefined ? [...connections.keys()] : [server_id];
184
+ await Promise.all(ids.map(close));
185
+ };
186
+ return { limits, list_tools, call_tool, forget, open_connections: () => connections.size };
187
+ }
@@ -0,0 +1,10 @@
1
+ export declare function text_hash(text: string): string;
2
+ export declare const chunk_chars = 1200;
3
+ export declare const overlap_chars = 200;
4
+ export declare function chunk_text(text: string, size?: number, overlap?: number): string[];
5
+ export declare function unit(vector: number[]): Float32Array;
6
+ export declare function to_blob(vector: Float32Array): Uint8Array;
7
+ export declare function from_blob(blob: Uint8Array): Float32Array;
8
+ export declare function dot(first: Float32Array, second: Float32Array): number;
9
+ export declare function fts_query(text: string, joiner?: "AND" | "OR"): string;
10
+ export declare function fuse_ranks(lists: string[][], k?: number): Map<string, number>;
@@ -0,0 +1,72 @@
1
+ // What a local search index does to text: a hash to see whether it changed, pieces cut for embedding, vectors as
2
+ // stored blobs and their dot product, the search words as an SQLite FTS5 query, and rankings fused into one.
3
+ // ── Hash ─────────────────────────────────────────────────────────────────────
4
+ // A 53-bit hash of the text (cyrb53) as hex, to tell changed text from unchanged; not for security.
5
+ export function text_hash(text) {
6
+ let first = 0xdeadbeef;
7
+ let second = 0x41c6ce57;
8
+ for (let at = 0; at < text.length; at++) {
9
+ const code = text.charCodeAt(at);
10
+ first = Math.imul(first ^ code, 2654435761);
11
+ second = Math.imul(second ^ code, 1597334677);
12
+ }
13
+ first = Math.imul(first ^ (first >>> 16), 2246822507) ^ Math.imul(second ^ (second >>> 13), 3266489909);
14
+ second = Math.imul(second ^ (second >>> 16), 2246822507) ^ Math.imul(first ^ (first >>> 13), 3266489909);
15
+ return (4294967296 * (2097151 & second) + (first >>> 0)).toString(16);
16
+ }
17
+ // ── Chunks ───────────────────────────────────────────────────────────────────
18
+ export const chunk_chars = 1200;
19
+ export const overlap_chars = 200;
20
+ // The text in pieces of at most chunk_chars, each starting overlap_chars before the last ended, cut at a space where
21
+ // one is near, so a long text is embedded whole and a sentence across a cut is in both pieces.
22
+ export function chunk_text(text, size = chunk_chars, overlap = overlap_chars) {
23
+ const flat = text.trim();
24
+ if (flat.length <= size)
25
+ return flat ? [flat] : [];
26
+ const chunks = [];
27
+ let start = 0;
28
+ while (start < flat.length) {
29
+ let end = Math.min(flat.length, start + size);
30
+ if (end < flat.length) {
31
+ const space = flat.lastIndexOf(" ", end);
32
+ if (space > start + size / 2)
33
+ end = space;
34
+ }
35
+ chunks.push(flat.slice(start, end).trim());
36
+ if (end >= flat.length)
37
+ break;
38
+ start = Math.max(end - overlap, start + 1);
39
+ }
40
+ return chunks.filter(Boolean);
41
+ }
42
+ // ── Vectors ──────────────────────────────────────────────────────────────────
43
+ // A vector scaled to length one, so the cosine of two is their dot product.
44
+ export function unit(vector) {
45
+ const length = Math.hypot(...vector) || 1;
46
+ return Float32Array.from(vector, (value) => value / length);
47
+ }
48
+ export function to_blob(vector) {
49
+ return new Uint8Array(vector.buffer.slice(vector.byteOffset, vector.byteOffset + vector.byteLength));
50
+ }
51
+ export function from_blob(blob) {
52
+ return new Float32Array(blob.buffer.slice(blob.byteOffset, blob.byteOffset + blob.byteLength));
53
+ }
54
+ export function dot(first, second) {
55
+ let sum = 0;
56
+ for (let at = 0; at < Math.min(first.length, second.length); at++)
57
+ sum += first[at] * second[at];
58
+ return sum;
59
+ }
60
+ // ── Queries ──────────────────────────────────────────────────────────────────
61
+ // The words typed as an FTS5 query, each a quoted prefix so no word is read as an operator; joined by AND, or OR.
62
+ export function fts_query(text, joiner = "AND") {
63
+ const words = text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
64
+ return words.map((word) => `"${word}"*`).join(` ${joiner} `);
65
+ }
66
+ // Reciprocal rank fusion: each list adds 1 / (k + rank) for every key it ranks, best first.
67
+ export function fuse_ranks(lists, k = 60) {
68
+ const scores = new Map();
69
+ for (const list of lists)
70
+ list.forEach((key, index) => scores.set(key, (scores.get(key) ?? 0) + 1 / (k + index + 1)));
71
+ return scores;
72
+ }
@@ -0,0 +1,5 @@
1
+ export declare const untrusted_open = "<untrusted-data>";
2
+ export declare const untrusted_close = "</untrusted-data>";
3
+ export declare const redacted_instruction = "[instruction removed]";
4
+ export declare function remove_instructions(text: string): string;
5
+ export declare function untrusted_block(text: string): string;
@@ -0,0 +1,24 @@
1
+ // Text anyone could have written, such as an item's title from another app or a page fetched from the web, fenced so a
2
+ // model reads it as data and never as orders.
3
+ // ── Fence ────────────────────────────────────────────────────────────────────
4
+ export const untrusted_open = "<untrusted-data>";
5
+ export const untrusted_close = "</untrusted-data>";
6
+ export const redacted_instruction = "[instruction removed]";
7
+ const fence_tag = /<\s*\/?\s*untrusted-data\s*>/gi;
8
+ // Sentences that give orders to whoever reads them; a small model obeys these even inside a fence.
9
+ const injection_patterns = new RegExp([
10
+ String.raw `\b(ignore|disregard|forget|override)\b[^.!?\n]{0,40}\b(instructions?|prompts?|rules|directions)\b`,
11
+ String.raw `\b(note|message|instructions?)\s+(to|for)\s+(ai|llms?|language models?|assistants?|chatbots?|the model)\b`,
12
+ String.raw `\bsystem prompt\b`,
13
+ String.raw `\b(end|start|begin|finish)\s+(every|each|all|your)\s+(answers?|replies|responses|messages)\b`,
14
+ String.raw `^\s*(system|assistant|developer)\s*:`,
15
+ ].join("|"), "im");
16
+ const sentence = /(\s*)([^.!?\n]*[.!?]*)/g;
17
+ // Blanks out every sentence that tells the reader what to do, keeping the facts around it.
18
+ export function remove_instructions(text) {
19
+ return text.replace(sentence, (whole, space, said) => (injection_patterns.test(said) ? space + redacted_instruction : whole));
20
+ }
21
+ // The text inside a fence, with fence tags and orders taken out so it cannot close the fence or take over.
22
+ export function untrusted_block(text) {
23
+ return `${untrusted_open}\n${remove_instructions(text.replace(fence_tag, "[tag removed]"))}\n${untrusted_close}`;
24
+ }
@@ -0,0 +1,4 @@
1
+ export declare function read_picked(event: {
2
+ currentTarget: HTMLInputElement;
3
+ }): Promise<string | null>;
4
+ export declare function save_text(file_name: string, text: string, type?: string): void;
@@ -0,0 +1,21 @@
1
+ // Files a page reads from a file picker and hands the user to save, such as an export and its import.
2
+ // ── Files ────────────────────────────────────────────────────────────────────
3
+ // Hands the picked file's text on, then clears the picker so the same file can be picked again; null when none was picked.
4
+ export async function read_picked(event) {
5
+ const input = event.currentTarget;
6
+ const file = input.files?.[0];
7
+ if (!file)
8
+ return null;
9
+ const text = await file.text();
10
+ input.value = "";
11
+ return text;
12
+ }
13
+ // Offers the text as a download under the name given.
14
+ export function save_text(file_name, text, type = "application/json") {
15
+ const url = URL.createObjectURL(new Blob([text], { type }));
16
+ const link = document.createElement("a");
17
+ link.href = url;
18
+ link.download = file_name;
19
+ link.click();
20
+ URL.revokeObjectURL(url);
21
+ }
@@ -5,6 +5,7 @@ export interface FollowTail<Element extends HTMLElement> {
5
5
  following: boolean;
6
6
  set_following: (following: boolean) => void;
7
7
  on_scroll: (event: UIEvent<Element>) => void;
8
+ jump: () => void;
8
9
  }
9
10
  export declare function use_follow_tail<Element extends HTMLElement>(dependency: unknown, active?: boolean): FollowTail<Element>;
10
11
  interface FollowToggleProps {
@@ -1,25 +1,44 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- // Output that keeps its newest lines in view as they arrive, unless the reader has scrolled up to read, with a Follow switch.
2
+ // Output that keeps its newest lines in view as they arrive, unless the reader has scrolled up to read, with a Follow
3
+ // switch; the hook under it follows any scrolling box, such as a conversation, and a nested one should set
4
+ // overscroll-behavior: contain so its scrolling stays inside it.
3
5
  import { useCallback, useLayoutEffect, useRef, useState } from "react";
4
6
  import { cx } from "../dom.js";
5
7
  // How far above the bottom still counts as at the bottom.
6
8
  const FOLLOW_SLACK_PIXELS = 8;
7
9
  export const at_bottom = (element) => element.scrollTop + element.clientHeight >= element.scrollHeight - FOLLOW_SLACK_PIXELS;
8
- // Scrolls the box to its end whenever the dependency changes while following; active false, such as once a run has ended, leaves the scroll alone.
10
+ // Scrolls the box to its end whenever the dependency changes while following; active false, such as once a run has
11
+ // ended, leaves the scroll alone. Content growing, or the box's own scroll landing short of the end as it grows, never
12
+ // stops the following, since only a scroll upward does.
9
13
  export function use_follow_tail(dependency, active = true) {
10
14
  const ref = useRef(null);
11
15
  const [following, set_following] = useState(true);
16
+ const last_top = useRef(0);
12
17
  useLayoutEffect(() => {
13
18
  const element = ref.current;
14
- if (following && active && element)
19
+ if (!element)
20
+ return;
21
+ if (following && active)
15
22
  element.scrollTop = element.scrollHeight;
23
+ last_top.current = element.scrollTop;
16
24
  }, [dependency, following, active]);
17
25
  const on_scroll = useCallback((event) => {
18
- if (!active)
19
- return;
20
- set_following(at_bottom(event.currentTarget));
26
+ const element = event.currentTarget;
27
+ if (active) {
28
+ if (at_bottom(element))
29
+ set_following(true);
30
+ else if (element.scrollTop < last_top.current)
31
+ set_following(false);
32
+ }
33
+ last_top.current = element.scrollTop;
21
34
  }, [active]);
22
- return { ref, following, set_following, on_scroll };
35
+ const jump = useCallback(() => {
36
+ const element = ref.current;
37
+ if (element)
38
+ element.scrollTop = element.scrollHeight;
39
+ set_following(true);
40
+ }, []);
41
+ return { ref, following, set_following, on_scroll, jump };
23
42
  }
24
43
  export function FollowToggle({ following, on_change, disabled = false, label = "Follow" }) {
25
44
  return (_jsxs("label", { className: "follow-toggle", children: [_jsx("input", { type: "checkbox", checked: following, disabled: disabled, onChange: (event) => on_change(event.currentTarget.checked) }), " ", label] }));
@@ -39,4 +39,21 @@ interface ComboFieldProps {
39
39
  id?: string;
40
40
  }
41
41
  export declare function ComboField({ label, value, options, on_change, on_take, on_enter, on_blur, list_on_focus, limit, placeholder, id }: ComboFieldProps): import("react").JSX.Element;
42
+ export interface ListedOption {
43
+ value: string;
44
+ label?: string;
45
+ }
46
+ export interface FieldListing {
47
+ options: ListedOption[];
48
+ problem?: string;
49
+ }
50
+ interface ListedFieldProps {
51
+ label: string;
52
+ value: string;
53
+ load: () => Promise<FieldListing>;
54
+ again?: unknown[];
55
+ on_choose: (value: string) => void;
56
+ placeholder?: string;
57
+ }
58
+ export declare function ListedField({ label, value, load, again, on_choose, placeholder }: ListedFieldProps): import("react").JSX.Element;
42
59
  export {};
@@ -1,8 +1,10 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // Completions listed under a text field as it is typed into, such as slash commands: arrow keys choose, Tab or Enter take, Escape dismisses.
3
3
  // With open_on_focus the list opens as soon as the field is entered, nothing lit until an arrow key picks one, so Enter
4
- // still hands on free text; ComboField is that mode over a list of known values, such as categories already in use.
4
+ // still hands on free text; ComboField is that mode over a list of known values, such as categories already in use,
5
+ // and ListedField a ComboField over values fetched from somewhere, such as the models a server offers.
5
6
  import { useEffect, useId, useRef, useState } from "react";
7
+ import { use_resource } from "./states.js";
6
8
  export function Suggestions({ value, source, lookup_key, key_of, render, detail, on_take, label, on_key_down, on_blur, open_on_focus = false, children }) {
7
9
  const list_id = useId();
8
10
  const [items, set_items] = useState([]);
@@ -109,3 +111,18 @@ export function ComboField({ label, value, options, on_change, on_take, on_enter
109
111
  }
110
112
  }, children: (field) => (_jsx("input", { ...field, id: id, type: "text", role: "combobox", "aria-label": label, autoComplete: "off", placeholder: placeholder, value: value, onChange: (event) => on_change(event.currentTarget.value) })) }));
111
113
  }
114
+ // A text field offering the values a source lists while still taking any text typed, with the listed values in their
115
+ // own words under it, or why there are none.
116
+ export function ListedField({ label, value, load, again = [], on_choose, placeholder }) {
117
+ const listing = use_resource(load, [value, ...again]);
118
+ const [draft, set_draft] = useState(value);
119
+ useEffect(() => set_draft(value), [value]);
120
+ const keep = (chosen) => {
121
+ set_draft(chosen);
122
+ if (chosen.trim() !== value)
123
+ on_choose(chosen.trim());
124
+ };
125
+ const options = listing.data?.options ?? [];
126
+ const note = options.length > 0 ? options.map((option) => option.label ?? option.value).join(", ") : (listing.data?.problem ?? "");
127
+ return (_jsxs("div", { className: "listed-field", children: [_jsx(ComboField, { label: label, value: draft, options: options.map((option) => option.value), placeholder: placeholder, on_change: set_draft, on_take: keep, on_enter: () => keep(draft), on_blur: () => keep(draft) }), note && _jsx("div", { className: "muted small", children: note })] }));
128
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.107.0",
3
+ "version": "0.109.0",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -50,6 +50,7 @@
50
50
  "@fastify/static": "^10.1.10",
51
51
  "@fastify/websocket": "^11.3.5",
52
52
  "@mdx-js/rollup": "^3.1.1",
53
+ "@modelcontextprotocol/client": "^2.4.0",
53
54
  "@modelcontextprotocol/server": "^2.4.0",
54
55
  "@resvg/resvg-js": "^2.6.2",
55
56
  "@shikijs/rehype": "^4.6.0",
@@ -105,6 +106,9 @@
105
106
  "@mdx-js/rollup": {
106
107
  "optional": true
107
108
  },
109
+ "@modelcontextprotocol/client": {
110
+ "optional": true
111
+ },
108
112
  "@modelcontextprotocol/server": {
109
113
  "optional": true
110
114
  },
@@ -186,6 +190,7 @@
186
190
  "@fastify/static": "^10.1.10",
187
191
  "@fastify/websocket": "^11.3.5",
188
192
  "@mdx-js/rollup": "^3.1.1",
193
+ "@modelcontextprotocol/client": "^2.4.0",
189
194
  "@modelcontextprotocol/server": "^2.4.0",
190
195
  "@resvg/resvg-js": "^2.6.2",
191
196
  "@shikijs/rehype": "^4.6.0",