local-llm-gateway 0.1.1 → 0.3.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/CHANGELOG.md +31 -0
- package/README.md +30 -2
- package/cli/dist/api/client.js +14 -0
- package/cli/dist/commands/open.js +41 -0
- package/cli/dist/commands/phone.js +85 -0
- package/cli/dist/commands/start.js +3 -1
- package/cli/dist/index.js +19 -0
- package/cli/dist/qr.js +64 -0
- package/cli/dist/repl.js +1 -1
- package/dist/src/api/endpoints.js +65 -1
- package/dist/src/api/openapi.js +9 -2
- package/dist/src/api/schemas.js +26 -0
- package/dist/src/app.js +42 -2
- package/dist/src/config.js +9 -0
- package/dist/src/lib/network.js +129 -0
- package/dist/src/lib/web-root.js +16 -0
- package/dist/src/plugins/auth.js +39 -8
- package/dist/src/plugins/web-guard.js +37 -0
- package/dist/src/routes/web-page.js +43 -0
- package/dist/src/routes/web-session.js +108 -0
- package/dist/src/server.js +10 -3
- package/dist/src/services/web-session.service.js +85 -0
- package/dist/src/storage/postgres/index.js +2 -0
- package/dist/src/storage/postgres/schema.js +24 -0
- package/dist/src/storage/postgres/web-sessions.js +72 -0
- package/dist/src/storage/sqlite/index.js +2 -0
- package/dist/src/storage/sqlite/schema.js +23 -0
- package/dist/src/storage/sqlite/web-sessions.js +76 -0
- package/dist/web/assets/index-BH2EiFDE.css +1 -0
- package/dist/web/assets/index-C52qddcS.js +24 -0
- package/dist/web/index.html +15 -0
- package/drizzle/0003_pale_spectrum.sql +24 -0
- package/drizzle/0004_married_frog_thor.sql +3 -0
- package/drizzle/meta/0003_snapshot.json +735 -0
- package/drizzle/meta/0004_snapshot.json +755 -0
- package/drizzle/meta/_journal.json +14 -0
- package/drizzle/sqlite/0001_blushing_jack_murdock.sql +24 -0
- package/drizzle/sqlite/0002_dry_the_fallen.sql +3 -0
- package/drizzle/sqlite/meta/0001_snapshot.json +698 -0
- package/drizzle/sqlite/meta/0002_snapshot.json +721 -0
- package/drizzle/sqlite/meta/_journal.json +14 -0
- package/package.json +18 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 (2026-11-25)
|
|
4
|
+
|
|
5
|
+
- **Use it from your phone, no app.** `llm phone` (or **Phones & devices** in the page on
|
|
6
|
+
the computer) shows a QR code; the phone scans it and opens the same chat, signed in. Two
|
|
7
|
+
ways to connect: the same Wi-Fi (`llm start --phone`; not encrypted, home only) or
|
|
8
|
+
Tailscale (`tailscale serve --bg 3000`; encrypted, anywhere).
|
|
9
|
+
- **See and remove devices.** `llm devices` and the page list every signed-in browser and
|
|
10
|
+
phone; removing one signs it out at once. Only the computer running the assistant can
|
|
11
|
+
pair phones or remove other devices: a phone can never add more phones.
|
|
12
|
+
- An `llm open` link now works only on the computer itself, so a leaked link is useless.
|
|
13
|
+
- From the network, single-user mode serves only the page, sign-in and the API;
|
|
14
|
+
`/metrics`, `/readyz` and `/openapi.json` stay on the computer.
|
|
15
|
+
- Phone-friendly page: the conversation list becomes a drawer, room for the home bar.
|
|
16
|
+
- `llm phone` draws a QR code phones can read in macOS Terminal (no font characters when
|
|
17
|
+
the window is big enough); `llm phone --browser` shows it on the web page instead.
|
|
18
|
+
- Fixed: chats didn't show in Chrome (Android phones). Fixed: the page was cached for a
|
|
19
|
+
year, so browsers could keep an old version after an update.
|
|
20
|
+
|
|
21
|
+
## 0.2.0 (2026-11-24)
|
|
22
|
+
|
|
23
|
+
- **Web chat.** `llm open` opens the assistant in your browser at `http://localhost:3000`,
|
|
24
|
+
already signed in: conversations, streaming answers with Stop, rename, delete, a model
|
|
25
|
+
picker, a Back up button, and "Branch from here" on any message. Problems show as a plain
|
|
26
|
+
banner with what to do. Light and dark mode.
|
|
27
|
+
- Browser sign-in is a one-time link (60 seconds, works once) exchanged for an HttpOnly,
|
|
28
|
+
SameSite=Strict session cookie. Other websites can't use it: the gateway checks the Host
|
|
29
|
+
and Origin of every cookie request, and the page runs under a strict Content-Security-
|
|
30
|
+
Policy. Model answers are shown as text, never as HTML. API keys work as before.
|
|
31
|
+
- The gateway waits up to a second for Redis at startup, so rate limits apply from the
|
|
32
|
+
first request (server mode).
|
|
33
|
+
|
|
3
34
|
## 0.1.1 (2026-11-20)
|
|
4
35
|
|
|
5
36
|
- `npx local-llm-gateway` now starts the assistant (0.1.0 said "could not determine
|
package/README.md
CHANGED
|
@@ -24,10 +24,15 @@ get, for example `ollama pull qwen3:8b`. `llm start` keeps running in that windo
|
|
|
24
24
|
stops it.
|
|
25
25
|
|
|
26
26
|
```bash
|
|
27
|
-
# 3. In a second window
|
|
27
|
+
# 3. In a second window: chat in your browser...
|
|
28
|
+
llm open
|
|
29
|
+
# ...or in the terminal
|
|
28
30
|
llm chat "hello"
|
|
29
31
|
```
|
|
30
32
|
|
|
33
|
+
`llm open` opens the chat page at `http://localhost:3000`, already signed in. Only your
|
|
34
|
+
browser on this computer can use that sign-in: other websites can't.
|
|
35
|
+
|
|
31
36
|
To try it without installing: `npx local-llm-gateway` starts the assistant, and
|
|
32
37
|
`npx -p local-llm-gateway llm chat "hello"` chats from a second window.
|
|
33
38
|
|
|
@@ -44,7 +49,8 @@ fix whatever is wrong.
|
|
|
44
49
|
|
|
45
50
|
| Command | What it does |
|
|
46
51
|
| --- | --- |
|
|
47
|
-
| `llm
|
|
52
|
+
| `llm open` | Chat in your browser (opens already signed in) |
|
|
53
|
+
| `llm chat` | Talk in the terminal. `llm chat "question"` asks once |
|
|
48
54
|
| `llm ls`, `llm show <id>`, `llm resume <id>` | Your conversations |
|
|
49
55
|
| `llm fork <id>` | Try another way from an earlier answer |
|
|
50
56
|
| `llm models` | Downloaded models; `*` marks the one in use |
|
|
@@ -52,6 +58,28 @@ fix whatever is wrong.
|
|
|
52
58
|
| `llm backup` | Save a copy of all conversations |
|
|
53
59
|
| `llm restore <file>` | How to put a backup back |
|
|
54
60
|
| `llm stats` | Speed and token use |
|
|
61
|
+
| `llm phone` | Connect a phone: shows a QR code to scan |
|
|
62
|
+
| `llm devices` | Signed-in browsers and phones; `llm devices revoke <id>` removes one |
|
|
63
|
+
|
|
64
|
+
### Use it from your phone
|
|
65
|
+
|
|
66
|
+
No app needed: the phone opens the same chat page in its browser, and your conversations
|
|
67
|
+
are the same on both.
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
llm start --phone # also lets phones on this Wi-Fi connect
|
|
71
|
+
llm phone # shows a QR code: scan it with the phone's camera (works once, 5 minutes)
|
|
72
|
+
llm phone --browser # the same QR code on a web page, if the terminal one won't scan
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- **Same Wi-Fi** (at home): the connection is not encrypted, so use it only on a Wi-Fi you
|
|
76
|
+
trust. Guest and many office networks block devices from reaching each other.
|
|
77
|
+
- **Anywhere, encrypted**: install [Tailscale](https://tailscale.com) on the computer and the
|
|
78
|
+
phone, then run `tailscale serve --bg 3000`. `llm phone` then uses the Tailscale address.
|
|
79
|
+
The assistant itself never opens a port on your network.
|
|
80
|
+
- **Lost a phone, or someone left?** `llm devices revoke <id>`, or **Phones & devices** in the
|
|
81
|
+
page on the computer. It is signed out at once. A phone can never pair other phones.
|
|
82
|
+
- The computer has to be awake and running the assistant.
|
|
55
83
|
|
|
56
84
|
### Where your data is
|
|
57
85
|
|
package/cli/dist/api/client.js
CHANGED
|
@@ -85,6 +85,20 @@ export class ApiClient {
|
|
|
85
85
|
me() {
|
|
86
86
|
return this.json('GET', '/v1/me');
|
|
87
87
|
}
|
|
88
|
+
/** A one-time code that signs the web page in (60 seconds, works once). API key only. */
|
|
89
|
+
webCode(purpose = 'open') {
|
|
90
|
+
return this.json('POST', '/v1/web/codes', { purpose });
|
|
91
|
+
}
|
|
92
|
+
/** How a phone can reach this gateway (Wi-Fi addresses, Tailscale), and whether we may pair. */
|
|
93
|
+
phoneInfo() {
|
|
94
|
+
return this.json('GET', '/v1/web/phone');
|
|
95
|
+
}
|
|
96
|
+
devices() {
|
|
97
|
+
return this.json('GET', '/v1/web/sessions');
|
|
98
|
+
}
|
|
99
|
+
revokeDevice(id) {
|
|
100
|
+
return this.json('DELETE', `/v1/web/sessions/${encodeURIComponent(id)}`);
|
|
101
|
+
}
|
|
88
102
|
/** Asks the gateway to write a checked backup into its data folder. Single-user mode. */
|
|
89
103
|
backup() {
|
|
90
104
|
return this.json('POST', '/v1/backup');
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { loadConfig } from '../config.js';
|
|
3
|
+
import { out } from '../format.js';
|
|
4
|
+
import { getClient } from './shared.js';
|
|
5
|
+
/** How to open a URL in the default browser on this system. */
|
|
6
|
+
export function browserCommand(url, platform = process.platform) {
|
|
7
|
+
if (platform === 'darwin')
|
|
8
|
+
return ['open', [url]];
|
|
9
|
+
if (platform === 'win32')
|
|
10
|
+
return ['cmd', ['/c', 'start', '""', url]];
|
|
11
|
+
return ['xdg-open', [url]];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Opens the web chat, already signed in: asks the gateway (with this CLI's key) for a
|
|
15
|
+
* one-time code and opens `<gateway>/#code=...`. The code sits after `#`, so it never
|
|
16
|
+
* reaches a server log; the page exchanges it once for a session cookie.
|
|
17
|
+
*/
|
|
18
|
+
export async function openCommand(opts) {
|
|
19
|
+
const { baseUrl } = loadConfig();
|
|
20
|
+
const { code } = await getClient().webCode();
|
|
21
|
+
// show=phone: the page opens "Phones & devices", which shows the pairing QR as an image.
|
|
22
|
+
const url = `${baseUrl}/#code=${code}${opts.show ? `&show=${opts.show}` : ''}`;
|
|
23
|
+
if (!opts.print) {
|
|
24
|
+
const [cmd, args] = browserCommand(url);
|
|
25
|
+
const opened = await new Promise((done) => {
|
|
26
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
27
|
+
child.on('error', () => done(false));
|
|
28
|
+
child.on('spawn', () => {
|
|
29
|
+
child.unref();
|
|
30
|
+
done(true);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
if (opened) {
|
|
34
|
+
console.log(opts.show === 'phone' ? 'Showing the QR code in your browser ("Phones & devices").' : `Opening the assistant in your browser: ${baseUrl}`);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
console.log('Open this link to sign in (it works once, within 60 seconds):');
|
|
39
|
+
console.log(` ${url}`);
|
|
40
|
+
console.log(out.dim('Then the page stays signed in for 30 days of use. To sign in again later: llm open'));
|
|
41
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { terminalQr } from '../qr.js';
|
|
2
|
+
import { openCommand } from './open.js';
|
|
3
|
+
import { loadConfig } from '../config.js';
|
|
4
|
+
import { CliError } from '../errors.js';
|
|
5
|
+
import { out, relativeTime, shortId } from '../format.js';
|
|
6
|
+
import { getClient } from './shared.js';
|
|
7
|
+
/** Where a phone should go: Tailscale (HTTPS, anywhere) first, else the Wi-Fi address. */
|
|
8
|
+
export function phoneUrl(info) {
|
|
9
|
+
if (info.tailscale.serving && info.tailscale.url)
|
|
10
|
+
return { url: info.tailscale.url, via: 'tailscale' };
|
|
11
|
+
if (info.wifi.listening && info.wifi.urls[0])
|
|
12
|
+
return { url: info.wifi.urls[0], via: 'wifi' };
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
/** What to do when no phone can reach the assistant yet. */
|
|
16
|
+
export function howToEnable(info, port) {
|
|
17
|
+
const tailscale = info.tailscale.name
|
|
18
|
+
? `Tailscale is installed here (${info.tailscale.name}). Run: tailscale serve --bg ${port}`
|
|
19
|
+
: 'Install Tailscale on this computer and your phone (tailscale.com), sign in to both, then run: tailscale serve --bg ' + port;
|
|
20
|
+
return [
|
|
21
|
+
"Phones can't reach the assistant yet. Choose one:",
|
|
22
|
+
'',
|
|
23
|
+
' Same Wi-Fi (at home; the connection is not encrypted):',
|
|
24
|
+
' stop the assistant (Ctrl+C), then start it with: llm start --phone',
|
|
25
|
+
'',
|
|
26
|
+
' Anywhere, encrypted (Tailscale):',
|
|
27
|
+
` ${tailscale}`,
|
|
28
|
+
'',
|
|
29
|
+
'Then run llm phone again.',
|
|
30
|
+
].join('\n');
|
|
31
|
+
}
|
|
32
|
+
export async function phoneCommand(opts) {
|
|
33
|
+
const client = getClient();
|
|
34
|
+
const info = await client.phoneInfo();
|
|
35
|
+
if (!info.canPair) {
|
|
36
|
+
throw new CliError("Phones can only be connected from the computer running the assistant.");
|
|
37
|
+
}
|
|
38
|
+
const target = phoneUrl(info);
|
|
39
|
+
if (!target)
|
|
40
|
+
throw new CliError(howToEnable(info, Number(new URL(loadConfig().baseUrl).port || 80)));
|
|
41
|
+
// The page's "Phones & devices" makes its own pairing code and shows the QR as an image.
|
|
42
|
+
if (opts.browser)
|
|
43
|
+
return openCommand({ show: 'phone' });
|
|
44
|
+
const { code } = await client.webCode('pair');
|
|
45
|
+
const link = `${target.url}/#code=${code}`;
|
|
46
|
+
if (opts.print)
|
|
47
|
+
return void console.log(link);
|
|
48
|
+
const qr = terminalQr(link, { columns: process.stdout.columns, rows: process.stdout.rows });
|
|
49
|
+
console.log(qr.text);
|
|
50
|
+
console.log("Scan this with your phone's camera. It works once, for 5 minutes.");
|
|
51
|
+
if (qr.mode === 'compact') {
|
|
52
|
+
// Some terminals (macOS Terminal with many fonts) leave thin gaps between lines here,
|
|
53
|
+
// which phones can't read. The sharp form has no such gaps but needs a bigger window.
|
|
54
|
+
const now = `${process.stdout.columns}x${process.stdout.rows}`;
|
|
55
|
+
console.log(out.yellow(`This window is small (${now}), so the code may not scan. Either:`));
|
|
56
|
+
console.log(out.yellow(` make the window at least ${qr.needs.columns}x${qr.needs.rows} (or shrink the text with Cmd -) and run llm phone again,`));
|
|
57
|
+
console.log(out.yellow(' or show it in your browser: llm phone --browser'));
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
console.log(out.dim("Won't scan? Show it in your browser: llm phone --browser"));
|
|
61
|
+
}
|
|
62
|
+
console.log(out.dim(` ${target.url} (${target.via === 'tailscale' ? 'Tailscale, encrypted, works anywhere' : 'same Wi-Fi only, not encrypted'})`));
|
|
63
|
+
console.log(out.dim('See or remove connected phones: llm devices'));
|
|
64
|
+
}
|
|
65
|
+
export async function devicesCommand() {
|
|
66
|
+
const { data } = await getClient().devices();
|
|
67
|
+
if (data.length === 0)
|
|
68
|
+
return void console.log(out.dim('No signed-in browsers or phones. Connect a phone with: llm phone'));
|
|
69
|
+
for (const d of data) {
|
|
70
|
+
const where = d.createdFrom === 'local' ? 'this computer' : 'paired device';
|
|
71
|
+
console.log(`${shortId(d.id)} ${(d.deviceName ?? 'Browser').padEnd(14)} ${where.padEnd(14)} ${out.dim(`last used ${relativeTime(d.lastSeenAt)}`)}`);
|
|
72
|
+
}
|
|
73
|
+
console.log(out.dim('\nRemove one (it is signed out at once): llm devices revoke <id>'));
|
|
74
|
+
}
|
|
75
|
+
export async function revokeDeviceCommand(idOrPrefix) {
|
|
76
|
+
const client = getClient();
|
|
77
|
+
const { data } = await client.devices();
|
|
78
|
+
const hits = data.filter((d) => d.id.startsWith(idOrPrefix));
|
|
79
|
+
if (hits.length === 0)
|
|
80
|
+
throw new CliError(`No signed-in device starts with "${idOrPrefix}". See: llm devices`);
|
|
81
|
+
if (hits.length > 1)
|
|
82
|
+
throw new CliError(`"${idOrPrefix}" matches ${hits.length} devices; use more characters.`);
|
|
83
|
+
await client.revokeDevice(hits[0].id);
|
|
84
|
+
console.log(`Removed ${hits[0].deviceName ?? 'the device'} (${shortId(hits[0].id)}). It is signed out.`);
|
|
85
|
+
}
|
|
@@ -21,7 +21,9 @@ export async function startCommand(opts) {
|
|
|
21
21
|
throw new CliError(`There is no file at ${file}.`);
|
|
22
22
|
args.push(`--env-file=${file}`);
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
// --phone: also listen on the local network so paired phones on this Wi-Fi can connect.
|
|
25
|
+
const env = opts.phone ? { ...process.env, PHONE_ACCESS: 'wifi' } : process.env;
|
|
26
|
+
const child = spawn(process.execPath, [...args, entry], { stdio: 'inherit', env });
|
|
25
27
|
// Pass stop signals on and wait, so the gateway always shuts down cleanly (releases its
|
|
26
28
|
// lock, closes the database). Ctrl+C in a terminal reaches both processes anyway; a
|
|
27
29
|
// signal sent to `llm` alone (a process manager, `kill`) must still reach the gateway.
|
package/cli/dist/index.js
CHANGED
|
@@ -6,6 +6,8 @@ import { configPathCommand, configSetCommand, configShowCommand, modelsCommand,
|
|
|
6
6
|
import { backupCommand, restoreCommand } from './commands/backup.js';
|
|
7
7
|
import { doctorCommand } from './commands/doctor.js';
|
|
8
8
|
import { startCommand } from './commands/start.js';
|
|
9
|
+
import { openCommand } from './commands/open.js';
|
|
10
|
+
import { devicesCommand, phoneCommand, revokeDeviceCommand } from './commands/phone.js';
|
|
9
11
|
import { CliError } from './errors.js';
|
|
10
12
|
import { describeErrorFully } from './key-diagnosis.js';
|
|
11
13
|
import { errc } from './format.js';
|
|
@@ -78,9 +80,26 @@ program
|
|
|
78
80
|
.option('--recent <n>', 'recent generations to list', '5')
|
|
79
81
|
.option('--json', 'machine-readable output')
|
|
80
82
|
.action(wrap(statsCommand));
|
|
83
|
+
program
|
|
84
|
+
.command('open')
|
|
85
|
+
.description('open the web chat in your browser, already signed in')
|
|
86
|
+
.option('--print', "print the sign-in link instead of opening the browser")
|
|
87
|
+
.action(wrap(openCommand));
|
|
88
|
+
program
|
|
89
|
+
.command('phone')
|
|
90
|
+
.description('connect a phone: shows a QR code to scan (works once, for 5 minutes)')
|
|
91
|
+
.option('--print', 'print the link instead of a QR code')
|
|
92
|
+
.option('--browser', 'show the QR code in your browser instead (if the terminal one will not scan)')
|
|
93
|
+
.action(wrap(phoneCommand));
|
|
94
|
+
const devices = program
|
|
95
|
+
.command('devices')
|
|
96
|
+
.description('signed-in browsers and phones; remove one with: llm devices revoke <id>')
|
|
97
|
+
.action(wrap(devicesCommand));
|
|
98
|
+
devices.command('revoke').argument('<id>', 'device id or its first characters').description('sign a device out').action(wrap(revokeDeviceCommand));
|
|
81
99
|
program
|
|
82
100
|
.command('start')
|
|
83
101
|
.description('start the assistant in this window (Ctrl+C stops it)')
|
|
102
|
+
.option('--phone', 'also let phones on this Wi-Fi connect (pair them with llm phone)')
|
|
84
103
|
.option('--env-file <path>', 'read settings from this file (for example server mode: DATABASE_URL, REDIS_URL)')
|
|
85
104
|
.action(wrap(startCommand));
|
|
86
105
|
program
|
package/cli/dist/qr.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import QRCode from 'qrcode';
|
|
2
|
+
// A QR code drawn in the terminal that phones can actually scan. The qrcode package's own
|
|
3
|
+
// terminal output uses the theme's "white" and "black" (often grey and dark grey) and only a
|
|
4
|
+
// 1-module border, so cameras often can't read it. Here:
|
|
5
|
+
// - pure black and white from the 256-colour cube (16 = #000000, 231 = #ffffff), which
|
|
6
|
+
// themes don't remap; black on white also passes any minimum-contrast setting unchanged;
|
|
7
|
+
// - a white border (quiet zone): 4 modules as the QR standard asks, 2 when space is short;
|
|
8
|
+
// - error correction L: the smallest code for the link, so each module is as big as possible.
|
|
9
|
+
//
|
|
10
|
+
// Two ways to draw it:
|
|
11
|
+
// - "sharp": each module is two spaces with a background colour. No font glyphs at all, so
|
|
12
|
+
// it can't break: terminals fill the background across the whole cell, line spacing
|
|
13
|
+
// included. macOS Terminal leaves gaps between lines of block characters with many fonts,
|
|
14
|
+
// which stripes a half-block QR code and makes Android scanners fail. Needs a big window
|
|
15
|
+
// (about 74 x 41 for a Wi-Fi link).
|
|
16
|
+
// - "compact": two modules per cell, '▀' with the top as foreground and the bottom as
|
|
17
|
+
// background. Half the height, but depends on the font drawing '▀' edge to edge.
|
|
18
|
+
const BLACK = 16;
|
|
19
|
+
const WHITE = 231;
|
|
20
|
+
/** The QR code for `text` as rows of dark (true) / light (false) modules, border included. */
|
|
21
|
+
export function qrMatrix(text, quiet = 4) {
|
|
22
|
+
const { modules } = QRCode.create(text, { errorCorrectionLevel: 'L' });
|
|
23
|
+
const n = modules.size + quiet * 2;
|
|
24
|
+
return Array.from({ length: n }, (_, y) => Array.from({ length: n }, (_, x) => {
|
|
25
|
+
const r = y - quiet;
|
|
26
|
+
const c = x - quiet;
|
|
27
|
+
return r >= 0 && c >= 0 && r < modules.size && c < modules.size && Boolean(modules.get(r, c));
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
const colour = (dark) => (dark ? BLACK : WHITE);
|
|
31
|
+
function sharp(m) {
|
|
32
|
+
return m.map((row) => row.map((dark) => `\x1b[48;5;${colour(dark)}m `).join('') + '\x1b[0m').join('\n');
|
|
33
|
+
}
|
|
34
|
+
function compact(m) {
|
|
35
|
+
const lines = [];
|
|
36
|
+
for (let y = 0; y < m.length; y += 2) {
|
|
37
|
+
let line = '';
|
|
38
|
+
for (let x = 0; x < m.length; x++) {
|
|
39
|
+
const top = m[y][x];
|
|
40
|
+
const bottom = y + 1 < m.length ? m[y + 1][x] : false;
|
|
41
|
+
line += `\x1b[38;5;${colour(top)}m\x1b[48;5;${colour(bottom)}m▀`;
|
|
42
|
+
}
|
|
43
|
+
lines.push(`${line}\x1b[0m`);
|
|
44
|
+
}
|
|
45
|
+
return lines.join('\n');
|
|
46
|
+
}
|
|
47
|
+
/** Lines printed under the code (instructions); the sharp code must leave room for them. */
|
|
48
|
+
const LINES_BELOW = 5; // 4 lines of text, then the shell prompt
|
|
49
|
+
/**
|
|
50
|
+
* Terminal text for the QR code: the sharp form when the window has room for it (4-module
|
|
51
|
+
* border, else 2), otherwise the compact form. `window` is the terminal size; without one
|
|
52
|
+
* (output piped to a file) the sharp form is used.
|
|
53
|
+
*/
|
|
54
|
+
export function terminalQr(text, window) {
|
|
55
|
+
const smallest = qrMatrix(text, 2).length;
|
|
56
|
+
const needs = { columns: smallest * 2, rows: smallest + LINES_BELOW }; // the smallest sharp form
|
|
57
|
+
for (const quiet of [4, 2]) {
|
|
58
|
+
const m = qrMatrix(text, quiet);
|
|
59
|
+
const fits = !window?.columns || !window.rows || (m.length * 2 <= window.columns && m.length + LINES_BELOW <= window.rows);
|
|
60
|
+
if (fits)
|
|
61
|
+
return { text: sharp(m), mode: 'sharp', needs };
|
|
62
|
+
}
|
|
63
|
+
return { text: compact(qrMatrix(text, 4)), mode: 'compact', needs };
|
|
64
|
+
}
|
package/cli/dist/repl.js
CHANGED
|
@@ -31,7 +31,7 @@ export function printSummary(res, quiet) {
|
|
|
31
31
|
}
|
|
32
32
|
return ok;
|
|
33
33
|
}
|
|
34
|
-
const LLM_SUBCOMMANDS = 'profile|config|start|doctor|backup|restore|chat|resume|ls|conversations|show|fork|rename|rm|models|stats|whoami';
|
|
34
|
+
const LLM_SUBCOMMANDS = 'open|phone|devices|profile|config|start|doctor|backup|restore|chat|resume|ls|conversations|show|fork|rename|rm|models|stats|whoami';
|
|
35
35
|
/** `llm profile use local` typed into the chat: a command for the terminal, not a question. */
|
|
36
36
|
export const looksLikeLlmCommand = (line) => new RegExp(`^llm\\s+(${LLM_SUBCOMMANDS})\\b`).test(line);
|
|
37
37
|
export async function runRepl(opts) {
|
|
@@ -2,7 +2,7 @@ import * as S from './schemas.js';
|
|
|
2
2
|
const err = (description) => ({ description, schema: S.ErrorBody });
|
|
3
3
|
/** Errors any authenticated endpoint can return. */
|
|
4
4
|
const AUTH_ERRORS = {
|
|
5
|
-
401: err('Missing, unknown or revoked API key (`invalid_api_key`)'),
|
|
5
|
+
401: err('Missing, unknown or revoked API key (`invalid_api_key`), or an ended web session (`session_expired`)'),
|
|
6
6
|
429: err('Too many requests for this key (`rate_limited`)'),
|
|
7
7
|
};
|
|
8
8
|
const NOT_FOUND = { 404: err('No such conversation for this key (`conversation_not_found`)') };
|
|
@@ -28,6 +28,15 @@ export const ENDPOINTS = [
|
|
|
28
28
|
summary: 'Prometheus metrics',
|
|
29
29
|
responses: { 200: { description: 'Prometheus text format', contentType: 'text/plain' } },
|
|
30
30
|
},
|
|
31
|
+
{
|
|
32
|
+
method: 'get', path: '/', tag: 'web', auth: false,
|
|
33
|
+
summary: 'The web chat page',
|
|
34
|
+
description: 'Served with a strict Content-Security-Policy (only the gateway\'s own scripts and styles). Its files are under /assets/.',
|
|
35
|
+
responses: {
|
|
36
|
+
200: { description: 'The page', contentType: 'text/html' },
|
|
37
|
+
404: err("The page hasn't been built (`page_not_built`)"),
|
|
38
|
+
},
|
|
39
|
+
},
|
|
31
40
|
{
|
|
32
41
|
method: 'get', path: '/openapi.json', tag: 'health', auth: false,
|
|
33
42
|
summary: 'This document',
|
|
@@ -72,6 +81,61 @@ export const ENDPOINTS = [
|
|
|
72
81
|
500: err('The backup could not be written or verified (`backup_failed`)'),
|
|
73
82
|
},
|
|
74
83
|
},
|
|
84
|
+
// ---- web sign-in ----
|
|
85
|
+
{
|
|
86
|
+
method: 'post', path: '/v1/web/codes', tag: 'web', auth: true,
|
|
87
|
+
summary: 'Make a one-time sign-in code (llm open) or a phone pairing code (llm phone)',
|
|
88
|
+
description: "'open' (default): API key only; works once, for 60 seconds, and only on this computer. " +
|
|
89
|
+
"'pair': an API key or a browser on this computer; works once, for 5 minutes, from a phone. A paired phone can't make codes.",
|
|
90
|
+
body: S.WebCodeBody,
|
|
91
|
+
responses: {
|
|
92
|
+
201: { description: 'A code', schema: S.WebCode },
|
|
93
|
+
...INVALID,
|
|
94
|
+
...AUTH_ERRORS,
|
|
95
|
+
403: err('Not allowed from this caller (`key_required`, `pair_from_computer`)'),
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
method: 'get', path: '/v1/web/sessions', tag: 'web', auth: true,
|
|
100
|
+
summary: 'Signed-in devices: this computer\'s browser and paired phones',
|
|
101
|
+
responses: { 200: { description: 'Devices, most recently used first', schema: S.DeviceList }, ...AUTH_ERRORS },
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
method: 'delete', path: '/v1/web/sessions/{id}', tag: 'web', auth: true,
|
|
105
|
+
summary: 'Remove a device: it is signed out on its next request',
|
|
106
|
+
description: 'From this computer (API key or its browser) any device; a phone only itself.',
|
|
107
|
+
params: S.IdParams,
|
|
108
|
+
responses: {
|
|
109
|
+
204: { description: 'Removed' },
|
|
110
|
+
...INVALID,
|
|
111
|
+
...AUTH_ERRORS,
|
|
112
|
+
403: err('A phone removing another device (`manage_from_computer`)'),
|
|
113
|
+
404: err('No such signed-in device (`device_not_found`)'),
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
method: 'get', path: '/v1/web/phone', tag: 'web', auth: true,
|
|
118
|
+
summary: 'How a phone can reach this assistant (for the pairing QR code)',
|
|
119
|
+
responses: { 200: { description: 'Addresses and whether this caller may pair', schema: S.PhoneInfo }, ...AUTH_ERRORS },
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
method: 'post', path: '/web/session', tag: 'web', auth: false,
|
|
123
|
+
summary: 'Exchange a sign-in code for a session cookie',
|
|
124
|
+
description: 'Sets an HttpOnly, SameSite=Strict cookie. Refused for a host other than localhost (or `WEB_HOSTS`), ' +
|
|
125
|
+
'and for an `Origin` other than the gateway itself.',
|
|
126
|
+
body: S.RedeemCodeBody,
|
|
127
|
+
responses: {
|
|
128
|
+
204: { description: 'Signed in: the session cookie is set' },
|
|
129
|
+
...INVALID,
|
|
130
|
+
401: err('The code is unknown, used or expired (`invalid_code`)'),
|
|
131
|
+
403: err('Wrong host or origin (`forbidden_host`, `bad_origin`), or an llm open link used from another device (`open_link_local_only`)'),
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
method: 'delete', path: '/web/session', tag: 'web', auth: true, authBy: ['cookie'],
|
|
136
|
+
summary: 'Sign out: end the session and clear the cookie',
|
|
137
|
+
responses: { 204: { description: 'Signed out' }, 403: err('Wrong host or origin (`forbidden_host`, `bad_origin`)') },
|
|
138
|
+
},
|
|
75
139
|
// ---- conversations ----
|
|
76
140
|
{
|
|
77
141
|
method: 'post', path: '/v1/conversations', tag: 'conversations', auth: true,
|
package/dist/src/api/openapi.js
CHANGED
|
@@ -47,7 +47,7 @@ function operation(e) {
|
|
|
47
47
|
...(e.description ? { description: e.description } : {}),
|
|
48
48
|
tags: [e.tag],
|
|
49
49
|
...(e.deprecated ? { deprecated: true } : {}),
|
|
50
|
-
...(e.auth ? {} : { security: [] }),
|
|
50
|
+
...(!e.auth ? { security: [] } : e.authBy ? { security: e.authBy.map((a) => ({ [a === 'cookie' ? 'webSession' : 'apiKey']: [] })) } : {}),
|
|
51
51
|
...(e.params || e.query ? { parameters: [...parameters('path', e.params), ...parameters('query', e.query)] } : {}),
|
|
52
52
|
...(e.body ? { requestBody: { required: true, content: { 'application/json': { schema: schemaFor(e.body, 'input') } } } } : {}),
|
|
53
53
|
responses,
|
|
@@ -68,12 +68,13 @@ export function buildOpenApi(version = '1.0.0') {
|
|
|
68
68
|
'`code` is stable for programs, `message` and `hint` are written for people.',
|
|
69
69
|
},
|
|
70
70
|
servers: [{ url: 'http://localhost:3000' }],
|
|
71
|
-
security: [{ apiKey: [] }],
|
|
71
|
+
security: [{ apiKey: [] }, { webSession: [] }],
|
|
72
72
|
tags: [
|
|
73
73
|
{ name: 'conversations' },
|
|
74
74
|
{ name: 'models' },
|
|
75
75
|
{ name: 'account' },
|
|
76
76
|
{ name: 'operations' },
|
|
77
|
+
{ name: 'web' },
|
|
77
78
|
{ name: 'health' },
|
|
78
79
|
{ name: 'legacy' },
|
|
79
80
|
],
|
|
@@ -81,6 +82,12 @@ export function buildOpenApi(version = '1.0.0') {
|
|
|
81
82
|
components: {
|
|
82
83
|
securitySchemes: {
|
|
83
84
|
apiKey: { type: 'http', scheme: 'bearer', description: 'An API key: `Authorization: Bearer llmgw_...`' },
|
|
85
|
+
webSession: {
|
|
86
|
+
type: 'apiKey',
|
|
87
|
+
in: 'cookie',
|
|
88
|
+
name: 'llmgw_session',
|
|
89
|
+
description: 'The web page\'s session, from `POST /web/session`. State-changing requests must come from the gateway\'s own origin.',
|
|
90
|
+
},
|
|
84
91
|
},
|
|
85
92
|
schemas: Object.fromEntries(Object.entries(schemas).map(([id, s]) => [id, clean(s)])),
|
|
86
93
|
},
|
package/dist/src/api/schemas.js
CHANGED
|
@@ -53,6 +53,10 @@ export const StatsQuery = z.object({
|
|
|
53
53
|
hours: z.coerce.number().int().min(1).max(720).default(24),
|
|
54
54
|
recent: z.coerce.number().int().min(0).max(50).default(5),
|
|
55
55
|
});
|
|
56
|
+
export const WebCodeBody = z.object({
|
|
57
|
+
purpose: z.enum(['open', 'pair']).default('open').describe("'open': this computer's browser (llm open); 'pair': a phone (llm phone)"),
|
|
58
|
+
});
|
|
59
|
+
export const RedeemCodeBody = z.object({ code: z.string().min(16).max(200).describe('The one-time code from the sign-in link') });
|
|
56
60
|
export const LegacyChatBody = z.object({
|
|
57
61
|
model: z.string(),
|
|
58
62
|
messages: z
|
|
@@ -141,6 +145,28 @@ export const BackupSummary = named(z.strictObject({
|
|
|
141
145
|
bytes: z.number().int(),
|
|
142
146
|
createdAt: timestamp,
|
|
143
147
|
}), 'BackupSummary');
|
|
148
|
+
export const WebCode = named(z.strictObject({ code: z.string(), expiresAt: timestamp }), 'WebCode', 'A one-time sign-in code for the web page; works once, for 60 seconds');
|
|
149
|
+
export const Device = named(z.strictObject({
|
|
150
|
+
id: z.uuid(),
|
|
151
|
+
deviceName: z.string().nullable().describe('From the browser, e.g. "iPhone"'),
|
|
152
|
+
createdFrom: z.enum(['local', 'network']).describe("'local': signed in on the computer running the assistant; 'network': a paired device"),
|
|
153
|
+
createdAt: timestamp,
|
|
154
|
+
lastSeenAt: timestamp,
|
|
155
|
+
current: z.boolean().describe('The device making this request'),
|
|
156
|
+
}), 'Device', 'A browser signed in to this account: the laptop, or a paired phone');
|
|
157
|
+
export const DeviceList = named(z.strictObject({ data: z.array(Device) }), 'DeviceList');
|
|
158
|
+
export const PhoneInfo = named(z.strictObject({
|
|
159
|
+
canPair: z.boolean().describe('Whether this caller may create pairing codes (an API key, or the computer itself)'),
|
|
160
|
+
wifi: z.strictObject({
|
|
161
|
+
listening: z.boolean().describe('Started with phone access (llm start --phone)'),
|
|
162
|
+
urls: z.array(z.string()).describe('Addresses a phone on the same Wi-Fi can open'),
|
|
163
|
+
}),
|
|
164
|
+
tailscale: z.strictObject({
|
|
165
|
+
name: z.string().nullable(),
|
|
166
|
+
url: z.string().nullable(),
|
|
167
|
+
serving: z.boolean().describe('tailscale serve forwards to this gateway'),
|
|
168
|
+
}),
|
|
169
|
+
}), 'PhoneInfo', 'How a phone can reach this assistant');
|
|
144
170
|
export const Health = named(z.strictObject({ ok: z.literal(true), mode: z.enum(['single', 'server']) }), 'Health');
|
|
145
171
|
export const Readiness = named(z.strictObject({ ok: z.boolean(), ollama: z.boolean(), db: z.boolean() }), 'Readiness');
|
|
146
172
|
export const LegacyChatResponse = named(z.looseObject({}).describe('OpenAI-compatible chat completion, passed through from Ollama'), 'LegacyChatResponse');
|
package/dist/src/app.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
import { totalmem } from 'node:os';
|
|
3
|
+
import cookie from '@fastify/cookie';
|
|
3
4
|
import rateLimit from '@fastify/rate-limit';
|
|
4
5
|
import Fastify from 'fastify';
|
|
5
6
|
import { Redis } from 'ioredis';
|
|
@@ -26,6 +27,11 @@ import { meRoutes } from './routes/me.js';
|
|
|
26
27
|
import { statsRoutes } from './routes/stats.js';
|
|
27
28
|
import { doctorRoutes } from './routes/doctor.js';
|
|
28
29
|
import { backupRoutes } from './routes/backup.js';
|
|
30
|
+
import { webCodeRoutes, webSessionRoutes } from './routes/web-session.js';
|
|
31
|
+
import { webPageRoutes } from './routes/web-page.js';
|
|
32
|
+
import { findWebRoot } from './lib/web-root.js';
|
|
33
|
+
import { isLocalRequest, WebHosts } from './lib/network.js';
|
|
34
|
+
import { WebSessionService } from './services/web-session.service.js';
|
|
29
35
|
export async function buildApp(opts = {}) {
|
|
30
36
|
const config = opts.config ?? createConfig();
|
|
31
37
|
const app = Fastify({
|
|
@@ -44,6 +50,19 @@ export async function buildApp(opts = {}) {
|
|
|
44
50
|
if (method !== 'HEAD')
|
|
45
51
|
routes.push({ method, url: r.url });
|
|
46
52
|
});
|
|
53
|
+
// Single-user mode, request from the network (a paired phone, or through Tailscale): only
|
|
54
|
+
// what the phone needs. Metrics, readiness and the API description stay on this computer.
|
|
55
|
+
if (config.mode === 'single') {
|
|
56
|
+
app.addHook('onRequest', async (req, reply) => {
|
|
57
|
+
if (isLocalRequest(req))
|
|
58
|
+
return;
|
|
59
|
+
const path = req.url.split('?')[0];
|
|
60
|
+
const allowed = path === '/' || path.startsWith('/assets/') || path === '/web/session' || path.startsWith('/v1/') || path === '/healthz';
|
|
61
|
+
if (!allowed) {
|
|
62
|
+
return reply.code(404).send({ error: { code: 'not_found', message: `There is no ${req.method} ${path}.`, request_id: req.id } });
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
47
66
|
// Unknown URLs get the same error shape as everything else.
|
|
48
67
|
app.setNotFoundHandler((req, reply) => reply.code(404).send({
|
|
49
68
|
error: { code: 'not_found', message: `There is no ${req.method} ${req.url.split('?')[0]}.`, request_id: req.id },
|
|
@@ -94,6 +113,8 @@ export async function buildApp(opts = {}) {
|
|
|
94
113
|
const provider = opts.provider ?? new OllamaProvider(config.OLLAMA_URL);
|
|
95
114
|
const ollama = opts.ollama ?? new OllamaModels(config.OLLAMA_URL);
|
|
96
115
|
const auth = new AuthService(repos.apiKeys);
|
|
116
|
+
const webSessions = new WebSessionService(storage.webSessions);
|
|
117
|
+
const webHosts = new WebHosts({ extra: config.webHosts, detect: opts.detectNetwork ?? false, port: config.PORT, fixed: opts.networkHosts });
|
|
97
118
|
const models = new ModelsService({
|
|
98
119
|
...config.models,
|
|
99
120
|
source: ollama,
|
|
@@ -115,7 +136,7 @@ export async function buildApp(opts = {}) {
|
|
|
115
136
|
messages: repos.messages,
|
|
116
137
|
generations: repos.generations,
|
|
117
138
|
});
|
|
118
|
-
const deps = { config, storage, limiter, metrics, provider, ollama, auth, conversations, models, repos };
|
|
139
|
+
const deps = { config, storage, limiter, metrics, provider, ollama, auth, webSessions, webHosts, conversations, models, repos };
|
|
119
140
|
let redis = null;
|
|
120
141
|
if (config.REDIS_URL) {
|
|
121
142
|
redis = new Redis(config.REDIS_URL, {
|
|
@@ -124,6 +145,21 @@ export async function buildApp(opts = {}) {
|
|
|
124
145
|
enableOfflineQueue: false, // fail fast if Redis is down
|
|
125
146
|
});
|
|
126
147
|
redis.on('error', (e) => app.log.warn({ err: e.message }, 'redis error'));
|
|
148
|
+
// Wait briefly for the connection, so limits apply from the first request. Without this,
|
|
149
|
+
// requests that arrive before Redis is ready skip the limit (skipOnError below). If Redis
|
|
150
|
+
// is down, start anyway after 1 s: serving beats refusing.
|
|
151
|
+
const client = redis;
|
|
152
|
+
if (client.status !== 'ready') {
|
|
153
|
+
await new Promise((done) => {
|
|
154
|
+
const timer = setTimeout(done, 1000);
|
|
155
|
+
const finish = () => {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
done();
|
|
158
|
+
};
|
|
159
|
+
client.once('ready', finish);
|
|
160
|
+
client.once('error', finish);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
127
163
|
}
|
|
128
164
|
app.log.info({
|
|
129
165
|
mode: config.mode,
|
|
@@ -141,9 +177,12 @@ export async function buildApp(opts = {}) {
|
|
|
141
177
|
await storage.close();
|
|
142
178
|
});
|
|
143
179
|
// ---- routes ----
|
|
180
|
+
await app.register(cookie); // parses cookies for the web page's session (no signing: the token is random)
|
|
144
181
|
await app.register(healthRoutes, { deps });
|
|
182
|
+
await app.register(webSessionRoutes, { deps });
|
|
183
|
+
await app.register(webPageRoutes, { root: opts.webRoot === undefined ? findWebRoot() : opts.webRoot });
|
|
145
184
|
await app.register(async (v1) => {
|
|
146
|
-
v1.addHook('onRequest', makeAuthHook(auth)); // auth first, so rate limiting can key on the key id
|
|
185
|
+
v1.addHook('onRequest', makeAuthHook(auth, webSessions, webHosts)); // auth first, so rate limiting can key on the key id
|
|
147
186
|
await v1.register(rateLimit, {
|
|
148
187
|
max: config.RATE_LIMIT_MAX,
|
|
149
188
|
timeWindow: config.RATE_LIMIT_WINDOW,
|
|
@@ -159,6 +198,7 @@ export async function buildApp(opts = {}) {
|
|
|
159
198
|
await v1.register(statsRoutes, { deps });
|
|
160
199
|
await v1.register(doctorRoutes, { deps });
|
|
161
200
|
await v1.register(backupRoutes, { deps });
|
|
201
|
+
await v1.register(webCodeRoutes, { deps });
|
|
162
202
|
}, { prefix: '/v1' });
|
|
163
203
|
return { app, deps, routes };
|
|
164
204
|
}
|