@x-tech-laboratories/x-app 0.120.0 → 0.122.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.
Files changed (48) hide show
  1. package/README.md +27 -6
  2. package/dist/agent/ssh_config.d.ts +12 -0
  3. package/dist/agent/ssh_config.js +72 -0
  4. package/dist/app/daemon.d.ts +7 -1
  5. package/dist/app/daemon.js +82 -8
  6. package/dist/app/define.d.ts +38 -1
  7. package/dist/app/define.js +34 -1
  8. package/dist/app/desktop.d.ts +13 -0
  9. package/dist/app/desktop.js +35 -3
  10. package/dist/app/host_tables.d.ts +21 -0
  11. package/dist/app/host_tables.js +105 -0
  12. package/dist/app/preload.js +5 -0
  13. package/dist/app/protocol.d.ts +31 -1
  14. package/dist/app/protocol.js +8 -1
  15. package/dist/app/remote_access.d.ts +17 -0
  16. package/dist/app/remote_access.js +85 -0
  17. package/dist/app/server.d.ts +20 -5
  18. package/dist/app/server.js +101 -22
  19. package/dist/app/services.d.ts +25 -2
  20. package/dist/app/web/app_page.d.ts +1 -1
  21. package/dist/app/web/app_page.js +73 -12
  22. package/dist/app/web/hosts.d.ts +5 -3
  23. package/dist/app/web/hosts.js +35 -2
  24. package/dist/app/web/page.d.ts +3 -0
  25. package/dist/app/web/page.js +24 -4
  26. package/dist/app/web/portal.d.ts +14 -0
  27. package/dist/app/web/portal.js +115 -0
  28. package/dist/app/web/settings_page.d.ts +13 -2
  29. package/dist/app/web/settings_page.js +36 -8
  30. package/dist/change_checks.js +1 -1
  31. package/dist/github_targets.d.ts +12 -0
  32. package/dist/github_targets.js +90 -0
  33. package/dist/remote_access_protocol.d.ts +26 -0
  34. package/dist/remote_access_protocol.js +33 -0
  35. package/dist/server/github_webhook.d.ts +2 -12
  36. package/dist/server/github_webhook.js +2 -87
  37. package/dist/server/sqlite_backups.d.ts +2 -2
  38. package/dist/server/sqlite_backups.js +2 -2
  39. package/dist/server/viewer_scope.d.ts +3 -0
  40. package/dist/server/viewer_scope.js +14 -0
  41. package/dist/web/react/remote_access_settings.d.ts +5 -0
  42. package/dist/web/react/remote_access_settings.js +55 -0
  43. package/dist/web/react/shell.js +1 -1
  44. package/dist/web/remote_daemon.d.ts +26 -0
  45. package/dist/web/remote_daemon.js +105 -0
  46. package/dist/web/theme.d.ts +8 -0
  47. package/dist/web/theme.js +23 -0
  48. package/package.json +1 -1
package/README.md CHANGED
@@ -9,14 +9,15 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
9
9
 
10
10
  | Import | What it holds |
11
11
  | ---------------------------------------- | ----------------------------------------------------------------------------- |
12
- | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. `history_days` sets how far an app's history reaches back until the user chooses (365 unless set); what opening changed is recorded as this device's version, and old versions are pruned on opening and after a write once a day. `settings_knows(key)` lets an import take keys without a spec of their own, such as `diet.target_protein`; `upgrade_layout: { needed, run }` brings a database an older version laid out its own way, such as a versions table keyed another way, in line before any migration, backed up first; `adopt_backup_schedule(database, saved)` moves a schedule an older version kept elsewhere into the setting once. `tools`, a feature of the app's own, is what MCP offers in place of the page's calls, such as tools that take names rather than ids, each run as the `program` caller (`app.mcp`). Sync's and history's triggers come off while migrations run, so a step may drop a column they name. `take_data_change(database)` names the synced tables written since the last call for that connection (null on its first call and after a restore); the server and daemon send it with each change, so a page's `on_change(listener)` hears `{ tables }` and fetches only what it shows from them, or everything on null. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. |
13
- | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. A `backup-schedule.json` an older version kept beside the database moves into this device's setting on opening. Both tell every page when another program, such as an older build, writes the database file (`watch_outside_changes`, on SQLite's `data_version`). `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. |
14
- | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. |
12
+ | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. `history_days` sets how far an app's history reaches back until the user chooses (365 unless set); what opening changed is recorded as this device's version, and old versions are pruned on opening and after a write once a day. `settings_knows(key)` lets an import take keys without a spec of their own, such as `diet.target_protein`; `upgrade_layout: { needed, run }` brings a database an older version laid out its own way, such as a versions table keyed another way, in line before any migration, backed up first; `adopt_backup_schedule(database, saved)` moves a schedule an older version kept elsewhere into the setting once. `tools`, a feature of the app's own, is what MCP offers in place of the page's calls, such as tools that take names rather than ids, each run as the `program` caller (`app.mcp`). Sync's and history's triggers come off while migrations run, so a step may drop a column they name. `take_data_change(database)` names the synced tables written since the last call for that connection (null on its first call and after a restore); the server and daemon send it with each change, so a page's `on_change(listener)` hears `{ tables }` and fetches only what it shows from them, or everything on null. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. `roles` gives the accounts' roles from least to most able (`["user", "admin"]` unless set); `sync: false` is an app whose server is the only copy of its data, such as one watching other machines, so the server keeps no sync peer and Settings shows no Sync section; `declared_tokens: { key, scopes }` reads tokens from that key of the server's config through `server/declared_tokens`. |
13
+ | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. A `backup-schedule.json` an older version kept beside the database moves into this device's setting on opening. Both tell every page when another program, such as an older build, writes the database file (`watch_outside_changes`, on SQLite's `data_version`). `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. The server also signs in through OpenID Connect from `<PREFIX>_OIDC_*` (`oidc_from_environment`), bounds sessions by the config's `session_seconds` and `remembered_seconds`, and serves the config's `theme` (`{ scheme, colors }`, read by `read_server_theme`) at the open `GET /api/theme`, which the browser's page applies before it draws: a pinned scheme leaves the Shell's theme row out, and each colour sets a Halon token over both schemes. With the config's `plugins_folder` it serves each plugin's page side under `/api/plugins` (`server/plugin_files`). The app's `routes` may name `open_prefixes`, such as `/api/push/`, `guarded_paths` outside the API, such as `/metrics`, and `needed(method, path)`, what a route of its own needs of the one asking, such as an operator's role. |
14
+ | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. On the server it also gets `config_file`, the path of the config it read, for an app that reads its own keys again when the file changes (with `config_watch`), `declared_tokens()` and `reread_declared_tokens(config)` after such a reload. `before_restore` and `after_restore` may return a promise, which the restore waits for, such as a writer flushing first. |
15
+ | `app/host_tables`, `app/remote_access`, `remote_access_protocol` | What an app's hosts answer themselves beside its data calls, such as files a computer keeps or programs it runs: `define_app({ host_tables })` names each table with its `api`, the `hosts` that answer it (`"server"`, `"desktop"`) and who reaches it from the network or MCP (`network`: `"admin"` unless set, `"any"`, or `"none"` for this computer's own window alone); the services hand in each table's `methods`, and `elsewhere`, the same calls refusing what only this computer's user may do, for the network and MCP. Every host serves them under `/api/<table>/<call>` (503 until the services started), `/api/host/get_host_abilities` says what the viewer reaches (`admin`, `tables`), MCP and OpenAPI offer them beside the data calls, and the desktop bridges them, a `"none"` table staying on this computer's daemon. `remote_access: true` is the daemon's "Let other devices connect" for its own calls (`create_remote_access`: `remote.json` and the admins in `remote-admins`, mode 0600, https from a certificate and key, listening only while on, changed only over the socket), on `build_server` with the accounts in `accounts.db`, moved there once from the data's own file; `read_remote_access`, `remote_access_problem`. A table's `needs(method)` names the role a call needs from the network or MCP beyond the table's reach, such as an operator's for the calls that change something, refused with 403; every call runs with its request's viewer, which `current_viewer()` of `server/viewer_scope` reads, so the services can name who asked. |
15
16
  | `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
17
  | `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, a write a row makes reaching every window at once, 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. The page's `desktop` calls also give the computer's idle seconds (`get_idle_seconds`, from Electron's `powerMonitor`) `set_window_theme`, which the page calls so the window's own parts follow its theme, `get_data_paths` and `show_data_path`, which show this computer's database and backups folder in the file manager from Settings, and `save_text_file`, which asks where through the Save dialog, starting in Downloads (`save_dialog_options`); opening the window replaces a daemon another build left running, and a Flatpak keeps its profile in `~/.config/<id>` as the other builds do. 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
18
  | `app/window_size` | `fit_window_size(work_area)`: a first window of most of the screen's free area, between 960×640 and 1800×1200 and never past the screen; hand it to `run_desktop` as `default_size`. |
18
19
  | `app/seed` | A development database of an app's example data, made by its own calls: `seed_app_database(app, { file, reset, seed })` opens a fresh file with the app's schema and hands `seed` the app's calls, refusing a file already there without `reset` (which takes its `-wal` and `-shm` too) and the desktop app's real database in `~/.config/<id>` (`real_database_path`) whatever path leads there; `run_seed(app, seed)` is the seed script's whole command line, `<file> [--reset]`, read by `seed_target`. |
19
- | `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, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, 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`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row), and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. |
20
+ | `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, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, 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`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row), and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
20
21
  | `config/vite`, `config/electron_vite`, `config/vitest`, `config/electron_builder`, `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. `electron_builder_config({ id, name, app_id, comment, categories, link_scheme })` is the desktop app's AppImage and Flatpak bundle for electron-builder, the Flatpak keeping its data in `~/.config/<id>` as the other builds do. |
21
22
  | `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`. |
22
23
  | `idle_watch` | `step_idle_watch`: time away from the computer while something runs, such as a timer: each look at the idle seconds (the desktop's `get_idle_seconds`) moves the watch on, and once someone comes back it hands back the stretch away (`AwaySpan`) when it passed the threshold, a long gap between looks, as when the computer slept, counting as time away from the last look; `fresh_idle_watch` to start. |
@@ -68,6 +69,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
68
69
  | `phone_certificates` | `phone_certificates()`: the page's certificate calls on a phone, answered by X-App's Android plugin `XLibsCertificates`, which `cap sync` adds by itself: it reads a server's certificate and what is wrong with it, keeps the ones the user trusts for their own host and fingerprint, and installs a WebView client that lets the page's requests through to them, so `SyncSettings`, `SyncCertificatePrompt` and `TrustedCertificates` work on a phone as on the desktop. Forgetting one holds from the app's next start, since the WebView keeps a connection it already opened. An app that sets its own WebView client replaces that one. |
69
70
  | `phone_backups` | `phone_backups`: a phone app's `backups` in a folder the user picks once in its storage, where file managers and sync apps reach them, through X-App's Android plugin `XLibsBackupFolder`, which `cap sync` adds by itself; `restore` backs up first, swaps the phone database's bytes and saves, `folder_name` and `choose_folder` for the settings row, and daily backups wait quietly until a folder is picked. |
70
71
  | `phone_notices` | `keep_phone_notices`: notices handed to a phone ahead of time through Capacitor's local notifications, the app passing its own `LocalNotifications`, since a phone has no daemon; `refresh` takes back every pending notice and sets the soonest 64 of the next 14 days again, `ask_permission` asks once, `show` puts a notice up at once with no alarm (`isExactNotification: false`), so a notice for now never needs Android's exact-alarm leave or opens its settings screen, `exact: false` lets the notices set ahead ring inexactly too, and a tap hands the notice's `extra` back, such as a link to open. `notice_id` names a key as Android's number. |
72
+ | `web/remote_daemon` | A page's calls to a daemon or server on another computer with this device's token, as a phone that keeps no data makes them: `call_remote` (a refusal in the host's words, a 401 as `LoginNeeded`, no host chosen or out of reach in plain words), `remote_table` for every call under a path, and `follow_remote` reading the event stream over `fetch`, since EventSource sends no token, reconnecting until stopped (`parse_remote_event`). |
71
73
  | `phone_service` | `phone_service`: work a phone app keeps doing while it is closed, such as staying reachable, in an Android foreground service run by X-App's plugin `XLibsForegroundService`, which `cap sync` adds by itself: the service loads the app's own worker page (such as `worker.html` from its page files) in a WebView it owns, so the work outlives the app's window, a killed process (Android starts it again) and, with `start_at_boot`, a reboot; `start`, `stop`, `is_running`, `post` and `on_message` for the page, and `worker_host` for the worker's side, the messages crossing as JSON. The app declares the service and the boot receiver in its own manifest, with the `connectedDevice` foreground service permissions, as the module's opening comment shows, so no other app gets them. |
72
74
  | `phone_sockets` | `phone_sockets()`: UDP and TCP sockets for a `phone_service` worker, answered by X-App's Android side: `udp_open` (with `broadcast`, holding Android's multicast lock), `tcp_listen`, `tcp_connect` and `list_interfaces`; a TCP socket reads nothing until `read_line` takes one line or `start_reading` everything after, so `start_tls` can follow plain text in either TLS role, as KDE Connect's identity line does, with the app's PEM certificate and key, letting any peer through and handing back its certificate for the worker to pin; `pause` and `resume` for a slow reader, and `write` settling once sent. Events that arrive before a listener are kept for it. Needs `CHANGE_WIFI_MULTICAST_STATE` and `WAKE_LOCK` in the app's manifest; each event keeps the phone awake a few seconds so the worker can answer. |
73
75
  | `app/item_history`, `app/web/item_history` | A history for each kind of item made of rows across tables, such as a workout with its exercises and sets: `item_history_feature(kinds)` keeps each kind's versions (an `ItemLevel` list read by `read_snapshot` and put back by `apply_snapshot`, a deleted item coming back whole) and adds `list_item_history`, `list_recent_changes` and `restore_item_version` with their specs; on the page, `HistoryView` lists the latest changes, `HistoryButton` and `open_item_history` open one item's versions, each restorable after a confirm. |
@@ -89,6 +91,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
89
91
  | `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. |
90
92
  | `agent/commands` | `run_command` and `stream_command`: one shell command, in its own process group. |
91
93
  | `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; `start_line_program`, a program talked to in lines both ways while it runs, each whole line it prints handed on as it arrives (a character split across chunks kept whole), lines written to it until `end_input`, its group stopped by the signal; `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. |
94
+ | `agent/ssh_config` | `ssh_host_options(text, host, { home, local_user })`: what an OpenSSH client config such as `~/.ssh/config` says of one host (`host_name`, `user`, `port`, `identity_files` with `~`, `%h`, `%u` filled in), the first value of each keyword winning and Host patterns taking `*`, `?` and `!`, so a program reaching hosts over SSH honours its user's aliases as `ssh` and asyncssh do; `host_line_matches`. Match blocks and Include are not followed. |
92
95
  | `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`. |
93
96
  | `agent/claude_stream` | `start_claude_stream`: a Claude Code session driven over its stream-json protocol (`claude -p --input-format stream-json --output-format stream-json`) on `start_line_program`: `send_user` writes a message with the id the session echoes once it has read it, `control` sends a control request such as an interrupt or a change of permission mode and settles with the answer, a refusal or a timeout, the session's own requests such as `can_use_tool` go to `on_request` and are answered with `respond` (`allow_tool`, `deny_tool`), any not taken refused, and every other line is handed on with its JSON; `user_message_line`. |
94
97
  | `agent/git` | Git through `run_program`, never a shell: `git` throws git's own last words on an exit code not allowed; `default_branch` from origin's HEAD; `add_worktree` makes a worktree once at a path on its own branch, from the freshly fetched default branch or a `base`, or takes the branch when it exists; `list_worktrees`, the main checkout first with each head and branch; `reset_worktree` back to a commit, new files cleaned; `remove_worktree`, forced or not, with its branch; `read_raw_changes` and `read_numstat` for `git diff --raw -z` and `--numstat -z` (renames by their new path, binary files as null), `sum_numstat` and `untracked_files`. |
@@ -129,6 +132,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
129
132
  | `server/forge_webhook` | A forge's pushes: `is_signed` for GitHub's HMAC, Gitea's and Forgejo's signatures, a bearer token or GitLab's token; `event_of`, `parse_payload` and `read_push`, which names the branch and the repository URLs through the app's own normaliser; `AddressLockout` for an address that keeps failing to sign; `SeenDeliveries`, whose `is_replay` notices a signed body sent again within a day; `Debouncer` so a burst of pushes starts one run; `register_webhook_route`, which keeps the raw body the signature covers. |
130
133
  | `server/poller`, `server/runs` | `CyclePoller`: each watched item's cycle on its own timer, every `interval` or every `job_poll` while busy, with `refresh` and `soon`; `follow_run`: a long run's new output copied to a sink and the run finished once it has ended, with `describe` and `translate` hooks, an unreachable agent, a malformed or stuck poll reply, or a failing sink leaving it as `unreachable` to be followed again and only an agent that no longer knows the run ending it early, each follow taking at most `most_polls_per_follow` polls and about `most_output_per_follow_in_bytes`, and a `translate` that throws keeping the raw output. |
131
134
  | `server/github_webhook` | GitHub's webhooks on `forge_webhook`: `create_github_receiver` is a `register_webhook_route` receive that counts a delivery only when signed with X-Hub-Signature-256 under the app's secret (never a bearer token or another forge's header), turns away an address that keeps failing, answers a replayed delivery id without passing it on again, answers a ping and passes on only the repository and the pull requests, branches and issues an event names (`targets_of`, for `github_target_events`), each checked for shape and a fork's branch left out; `read_targets` for stored ones, `delivery_id_of`, `repository_of`, `is_repository_name`, `read_public_url` and `payload_url_of`. |
135
+ | `github_targets` | GitHub's webhook payloads as any part of an app reads them, in a page, a phone or Node: `targets_of(event, payload)` (the repository and the pull requests, branches and issues it names, each list at most 50, or null), `read_targets` for targets as stored, `repository_of`, `delivery_id_of`, `is_repository_name` and `github_target_events`; `server/github_webhook` passes them on. |
132
136
  | `server/events` | `EventStream`: server-sent events with a client id per page, a heartbeat, `announce_change(except_client_id)` so the page that made a change is not told, nameless or named events to all or chosen clients, headers set before the stream opens (such as `register_open_cors`'s) sent with it, and every stream ended with the app; `leading_cooldown` sends the first change at once and a burst's rest once per cooldown. |
133
137
  | `server/call_table` | `register_call_table`: a table of calls served as POST `<path>/<method>` with the arguments as a JSON list, as a desktop app's daemon and a web server both answer them, and by name as a JSON object for the calls whose argument names `params` gives, such as the app's `api_spec` (`api_spec`'s `NamedParams` is all it needs); a name the table lacks (its prototype's included) is refused, every answer goes as JSON so a string stays a string, a read is sent uncached, and `on_change` runs after any call `is_read_only` does not pass, with the caller's client id. |
134
138
  | `server/leases` | `Leases`: what a page holds open while it shows something costly, such as fast polling of a running job while its log is open, each lease ending when closed or once it goes unrenewed for a while. |
@@ -137,6 +141,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
137
141
  | `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`. |
138
142
  | `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`; `create_secret_file`, a new random secret, such as a webhook's, in a file only its owner reads (mode 0600, tightened over an older file), read back only when the app is asked for it, and `has_secret_file`, whether there is one without reading it out; 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. |
139
143
  | `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. |
144
+ | `server/viewer_scope` | `with_viewer(viewer, work)` runs work as a request's viewer, kept across its awaits, and `current_viewer()` reads it, so work a route hands off, such as a host table's call, can name who asked. Node only. |
140
145
  | `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. |
141
146
  | `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`. |
142
147
  | `server/mqtt_discovery` | Home Assistant's MQTT discovery: `slug` for topic levels and ids, `discovery_topic`, and `reading_traits`, the device class and unit a reading's name implies, such as `_bytes` or `_temp_c`. |
@@ -146,7 +151,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
146
151
  | `server/mcp_client` | `create_mcp_client({ name, version, limits })`: a client of the MCP servers a user adds (`McpServerTarget` from `mcp_servers`, whose shapes it also re-exports), 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. |
147
152
  | `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. |
148
153
  | `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. |
149
- | `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. |
154
+ | `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. `web/theme` also reads a server's `{ scheme, colors }` (`read_server_theme`), pins a scheme (`pinned_theme_choice`, whose `pinned` the Shell reads to leave out its theme row) and sets Halon tokens on the root (`apply_theme_colors`). |
150
155
  | `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. |
151
156
  | `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. |
152
157
  | `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. |
@@ -162,6 +167,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
162
167
  | `web/react/layout`, `badges`, `states` | `PageHeading` with a subtitle, icon, banner, actions and a `level` for inside dialogs and panels; panels (`Section`, with a `level` for one inside a dialog or under another heading), `GroupSections`, a panel per group from `group_items` headed by its name and count, facts, tiles, cards, tabs, `Crumbs` with chevrons between steps that link, run a function or mark where the reader is, `PathText` for a path shown with the same chevrons, steppers, `FormRow` for a form's labelled fields, `FormGroup` folding part of a form under a summary line such as "More options", `SettingsPage` with an `Outline` beside its sections, settings rows, `RowActions` and `moved` for ordered lists, `SelectionBar` for picked rows, their count with its thousands separated; badges, `StateBadge` naming each state's text and tone and `ToneBadge` showing the state's own name in its tone, chips in an item's own colour, dashed or removable, `ColorDot` and `StatusPill`, a state dot with text and an action; `use_resource` with its `status` (idle until `enabled`, loading, loaded, failed), a `watch` that reloads it quietly (bumps during a load fold into one load after it), and its loading states, `Loaded` going by the status so a null result shows its `empty` slot or the children. |
163
168
  | `web/react/sync_settings`, `backup_settings` | The settings rows every device shows: `SyncSettings`, the sync status, this device with its id and where others reach it, a pairing code to show when they can, each paired device with how it was last reached and Remove after a confirm, and a field to enter another device's code; `SyncButton`, the same status as a sidebar row with the changes waiting, syncing on a click or opening the settings when sync failed or no device is paired, and shown even then; `BackupSettings`, back up now, the daily schedule, and each backup to restore or delete after a confirm. |
164
169
  | `web/react/connections` | `ConnectionSettings`: the Connections section of Settings, every daemon the app can talk to with the one in use marked Connected, Connect to switch, Rename and Remove (after a confirm) for daemons on other hosts, and a form to add one by address, name and password, asking for the code when the daemon does and offering to trust a certificate the device refuses given `certificates`. |
170
+ | `web/react/remote_access_settings` | `RemoteAccessSettings`: "Let other devices connect" for a desktop daemon, with its state (listening where, or why not), address, port, https certificate and key files, Save, and the admins other devices sign in as, added with a password of 10 characters or more and removed after asking; `reach` words what they can do once in. The base app shows it under Settings → Other devices. |
165
171
  | `web/react/certificates` | `CertificateDialog`: what is wrong with a server's certificate in plain words, the certificate itself with its fingerprint, and Trust or Don't connect; `offer_certificate_trust` and `ask_to_trust_certificate` open it from anywhere, `with_certificate_prompt` wraps a fetch to ask and retry once, `SyncCertificatePrompt` asks whenever syncing with a paired device's https address fails over its certificate, and `TrustedCertificates` lists them to forget. |
166
172
  | `web/react/time` | `Age`: a time as how long ago, with the full stamp on hover; `use_now`, the time read again each minute; `use_countdown`, a countdown on a wall-clock deadline, so a page that slept shows the time really left, with start, stop, pause, resume and extend and a callback once at zero. |
167
173
  | `web/accounts` | `create_accounts_client`: the page's calls to `server/account_sign_in`, from the page itself or, given the server's address as `base`, from a desktop or phone app, which signs in with `sign_in_device` and keeps the token; `SignInRefused` says when only the code is missing; `pref(key)` and `set_pref(key, value, { keepalive })` read and write the signed-in user's own preferences (`AccountPref`). |
@@ -243,6 +249,21 @@ void render_app({ app, pages: [{ id: "plan", label: "Plan", view: () => <PlanVie
243
249
 
244
250
  A change an app needs in the base goes into the base, so no app keeps a copy of a base file.
245
251
 
252
+ An app whose work needs a computer, such as one that runs programs on checkouts, adds to that:
253
+
254
+ - **Host tables**: `host_tables: { stages: { hosts: ["server", "desktop"], api: stages_api } }` names calls the hosts
255
+ answer themselves; the services return `tables: { stages: { methods, elsewhere } }`. The page reaches them with
256
+ `host_table("stages")`, null where the host it works on does not answer them or does not let its viewer.
257
+ - **Notices**: `context.notify({ kind, title, body, key, url })` from the services; the desktop daemon shows it where
258
+ `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere shows it
259
+ by its own switch.
260
+ - **Other devices**: `remote_access: true` lets the daemon serve its calls and host tables on the network, and
261
+ `phone: "portal"` makes the phone a window onto a host chosen under Connections, keeping no data, its notices shown
262
+ through `phone_notifications` (Capacitor's `LocalNotifications`).
263
+ - **Routes**: `run_server(app, { routes })` and `run_daemon(app, env, { routes })` take routes of the app's own, such as
264
+ a webhook's, with their `open_paths`; `services().own` holds what they need. `run_desktop`'s `daemon_env` adds to the
265
+ daemon's environment, and the desktop bridge's `pick_folder` asks for a folder.
266
+
246
267
  The rest of an app's files are short calls into X-App too:
247
268
 
248
269
  - **Configs** sit in the app's `config/` folder: `tsconfig.<target>.json` extends `tsconfig.base.json` and
@@ -256,7 +277,7 @@ The rest of an app's files are short calls into X-App too:
256
277
  An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
257
278
  copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
258
279
  `pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
259
- data folder `/var/lib/<state_name>`; the desktop wrapper sets
280
+ data folder `/var/lib/<state_name>`, and `server_config`, such as `dir: { stages_folder = "${dir}/stages"; }`, adds the app's own keys to the server's config file; `sources`, such as `[ "src/core" "src/monitors" ]`, are more folders the server package runs from, and `programs`, such as `{ x-monitor-agent = "src/agent/main.ts"; }`, more commands it installs; the module's `settings` option adds keys of the machine's own to that file, winning over the module's; the desktop wrapper sets
260
281
  `<PREFIX>_LAUNCHER` so the login entry runs the installed command. `android_emulator_shell nixpkgs system app` adds an
261
282
  Android 36 emulator to the Android shell, with `<name>-emulator` to start it and `<name>-emulator-install` to build
262
283
  and open the app on it, never on a connected phone.
@@ -0,0 +1,12 @@
1
+ export interface SshHostOptions {
2
+ host_name: string | null;
3
+ user: string | null;
4
+ port: number | null;
5
+ identity_files: string[];
6
+ }
7
+ export interface SshConfigContext {
8
+ home: string;
9
+ local_user: string;
10
+ }
11
+ export declare function host_line_matches(patterns: readonly string[], host: string): boolean;
12
+ export declare function ssh_host_options(text: string, host: string, context: SshConfigContext): SshHostOptions;
@@ -0,0 +1,72 @@
1
+ // What an OpenSSH client config, such as ~/.ssh/config, says of one host: its real name, user, port and identity
2
+ // files, so a program connecting over SSH honours the aliases its user already set up, as ssh and asyncssh do. As
3
+ // OpenSSH reads it, the first value given for each keyword wins, and a Host line's patterns take * and ? and a !
4
+ // pattern that rules a host out. Match blocks and Include are not followed.
5
+ // ── Patterns ─────────────────────────────────────────────────────────────────
6
+ function pattern_matches(pattern, host) {
7
+ const expression = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*").replaceAll("?", ".");
8
+ return new RegExp(`^${expression}$`, "i").test(host);
9
+ }
10
+ // Whether a Host line's patterns take the host: one matches and no ! pattern rules it out.
11
+ export function host_line_matches(patterns, host) {
12
+ let matched = false;
13
+ for (const pattern of patterns) {
14
+ if (pattern.startsWith("!")) {
15
+ if (pattern_matches(pattern.slice(1), host))
16
+ return false;
17
+ }
18
+ else if (pattern_matches(pattern, host))
19
+ matched = true;
20
+ }
21
+ return matched;
22
+ }
23
+ // ── Reading ──────────────────────────────────────────────────────────────────
24
+ // A line's keyword and its arguments, quotes kept together, or null for a blank line or a comment.
25
+ function split_line(line) {
26
+ const text = line.trim();
27
+ if (text === "" || text.startsWith("#"))
28
+ return null;
29
+ const words = [...text.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2]);
30
+ const [first = "", ...rest] = words;
31
+ // "Keyword=value" and "Keyword = value" both name a value.
32
+ const equals = first.indexOf("=");
33
+ if (equals > 0)
34
+ return [first.slice(0, equals).toLowerCase(), [first.slice(equals + 1), ...rest].filter((word) => word !== "")];
35
+ return [first.toLowerCase(), rest.filter((word, index) => !(index === 0 && word === "="))];
36
+ }
37
+ function expand(path, host, context) {
38
+ const filled = path.replace(/%([%hu])/g, (_whole, code) => (code === "%" ? "%" : code === "h" ? host : context.local_user));
39
+ return filled === "~" ? context.home : filled.startsWith("~/") ? `${context.home}/${filled.slice(2)}` : filled;
40
+ }
41
+ // What the config's text says of the host given, the first value of each keyword winning.
42
+ export function ssh_host_options(text, host, context) {
43
+ const options = { host_name: null, user: null, port: null, identity_files: [] };
44
+ // Lines before any Host or Match line apply to every host.
45
+ let applies = true;
46
+ for (const line of text.split(/\r?\n/)) {
47
+ const split = split_line(line);
48
+ if (split === null)
49
+ continue;
50
+ const [keyword, args] = split;
51
+ if (keyword === "host") {
52
+ applies = host_line_matches(args, host);
53
+ continue;
54
+ }
55
+ if (keyword === "match") {
56
+ applies = false;
57
+ continue;
58
+ }
59
+ if (!applies || args.length === 0)
60
+ continue;
61
+ const value = args[0];
62
+ if (keyword === "hostname" && options.host_name === null)
63
+ options.host_name = value.replaceAll("%h", host);
64
+ else if (keyword === "user" && options.user === null)
65
+ options.user = value;
66
+ else if (keyword === "port" && options.port === null && /^\d+$/.test(value))
67
+ options.port = Number(value);
68
+ else if (keyword === "identityfile" && value.toLowerCase() !== "none")
69
+ options.identity_files.push(expand(value, options.host_name ?? host, context));
70
+ }
71
+ return options;
72
+ }
@@ -1,5 +1,6 @@
1
1
  import type { App } from "./define.ts";
2
- import { type StartServices } from "./services.ts";
2
+ import { type AppNotice } from "./protocol.ts";
3
+ import { type AppRoutes, type StartServices } from "./services.ts";
3
4
  export interface DaemonOptions {
4
5
  database_path: string;
5
6
  socket_path: string;
@@ -10,6 +11,9 @@ export interface DaemonOptions {
10
11
  services?: StartServices;
11
12
  declared_file?: string;
12
13
  icon_path?: string | null;
14
+ routes?: AppRoutes;
15
+ web_folder?: string;
16
+ show_notice?: (notice: AppNotice) => void;
13
17
  }
14
18
  export interface Daemon {
15
19
  shut_down: () => Promise<void>;
@@ -17,4 +21,6 @@ export interface Daemon {
17
21
  export declare function start_daemon(app: App, options: DaemonOptions): Promise<Daemon | null>;
18
22
  export declare function run_daemon(app: App, env?: NodeJS.ProcessEnv, extra?: {
19
23
  services?: StartServices;
24
+ routes?: AppRoutes;
25
+ web_folder?: URL;
20
26
  }): Promise<void>;
@@ -5,7 +5,11 @@
5
5
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
6
  import { hostname } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
+ import { DatabaseSync } from "node:sqlite";
9
+ import { fileURLToPath } from "node:url";
8
10
  import fastify from "fastify";
11
+ import { Notifier } from "../agent/desktop_notify.js";
12
+ import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
9
13
  import { create_certificate_trust } from "../certificates.js";
10
14
  import { create_local_mcp } from "../electron/mcp.js";
11
15
  import { DaemonRunningError, daemon_socket_path, listen_on_socket } from "../local_daemon.js";
@@ -15,9 +19,11 @@ import { register_error_replies, register_lenient_json_body } from "../server/re
15
19
  import { file_sync_storage } from "../sync_file_storage.js";
16
20
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
17
21
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
22
+ import { mcp_tools, register_host_tables } from "./host_tables.js";
23
+ import { notice_event, notice_is_on, read_desktop_settings } from "./protocol.js";
24
+ import { create_remote_access } from "./remote_access.js";
18
25
  import { declared_file_of, no_services, side_databases } from "./services.js";
19
- import { read_desktop_settings } from "./protocol.js";
20
- import { call_body_limit, data_change_text, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
26
+ import { build_server, call_body_limit, data_change_text, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
21
27
  // ── Daemon ───────────────────────────────────────────────────────────────────
22
28
  // Answers on the socket and starts sync; null when another daemon on the same database already answers.
23
29
  export async function start_daemon(app, options) {
@@ -29,6 +35,8 @@ export async function start_daemon(app, options) {
29
35
  const opened = open_app_database(app, database_path, join(profile, "backups"));
30
36
  // Every window's event stream, told when the data changed or sync's status moved.
31
37
  const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
38
+ // The app's services once started, which answer its host tables and hear of sync's changes.
39
+ let services = no_services;
32
40
  // Server certificates the user trusted, such as a home server's self-signed one, handed to Node's own fetch.
33
41
  const certificates = create_certificate_trust({ file: join(profile, "trusted-certificates.json"), use_in_node: true });
34
42
  // Off until "Let other devices connect" is turned on; then other devices reach this computer's sync on its port.
@@ -41,7 +49,10 @@ export async function start_daemon(app, options) {
41
49
  storage: file_sync_storage({ file: join(profile, "sync-peers.json"), back_up_before_replace: opened.back_up }),
42
50
  device_name: `${app.name} on ${hostname()}`,
43
51
  addresses: () => listening.addresses(),
44
- on_remote_change: () => changes.announce_change(),
52
+ on_remote_change: () => {
53
+ changes.announce_change();
54
+ services.after_remote_change?.();
55
+ },
45
56
  on_status: (status) => changes.send(JSON.stringify(status), { event: "sync_status" }),
46
57
  });
47
58
  // ── Desktop settings ───────────────────────────────────────────────
@@ -58,18 +69,61 @@ export async function start_daemon(app, options) {
58
69
  stop_daemon: () => void setTimeout(() => void shut_down(), 0),
59
70
  set_window_in_front: (in_front) => void (window_in_front = in_front === true),
60
71
  };
72
+ const services_now = () => services;
73
+ // This computer's own AI clients reach the host tables too, as callers from elsewhere do, so what only this
74
+ // computer's user may change stays refused.
75
+ const local_tools = mcp_tools(app, { kind: "desktop", from_network: true, is_admin: () => true, has_role: () => true }, services_now, opened.database, () => changes.announce_change());
61
76
  // Off until turned on in Settings; a change made through it reaches the open windows and syncs like any other.
62
77
  const local_mcp = app.local_mcp
63
78
  ? create_local_mcp({
64
79
  name: app.id,
65
80
  version: app.version,
66
81
  instructions: app.instructions,
67
- api: app.mcp.api,
82
+ api: local_tools.api,
68
83
  is_read_only: app.is_read_only,
69
84
  page_only: app.mcp.page_only,
70
85
  settings_file: join(profile, "mcp.json"),
71
86
  default_port: app.local_mcp.default_port,
72
- call: (method, args) => app.mcp.call(opened.database, () => changes.announce_change(), method, args),
87
+ call: (method, args) => local_tools.call(method, args),
88
+ })
89
+ : null;
90
+ // ── Notices ────────────────────────────────────────────────────────
91
+ const notifier = new Notifier({ app_name: app.name, icons: options.icon_path ? { app: options.icon_path } : {}, on_error: (message) => console.error(`${app.id} notifications: ${message}`) });
92
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
93
+ // Shown here where this computer's switch for its kind is on, and sent to every window, for those working on this
94
+ // daemon from another computer to show there.
95
+ function notify(notice) {
96
+ if (notice_is_on(notice.kind, read_desktop()))
97
+ show_notice(notice);
98
+ changes.send(JSON.stringify(notice), { event: notice_event });
99
+ }
100
+ // ── Other devices ──────────────────────────────────────────────────
101
+ // Accounts that sign other devices in are a file of their own beside the data, as on the server.
102
+ const accounts_database = app.remote_access ? new DatabaseSync(join(profile, "accounts.db")) : null;
103
+ // An older version kept them in the data's own file; they move out once, after a backup of the file as it was.
104
+ if (accounts_database && holds_accounts(opened.database()) && !holds_accounts(accounts_database)) {
105
+ await opened.back_up();
106
+ move_accounts(opened.database(), accounts_database);
107
+ }
108
+ // The daemon runs as out/main/daemon.js, beside the desktop app's built page.
109
+ const web_folder = options.web_folder ?? join(dirname(process.argv[1] ?? "."), "../renderer");
110
+ // Off until turned on; then other devices sign in as an admin this computer added and reach the same calls and the
111
+ // host tables but those kept to this computer.
112
+ const remote = accounts_database
113
+ ? create_remote_access({
114
+ profile,
115
+ default_port: app.ports.server,
116
+ build: (admins, https) => build_server(app, {
117
+ database: opened.database,
118
+ accounts: new AccountStore({ database: accounts_database, app_name: app.name, declared: admins, ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}) }),
119
+ web_folder,
120
+ changes,
121
+ backup_methods: opened.backup_methods,
122
+ kind: "desktop",
123
+ services: services_now,
124
+ ...(options.routes ? { routes: options.routes } : {}),
125
+ ...(https ? { https } : {}),
126
+ }),
73
127
  })
74
128
  : null;
75
129
  // ── Calls ──────────────────────────────────────────────────────────
@@ -89,16 +143,21 @@ export async function start_daemon(app, options) {
89
143
  if (local_mcp)
90
144
  register_call_table(api, "/local_mcp", local_mcp.methods, { is_read_only });
91
145
  register_call_table(api, "/daemon", daemon_methods, { is_read_only, on_change: tell_others });
146
+ if (remote)
147
+ register_call_table(api, "/remote", remote.methods, { is_read_only });
148
+ // This computer's own window reaches every host table, those kept to it included.
149
+ const reach = { kind: "desktop", from_network: false, is_admin: () => true, has_role: () => true };
150
+ register_host_tables(api, app, reach, services_now, changes);
92
151
  }, { prefix: "/api" });
93
152
  // ── Lifecycle ──────────────────────────────────────────────────────
94
153
  let stopping = null;
95
154
  let unused_timer;
96
155
  const sides = side_databases(database_path);
97
- let services = no_services;
98
156
  function shut_down() {
99
157
  stopping ??= (async () => {
100
158
  clearInterval(unused_timer);
101
159
  stop_watching();
160
+ await remote?.stop();
102
161
  await services.stop();
103
162
  sync.stop();
104
163
  await local_mcp?.stop();
@@ -106,6 +165,7 @@ export async function start_daemon(app, options) {
106
165
  await listening.stop();
107
166
  sides.close_all();
108
167
  opened.close();
168
+ accounts_database?.close();
109
169
  options.on_stopped();
110
170
  })();
111
171
  return stopping;
@@ -116,6 +176,7 @@ export async function start_daemon(app, options) {
116
176
  catch (error) {
117
177
  await daemon.close();
118
178
  opened.close();
179
+ accounts_database?.close();
119
180
  // Another daemon on this database got there first, which is all that was asked for.
120
181
  if (error instanceof DaemonRunningError)
121
182
  return null;
@@ -132,17 +193,30 @@ export async function start_daemon(app, options) {
132
193
  profile,
133
194
  device_name: `${app.name} on ${hostname()}`,
134
195
  config: {},
196
+ config_file: null,
197
+ declared_tokens: () => [],
198
+ reread_declared_tokens: () => undefined,
135
199
  plugins_folder: join(profile, "plugins"),
136
200
  declared_file: options.declared_file ?? `/etc/${app.id}/declared.json`,
137
201
  announce: (client_id) => changes.announce_change(client_id),
202
+ wrote: () => {
203
+ app.record_writes(opened.database());
204
+ changes.announce_change();
205
+ },
138
206
  emit: (event, data) => changes.send(JSON.stringify(data), { event }),
139
207
  side_database: sides.open,
140
208
  back_up: opened.back_up,
141
209
  window_in_front: () => window_in_front,
142
210
  icon_path: options.icon_path ?? null,
211
+ notify,
143
212
  });
144
- opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
145
213
  }
214
+ // Devices signed in from elsewhere follow the restored data too.
215
+ opened.on_restore({ before: () => services.before_restore?.(), after: async () => {
216
+ await services.after_restore?.();
217
+ void remote?.restart();
218
+ } });
219
+ await remote?.restart();
146
220
  // Without "Keep running in the background", the daemon stops a while after its last window has gone.
147
221
  let unused_since = Date.now();
148
222
  unused_timer = setInterval(() => {
@@ -165,7 +239,7 @@ export async function run_daemon(app, env = process.env, extra = {}) {
165
239
  // A run on another database has a socket of its own.
166
240
  const socket_path = env[`${app.env_prefix}_SOCKET`] || daemon_socket_path({ app: app.id, data_file: database_path });
167
241
  try {
168
- const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0), declared_file: declared_file_of(app, env), icon_path: env[`${app.env_prefix}_ICON`] ?? null, ...extra });
242
+ const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0), declared_file: declared_file_of(app, env), icon_path: env[`${app.env_prefix}_ICON`] ?? null, ...(extra.services ? { services: extra.services } : {}), ...(extra.routes ? { routes: extra.routes } : {}), ...(extra.web_folder ? { web_folder: fileURLToPath(extra.web_folder) } : {}) });
169
243
  // Another daemon on this database got there first, which is all that was asked for.
170
244
  if (!daemon)
171
245
  process.exit(0);
@@ -7,12 +7,14 @@ import { type ConnectionMethods } from "../connection_protocol.ts";
7
7
  import { type Bridge } from "../electron/bridge.ts";
8
8
  import { type EventsBridge } from "../electron/events.ts";
9
9
  import type { History } from "../history.ts";
10
+ import type { ScopeSpec } from "../server/declared_tokens.ts";
10
11
  import { type LocalMcpMethods } from "../local_mcp_protocol.ts";
11
12
  import { type SettingSpec, type SettingsMethods, type SettingsStore, type SettingsStoreOptions } from "../settings.ts";
12
13
  import { type MigrationStep, type SqlDatabase } from "../sql.ts";
13
14
  import { type SyncedTable } from "../sync_engine.ts";
14
15
  import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
15
- import { type DataChange, type DesktopMethods, type DesktopSettingSpec } from "./protocol.ts";
16
+ import { type RemoteAccessMethods } from "../remote_access_protocol.ts";
17
+ import { type DataChange, type DesktopMethods, type DesktopSettingSpec, type HostAbilityMethods } from "./protocol.ts";
16
18
  export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
17
19
  export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune"> & Partial<Pick<History<unknown>, "drop_triggers">>;
18
20
  export interface Feature<Methods extends Record<string, StoreMethod> = Record<string, StoreMethod>> {
@@ -28,6 +30,14 @@ export interface Feature<Methods extends Record<string, StoreMethod> = Record<st
28
30
  }
29
31
  export declare function define_feature<Methods extends Record<string, StoreMethod>>(feature: Feature<Methods>): Feature<Methods>;
30
32
  export declare function is_read_only(method: string): boolean;
33
+ export type HostKind = "server" | "desktop";
34
+ export interface HostTable<Methods = Record<string, (...args: never[]) => unknown>> {
35
+ api: ApiSpec<Methods>;
36
+ hosts: readonly HostKind[];
37
+ network?: "admin" | "any" | "none";
38
+ needs?: (method: string) => string | null | undefined;
39
+ }
40
+ declare const host_table_route: (name: string) => string;
31
41
  type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Both) => void ? Both : never;
32
42
  type Bound<Methods> = {
33
43
  [Name in keyof Methods]: Methods[Name] extends (database: SqlDatabase, ...args: infer Args) => infer Result ? (...args: Args) => Result : never;
@@ -68,6 +78,16 @@ export interface AppOptions<Features extends readonly Feature[]> {
68
78
  default_port: number;
69
79
  };
70
80
  synced_theme?: boolean;
81
+ host_tables?: Readonly<Record<string, HostTable>>;
82
+ remote_access?: boolean;
83
+ phone?: "device" | "portal";
84
+ roles?: readonly string[];
85
+ sync?: boolean;
86
+ declared_tokens?: {
87
+ key: string;
88
+ scopes: Record<string, ScopeSpec>;
89
+ limit_key?: string;
90
+ };
71
91
  }
72
92
  export declare const base_setting_defaults: {
73
93
  history_days: number;
@@ -96,6 +116,9 @@ export interface AppBridges<Methods extends Record<keyof Methods, (...args: neve
96
116
  connections: Bridge<ConnectionMethods>;
97
117
  local_mcp: Bridge<LocalMcpMethods>;
98
118
  events: EventsBridge<AppEvents>;
119
+ host: Bridge<HostAbilityMethods>;
120
+ remote_access: Bridge<RemoteAccessMethods>;
121
+ host_tables: Readonly<Record<string, Bridge<Record<string, (...args: never[]) => unknown>>>>;
99
122
  }
100
123
  export declare function define_app<const Features extends readonly Feature[]>(options: AppOptions<Features>): {
101
124
  id: string;
@@ -130,6 +153,15 @@ export declare function define_app<const Features extends readonly Feature[]>(op
130
153
  default_port: number;
131
154
  };
132
155
  synced_theme?: boolean;
156
+ remote_access?: boolean;
157
+ phone?: "device" | "portal";
158
+ roles?: readonly string[];
159
+ sync?: boolean;
160
+ declared_tokens?: {
161
+ key: string;
162
+ scopes: Record<string, ScopeSpec>;
163
+ limit_key?: string;
164
+ };
133
165
  features: readonly Feature<Record<string, StoreMethod>>[];
134
166
  settings_store: SettingsStore;
135
167
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -164,6 +196,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
164
196
  is_read_only: typeof is_read_only;
165
197
  page_only: PageOnlyCalls;
166
198
  bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
199
+ record_writes: (database: SqlDatabase) => void;
167
200
  mcp: {
168
201
  api: ApiSpec<Record<string, StoreMethod>>;
169
202
  page_only: PageOnlyCalls;
@@ -174,6 +207,10 @@ export declare function define_app<const Features extends readonly Feature[]>(op
174
207
  adopt_backup_schedule: (database: SqlDatabase, saved: unknown) => void;
175
208
  backup_methods: (kept: Restorable, database: () => SqlDatabase, check_schedule: () => void) => BackupMethods;
176
209
  bridges: AppBridges<Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>>;
210
+ host_tables: Readonly<Record<string, HostTable<Record<string, (...args: never[]) => unknown>>>>;
211
+ tables_on: (kind: HostKind, from_network: boolean) => string[];
212
+ table_of_call: (method: string, kind: HostKind) => string | null;
213
+ host_table_path: typeof host_table_route;
177
214
  };
178
215
  type ErasedCalls = any;
179
216
  export type App = Omit<ReturnType<typeof define_app<readonly Feature[]>>, "bridges" | "bind_methods" | "api_spec" | "method_names"> & {