@ggml-org/llama-chat 0.0.0-stage → 0.1.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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +196 -2
  3. package/bin/cli.js +5 -0
  4. package/cli/server.js +385 -0
  5. package/dist/_app/immutable/assets/LlamaMono.7z2dnkpH.woff2 +0 -0
  6. package/dist/_app/immutable/assets/LlamaSans.C2rXtH67.woff2 +0 -0
  7. package/dist/_app/immutable/assets/bundle.DL4TcXwg.css +2 -0
  8. package/dist/_app/immutable/bundle.DIMNEksO.js +4068 -0
  9. package/dist/_app/version.json +1 -0
  10. package/dist/apple-splash-landscape-1136x640.png +0 -0
  11. package/dist/apple-splash-landscape-1334x750.png +0 -0
  12. package/dist/apple-splash-landscape-2266x1488.png +0 -0
  13. package/dist/apple-splash-landscape-2360x1640.png +0 -0
  14. package/dist/apple-splash-landscape-2388x1668.png +0 -0
  15. package/dist/apple-splash-landscape-2532x1170.png +0 -0
  16. package/dist/apple-splash-landscape-2556x1179.png +0 -0
  17. package/dist/apple-splash-landscape-2622x1206.png +0 -0
  18. package/dist/apple-splash-landscape-2732x2048.png +0 -0
  19. package/dist/apple-splash-landscape-2778x1284.png +0 -0
  20. package/dist/apple-splash-landscape-2796x1290.png +0 -0
  21. package/dist/apple-splash-landscape-2868x1320.png +0 -0
  22. package/dist/apple-splash-landscape-dark-1136x640.png +0 -0
  23. package/dist/apple-splash-landscape-dark-1334x750.png +0 -0
  24. package/dist/apple-splash-landscape-dark-2266x1488.png +0 -0
  25. package/dist/apple-splash-landscape-dark-2360x1640.png +0 -0
  26. package/dist/apple-splash-landscape-dark-2388x1668.png +0 -0
  27. package/dist/apple-splash-landscape-dark-2532x1170.png +0 -0
  28. package/dist/apple-splash-landscape-dark-2556x1179.png +0 -0
  29. package/dist/apple-splash-landscape-dark-2622x1206.png +0 -0
  30. package/dist/apple-splash-landscape-dark-2732x2048.png +0 -0
  31. package/dist/apple-splash-landscape-dark-2778x1284.png +0 -0
  32. package/dist/apple-splash-landscape-dark-2796x1290.png +0 -0
  33. package/dist/apple-splash-landscape-dark-2868x1320.png +0 -0
  34. package/dist/apple-splash-portrait-1170x2532.png +0 -0
  35. package/dist/apple-splash-portrait-1179x2556.png +0 -0
  36. package/dist/apple-splash-portrait-1206x2622.png +0 -0
  37. package/dist/apple-splash-portrait-1284x2778.png +0 -0
  38. package/dist/apple-splash-portrait-1290x2796.png +0 -0
  39. package/dist/apple-splash-portrait-1320x2868.png +0 -0
  40. package/dist/apple-splash-portrait-1488x2266.png +0 -0
  41. package/dist/apple-splash-portrait-1640x2360.png +0 -0
  42. package/dist/apple-splash-portrait-1668x2388.png +0 -0
  43. package/dist/apple-splash-portrait-2048x2732.png +0 -0
  44. package/dist/apple-splash-portrait-640x1136.png +0 -0
  45. package/dist/apple-splash-portrait-750x1334.png +0 -0
  46. package/dist/apple-splash-portrait-dark-1170x2532.png +0 -0
  47. package/dist/apple-splash-portrait-dark-1179x2556.png +0 -0
  48. package/dist/apple-splash-portrait-dark-1206x2622.png +0 -0
  49. package/dist/apple-splash-portrait-dark-1284x2778.png +0 -0
  50. package/dist/apple-splash-portrait-dark-1290x2796.png +0 -0
  51. package/dist/apple-splash-portrait-dark-1320x2868.png +0 -0
  52. package/dist/apple-splash-portrait-dark-1488x2266.png +0 -0
  53. package/dist/apple-splash-portrait-dark-1640x2360.png +0 -0
  54. package/dist/apple-splash-portrait-dark-1668x2388.png +0 -0
  55. package/dist/apple-splash-portrait-dark-2048x2732.png +0 -0
  56. package/dist/apple-splash-portrait-dark-640x1136.png +0 -0
  57. package/dist/apple-splash-portrait-dark-750x1334.png +0 -0
  58. package/dist/apple-touch-icon-180x180.png +0 -0
  59. package/dist/build.json +1 -0
  60. package/dist/favicon-dark.ico +0 -0
  61. package/dist/favicon-dark.svg +3 -0
  62. package/dist/favicon.ico +0 -0
  63. package/dist/favicon.svg +3 -0
  64. package/dist/index.html +94 -0
  65. package/dist/manifest.webmanifest +1 -0
  66. package/dist/maskable-icon-512x512.png +0 -0
  67. package/dist/pwa-192x192.png +0 -0
  68. package/dist/pwa-512x512.png +0 -0
  69. package/dist/pwa-64x64.png +0 -0
  70. package/dist/recommended-mcp/context7.png +0 -0
  71. package/dist/recommended-mcp/exa.ico +0 -0
  72. package/dist/recommended-mcp/github-dark.png +0 -0
  73. package/dist/recommended-mcp/github-light.png +0 -0
  74. package/dist/recommended-mcp/huggingface.ico +0 -0
  75. package/dist/service-worker.js +1 -0
  76. package/dist/sw.js +12 -0
  77. package/package.json +173 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) ggml
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,197 @@
1
- # Temporary Holding Version
1
+ # Llama Chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Llama Chat is the chat app for llama.cpp: a web interface for llama-server, built with SvelteKit on [Llama UI](../../lib/ui/README.md) (`@ggml-org/llama-ui`), the design system in `ui/lib/ui`. llama-server embeds it, and `npx llama-chat` runs it anywhere.
4
+
5
+ It works with a llama-server in either mode: **MODEL** (one model) or **ROUTER** (many models, loaded and unloaded on demand).
6
+
7
+ ## Contents
8
+
9
+ - [Run it with npx](#run-it-with-npx)
10
+ - [Self-hosting](#self-hosting)
11
+ - [Features](#features)
12
+ - [Development](#development)
13
+ - [Architecture](#architecture)
14
+ - [Build and embedding](#build-and-embedding)
15
+ - [Publishing to npm](#publishing-to-npm)
16
+
17
+ ## Run it with npx
18
+
19
+ Llama Chat is published to npm as [`@ggml-org/llama-chat`](https://www.npmjs.com/package/@ggml-org/llama-chat), with [`llama-chat`](https://www.npmjs.com/package/llama-chat) as its short name. It serves the prebuilt app as static files on localhost, or writes them to a folder for any static file server (see [Self-hosting](#self-hosting)); it brings no server and no models of its own. It needs Node.js 20 or later.
20
+
21
+ ```bash
22
+ npx @ggml-org/llama-chat # serve it on http://127.0.0.1:3000 and open the browser
23
+ npx llama-chat --host 0.0.0.0 --no-open # the same, by its short name, reachable from other devices
24
+ npx llama-chat build # write the static app to ./llama-chat instead
25
+ ```
26
+
27
+ | Flag | Default | What it does |
28
+ | --------------------------------- | ----------- | ------------------------------------------------------------------------------------------- |
29
+ | `--port <n>` | `3000` | Fixed, so the origin, and the chats the browser stores under it, stay the same between runs |
30
+ | `--host <addr>` | `127.0.0.1` | `0.0.0.0` to open it to the LAN |
31
+ | `--open` / `--no-open` | open | Opens the default browser once it listens |
32
+ | `-v`, `--version`, `-h`, `--help` | | As usual |
33
+
34
+ The bare command is the documented form; `start` is accepted as an alias for it. `build` takes `--out <dir>` (default `./llama-chat`) and `--force`, which lets it write into a folder that is not empty.
35
+
36
+ How it works: the CLI only serves the files of `dist`, with llama-server's headers for the UI (`index.html` cross-origin isolated, the PWA files revalidated, hashed assets cached for good), and forwards nothing. The browser talks to each llama-server you add in the app by URL directly, so llama-server's own rules apply: start it with `--cors-origins http://127.0.0.1:3000` (the address you open) when it restricts origins, as it does with tools or MCP enabled, and with `--api-key` when it is reachable from the LAN. An `http://` page like this one can reach a plain `http://` llama-server on the LAN, which an `https://` page cannot.
37
+
38
+ ## Self-hosting
39
+
40
+ The app is static and uses relative paths and a hash router, so any static host can serve it at any path. `npx @ggml-org/llama-chat build --out <dir>` writes the files (as does `npm run build` here, to `dist`); serve them with any static file server, for example `npx http-server llama-chat -p 3000`. Send the headers listed above with `index.html` and the PWA files, so the app behaves as it does under llama-server (see [Cross-origin isolation](#cross-origin-isolation)).
41
+
42
+ The app reaches the llama-server on its own origin, if there is one (llama-server serves it with `--path`, or your reverse proxy puts the API next to the files), and any other llama-server you add by URL, which needs `--cors-origins` for the app's address.
43
+
44
+ ## Features
45
+
46
+ - **Chat** - streaming replies, reasoning blocks, branching by edit or regenerate, tabs, search, import and export
47
+ - **Attachments** - images, PDFs (as text or as pages for vision models), audio and text files, by drag and drop or paste
48
+ - **Rendering** - Markdown (GFM), code highlighting, KaTeX math and Mermaid diagrams
49
+ - **Models** - in ROUTER mode, a selector and a models manager: load and unload, downloads, Discover from the Hugging Face Hub, favorites and hidden models
50
+ - **Tools** - built-in browser tools, llama-server's tools and MCP servers, each behind a permission prompt
51
+ - **Everywhere** - light and dark themes, phone layouts, installable as a PWA, keyboard shortcuts (`Ctrl/Cmd+K` search, `Shift+Ctrl/Cmd+O` new chat, `Ctrl/Cmd+B` sidebar)
52
+
53
+ ## Development
54
+
55
+ You need Node.js 20 or later and a llama-server to talk to.
56
+
57
+ ```bash
58
+ cd ui/apps/chat
59
+ npm ci
60
+ npm run dev # the app on http://localhost:5173, Storybook on http://localhost:6006
61
+ ```
62
+
63
+ The dev server forwards the API (`/v1`, `/props`, `/models`, `/tools`, `/slots`, `/cors-proxy`) to llama-server on `http://localhost:9931`, or to `VITE_PUBLIC_SERVER_ORIGIN` when it is set.
64
+
65
+ | Command | What it does |
66
+ | --------------------- | --------------------------------------------------------------- |
67
+ | `npm run build` | The production build, in `dist/` |
68
+ | `npm run check` | Type checking with svelte-check |
69
+ | `npm run lint` | Prettier and ESLint; `npm run format` fixes what they can |
70
+ | `npm run test:unit` | Unit tests (Vitest, `tests/unit`) |
71
+ | `npm run test:client` | Component tests in the browser (Vitest, `tests/client`) |
72
+ | `npm run test:ui` | Storybook stories run as tests (`tests/stories`) |
73
+ | `npm run test:e2e` | End-to-end tests (Playwright, `tests/e2e`), with a llama-server |
74
+ | `npm run storybook` | Storybook on its own |
75
+
76
+ Locally the browser tests run in your installed Google Chrome; CI uses Playwright's bundled Chromium.
77
+
78
+ ## Architecture
79
+
80
+ Llama Chat is the first app on Llama UI, and the reference for the line between library and app: **Llama UI draws and handles interaction, the app decides what happens.**
81
+
82
+ - **In Llama UI:** components, design tokens, fonts and surfaces, and the logic inside them (keyboard navigation, validation as you type, formatting a file size). Components take data in and report what the user did out.
83
+ - **In Llama Chat:** talking to llama-server, storing conversations, the agentic loop and its tool permissions, MCP servers, managing models, settings.
84
+
85
+ The app imports the library as `@ggml-org/llama-ui/ui/<name>` and compiles its sources in its own build, with no install of the library (see `scripts/vite-plugin-llama-ui.ts`). Data flows one way, through these layers:
86
+
87
+ | Layer | Lives in | What it holds |
88
+ | -------------- | ------------------------- | --------------------------------------------------------------------------------------------------- |
89
+ | Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` |
90
+ | App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area |
91
+ | UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI |
92
+ | Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard |
93
+ | Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings |
94
+ | Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox |
95
+ | Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` |
96
+
97
+ ```mermaid
98
+ flowchart LR
99
+ Routes --> Components["App components"]
100
+ Components --> Hooks
101
+ Components --> Stores
102
+ Hooks --> Stores
103
+ Stores --> Services
104
+ Services --> DB[("IndexedDB, localStorage")]
105
+ Services --> API["llama-server"]
106
+ Components -. "imports" .-> UI["Llama UI"]
107
+ Stores -. "reactive state" .-> Components
108
+ ```
109
+
110
+ ### Sending a message
111
+
112
+ ```mermaid
113
+ sequenceDiagram
114
+ participant User
115
+ participant Stores
116
+ participant DB as IndexedDB
117
+ participant API as llama-server
118
+
119
+ Note over Stores,API: on start
120
+ Stores->>API: GET /props, then the model list
121
+ User->>Stores: send a message
122
+ opt ROUTER mode, model not loaded
123
+ Stores->>API: POST /models/load, then poll GET /models
124
+ end
125
+ Stores->>DB: save the user message
126
+ Stores->>API: POST /v1/chat/completions (stream)
127
+ loop streaming
128
+ API-->>Stores: SSE chunks, shown as they arrive
129
+ end
130
+ opt the model called tools
131
+ Stores->>Stores: run them (after permission), send the results, stream again
132
+ end
133
+ Stores->>DB: save the assistant message
134
+ ```
135
+
136
+ ### Patterns worth knowing
137
+
138
+ - **Stores** hold state as Svelte 5 runes (`$state`, `$derived`); larger ones live in folders and compose focused sub-stores. **Services** are stateless and do all I/O.
139
+ - **Per-conversation state**: streaming, loading and abort controllers are kept per conversation, so several chats can stream at once.
140
+ - **Messages form a tree**: each message knows its parent and children, and a conversation points at the branch tip it shows, so editing or regenerating branches without losing history.
141
+ - **Server role**: one codebase serves MODEL and ROUTER mode; `serverStore` reads the role from `/props`, and ROUTER-only UI shows only there.
142
+ - **Modalities**: attachments a model cannot read (images for a text-only model, say) are refused before sending, from the model's `/props`.
143
+ - **Storage**: conversations and messages in IndexedDB (Dexie), settings and model preferences in localStorage, server state and Hub details in memory only.
144
+
145
+ ### Cross-origin isolation
146
+
147
+ llama-server serves the UI with `Cross-Origin-Embedder-Policy: require-corp` and `Cross-Origin-Opener-Policy: same-origin`, so every cross-origin asset needs the other origin's consent. Hugging Face Hub avatars and metadata are requested in CORS mode, which the Hub allows. MCP server icons and search-result favicons go through llama-server's `/cors-proxy` when it runs with `--ui-mcp-proxy`, and fall back to a bundled icon otherwise.
148
+
149
+ ## Build and embedding
150
+
151
+ `npm run build` generates the PWA icons, bundles the app with Vite and writes it to `dist/` (or to `LLAMA_UI_OUT_DIR`) as static files: `index.html`, one JS and one CSS bundle under `_app/`, the service worker, the web manifest and `build.json` with the version (`LLAMA_BUILD_NUMBER`, `b0000` locally). Paths are relative and routing uses the URL hash, so `dist` works from any path.
152
+
153
+ llama-server embeds it: when llama-server is built, `scripts/ui-assets.cmake` takes `ui/apps/chat/dist` if it exists, runs `npm run build` if `LLAMA_BUILD_UI` is on, or downloads the release's prebuilt `dist.tar.gz` from Hugging Face, and compiles every file into the binary. The same `dist` is what `npx @ggml-org/llama-chat` serves.
154
+
155
+ ```text
156
+ ui/apps/chat/
157
+ ├── src/
158
+ │ ├── lib/ # components, hooks, stores, services, types, utils, constants, enums
159
+ │ ├── routes/ # SvelteKit routes
160
+ │ └── service-worker/ # the PWA's service worker
161
+ ├── bin/, cli/ # the npx llama-chat command and its server
162
+ ├── alias/ # the llama-chat npm package, the short name
163
+ ├── scripts/ # Vite plugins and build scripts
164
+ ├── static/ # static assets
165
+ └── tests/ # unit, client and end-to-end tests, and the Storybook stories
166
+ ```
167
+
168
+ ## Publishing to npm
169
+
170
+ Two packages go out with the same version: `@ggml-org/llama-chat`, which carries the app and the CLI, and `llama-chat` (in `alias/`), which depends on it and only forwards to its CLI so that `npx llama-chat` works. A unit test (`tests/unit/cli.test.ts`) fails when their versions drift apart.
171
+
172
+ The version is set by hand and CI publishes it, as for `@ggml-org/llama-ui` (see [Releases](../../README.md#releases)). To release, bump the version in the PR that should ship it:
173
+
174
+ ```bash
175
+ cd ui/apps/chat
176
+ npm version <version> --no-git-tag-version
177
+ # then set the same version, and the same @ggml-org/llama-chat dependency, in alias/package.json
178
+ ```
179
+
180
+ Once that reaches `master`, [`ui-chat-publish.yml`](../../../.github/workflows/ui-chat-publish.yml) builds `dist`, checks that the package holds `dist/index.html` and no source maps, and publishes both packages with npm trusted publishing. A version npm already has publishes nothing, and a PR that changes the packages gets a dry run.
181
+
182
+ To try a package before it is published:
183
+
184
+ ```bash
185
+ npm run build
186
+ npm pack
187
+ npx ./ggml-org-llama-chat-<version>.tgz
188
+ ```
189
+
190
+ Build right before packing: the package carries whatever is in `dist`, and this folder's `.npmrc` sets `ignore-scripts`, so npm runs no lifecycle script such as `prepack` that could build it for you.
191
+
192
+ ## Related documentation
193
+
194
+ - [llama.cpp server](../../../tools/server/README.md)
195
+ - [Multimodal input](../../../docs/multimodal.md)
196
+ - [Function calling](../../../docs/function-calling.md)
197
+ - [`DESIGN.md`](DESIGN.md), the design rules, and [`AGENTS.md`](AGENTS.md), the conventions for agents
package/bin/cli.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // `npx @ggml-org/llama-chat` and `llama-chat`, see cli/server.js
3
+ import { main } from '../cli/server.js';
4
+
5
+ await main(process.argv.slice(2));
package/cli/server.js ADDED
@@ -0,0 +1,385 @@
1
+ /**
2
+ * `npx @ggml-org/llama-chat`: serves the prebuilt Llama Chat (`dist`) as static files on
3
+ * localhost. `npx @ggml-org/llama-chat build` writes the same files to a folder instead, for any
4
+ * static file server. Node built-ins only, so the published package has no dependencies: no
5
+ * llama-server, no models, no Vite or SvelteKit.
6
+ *
7
+ * It only serves files and forwards nothing: the browser calls each llama-server the app is
8
+ * pointed at directly, so llama-server's own rules (--cors-origins, --api-key) apply as they do
9
+ * to any other page.
10
+ */
11
+
12
+ import { spawn } from 'node:child_process';
13
+ import { createReadStream, readFileSync } from 'node:fs';
14
+ import { cp, readdir, stat } from 'node:fs/promises';
15
+ import http from 'node:http';
16
+ import { extname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { parseArgs } from 'node:util';
19
+
20
+ export const PACKAGE_ROOT = fileURLToPath(new URL('..', import.meta.url));
21
+ export const DIST_DIR = join(PACKAGE_ROOT, 'dist');
22
+
23
+ export const DEFAULTS = Object.freeze({
24
+ host: '127.0.0.1',
25
+ // the folder `build` writes to, in the current directory
26
+ out: 'llama-chat',
27
+ // fixed, so the origin, and the chats the browser stores under it, stay the same between runs
28
+ port: 3000
29
+ });
30
+
31
+ // The same caching llama-server applies to the UI it embeds (tools/server/server-http.cpp):
32
+ // index.html and the PWA's update checks are revalidated, hashed assets are cached for good.
33
+ const NO_CACHE = new Set([
34
+ '/index.html',
35
+ '/service-worker.js',
36
+ '/sw.js',
37
+ '/manifest.webmanifest',
38
+ '/_app/version.json',
39
+ '/build.json'
40
+ ]);
41
+ const CACHE_IMMUTABLE = 'public, max-age=31536000, immutable';
42
+ const CACHE_REVALIDATE = 'no-cache';
43
+ /** @type {Record<string, string>} */
44
+ const MIME_TYPES = {
45
+ '.css': 'text/css; charset=utf-8',
46
+ '.gif': 'image/gif',
47
+ '.html': 'text/html; charset=utf-8',
48
+ '.ico': 'image/x-icon',
49
+ '.jpg': 'image/jpeg',
50
+ '.js': 'text/javascript; charset=utf-8',
51
+ '.json': 'application/json; charset=utf-8',
52
+ '.map': 'application/json; charset=utf-8',
53
+ '.mjs': 'text/javascript; charset=utf-8',
54
+ '.png': 'image/png',
55
+ '.svg': 'image/svg+xml',
56
+ '.ttf': 'font/ttf',
57
+ '.txt': 'text/plain; charset=utf-8',
58
+ '.wasm': 'application/wasm',
59
+ '.webmanifest': 'application/manifest+json; charset=utf-8',
60
+ '.webp': 'image/webp',
61
+ '.woff': 'font/woff',
62
+ '.woff2': 'font/woff2'
63
+ };
64
+ const SERVE_OPTIONS = ['host', 'open', 'port'];
65
+ const BUILD_OPTIONS = ['force', 'out'];
66
+
67
+ export const USAGE = `Usage: llama-chat [options]
68
+ llama-chat build [--out <dir>] [--force]
69
+
70
+ Serves Llama Chat on localhost as static files, or, with build, writes them to
71
+ a folder for any HTTP server. The browser talks to llama-server directly: start
72
+ it with --cors-origins set to this page's address when it restricts origins.
73
+
74
+ Options:
75
+ --port <n> port to listen on (default: ${DEFAULTS.port})
76
+ --host <addr> address to listen on, 0.0.0.0 for the LAN (default: ${DEFAULTS.host})
77
+ --open open the browser once it listens (default)
78
+ --no-open do not open the browser
79
+ -v, --version print the version
80
+ -h, --help print this help
81
+
82
+ Build options:
83
+ --out <dir> folder to write to (default: ./${DEFAULTS.out})
84
+ --force write into a folder that is not empty
85
+
86
+ Examples:
87
+ npx @ggml-org/llama-chat
88
+ npx @ggml-org/llama-chat --host 0.0.0.0 --port 3000 --no-open
89
+ npx @ggml-org/llama-chat build --out ./public`;
90
+
91
+ /** The version in this package's package.json. */
92
+ export function packageVersion() {
93
+ return JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8')).version;
94
+ }
95
+
96
+ /**
97
+ * Reads the command line. No verb serves the app, `start` means the same, and `build` writes it
98
+ * to a folder.
99
+ * @param {string[]} argv the arguments after the command
100
+ * @returns {{ command: 'build' | 'serve', force: boolean, help: boolean, host: string, open: boolean, out: string, port: number, version: boolean }}
101
+ */
102
+ export function parseCliArgs(argv) {
103
+ const { positionals, values } = parseArgs({
104
+ allowNegative: true,
105
+ allowPositionals: true,
106
+ args: argv,
107
+ options: {
108
+ force: { type: 'boolean' },
109
+ help: { short: 'h', type: 'boolean' },
110
+ host: { type: 'string' },
111
+ open: { type: 'boolean' },
112
+ out: { type: 'string' },
113
+ port: { type: 'string' },
114
+ version: { short: 'v', type: 'boolean' }
115
+ },
116
+ strict: true
117
+ });
118
+ const [verb, ...rest] = positionals;
119
+
120
+ if ((verb !== undefined && verb !== 'start' && verb !== 'build') || rest.length > 0) {
121
+ throw new Error(`unknown command: ${positionals.join(' ')}`);
122
+ }
123
+
124
+ const command = verb === 'build' ? 'build' : 'serve';
125
+ const misplaced = (command === 'build' ? SERVE_OPTIONS : BUILD_OPTIONS).find(
126
+ (name) => name in values
127
+ );
128
+
129
+ if (misplaced) {
130
+ throw new Error(
131
+ `--${misplaced} does not apply to ${command === 'build' ? 'build' : 'serving'}`
132
+ );
133
+ }
134
+
135
+ const port = Number(values.port ?? DEFAULTS.port);
136
+
137
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
138
+ throw new Error(`invalid --port: ${values.port}`);
139
+ }
140
+
141
+ return {
142
+ command,
143
+ force: values.force ?? false,
144
+ help: values.help ?? false,
145
+ host: values.host ?? DEFAULTS.host,
146
+ open: values.open ?? true,
147
+ out: values.out ?? DEFAULTS.out,
148
+ port,
149
+ version: values.version ?? false
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Maps a request path to a file under `root`, or null when it falls outside it.
155
+ * @param {string} root
156
+ * @param {string} pathname
157
+ */
158
+ function resolveStatic(root, pathname) {
159
+ let decoded;
160
+
161
+ try {
162
+ decoded = decodeURIComponent(pathname);
163
+ } catch {
164
+ return null;
165
+ }
166
+
167
+ if (decoded.includes('\0')) return null;
168
+
169
+ const file = normalize(join(root, decoded === '/' ? '/index.html' : decoded));
170
+
171
+ return file === root || file.startsWith(root.endsWith(sep) ? root : root + sep) ? file : null;
172
+ }
173
+
174
+ /**
175
+ * Sends a file from `dist`, with llama-server's caching and cross-origin isolation headers.
176
+ * @param {http.IncomingMessage} req
177
+ * @param {http.ServerResponse} res
178
+ * @param {string} file
179
+ * @param {string} pathname
180
+ * @param {import('node:fs').Stats} stats
181
+ */
182
+ function sendFile(req, res, file, pathname, stats) {
183
+ const name = pathname === '/' ? '/index.html' : pathname;
184
+ const etag = `W/"${stats.size.toString(16)}-${Math.floor(stats.mtimeMs).toString(16)}"`;
185
+
186
+ res.setHeader('ETag', etag);
187
+ res.setHeader('Cache-Control', NO_CACHE.has(name) ? CACHE_REVALIDATE : CACHE_IMMUTABLE);
188
+
189
+ if (name === '/index.html') {
190
+ res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
191
+ res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
192
+ }
193
+
194
+ if (req.headers['if-none-match'] === etag) {
195
+ res.writeHead(304).end();
196
+
197
+ return;
198
+ }
199
+
200
+ res.setHeader(
201
+ 'Content-Type',
202
+ MIME_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream'
203
+ );
204
+ res.setHeader('Content-Length', stats.size);
205
+ res.writeHead(200);
206
+
207
+ if (req.method === 'HEAD') {
208
+ res.end();
209
+
210
+ return;
211
+ }
212
+
213
+ createReadStream(file).pipe(res);
214
+ }
215
+
216
+ /**
217
+ * @param {http.ServerResponse} res
218
+ * @param {number} status
219
+ * @param {string} message
220
+ */
221
+ function sendError(res, status, message) {
222
+ res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' });
223
+ res.end(`${message}\n`);
224
+ }
225
+
226
+ /**
227
+ * The HTTP server: the files of `dist`, read-only.
228
+ * @param {{ distDir?: string }} [options]
229
+ */
230
+ export function createChatServer({ distDir = DIST_DIR } = {}) {
231
+ const root = normalize(distDir);
232
+
233
+ return http.createServer(async (req, res) => {
234
+ const { pathname } = new URL(req.url ?? '/', 'http://localhost');
235
+
236
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
237
+ res.setHeader('Allow', 'GET, HEAD');
238
+ sendError(res, 405, 'Method Not Allowed');
239
+
240
+ return;
241
+ }
242
+
243
+ const file = resolveStatic(root, pathname);
244
+ const stats = file ? await stat(file).catch(() => null) : null;
245
+
246
+ if (file && stats?.isFile()) {
247
+ sendFile(req, res, file, pathname, stats);
248
+
249
+ return;
250
+ }
251
+
252
+ sendError(res, 404, 'Not Found');
253
+ });
254
+ }
255
+
256
+ /**
257
+ * Writes the app to a folder: the files of `dist` without source maps, ready for any static
258
+ * file server. Refuses a folder that is not empty unless `force` is set, and a folder in `dist`.
259
+ * @param {{ distDir?: string, force?: boolean, out: string }} options
260
+ * @returns {Promise<string>} the absolute path of the folder
261
+ */
262
+ export async function buildStatic({ distDir = DIST_DIR, force = false, out }) {
263
+ const source = resolve(distDir);
264
+ const target = resolve(out);
265
+ const inside = relative(source, target);
266
+
267
+ if (inside === '' || !(inside.startsWith('..') || isAbsolute(inside))) {
268
+ throw new Error(`cannot build into ${target}, it is inside the app's own files`);
269
+ }
270
+
271
+ const entries = await readdir(target).catch(() => []);
272
+
273
+ if (entries.length > 0 && !force) {
274
+ throw new Error(`${target} is not empty, pick another --out or add --force`);
275
+ }
276
+
277
+ await cp(source, target, { filter: (file) => !file.endsWith('.map'), recursive: true });
278
+
279
+ return target;
280
+ }
281
+
282
+ /**
283
+ * Opens a URL in the default browser, quietly doing nothing where that fails.
284
+ * @param {string} url
285
+ */
286
+ function openBrowser(url) {
287
+ const [command, args] =
288
+ process.platform === 'darwin'
289
+ ? ['open', [url]]
290
+ : process.platform === 'win32'
291
+ ? ['cmd', ['/c', 'start', '""', url]]
292
+ : ['xdg-open', [url]];
293
+
294
+ try {
295
+ // verbatim, or Node quotes the empty title of `start` into one cmd.exe misreads
296
+ spawn(command, args, { detached: true, stdio: 'ignore', windowsVerbatimArguments: true })
297
+ .on('error', () => {})
298
+ .unref();
299
+ } catch {
300
+ // no browser to open, e.g. on a headless machine
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Runs the command.
306
+ * @param {string[]} argv the arguments after the command
307
+ * @returns {Promise<http.Server | undefined>} the server, once it listens
308
+ */
309
+ export async function main(argv) {
310
+ let options;
311
+
312
+ try {
313
+ options = parseCliArgs(argv);
314
+ } catch (error) {
315
+ console.error(`llama-chat: ${error instanceof Error ? error.message : error}\n\n${USAGE}`);
316
+ process.exitCode = 2;
317
+
318
+ return;
319
+ }
320
+
321
+ if (options.help) {
322
+ console.log(USAGE);
323
+
324
+ return;
325
+ }
326
+
327
+ if (options.version) {
328
+ console.log(packageVersion());
329
+
330
+ return;
331
+ }
332
+
333
+ if (!(await stat(join(DIST_DIR, 'index.html')).catch(() => null))) {
334
+ console.error(`llama-chat: no build found in ${DIST_DIR}, run \`npm run build\` first`);
335
+ process.exitCode = 1;
336
+
337
+ return;
338
+ }
339
+
340
+ if (options.command === 'build') {
341
+ try {
342
+ const target = await buildStatic({ force: options.force, out: options.out });
343
+ const shown = relative(process.cwd(), target) || '.';
344
+
345
+ console.log(`Llama Chat ${packageVersion()} written to ${target}`);
346
+ console.log(`Serve it with any static file server, e.g.: npx http-server ${shown}`);
347
+ } catch (error) {
348
+ console.error(`llama-chat: ${error instanceof Error ? error.message : error}`);
349
+ process.exitCode = 1;
350
+ }
351
+
352
+ return;
353
+ }
354
+
355
+ const server = createChatServer();
356
+
357
+ return new Promise((resolve) => {
358
+ server.on('error', (error) => {
359
+ const busy = /** @type {NodeJS.ErrnoException} */ (error).code === 'EADDRINUSE';
360
+
361
+ console.error(
362
+ busy
363
+ ? `llama-chat: port ${options.port} is in use, pick another with --port`
364
+ : `llama-chat: ${error.message}`
365
+ );
366
+ process.exitCode = 1;
367
+ resolve(undefined);
368
+ });
369
+
370
+ server.listen(options.port, options.host, () => {
371
+ const address = /** @type {import('node:net').AddressInfo} */ (server.address());
372
+ const shown = ['0.0.0.0', '::'].includes(options.host) ? 'localhost' : options.host;
373
+ const url = `http://${shown.includes(':') ? `[${shown}]` : shown}:${address.port}/`;
374
+
375
+ console.log(`Llama Chat ${packageVersion()} on ${url}`);
376
+ console.log(
377
+ `If llama-server restricts origins (tools or MCP on), start it with --cors-origins ${url.slice(0, -1)}`
378
+ );
379
+
380
+ if (options.open) openBrowser(url);
381
+
382
+ resolve(server);
383
+ });
384
+ });
385
+ }