@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.
package/README.md CHANGED
@@ -15,15 +15,22 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
15
15
  | `app/links` | `app_link(scheme, route)` and `route_of_link(scheme, link)`: an app's links such as `x-notes://note/<id>` and the page route they open. |
16
16
  | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window (`default_size` fixed or from the screen's free area, the daemon told while one is in front for its services' `window_in_front`), the tray (`show_tray_icon`, the app's own `tray` rows above Show, Quit and Quit completely, closing the last window leaving the app in it, `--hidden` starting there), the app's `link_scheme` links opening the window on their page (`route_of_link` to map them its own way; the page follows the `open` event), the login entry, a second launch and `--daemon`; the app's own `desktop_settings` switches sit in Settings → Desktop app beside the base's; `run_preload(app, electron)` puts every bridge on the page. Electron is handed in, so neither imports it. An app with `local_mcp: { default_port }` serves its calls as MCP on 127.0.0.1 from the desktop daemon (`electron/mcp`, page-only calls left out, calls run as `program`), turned on under Settings → MCP server. |
17
17
  | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools` and a `side_pane`. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. |
18
- | `config/vite`, `config/electron_vite`, `config/vitest`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. |
18
+ | `config/vite`, `config/electron_vite`, `config/vitest`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. The page presets stand in for Capacitor where the app has none installed (`config/capacitor`'s `capacitor_stand_in`), so a web and desktop app needs no phone packages, and the dev server proxies `/api/`, leaving the page's own `api.ts` to Vite. |
19
19
  | `app_new` | The `x-app-new <X-Name>` command: a new X-app's files written once, laid out as the Application Standard asks, on the base app, the presets, X-App's Nix lib and its CI actions, with an example notes feature; `--port`, `--folder`, `--no-desktop` and `--no-android`. |
20
20
  | `durations` | `parse_duration` for settings such as `"2h30m"`, `format_duration` in months down to seconds and "less than a second" below one, `format_age`, and `format_clock` for a playing time such as `"3:07"`, with `{ hours: "always" }` writing `"0:03:07"` so a column of times lines up and `empty` for no time. |
21
21
  | `log` | Loggers by scope and level from a setting such as `"warn,play:debug"`; a malformed setting falls back instead of silencing logging, and a setting read through a function applies to loggers made before it arrived; a dotted scope such as `app.core.db` without its own level takes its nearest parent's. |
22
- | `cron` | `CronSchedule.parse`: five-field cron lines read in local time, with `@daily`-style aliases, month and weekday names, steps, ranges and lists, 7 as Sunday, a restricted day of month and weekday matching either as cron does, and a line that never matches a real date refused; `next_after` gives the first run strictly after a moment. |
22
+ | `cron` | `CronSchedule.parse`: five-field cron lines read in local time, with `@daily`-style aliases, month and weekday names, steps, ranges and lists, 7 as Sunday, a restricted day of month and weekday matching either as cron does, and a line that never matches a real date refused; `next_after` gives the first run strictly after a moment. On it, the schedules a user picks for recurring work (`RunSchedule`): every so many minutes, hours or days after the last run, or at a time on chosen weekdays; `checked_schedule(given, { min_minutes })` with a plain reason for a bad one, `describe_schedule` ("at 07:30 on Monday and Friday", "every 2 hours"), `schedule_cron` for an "at" schedule, and `is_due` and `next_due` given the last run, due once however many times it was missed. |
23
23
  | `recurrence` | iCalendar recurrence (RFC 5545) on rrule.js, ported from recurrence-input: `parse_rule` and `format_rule` for a rule without its `RRULE:` prefix, every `BY` part a list, unknown parts such as `X-` kept and an `RSCALE` calendar (RFC 7529) kept first; `parse_recurrence` and `format_recurrence` for `RRULE`, `EXDATE` and `RDATE` lines, folded lines read and `TZID` lines kept as written; `UNTIL` and dates written as plain dates, floating or UTC to match the event's start; `describe_rule` in plain English with times and `BYSETPOS`; `next_occurrence` with `COUNT` lowered in the value to keep; `next_from_now`; `parse_rule_part` naming the values a `BY` part allows. |
24
24
  | `python_text` | Text as Python writes and reads it, for apps ported from Python: `python_repr`, `python_str`, `python_dumps` (json.dumps with its separators and escapes, keys sorted when asked), `python_format` with `apply_format_spec`, `format_fixed` and `format_grouped` ("{:.1f}" rounding an exact tie to even, "{:,.1f}"), `round_half_even`, `python_float_repr`, `split_lines`, `split_words`, `partition`, `parse_int`, `parse_float` and their `_or_null` forms, `fnmatch` and `python_regex` for `(?P<name>...)`. |
25
25
  | `csv` | CSV as RFC 4180 writes it: `parse_csv` into rows, a byte-order mark and blank rows dropped, `csv_records` by the header's names, `tsv_records` for unquoted tab-separated text such as LibraryThing's export, and `csv_field`, `write_csv` and `write_csv_records`, which quote only the cells that need it. Written in-house, as it is a page of code and the libraries add streaming and type guessing no app uses. |
26
26
  | `zip` | Several text files as one zip, such as an export of a few CSV tables: `zip_text_files`, `unzip_text_files` (folders left out, a file that is no zip refused in plain words) and `is_zip`, on fflate, chosen over JSZip because it works synchronously in a browser, on Node and in a phone's page with no dependencies, at a tenth the size. |
27
+ | `text_index` | A local search index's text helpers, for SQLite FTS5 beside stored vectors: `text_hash` (cyrb53, to tell changed text, not for security), `chunk_text(text, size, overlap)` cut at a space near the end so a sentence across a cut is in both pieces, `unit`, `dot`, `to_blob` and `from_blob` for vectors kept as blobs, `fts_query(text, "AND" | "OR")` quoting each word as a prefix so none is read as an operator, and `fuse_ranks`, reciprocal rank fusion of several rankings. |
28
+ | `html_text` | `html_to_text(html, base)`: a web page's title and readable text, a block to a line, scripts, styles and drawings left out, each link kept as plain text with its address made whole after it; `unescape_html` for character references. Runs anywhere, with no DOM. |
29
+ | `untrusted_text` | Text anyone could have written, such as another app's item or a fetched page, fenced before a model reads it: `untrusted_block` wraps it in `<untrusted-data>` with fence tags taken out, and `remove_instructions` blanks each sentence that gives the reader orders (`redacted_instruction`), keeping the facts around it. |
30
+ | `repetition` | `is_repeating`: text going round in circles, such as a model stuck in a loop, told by its last 1200 characters packing to under a fifth (on fflate, so it runs in a page too); `repetition_watch()` checks streaming text every 200 characters. |
31
+ | `endpoints` | An API endpoint a user points an app at: `is_local_endpoint` (loopback, private or link-local, and `localhost`), `host_of(endpoint, default_endpoint)` by host and port alone, `hide_keys`, `PlainError` and `PlainFailure` (a message with its raw `detail`), `ContextOverflow` and `overflow_of` for a request too large for the model, with the tokens counted when the server says, and `explain_endpoint_failure(error, where)`: a timeout, an unreachable server, a refused key, an unknown model or path, a rate limit or an overflow in plain words naming the `label` ("engine"), its `settings`, `key_name`, `serves`, `retry`, `rate_limit_advice` and `overflow_advice`; `keep_unknown` keeps a failure of the app's own as it is. |
32
+ | `endpoint_models` | `list_endpoint_models(endpoint, api_key, signal, fetcher)`: the models an OpenAI-compatible endpoint lists at GET /models, each once, at most 500, with a llama.cpp router's load state (`state_of`), never throwing: a failure is no list and a `problem` in words that never hold the key; `models_of` reads an answer, `model_label` says "qwen3 (loaded)", and `may_load` whether the next request may wait while the server loads the model. |
33
+ | `embeddings` | `embeddings_client(settings, { api_key, fetcher, words })`: any OpenAI-compatible embeddings endpoint, Ollama's on this computer unless set: `embed(texts)` one vector per text in order, checked against the `dimensions` set (768 unless set), `embed_query` with the `query_prefix` before it, `is_local`, the key asked for on each call, its failures thrown as `PlainFailure` through `explain_endpoint_failure`. |
27
34
  | `dates` | Local dates as `"2026-06-10"` or `"2026-06-10T09:30"`: reading, writing, adding days and months, overdue, and Yesterday/Today/Tomorrow labels; days and months as text, such as `today`, `shift_day`, `month_of`, `shift_month`, `months_from` and `format_month` for `"June 2026"`, the month taken from the text so a time zone never moves the 1st. |
28
35
  | `date_ranges` | Spans of time named from now as day.js rules: a date `is_before`, `is_after` or `is_between` (with a chosen inclusivity) points such as now or the start or end of last, this or next day, week, month or year; `resolve_rule` works the points out with the week starting on a chosen day, `matches_rule` places a plain date at the end of its day, and `DATE_POINTS` with `date_point_label` feed a picker. |
29
36
  | `units` | `convert`, `to_shown`, `to_stored` and `format_measure`; `GramUnit` with `from_grams`, `to_grams` and `format_grams` for small amounts kept in grams and shown in g, mg or µg, such as a food's nutrients; weights, lengths, distances and energy kept in kg, cm, km and kcal and shown in the unit each person picks, such as `"225 lb"`; `format_number`, whole numbers whole and the rest to a tenth, and `format_change`, a signed difference such as `"+1.5 kg"`. |
@@ -72,6 +79,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
72
79
  | `electron/mcp`, `local_mcp_protocol`, `web/react/local_mcp_settings` | A desktop app's own MCP endpoint, for AI clients on the same computer: `create_local_mcp` serves an `api_spec`'s calls as tools through `server/mcp` on 127.0.0.1 only, leaving out page-only calls and refusing the uses its `page_only` rule names, since the window reaches those over the daemon's socket, refusing any request whose Host or Origin is not a local name, turned on and given a port by `LocalMcpMethods` and kept in a settings file; with `require_token` on it also refuses any request without its token as `Authorization: Bearer`, the token made by the daemon and kept in `token_file` (`mcp-token` beside the settings unless set, mode 0600), kept across restarts and forgotten when the setting is turned off, and the status then carries `token` and `token_file`; `local_mcp_client_config` gives the `mcpServers` entry with its `headers`, and `local_mcp_add_command` the `claude mcp add` line reading the token from its file; `LocalMcpSettings` is the Settings rows to turn it on, pick the port, require a token, copy the `claude mcp add` command and show or copy the client config. |
73
80
  | `agent/commands` | `run_command` and `stream_command`: one shell command, in its own process group. |
74
81
  | `agent/programs` | `run_program`: one program with its arguments and no shell, each stream shown to a sink, kept, both or dropped, stopped by an abort signal and, in a process group of its own, with all it started; 127 when it is not installed; `BoundedBuffer`, `signal_group` and `on_path`; `whole_lines(sink)` passes on only whole lines, decoding characters split across chunks, with `flush()` for the rest, so programs printing side by side into one output never split each other's lines. |
82
+ | `agent/firefox_bookmarks` | Firefox's bookmarks on this computer: `firefox_profile(set_folder)` (the folder set, with `~`, or the default profile from `profiles.ini`, read by `default_profile_of`), `read_firefox_bookmarks(profile)` from a copy of `places.sqlite` with its write-ahead log, since Firefox keeps it locked, read again only once either changes, tags left out; `bookmark_folders` by path, `bookmark_folder_path`, `bookmarks_in_folder` with every folder inside, `search_bookmarks` by every word of the title or address, `bookmarks_by_guid` and `is_page_bookmark`. |
75
83
  | `mpv` | Media played through mpv, run as a program of its own and driven over its JSON IPC socket: `MpvEngine` plays one file at a time behind `PlaybackEngine` (load with a start, an end, a gain in decibels and mpv's own per-file options, the next file appended for a gapless join, play, pause, stop, seek, volume, and `state`, `position` and `ended` events), sound only unless `video`; `MpvProcess` is mpv itself, found by `find_mpv` (each override in turn, then the PATH, through `on_path`) and started on the first command, its socket moved to /tmp when the temporary folder's path is too long for one, a start that fails or times out refused with why and mpv's last log line, started again by the next command after a failure or an exit, with `observe` for properties kept across restarts, `on_event`, `on_stop` and `close`, which waits until mpv has gone; `NullEngine` for testing an app's player without mpv. |
76
84
  | `agent/wake` | `magic_packet` and `send_magic_packet`: Wake-on-LAN, a few copies of the packet broadcast to a port, sent by a server or by an agent on the sleeping machine's network; `parse_mac` takes colons, dashes, dots or none, a SecureOn `password` follows the packet (`parse_password`), `send_wake_packet` sends a ready packet, and `remote_send_command` is the shell line that sends it from another host with python3 or socat. |
77
85
  | `agent/desktop_notify` | `Notifier`: desktop notifications through notify-send in the agent's own session, with a Dismiss button, a link opened by xdg-open on a click, a timeout the agent enforces even for critical ones, and keys, so a newer notification for a key replaces the old and dismissing the key closes it; the app names itself and maps its own icon names to files. |
@@ -111,7 +119,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
111
119
  | `server/security_headers` | `register_security_headers`: every answer carries a content security policy that runs only the app's own scripts (`default_content_security_policy`, with directives the app replaces through `content_security_policy`, or none with null), `X-Frame-Options` and `frame-ancestors` refusing framing unless `allow_same_origin_frames`, `nosniff`, a same-origin referrer policy and opener policy; headers a route sets itself are kept. |
112
120
  | `server/web_folder` | `register_web_folder`: the built page from a folder, tuned for the Nix store (no etag or date, hashed `/assets/` kept a year, the page fetched fresh), a warning, error or nothing when the folder is missing, and the page for unknown paths when it routes itself. |
113
121
  | `server/replies` | `register_error_replies`: errors and unknown paths answered in plain text or as `{ error }`; `register_lenient_json_body`: an empty body as no arguments and bad JSON as `BAD_JSON`, for the route to refuse in its own words, or refused with 400 before any route runs with `refuse_bad_json`; `send_text`. |
114
- | `server/config` | `read_server_config`: host, port, web folder and the app's options from flags, then the environment, then defaults, with usage text for `--help`, the secret from `<PREFIX>_TOKEN_FILE` or `<PREFIX>_TOKEN`, and no listening beyond this machine without one; `read_secret_file`. |
122
+ | `server/config` | `read_server_config`: host, port, web folder and the app's options from flags, then the environment, then defaults, with usage text for `--help`, the secret from `<PREFIX>_TOKEN_FILE` or `<PREFIX>_TOKEN`, and no listening beyond this machine without one; `read_secret_file`; a secret printed by a command, such as a password manager's, so a setting names the program and never holds the secret: `command_words` splits the setting as a shell would without expanding anything, `secret_command_reader({ what, secret })` runs it without a shell and keeps its first line, refusing a failure, an empty or an overlong line (`max_secret_chars`) in words that never hold what it printed, `read_secret_command` with the default words, and `secret_from_command(line, read)`, `""` when no command is set. |
115
123
  | `server/declared_tokens` | Tokens declared in the app's config, so a scraper's token can live in a NixOS config: `read_declared_tokens` reads each entry's name, its `token_hash` (`sha256:<hex>` from `token_hash`), `token_file` or plain `token`, and a scope the app maps onto a role, read-only or not, or onto no role for a token only the app's own routes check, optionally limited to some of the app's items; bad entries are skipped and explained. Given to `AccountStore` as `declared_tokens` (or `set_declared_tokens` after a reload), they sign in with `server/account_sign_in` as their scope's role, cannot be revoked from the page, and `check_declared_token` finds the role-less ones. |
116
124
  | `config_watch` | `watch_config`: re-reads a config file when it changes, checking a fingerprint of what its path points at (symlinks followed, inode, change time, size) every few seconds, waiting one more check for it to hold still, and reloading only when the content's sha256 differs from what was loaded; a failed reload is reported and the watch goes on. |
117
125
  | `server/prometheus` | `render_metrics`: metric families in Prometheus' text format, with HELP and TYPE lines, labels in order, names made valid, label values and help escaped and infinities written as the format asks; `metrics_content_type`. |
@@ -119,11 +127,14 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
119
127
  | `server/notify/*` | Notification channels, each a settings reader that throws in plain words and a sender that throws when delivery fails: `ntfy` (topic, priority by name or 1-5, tags, a link to open, token or name and password), `webhook` (JSON or a `{name}` template, as text when it is a string, with headers and a bearer token; `headers_file` names a JSON object of more headers, read at each send so a rotated secret needs no restart and in place of inline ones of the same name, a missing or malformed file failing that send with its path but never its contents), `mail` (SMTP on nodemailer, an optional peer, over STARTTLS, TLS or none), `apprise` (the `apprise` program, its URLs passed in the environment, never on its command line); `settings` reads a secret inline or from `<key>_file` and a setting given once or per kind. |
120
128
  | `server/notify/channels` | `read_channels`: the channels in a config list, each picked by its `type` (`ntfy`, `webhook`, `mail` or `apprise`) and read at once so a mistake stops the app starting, named by the list's key; `Notifier` sends a notification (title, body, level) to all of them, a failing one logged while the rest still get it; the level sets ntfy's priority and Apprise's type. |
121
129
  | `server/mcp` | `register_mcp_route`: the calls an `api_spec` describes, served as MCP tools over the official SDK's streamable HTTP (`@modelcontextprotocol/server`), each marked read-only or not, and destructive when its spec says `destructive: true`, as a call that deletes does, a call whose spec says `page_only: true` left out and a use the `page_only` rule names (from `page_only_calls`) refused, its arguments checked against the schema, its result as JSON text and a failure as a tool error in the call's own words; a read-only token runs only the tools that read, and a scoped one its scope's calls too; it sits behind the app's sign-in like any other API path. `route_tools` offers a REST app's routes the same way, running each route inside the app with the caller's headers and address, so it is signed in and checked exactly as the page's request is. |
130
+ | `server/mcp_client` | `create_mcp_client({ name, version, limits })`: a client of the MCP servers a user adds (`McpServerTarget`), on the official SDK's client (`@modelcontextprotocol/client`): streamable HTTP with an optional bearer token, or a local command started without a shell with only the SDK's safe variables and those named (`passed_variables`); `list_tools` with the server's instructions (`instructions_of`) and each tool's read-only mark, `call_tool` answering in text (`result_text`), `forget` and `open_connections`; one connection per server kept while used and closed when idle, a server that exits, hangs or answers badly a plain error naming it and never its token. |
131
+ | `server/address_guard` | Which web addresses a server may fetch for its user or a program: `checked_web_address` (http or https, no name or password, port 80 or 443 unless `allowed_ports`, read from a setting by `ports_of`, with a `ports_hint`), `is_public_address` and `public_addresses`, refusing a host any of whose addresses is loopback, private, link-local or otherwise not public, IPv4 inside IPv6 judged as itself, and `guarded_lookup` for node:http's `lookup`, so a name that answers differently when connecting still reaches only checked addresses. |
122
132
  | `server/cors` | `register_open_cors`: any origin may call the API, as a native or mobile shell does from a page of its own, with the client id header allowed. |
123
133
  | `web/dom`, `web/format`, `web/router`, `web/theme` | The page's element builder and `cx` class joiner, formatters (including `compact_count`, such as `"1.4M"`, and `format_count`, such as `"60,000"`), hash router and theme choice, kept in this browser or the app's settings, and `follow_host_theme` for taking a host page's colours, such as the Linux sidebar's. |
124
134
  | `web/sqlite_wasm` | `open_wasm_database`: SQLite in WebAssembly for a page that keeps its own database, such as a phone app, saved whole to IndexedDB through `indexed_db_files` shortly after each change; `indexed_db_files` with `has` also keeps synced files. |
125
135
  | `web/pictures` | `shrink_picture`: a picture file or data URL redrawn at most 480 pixels on its longest side, or another limit, as a WebP data URL small enough to store and sync, such as a photo from a phone's camera. |
126
136
  | `web/markdown_text` | `as_code_block` and `code_fence`: text as a fenced code block whose fence outruns any backticks inside it, with no page needed, such as for a database upgrade. |
137
+ | `web/files` | `read_picked`: a file picker's text, the picker cleared so the same file can be picked again; `save_text(file_name, text, type)` offers text as a download, such as a settings export. |
127
138
  | `web/states`, `web/tables`, `web/menus`, `web/split`, `web/errors` | `LoginNeeded`; sorting by several columns, trees and column order; for rows of plain objects, the same on a server and in the page, `sort_rows` (numbers before text, natural order, empty cells last), `filter_rows` on every typed word, `next_sort_keys` for header clicks, `keyed_rows` from contents and `tree_rows` by a parent field; menu items, placement and keys; pane sizing; `describe_error` for anything thrown, such as shaka's coded objects, and `describe_call_error`, the same without Electron's remote-method prefix, for a failed call shown to the user. |
128
139
  | `web/api`, `web/events` | `create_api`: JSON calls whose 401 throws `LoginNeeded` except on open paths such as the login, whose refusals throw `ApiError` in the server's words (a proxy's HTML error page, such as a 504, in plain ones), with headers read afresh per call and `{ keepalive: true }` letting a call outlive the page while its body fits under the browser's 64 KiB; `follow_changes`: the page's side of `EventStream`, a watch bumped on each change and after a reconnect, and the client id to send back. |
129
140
  | `web/tree` | Rows with `parent_id` and `position`: nesting, subtrees, tree order, paths, and where a dropped or keyed row lands, its siblings ordered by position or, with `by_list_order`, as the list gives them. |
@@ -166,7 +177,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
166
177
  | `web/react/progress` | `ProgressBar`: a bar with its value out of a max, busy while the amount of work is unknown, and words or the percentage beside it. |
167
178
  | `web/react/rating` | `Rating`: stars that show a rating or take one by click or keyboard, with unrated kept apart from none. |
168
179
  | `web/react/volume` | `VolumeButton`: a speaker button, a line icon showing how loud it is, that opens a slider; scrolling over it adjusts the volume and a middle-click mutes. |
169
- | `web/react/following` | `use_follow_tail`, `FollowingOutput` and `FollowToggle`: output that keeps its newest lines in view as they arrive unless the reader scrolled up, with a Follow switch. |
180
+ | `web/react/following` | `use_follow_tail`, `FollowingOutput` and `FollowToggle`: output that keeps its newest lines in view as they arrive unless the reader scrolled up, with a Follow switch. Only the reader scrolling up lets go, so content growing, or the box's own scroll landing short as it grows, never stops the following; coming back to the end or `jump()` (a "Jump to latest" button) follows again. A nested scrolling box should set `overscroll-behavior: contain`. |
170
181
  | `web/react/events_list` | `EventsList`: a log of what happened, each row the event's age, its level as a badge (`LevelBadge`, in any case, so "WARNING" and "warning" match), the app's own part such as a link, and the message; an entry without a time, such as a message from the last check, shows none; `empty` for what shows when there is nothing. |
171
182
  | `web/react/jobs` | Jobs an app runs on its own: `JobsTable` links each to its page, with what it is for when `owner` is given, its `JobBadge`, when and by whom it started and its last line; `JobDetails` shows one job's facts with the app's own, its error, a slot for progress, its command and its output followed while it runs; `StopJobButton` asks before stopping. |
172
183
  | `web/react/markdown` | `Markdown` and `render_markdown` on marked and DOMPurify, chosen because marked covers the hand-written parser feature for feature and adds tables and nested lists: raw HTML shows as text, only web links are clickable and open in a new tab, and `follow` keeps streamed text in view. |
@@ -174,7 +185,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
174
185
  | `web/react/search_dialog` | `SearchDialog`: results that come in as the reader types, a pause apart, each page with its matching sections under it, worked with the arrow keys and Enter as a combobox over a listbox, excerpts keeping only their `<mark>`s; `SearchButton`, a field-like button that also opens it from Ctrl+K (Cmd+K) or "/". |
175
186
  | `site/*`, `web/react/site`, `web/site/*` | A static site for GitHub Pages in the X-apps' frame: see [A static site](#a-static-site). |
176
187
  | `web/react/rich_text` | `RichText`: a formatted text field on Tiptap that reads and writes Markdown, chosen because Tiptap ships no look of its own, so its toolbar is Halon markup, and its Markdown extension keeps the stored text plain: bold, italic, strikethrough, code, headings, lists, checklists, quotes, code blocks and web links, `on_change` only for typing, never for showing a value. |
177
- | `web/react/suggestions` | `Suggestions`: completions under any text field from a sync or async source; arrow keys choose, Tab or Enter take, Escape dismisses, other keys pass through; `open_on_focus` lists them once the field is entered, nothing lit, so Enter still hands on free text. `ComboField`: that mode over known values, every one listed on focus and narrowed as typed. |
188
+ | `web/react/suggestions` | `Suggestions`: completions under any text field from a sync or async source; arrow keys choose, Tab or Enter take, Escape dismisses, other keys pass through; `open_on_focus` lists them once the field is entered, nothing lit, so Enter still hands on free text. `ComboField`: that mode over known values, every one listed on focus and narrowed as typed. `ListedField`: a `ComboField` over values a `load` fetches, such as the models a server offers, asked again when the value or `again` changes, still taking any text typed, keeping it trimmed on a pick, Enter or leaving the field (`on_choose`), with the listed values in their own words under it, or the `problem` saying why there are none. |
178
189
  | `web/react/chip_field` | `ChipField`: values as removable chips with a `ComboField` that suggests those not yet chosen and an Add button; `with_draft` takes in a value still in the field when a form saves; `TreeChipField`: items of a tree as chips showing their paths, with a `TreePicker` to add one or, with `can_create`, new text. |
179
190
  | `web/react/recurrence` | `RecurrenceField`: a rule or its iCalendar lines edited as Halon fields, with a Repeats switch, every N seconds to years, weekdays, months, several days of the month and weekday entries such as "the last Friday", "only the last of those", several times of day or minutes past, an end after a count or on a date, dates to skip and add, and every `BY` part and `WKST` under More options; `features` from `simple` to `full` with names added or taken away, read by `read_features`; it describes the rule below, keeps what it cannot edit as written, and blocks its form while a field or the value cannot be read. |
180
191
 
@@ -221,6 +232,9 @@ The rest of an app's files are short calls into X-App too:
221
232
  - **Nix**: X-App's flake has a `lib` with `package`, `desktop_package`, `module`, `shell` and `android_shell`, each
222
233
  taking the app's package set and its `nix/app.nix` (name, display name, variables' prefix, port, database file and
223
234
  words); the app's `nix/flake.nix` takes `github:x-tech-laboratories/X-App` as an input and calls them.
235
+ An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
236
+ copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; the desktop wrapper sets
237
+ `<PREFIX>_LAUNCHER` so the login entry runs the installed command.
224
238
  - **Android**: `npm run build:android` builds the phone's page and runs `x-app-android`, which makes or updates the
225
239
  Capacitor project in `android/`, so the app keeps only `capacitor.config.json` and leaves `android/` out of git.
226
240
  - **CI**: the app's `ci` job runs `x-tech-laboratories/X-App/.github/actions/app-ci@main`, its `nix` job
@@ -0,0 +1,29 @@
1
+ export declare function firefox_folders(home?: string): string[];
2
+ export declare function default_profile_of(ini: string): {
3
+ path: string;
4
+ is_relative: boolean;
5
+ } | null;
6
+ export declare function firefox_profile(set_folder?: string, folders?: string[]): Promise<string>;
7
+ export interface FirefoxBookmark {
8
+ id: number;
9
+ parent: number;
10
+ type: number;
11
+ title: string | null;
12
+ guid: string;
13
+ url: string | null;
14
+ }
15
+ export interface FirefoxBookmarks {
16
+ rows: FirefoxBookmark[];
17
+ by_id: Map<number, FirefoxBookmark>;
18
+ }
19
+ export declare const root_names: Record<string, string>;
20
+ export declare function read_firefox_bookmarks(profile: string): Promise<FirefoxBookmarks>;
21
+ export declare function bookmark_folder_path(bookmarks: FirefoxBookmarks, id: number): string;
22
+ export declare function is_page_bookmark(row: FirefoxBookmark): boolean;
23
+ export declare function search_bookmarks(bookmarks: FirefoxBookmarks, query: string, limit?: number): FirefoxBookmark[];
24
+ export declare function bookmarks_by_guid(bookmarks: FirefoxBookmarks, guids: string[]): Record<string, FirefoxBookmark>;
25
+ export declare function bookmark_folders(bookmarks: FirefoxBookmarks): {
26
+ guid: string;
27
+ path: string;
28
+ }[];
29
+ export declare function bookmarks_in_folder(bookmarks: FirefoxBookmarks, guid: string): FirefoxBookmark[];
@@ -0,0 +1,147 @@
1
+ // Firefox's bookmarks on this computer: its default profile found from profiles.ini, and the bookmarks and folders in
2
+ // the profile's places.sqlite, read from a copy taken with its write-ahead log, since Firefox keeps the file locked
3
+ // while it runs. Tags, which Firefox keeps as folders of their own, are left out.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { copyFile, mkdtemp, readFile, rm, stat } from "node:fs/promises";
6
+ import { homedir, tmpdir } from "node:os";
7
+ import { join, resolve } from "node:path";
8
+ import { DatabaseSync } from "node:sqlite";
9
+ // ── Profile ──────────────────────────────────────────────────────────────────
10
+ // Where Firefox keeps its profiles: the XDG folder newer versions use, then the older one.
11
+ export function firefox_folders(home = homedir()) {
12
+ return [join(home, ".config", "mozilla", "firefox"), join(home, ".mozilla", "firefox")];
13
+ }
14
+ // The default profile named in a profiles.ini, as a folder relative to it or absolute.
15
+ export function default_profile_of(ini) {
16
+ const sections = ini.split(/^\[/m).map((section) => {
17
+ const [head = "", ...lines] = section.split("\n");
18
+ const values = Object.fromEntries(lines.map((line) => line.split(/=(.*)/s)).filter((pair) => pair.length >= 2).map(([key, value]) => [key.trim(), value.trim()]));
19
+ return { head: head.replace(/\].*$/, ""), values };
20
+ });
21
+ const install = sections.find((section) => section.head.startsWith("Install") && section.values.Default);
22
+ if (install)
23
+ return { path: install.values.Default, is_relative: true };
24
+ const profiles = sections.filter((section) => section.head.startsWith("Profile") && section.values.Path);
25
+ const chosen = profiles.find((section) => section.values.Default === "1") ?? profiles[0];
26
+ return chosen ? { path: chosen.values.Path, is_relative: chosen.values.IsRelative !== "0" } : null;
27
+ }
28
+ // The profile folder set, with ~ as the home folder, or else Firefox's default profile in the folders given.
29
+ export async function firefox_profile(set_folder = "", folders = firefox_folders()) {
30
+ const set = set_folder.trim();
31
+ if (set)
32
+ return resolve(set.replace(/^~(?=$|\/)/, homedir()));
33
+ for (const folder of folders) {
34
+ let ini;
35
+ try {
36
+ ini = await readFile(join(folder, "profiles.ini"), "utf8");
37
+ }
38
+ catch {
39
+ continue;
40
+ }
41
+ const found = default_profile_of(ini);
42
+ if (found)
43
+ return found.is_relative ? join(folder, found.path) : found.path;
44
+ }
45
+ throw new Error("Firefox's profile was not found.");
46
+ }
47
+ const bookmark_type = 1;
48
+ const folder_type = 2;
49
+ // Firefox's own root folders, by guid, with the names its window shows.
50
+ export const root_names = { menu________: "Menu", toolbar_____: "Toolbar", unfiled_____: "Other Bookmarks", mobile______: "Mobile" };
51
+ let kept = null;
52
+ // The bookmarks in the profile's places.sqlite; read again only once it or its write-ahead log changes.
53
+ export async function read_firefox_bookmarks(profile) {
54
+ const places = join(profile, "places.sqlite");
55
+ const sizes = await Promise.all([places, `${places}-wal`].map((path) => stat(path).then((info) => `${info.mtimeMs}:${info.size}`, () => "")));
56
+ if (!sizes[0])
57
+ throw new Error(`Firefox's bookmarks were not found in ${profile}.`);
58
+ const key = `${places}|${sizes.join("|")}`;
59
+ if (kept?.key === key)
60
+ return kept.bookmarks;
61
+ const folder = await mkdtemp(join(tmpdir(), "firefox-bookmarks-"));
62
+ try {
63
+ const copy = join(folder, "places.sqlite");
64
+ await copyFile(places, copy);
65
+ if (sizes[1])
66
+ await copyFile(`${places}-wal`, `${copy}-wal`);
67
+ const database = new DatabaseSync(copy);
68
+ try {
69
+ const rows = database
70
+ .prepare("SELECT b.id, b.parent, b.type, b.title, b.guid, p.url FROM moz_bookmarks b LEFT JOIN moz_places p ON p.id = b.fk ORDER BY b.parent, b.position")
71
+ .all();
72
+ const tags = rows.find((row) => row.guid === "tags________")?.id;
73
+ const by_id = new Map(rows.map((row) => [row.id, row]));
74
+ const shown = rows.filter((row) => {
75
+ let parent = row.parent;
76
+ for (let step = 0; step < 50 && parent; step++) {
77
+ if (parent === tags)
78
+ return false;
79
+ parent = by_id.get(parent)?.parent ?? 0;
80
+ }
81
+ return row.id !== tags;
82
+ });
83
+ const bookmarks = { rows: shown, by_id: new Map(shown.map((row) => [row.id, row])) };
84
+ kept = { key, bookmarks };
85
+ return bookmarks;
86
+ }
87
+ finally {
88
+ database.close();
89
+ }
90
+ }
91
+ finally {
92
+ await rm(folder, { recursive: true, force: true });
93
+ }
94
+ }
95
+ // ── Finding ──────────────────────────────────────────────────────────────────
96
+ // A folder's names from its root down, such as "Other Bookmarks/1. Career/5. Job Hunting".
97
+ export function bookmark_folder_path(bookmarks, id) {
98
+ const names = [];
99
+ let row = bookmarks.by_id.get(id);
100
+ for (let step = 0; step < 50 && row && row.parent !== 0; step++) {
101
+ names.unshift(root_names[row.guid] ?? (row.title ?? "").trim());
102
+ row = bookmarks.by_id.get(row.parent);
103
+ }
104
+ return names.join("/");
105
+ }
106
+ // A bookmark of a web page, not a folder, a separator or a saved query.
107
+ export function is_page_bookmark(row) {
108
+ return row.type === bookmark_type && Boolean(row.url) && !row.url.startsWith("place:");
109
+ }
110
+ // Bookmarks whose title or address holds every word typed, the first `limit` of them.
111
+ export function search_bookmarks(bookmarks, query, limit = 30) {
112
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
113
+ if (words.length === 0)
114
+ return [];
115
+ return bookmarks.rows.filter((row) => is_page_bookmark(row) && words.every((word) => `${row.title ?? ""} ${row.url}`.toLowerCase().includes(word))).slice(0, limit);
116
+ }
117
+ // Each bookmark still there, by guid; one deleted is left out.
118
+ export function bookmarks_by_guid(bookmarks, guids) {
119
+ const wanted = new Set(guids);
120
+ return Object.fromEntries(bookmarks.rows.filter((row) => is_page_bookmark(row) && wanted.has(row.guid)).map((row) => [row.guid, row]));
121
+ }
122
+ // Every folder that is not one of Firefox's roots, with its path, in the order of their paths.
123
+ export function bookmark_folders(bookmarks) {
124
+ return bookmarks.rows
125
+ .filter((row) => row.type === folder_type && row.parent !== 0 && !root_names[row.guid] && bookmarks.by_id.get(row.parent))
126
+ .map((row) => ({ guid: row.guid, path: bookmark_folder_path(bookmarks, row.id) }))
127
+ .sort((first, second) => first.path.localeCompare(second.path, undefined, { numeric: true }));
128
+ }
129
+ // The bookmarks in a folder and every folder inside it; throws when there is no such folder.
130
+ export function bookmarks_in_folder(bookmarks, guid) {
131
+ const folder = bookmarks.rows.find((row) => row.guid === guid && row.type === folder_type);
132
+ if (!folder)
133
+ throw new Error(`Firefox has no bookmark folder ${guid}.`);
134
+ const inside = new Set([folder.id]);
135
+ // Rows come by parent, so a folder can come before the one holding it; go again until nothing new is found.
136
+ let grew = true;
137
+ while (grew) {
138
+ grew = false;
139
+ for (const row of bookmarks.rows) {
140
+ if (row.type === folder_type && inside.has(row.parent) && !inside.has(row.id)) {
141
+ inside.add(row.id);
142
+ grew = true;
143
+ }
144
+ }
145
+ }
146
+ return bookmarks.rows.filter((row) => is_page_bookmark(row) && inside.has(row.parent));
147
+ }
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from "vite";
2
+ export declare function has_package(root: string, name: string): boolean;
3
+ export declare function capacitor_stand_in(root?: string): Plugin;
@@ -0,0 +1,33 @@
1
+ // Stands in for Capacitor in an app that has no phone app: the base app's page loads its phone host only on a phone,
2
+ // but the bundler still follows that import, so without Capacitor installed the build would fail. An app that has
3
+ // Capacitor gets the real one.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { createRequire } from "node:module";
6
+ import { join } from "node:path";
7
+ // ── Stand-ins ────────────────────────────────────────────────────────────────
8
+ // What the base app takes from each package, none of which a page off the phone ever calls.
9
+ const stand_ins = {
10
+ "@capacitor/core": `export function registerPlugin() { throw new Error("Capacitor is not installed in this app."); }\nexport const Capacitor = { getPlatform: () => "web", isNativePlatform: () => false };\n`,
11
+ "@capacitor/app": `export const App = { addListener: () => { throw new Error("Capacitor is not installed in this app."); } };\n`,
12
+ };
13
+ const prefix = "\0x-app-capacitor:";
14
+ // Whether the app at root has the package installed.
15
+ export function has_package(root, name) {
16
+ try {
17
+ createRequire(join(root, "package.json")).resolve(name);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ // Points the Capacitor imports at stand-ins when the app at root, the working directory unless given, lacks them.
25
+ export function capacitor_stand_in(root = process.cwd()) {
26
+ const missing = new Set(Object.keys(stand_ins).filter((name) => !has_package(root, name)));
27
+ return {
28
+ name: "x-app-capacitor-stand-in",
29
+ enforce: "pre",
30
+ resolveId: (source) => (missing.has(source) ? prefix + source : null),
31
+ load: (id) => (id.startsWith(prefix) ? stand_ins[id.slice(prefix.length)] : null),
32
+ };
33
+ }
@@ -3,6 +3,7 @@
3
3
  import { resolve } from "node:path";
4
4
  import react from "@vitejs/plugin-react";
5
5
  import { externalizeDepsPlugin } from "electron-vite";
6
+ import { capacitor_stand_in } from "./capacitor.js";
6
7
  export function desktop_vite_config(options = {}) {
7
8
  const daemon = options.daemon === undefined ? "src/daemon/main.ts" : options.daemon;
8
9
  return {
@@ -16,7 +17,7 @@ export function desktop_vite_config(options = {}) {
16
17
  },
17
18
  renderer: {
18
19
  root: resolve("src/web"),
19
- plugins: [react()],
20
+ plugins: [react(), capacitor_stand_in()],
20
21
  build: { rollupOptions: { input: { index: resolve("src/web/index.html") } } },
21
22
  },
22
23
  };
@@ -1,6 +1,7 @@
1
1
  // The base app's Vite configs: the page for a browser, and the page for the phone app, built from src/web.
2
2
  // ── Imports ──────────────────────────────────────────────────────────────────
3
3
  import react from "@vitejs/plugin-react";
4
+ import { capacitor_stand_in } from "./capacitor.js";
4
5
  // The page for a browser, with relative paths so a proxy can serve it under a folder; the dev page reaches the API
5
6
  // through the separately running server.
6
7
  export function web_vite_config({ port }) {
@@ -8,9 +9,10 @@ export function web_vite_config({ port }) {
8
9
  return {
9
10
  root: "src/web",
10
11
  base: "./",
11
- plugins: [react()],
12
+ plugins: [react(), capacitor_stand_in()],
12
13
  build: { outDir: "../../out/web", emptyOutDir: true },
13
- server: { proxy: { "/api": server, "/login": server } },
14
+ // With the slash, so the page's own src/web/api.ts is served by Vite rather than sent to the server.
15
+ server: { proxy: { "/api/": server, "/login": server } },
14
16
  };
15
17
  }
16
18
  // ── Android ──────────────────────────────────────────────────────────────────
package/dist/cron.d.ts CHANGED
@@ -12,3 +12,23 @@ export declare class CronSchedule {
12
12
  matches_day(day: Date): boolean;
13
13
  next_after(moment: Date): Date | null;
14
14
  }
15
+ export type IntervalUnit = "minutes" | "hours" | "days";
16
+ export type RunSchedule = {
17
+ kind: "every";
18
+ every: number;
19
+ unit: IntervalUnit;
20
+ } | {
21
+ kind: "at";
22
+ time: string;
23
+ weekdays: number[];
24
+ };
25
+ export interface ScheduleLimits {
26
+ min_minutes?: number;
27
+ }
28
+ export declare function checked_schedule(given: unknown, limits?: ScheduleLimits): RunSchedule;
29
+ export declare function describe_schedule(schedule: RunSchedule): string;
30
+ export declare function schedule_cron(schedule: Extract<RunSchedule, {
31
+ kind: "at";
32
+ }>): CronSchedule;
33
+ export declare function next_due(schedule: RunSchedule, since: number): number;
34
+ export declare function is_due(schedule: RunSchedule, since: number, now: number): boolean;
package/dist/cron.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // Five-field cron expressions read in local time: minute, hour, day of month, month, day of week, with the @daily
2
- // style aliases and month and weekday names.
2
+ // style aliases and month and weekday names. On them, the simpler schedules a user picks for recurring work: every so
3
+ // many minutes, hours or days after it last ran, or at a time on chosen weekdays, due once however often it was missed.
4
+ // ── Expressions ──────────────────────────────────────────────────────────────
3
5
  const aliases = {
4
6
  "@hourly": "0 * * * *",
5
7
  "@daily": "0 0 * * *",
@@ -123,3 +125,63 @@ export class CronSchedule {
123
125
  return null;
124
126
  }
125
127
  }
128
+ const unit_ms = { minutes: 60_000, hours: 3_600_000, days: 86_400_000 };
129
+ const weekday_words = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
130
+ // The schedule given, checked, or a plain reason it is not one.
131
+ export function checked_schedule(given, limits = {}) {
132
+ const value = (given ?? {});
133
+ if (value.kind === "every") {
134
+ const every = Number(value.every);
135
+ const unit = String(value.unit);
136
+ const min_minutes = limits.min_minutes ?? 1;
137
+ if (!Object.hasOwn(unit_ms, unit))
138
+ throw new Error('A schedule\'s unit is "minutes", "hours" or "days".');
139
+ if (!Number.isInteger(every) || every < 1)
140
+ throw new Error("A schedule runs every whole number of minutes, hours or days, one or more.");
141
+ if (unit === "minutes" && every < min_minutes)
142
+ throw new Error(`A schedule runs at most every ${min_minutes} minutes.`);
143
+ return { kind: "every", every, unit };
144
+ }
145
+ if (value.kind === "at") {
146
+ const time = String(value.time ?? "");
147
+ const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(time);
148
+ if (!match)
149
+ throw new Error("A schedule's time is a 24-hour time such as 07:30.");
150
+ const weekdays = Array.isArray(value.weekdays) ? [...new Set(value.weekdays.map(Number))].filter((day) => Number.isInteger(day) && day >= 0 && day <= 6).sort((a, b) => a - b) : [];
151
+ if (weekdays.length === 0)
152
+ throw new Error("A schedule at a time runs on one weekday or more, 0 being Sunday.");
153
+ return { kind: "at", time: `${match[1].padStart(2, "0")}:${match[2]}`, weekdays };
154
+ }
155
+ throw new Error('A schedule is { kind: "every", every, unit } or { kind: "at", time, weekdays }.');
156
+ }
157
+ function word_list(words) {
158
+ return words.length <= 1 ? (words[0] ?? "") : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
159
+ }
160
+ // The schedule in plain words, such as "every 2 hours" or "at 07:30 on Monday and Friday".
161
+ export function describe_schedule(schedule) {
162
+ if (schedule.kind === "every")
163
+ return schedule.every === 1 ? `every ${schedule.unit.slice(0, -1)}` : `every ${schedule.every} ${schedule.unit}`;
164
+ const days = schedule.weekdays.length === 7
165
+ ? "every day"
166
+ : schedule.weekdays.length === 5 && schedule.weekdays.every((day) => day >= 1 && day <= 5)
167
+ ? "on weekdays"
168
+ : `on ${word_list(schedule.weekdays.map((day) => weekday_words[day]))}`;
169
+ return `at ${schedule.time} ${days}`;
170
+ }
171
+ // An "at" schedule as the cron expression naming the same moments.
172
+ export function schedule_cron(schedule) {
173
+ const [hours, minutes] = schedule.time.split(":").map(Number);
174
+ return CronSchedule.parse(`${minutes} ${hours} * * ${schedule.weekdays.join(",")}`);
175
+ }
176
+ // When the work falls due next, given when it last ran or was made.
177
+ export function next_due(schedule, since) {
178
+ if (schedule.kind === "every")
179
+ return since + schedule.every * unit_ms[schedule.unit];
180
+ return schedule_cron(schedule).next_after(new Date(since))?.getTime() ?? since + unit_ms.days;
181
+ }
182
+ // Whether the work is due now, given when it last ran or was made: once, however many times it was missed.
183
+ export function is_due(schedule, since, now) {
184
+ if (schedule.kind === "every")
185
+ return now - since >= schedule.every * unit_ms[schedule.unit];
186
+ return next_due(schedule, since) <= now;
187
+ }
@@ -0,0 +1,23 @@
1
+ import { type EndpointWhere } from "./endpoints.ts";
2
+ export declare const default_embeddings_endpoint = "http://localhost:11434/v1";
3
+ export declare const default_dimensions = 768;
4
+ export interface EmbeddingsSettings {
5
+ endpoint?: string;
6
+ model: string;
7
+ dimensions?: number;
8
+ query_prefix?: string;
9
+ }
10
+ export interface EmbeddingsOptions {
11
+ api_key?: () => Promise<string>;
12
+ fetcher?: typeof fetch;
13
+ words?: Omit<EndpointWhere, "endpoint" | "default_endpoint" | "model">;
14
+ }
15
+ export interface EmbeddingsClient {
16
+ model(): string;
17
+ dimensions(): number;
18
+ is_local(): boolean;
19
+ embed(texts: string[], signal?: AbortSignal): Promise<number[][]>;
20
+ embed_query(query: string, signal?: AbortSignal): Promise<number[]>;
21
+ }
22
+ export declare function embeddings_endpoint(settings: EmbeddingsSettings): string;
23
+ export declare function embeddings_client(settings: () => EmbeddingsSettings, options?: EmbeddingsOptions): EmbeddingsClient;
@@ -0,0 +1,80 @@
1
+ // A client for any OpenAI-compatible embeddings endpoint, Ollama's on this computer unless set otherwise: texts in,
2
+ // one vector each out, checked against the size the settings expect, its failures in plain words. Its key is asked
3
+ // for afresh on each call and dropped with it. Needs only fetch, so it runs in a page as on Node.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { PlainFailure, explain_endpoint_failure, is_local_endpoint } from "./endpoints.js";
6
+ // ── Shapes ───────────────────────────────────────────────────────────────────
7
+ export const default_embeddings_endpoint = "http://localhost:11434/v1";
8
+ export const default_dimensions = 768;
9
+ // ── Client ───────────────────────────────────────────────────────────────────
10
+ export function embeddings_endpoint(settings) {
11
+ return (String(settings.endpoint ?? "").trim() || default_embeddings_endpoint).replace(/\/+$/, "");
12
+ }
13
+ // An embeddings client on the endpoint the settings name now, read again on every call.
14
+ export function embeddings_client(settings, options = {}) {
15
+ const fetcher = options.fetcher ?? fetch;
16
+ const under = options.words?.settings ? ` under ${options.words.settings}` : "";
17
+ const model = () => String(settings().model ?? "").trim();
18
+ const dimensions = () => Number(settings().dimensions) || default_dimensions;
19
+ const query_prefix = () => String(settings().query_prefix ?? "").replace(/\\n/g, "\n");
20
+ const client = {
21
+ model,
22
+ dimensions,
23
+ is_local: () => is_local_endpoint(embeddings_endpoint(settings())),
24
+ async embed(texts, signal) {
25
+ if (texts.length === 0)
26
+ return [];
27
+ if (!model())
28
+ throw new Error(`Set the embedding model${under}.`);
29
+ const api_key = options.api_key ? await options.api_key() : "";
30
+ const endpoint = embeddings_endpoint(settings());
31
+ const failure = (error) => {
32
+ const { message, detail } = explain_endpoint_failure(error, {
33
+ label: "embedder",
34
+ serves: "embeddings",
35
+ keep_unknown: true,
36
+ ...options.words,
37
+ endpoint,
38
+ default_endpoint: default_embeddings_endpoint,
39
+ model: model(),
40
+ });
41
+ return new PlainFailure(message, detail);
42
+ };
43
+ let response;
44
+ try {
45
+ response = await fetcher(`${endpoint}/embeddings`, {
46
+ method: "POST",
47
+ headers: { "content-type": "application/json", ...(api_key ? { authorization: `Bearer ${api_key}` } : {}) },
48
+ body: JSON.stringify({ model: model(), input: texts }),
49
+ signal: signal ?? null,
50
+ });
51
+ }
52
+ catch (error) {
53
+ if (signal?.aborted)
54
+ throw error;
55
+ throw failure(error);
56
+ }
57
+ if (!response.ok) {
58
+ const said = await response.text().catch(() => "");
59
+ throw failure(Object.assign(new Error(`The embeddings endpoint answered ${response.status} ${response.statusText}.${said ? ` ${said.slice(0, 500)}` : ""}`), { status: response.status }));
60
+ }
61
+ const answer = (await response.json());
62
+ const rows = [...(answer.data ?? [])].sort((first, second) => (first.index ?? 0) - (second.index ?? 0));
63
+ if (rows.length !== texts.length)
64
+ throw new Error(`The embeddings endpoint gave ${rows.length} vectors for ${texts.length} texts.`);
65
+ return rows.map((row) => {
66
+ const vector = row.embedding;
67
+ if (!Array.isArray(vector) || !vector.every((value) => typeof value === "number"))
68
+ throw new Error("The embeddings endpoint gave something other than a list of numbers.");
69
+ if (vector.length !== dimensions())
70
+ throw new Error(`The model gives vectors of ${vector.length} numbers, not the ${dimensions()} set${under}.`);
71
+ return vector;
72
+ });
73
+ },
74
+ async embed_query(query, signal) {
75
+ const [vector] = await client.embed([`${query_prefix()}${query}`], signal);
76
+ return vector;
77
+ },
78
+ };
79
+ return client;
80
+ }
@@ -0,0 +1,16 @@
1
+ export type ModelState = "loaded" | "loading" | "unloaded" | "failed" | "";
2
+ export interface EndpointModel {
3
+ id: string;
4
+ state: ModelState;
5
+ }
6
+ export interface ModelListing {
7
+ models: EndpointModel[];
8
+ problem: string;
9
+ }
10
+ export declare const list_timeout_ms = 5000;
11
+ export declare const most_models = 500;
12
+ export declare function state_of(entry: Record<string, unknown>): ModelState;
13
+ export declare function models_of(body: unknown): EndpointModel[] | null;
14
+ export declare function list_endpoint_models(endpoint: string, api_key: string, signal?: AbortSignal, fetcher?: typeof fetch): Promise<ModelListing>;
15
+ export declare function model_label(model: EndpointModel): string;
16
+ export declare function may_load(listing: ModelListing | null, model: string, just_chosen: boolean): boolean;