svarness 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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # svarness
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ef4586c: First release: Svelte coding harness with live components,
8
+ widgets, model-written views, undo and browser twin.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Scott Spence
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,595 @@
1
- # Temporary Holding Version
1
+ # svarness — Svelte + Harness
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
+ ![svarness: a coding harness built with Svelte, for your terminal and your browser](https://raw.githubusercontent.com/spences10/svarness/main/assets/readme-hero.png)
4
+
5
+ [![CI](https://img.shields.io/github/actions/workflow/status/spences10/svarness/ci.yml?branch=main&label=CI)](https://github.com/spences10/svarness/actions/workflows/ci.yml)
6
+ [![npm](https://img.shields.io/npm/v/svarness)](https://www.npmjs.com/package/svarness)
7
+ [![npm downloads](https://img.shields.io/npm/dm/svarness)](https://www.npmjs.com/package/svarness)
8
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
9
+ [![Built with Bun](https://img.shields.io/badge/built%20with-Bun-f9f1e1?logo=bun&logoColor=black)](https://bun.sh)
10
+ [![Svelte 5](https://img.shields.io/badge/Svelte-5-ff3e00?logo=svelte&logoColor=white)](https://svelte.dev)
11
+
12
+ svarness is a conversational coding harness for the terminal. Ask a
13
+ question and get a streaming Markdown reply. Ask about the actual
14
+ project, and the model can inspect it with workspace tools. Ask for a
15
+ change and the assistant edits or creates files, showing each change
16
+ as a diff in the chat. Press Shift+Tab to switch to reviewing each
17
+ edit before it is written. Type `/` to browse commands.
18
+
19
+ ## Start chatting
20
+
21
+ svarness runs on [Bun](https://bun.sh) 1.4.5 or later (it uses
22
+ `bun:sqlite`, `Bun.serve` and OpenTUI's native renderer). Run it from
23
+ npm in the project you want to work on:
24
+
25
+ ```sh
26
+ bunx svarness # or: bun add -g svarness && svarness
27
+ bunx svarness --demo # the offline guided tour, no account
28
+ bunx svarness --help
29
+ ```
30
+
31
+ The workspace is the current directory; pass `--workspace DIR` to work
32
+ elsewhere.
33
+
34
+ From source
35
+ ([github.com/spences10/svarness](https://github.com/spences10/svarness)),
36
+ Bun is also the package manager and test runner:
37
+
38
+ ```sh
39
+ git clone https://github.com/spences10/svarness.git
40
+ cd svarness
41
+ bun install --frozen-lockfile
42
+ bun run start # same flags, e.g. bun run start --demo
43
+ ```
44
+
45
+ `bun run start` uses the repository root as the workspace. Try
46
+ `Read README.md and summarize it in Markdown`, then ask a follow-up.
47
+ Live mode uses your Pi Codex login unless `OPENAI_API_KEY` is set for
48
+ direct API access. Messages use the corresponding subscription or API
49
+ quota. Set the model in `/settings`; `OPENAI_MODEL` overrides it. Each
50
+ launch starts a fresh chat; `/history` reopens a saved one in the same
51
+ workspace.
52
+
53
+ ### Commands and tools
54
+
55
+ Type `@` in a chat message to browse workspace files. Type to filter,
56
+ use ↑/↓ to highlight a file or folder, then Tab or Enter to insert the
57
+ path or open the folder. Esc dismisses the picker without changing the
58
+ draft. A mention is a reference: picking it does not read the file, or
59
+ send the message.
60
+
61
+ Type `/` in the composer to filter commands. Tab completes the
62
+ highlighted command without running it; Enter chooses it. `/theme`
63
+ chooses a palette, `/tools` explains the available tools, `/history`
64
+ lists this workspace's saved conversations, and `/new` starts a fresh
65
+ one. `/mode` matches Shift+Tab; `/check` sets the check command.
66
+
67
+ Live chat can call `read`, `list`, `codemode`, `edit_file` and
68
+ `write_file`. To run code explicitly **without calling a model**, for
69
+ example:
70
+
71
+ ```text
72
+ /codemode return (await tools.read({path:'README.md'})).split('\n').filter(line => line.startsWith('#'))
73
+ ```
74
+
75
+ Codemode runs model- or user-written JavaScript in a bounded QuickJS
76
+ VM, not in Bun's host process. The injected capabilities are
77
+ `tools.read({path})` and `tools.list({path:'.'})`. There is no shell,
78
+ filesystem write, environment access, or network API in the VM. Reads
79
+ are scoped to the launch workspace. Symlinks, parent traversal, and
80
+ common credential filenames are rejected; filename checks are **not**
81
+ secret scanning. Only use workspaces whose readable files you're
82
+ comfortable sending to the provider.
83
+
84
+ For this first version, `read` accepts single-link UTF-8 text files up
85
+ to 16 KiB. `list` returns at most 100 visible entries (a truncated
86
+ listing is marked). File operations use directory descriptors and fail
87
+ closed if the OS doesn't support safe traversal; tested on Linux.
88
+ Codemode has a 2-second deadline, 16 MiB VM heap and up to 16 nested
89
+ file calls per execution.
90
+
91
+ ### Markdown
92
+
93
+ Replies are parsed as Penguin-Flavoured Markdown (PFM) by
94
+ [`@mdsvex/parse`](https://www.npmjs.com/package/@mdsvex/parse) into
95
+ the streaming tree in
96
+ [`@svarness/markdown`](packages/markdown/src/index.ts), and drawn by
97
+ [`Markdown.svelte`](apps/terminal/src/Markdown.svelte). The system
98
+ prompt asks the model for PFM (`_emphasis_`, `*strong*`, fenced code,
99
+ ATX headings, `<https://…>` links). Fenced code is coloured by
100
+ [twinkleplop](https://www.npmjs.com/package/@twinkleplop/core) with
101
+ the theme's syntax colours; unknown languages stay plain, and while a
102
+ block is still streaming only its finished lines are coloured.
103
+
104
+ Because models write other Markdown dialects, the display rules live
105
+ in one place, [`policy.ts`](packages/markdown/src/policy.ts): `**x**`
106
+ shows as one bold, `__x__` shows as bold (PFM reads it as nested
107
+ emphasis), `*x*` is bold, and `{expr}` in prose shows as written.
108
+ Links show their text then the address; bare URLs are not linked.
109
+ Diffs keep their own colouring.
110
+
111
+ ### Components in replies
112
+
113
+ The model can place small live components in a reply with directives.
114
+ A leaf is one line, `::name(key=value)`; a container wraps a markdown
115
+ body between `:::name(key=value)` and `:::`. Quote values with spaces.
116
+ They stream in place, and a container renders while its body is still
117
+ arriving. The specs live in
118
+ [`@svarness/directives`](packages/directives/src/specs.ts) (no
119
+ renderer code); the system prompt is generated from them, and the
120
+ terminal maps each name to a Svelte component in
121
+ [`apps/terminal/src/directives`](apps/terminal/src/directives). Bad
122
+ arguments or an unknown name show `⚠ ::name: <error>` and the body,
123
+ never an error.
124
+
125
+ | Directive | Example |
126
+ | --------------------------------------------- | ----------------------------------------------------------- |
127
+ | `:::callout(kind=info\|tip\|warning\|danger)` | `:::callout(kind=tip)` / `Run the tests.` / `:::` |
128
+ | `:::chart(type=bar\|sparkline, title?)` | `:::chart(type=bar)` / `- core: 14` / `- model: 21` / `:::` |
129
+ | `:::tree(title?)` | `:::tree` / `- src/` / ` - main.ts` / `:::` |
130
+ | `::progress(value, max=100, label?)` | `::progress(value=3, max=5, label="Steps")` |
131
+ | `:::details(summary)` | `:::details(summary="Log")` / `Long text.` / `:::` |
132
+ | `::usage(scope=session\|workspace)` | `::usage(scope=session)` |
133
+
134
+ A chart body is a two-column markdown table or `label: number` list;
135
+ rows that are not numbers are skipped and counted. A tree body is a
136
+ nested list, folders end in `/`. Details start collapsed and open on a
137
+ left click (local state, not saved). `usage` shows the app's live
138
+ totals and re-reads when a turn finishes.
139
+
140
+ Two directives are internal and not in the prompt: `::change(index=N)`
141
+ and `::check`. The conversation appends them to the reply text at the
142
+ moment a file change is recorded or a check result arrives, so a diff
143
+ or check result appears exactly where it happened and the model's
144
+ later text continues after it. A marker counts only if it is a
145
+ top-level marker for a change (or check) the message really has, and
146
+ only its first occurrence shows; anything the model writes itself
147
+ renders as nothing. For persistence and model replay,
148
+ `transcript_text` turns each marker into its one-line `_Edited ..._`
149
+ or check note, and a resumed session turns the notes back into
150
+ markers. History stores each message's changes and check in
151
+ `parts_json`; a change whose before and after exceed 256 KiB keeps
152
+ only its path and status and shows "diff not saved".
153
+
154
+ Components only receive data: a spec lists typed arguments and a body,
155
+ never code. App data (such as usage) reaches a component through a
156
+ Svelte context the app sets, not through imports of stores.
157
+
158
+ ### Edits
159
+
160
+ The model changes files with `edit_file` (replace one exact, unique
161
+ snippet) or `write_file` (create a file, or rewrite one in full;
162
+ missing folders are created). Each write is shown inline as a diff.
163
+
164
+ - **Auto mode** (default): writes apply immediately.
165
+ - **Ask mode** (Shift+Tab, `/mode`, or `--ask` at launch): each write
166
+ waits in a review panel. Enter applies it, A applies it and switches
167
+ to auto, E edits the contents first (Ctrl+Enter when done), Esc
168
+ declines. The model is told the outcome and carries on.
169
+
170
+ Writes are compare-and-swap: if the file changed on disk since the
171
+ model's snapshot, nothing is written and the model is told to re-read.
172
+ Esc while a reply is running stops it and declines any pending edit.
173
+
174
+ To run a check after every turn that changed files:
175
+
176
+ ```text
177
+ /check bun test
178
+ ```
179
+
180
+ or at launch:
181
+
182
+ ```sh
183
+ bunx svarness --workspace ../my-project -- bun test
184
+ ```
185
+
186
+ The check runs as an argv list in the workspace, **not** as a shell
187
+ expression. Quote arguments with spaces. `/check` with no arguments
188
+ clears it. A failing check does not undo the edits.
189
+
190
+ ### Undo, rewind and branch
191
+
192
+ Every applied change records its path, the text before (none if the
193
+ file was created) and the text after, on the reply that made it, and
194
+ history keeps them, so this also works after resuming a session.
195
+
196
+ - `/undo` (or Ctrl+Z with an empty composer) reverts the file changes
197
+ of the latest turn that has any. Run it again to go back another
198
+ turn. The conversation text stays; its changes show as `Reverted`,
199
+ and the next request tells the model they were reverted.
200
+ - `/rewind` (or Esc twice with an empty composer) lists turns, newest
201
+ first. Choose one with ↑/↓, then Enter to rewind the conversation
202
+ and the files of that turn and later ones, `c` for the conversation
203
+ only (files stay as they are), or `b` to branch. Rewinding puts the
204
+ turn's message back in the composer. The usage of the dropped turns
205
+ is forgotten.
206
+ - A branch is a new saved session holding the messages before that
207
+ turn; the original session is untouched and no files change.
208
+ `/history` shows it as `↳ title (from turn N)` under its parent and
209
+ marks the session you are in.
210
+
211
+ Reverting is compare-and-swap, newest change first: a file is put back
212
+ only if it still holds what the change wrote (a created file is
213
+ deleted only if unchanged). A file you edited since is skipped and
214
+ reported, for example
215
+ `Reverted 2 changes · 1 skipped: greet.ts changed since`. Changes
216
+ whose diff was too large to save cannot be reverted. Undo and rewind
217
+ wait for an idle session.
218
+
219
+ ### Live widgets
220
+
221
+ A widget is a tool result that stays reactive. The model pins one with
222
+ `watch`; it shows in the reply as
223
+ `● live · file greet.ts · updated 3s ago` and keeps updating as its
224
+ source changes. The model can read the current value with
225
+ `read_widget` instead of running a tool again, and stop it with
226
+ `unwatch`. You can pin one yourself with `/watch`.
227
+
228
+ | Source | Arguments | Shows |
229
+ | ------------ | --------- | ---------------------------------------------------------------------- |
230
+ | `file` | `path` | The file, re-read on change (100 ms debounce), "missing" if it is gone |
231
+ | `git_status` | none | Branch and changed files, refreshed on workspace changes (300 ms) |
232
+ | `check` | none | Your configured check, re-run on workspace changes (500 ms) |
233
+ | `usage` | `scope` | Session or workspace totals, refreshed after each turn |
234
+
235
+ Commands: `/watch <source> [key=value …]` (for example
236
+ `/watch file greet.ts`; the widget appears below the conversation, not
237
+ in a reply), `/widgets` lists live widgets and `/unwatch <id>` stops
238
+ one. There are no extra keys.
239
+
240
+ Safety and limits:
241
+
242
+ - No model-supplied commands. `git_status` runs one fixed `git status`
243
+ with no shell, and `check` only runs the command you set with
244
+ `/check`. If none is set the widget says so.
245
+ - `file` reads through the same workspace read path as `read`: private
246
+ names, parent traversal and symlinks are refused, and private names
247
+ never appear in `git_status`.
248
+ - Output is bounded: the text the model reads is at most 16 KiB,
249
+ `file` shows 200 lines (the terminal draws the first 40), `check`
250
+ keeps the last 40 lines. Changes under `.git` (except `HEAD` and
251
+ `index`) and `node_modules` do not trigger refreshes. A check that
252
+ writes into the workspace will re-trigger itself.
253
+ - A new change aborts a running check, and only one check runs at a
254
+ time.
255
+ - Widgets stop when you start a new session, resume one, rewind past
256
+ them, or quit. A resumed session shows each widget's last value as
257
+ `● ended` and does not restart it.
258
+
259
+ ### Model-written views
260
+
261
+ A view is a small layout the model writes for one reply. It calls
262
+ `create_view` with a `name`, a `script` and a `template`. The script
263
+ runs in the codemode sandbox and returns JSON, which becomes `data`.
264
+ The template is a restricted Svelte fragment that lays `data` out with
265
+ the shared components. The view shows in the reply where the call
266
+ happened. Step 7 of the offline tour (`svarness --demo`) builds one.
267
+
268
+ Allowed in a template
269
+ ([`validate.ts`](packages/views/src/validate.ts)):
270
+
271
+ | Construct | Allowed |
272
+ | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
273
+ | Components | `Box`, `Text`, `Span`, `Link`, `Callout`, `Chart`, `Tree`, `Progress`, each with a fixed prop list |
274
+ | Nesting | `Box` holds `Box`, `Text` and the other components; `Text` holds text, `Span`, `Link`; `Span` and `Link` hold text; the other components hold nothing |
275
+ | Blocks | `{#if}`, `{:else if}`, `{:else}`, `{#each list as item, i (key)}` and `{:else}`; each over arrays only, first 200 items, at most 2 deep |
276
+ | Expressions | `data`, names bound by `{#each}`, literals, template strings, arithmetic, comparison, `&&` `\|\|` `??`, `?:`, `!`, `typeof`, arrays and plain objects |
277
+ | Member reads | `a.b`, `a?.b`, `a[0]`, `a["key"]`, `a[i]` where `i` is an `{#each}` index |
278
+ | Calls | Only `x.m(...)` with `m` in `toFixed`, `toUpperCase`, `toLowerCase`, `trim`, `slice`, `join`, `includes`, `startsWith`, `endsWith`, `padStart`, `padEnd`, `at` |
279
+ | Limits | 8 KiB template, 32 levels deep; `padStart`/`padEnd` width is a number literal up to 200; `join` takes no argument or a string literal |
280
+
281
+ Refused: `<script>`, `<style>`, `<svelte:*>`, lowercase HTML or
282
+ OpenTUI elements, comments, `{@html}`, `{@render}`, `{@const}`,
283
+ `{@debug}`, `{@attach}`, `{#await}`, `{#key}`, `{#snippet}`, every
284
+ directive (`on:`, `bind:`, `use:`, `class:`, `style:`, `transition:`,
285
+ `animate:`, `let:`), spread attributes, props starting with `on`,
286
+ functions and arrow functions, `new`, assignment, update, sequence,
287
+ `this`, tagged templates, regular expressions, free function calls,
288
+ `delete`, `void`, `in`, `instanceof`, and the property names
289
+ `constructor`, `prototype`, `caller`, `callee`, `arguments` and
290
+ anything starting with `__`.
291
+
292
+ Safety model:
293
+
294
+ - The script has the codemode limits (2-second deadline, 16 MiB heap,
295
+ 16 file calls, read-only). Its return value must be JSON of at most
296
+ 64 KiB. The script is not kept.
297
+ - The template is validated before the script runs. A rejected
298
+ template runs nothing and stores nothing; the model gets the errors
299
+ and can try again.
300
+ - To render, the terminal validates the template again, wraps it in a
301
+ fixed `<script>` (imports, `let { data } = $props()`), and checks
302
+ that the result parses back to exactly that script plus a valid
303
+ template. Every `{#each}` list goes through a guard that returns an
304
+ array of at most 200 items. `Link` checks at render time that its
305
+ `href` is an http(s) URL. The component is compiled with
306
+ `opentui-svelte`'s compiler, its imports are replaced by lookups in
307
+ the modules the app already runs
308
+ ([`link_view`](packages/views/src/link.ts)), so a view shares the
309
+ app's Svelte runtime and imports nothing from disk. It is written to
310
+ `${XDG_STATE_HOME:-~/.local/state}/svarness/views/<hash>.js` and
311
+ imported, cached by hash.
312
+ - A template can only read `data` and call the pure methods above. It
313
+ cannot reach globals, prototypes or the wrapper's names. A render
314
+ error shows as a one-line warning in the reply.
315
+ - Limits make a view bounded, not cheap: a view can still draw up to
316
+ 200 × 200 rows.
317
+ - Saved sessions keep each view's name, template and data. The model
318
+ sees `_View "name" (template + data recorded)_` in its place.
319
+ - The browser twin draws each view in its own sandboxed iframe, on top
320
+ of the same validation (see Browser twin below).
321
+
322
+ ### Browser twin
323
+
324
+ `/web` starts a local web page that mirrors this session next to the
325
+ terminal and prints its link. The terminal process stays the single
326
+ source of truth: the page only shows the conversation and calls the
327
+ same methods the terminal does. Open the link on the same machine.
328
+
329
+ Security model:
330
+
331
+ - The server listens on `127.0.0.1` only, on a random port.
332
+ - Every request needs a random 32-byte token. The link carries it for
333
+ the first page load; after that it lives in an `HttpOnly`,
334
+ `SameSite=Strict` cookie. A new `/web` after a restart has a new
335
+ token.
336
+ - Requests whose `Host` is not `127.0.0.1:<port>` or
337
+ `localhost:<port>` get 403 (DNS rebinding). There are no CORS
338
+ headers. `POST` needs the token, `Content-Type: application/json`,
339
+ and a same-origin `Origin` if one is sent.
340
+ - Actions are a fixed list, strictly validated. The page cannot read
341
+ or write files or run commands except through those actions.
342
+ - The server stops when you exit the terminal.
343
+
344
+ Views in the page ([`views.ts`](apps/web/src/views.ts),
345
+ [`frame/`](apps/web/src/frame)):
346
+
347
+ - `GET /views/<sha256>.js` and `.html` need the token like every
348
+ route. The hash is the template's SHA-256. Only a template in the
349
+ current conversation (and without a recorded error) is found;
350
+ anything else is 404, so the route is not a general compiler. The
351
+ template is validated again before every build; a refused one is 422
352
+ and nothing is compiled.
353
+ - The build wraps the template exactly as the terminal does
354
+ (`component_source`), compiles it for the DOM and links it like the
355
+ terminal does. The script is the frame runtime
356
+ ([`frame/runtime.ts`](apps/web/src/frame/runtime.ts): the Svelte
357
+ runtime, `@svarness/ui` and the page's primitives, built once)
358
+ followed by the view, with no imports. Bundles are cached by hash,
359
+ at most 32.
360
+ - The `.html` document holds the bundle inline (`</script` and `<!--`
361
+ written as `\x3C`) and a CSP, sent as a header and a meta tag:
362
+ `default-src 'none'; script-src 'sha256-<that script>'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,
363
+ plus `frame-ancestors 'self'; sandbox allow-scripts` in the header.
364
+ No fetch, images, fonts, frames or forms; only that one script runs.
365
+ - The page loads it in `<iframe sandbox="allow-scripts">`, without
366
+ `allow-same-origin`, so the frame has an opaque origin: it cannot
367
+ read the page, its cookie or storage, or call the server with the
368
+ token. Without `allow-popups`, a view's links do not open.
369
+ - The page's own CSP adds only `frame-src 'self'`. The frame is served
370
+ from the server rather than `srcdoc` because a `srcdoc` document
371
+ inherits the page's CSP, which blocks inline scripts.
372
+ - postMessage contract: the page sends
373
+ `{ type: 'render', data, theme_vars }` after each load and when the
374
+ data or theme changes; the frame accepts it only from its parent,
375
+ and keeps only `--name` variables with plain colour values. The
376
+ frame sends `{ type: 'size', height }` on render and on resize; the
377
+ page accepts it only from that iframe's window and clamps the height
378
+ to 0..4000 px.
379
+ - If the bundle cannot be fetched or is refused, the reply shows a
380
+ one-line warning, as the terminal does.
381
+
382
+ From the browser you can read the transcript (Markdown, highlighted
383
+ code, directives, diffs, checks, live widgets and views), send
384
+ messages (Enter sends, Shift+Enter adds a line), stop a reply, toggle
385
+ auto/ask mode, undo the last turn's changes, and review a pending
386
+ change with Apply, Apply all, Edit or Decline. `#/usage` shows session
387
+ and workspace totals and a chart of tool time. The page follows the
388
+ terminal's theme.
389
+
390
+ ### Try it without a model account
391
+
392
+ ```sh
393
+ bunx svarness --demo # from source: bun run start --demo
394
+ ```
395
+
396
+ This is a guided tour in a temporary workspace with a scripted model.
397
+ Only the model is simulated: files, edits, the check, widgets, views,
398
+ the context sidecar and storage are real. It opens with a welcome that
399
+ lists the steps. Type a step number, its phrase, or `next`; `tour`
400
+ lists them again.
401
+
402
+ | Step | Phrase | Shows |
403
+ | ---- | -------------------- | ---------------------------------------------------------------------------------------------- |
404
+ | 1 | `show me components` | Markdown, a highlighted code block, callout, chart, tree, progress, details and live `::usage` |
405
+ | 2 | `watch the greeting` | A live widget on `greet.ts`, plus `git_status` when git is installed |
406
+ | 3 | `fix the greeting` | An edit in auto mode with an inline diff and the real `bun test` check |
407
+ | 4 | `review an edit` | Switches to ask mode and proposes two edits for the review panel (Enter / A / E / Esc) |
408
+ | 5 | `undo` | `/undo` (Ctrl+Z), `/rewind` (Esc Esc) and branching; try undoing step 4 |
409
+ | 6 | `context sidecar` | Reads a 40 KB+ `CHANGELOG.md` into the sidecar, then `context_search` |
410
+ | 7 | `make a view` | A model-written view: a sandboxed script over the workspace and a template |
411
+ | 8 | `browser twin` | What `/web` offers; the demo does not start it |
412
+ | 9 | `usage` | The per-reply usage line, `/usage` and `::usage(scope=workspace)` |
413
+
414
+ Each step ends with what to try and what comes next. Older phrases
415
+ still work: `make a file`, `what is in the readme`. Replies report
416
+ scripted usage, so the usage line and `/usage` have numbers. The
417
+ scratch directory is removed on normal exit.
418
+
419
+ ## Terminal controls
420
+
421
+ | Key | Action |
422
+ | -------------------------- | ------------------------------------------------------------------------- |
423
+ | Enter / Shift+Enter | Send / insert a newline (terminal support varies) |
424
+ | `@` / `/` | Browse workspace files / slash commands |
425
+ | Tab in the composer picker | Complete the highlighted file or command without sending |
426
+ | Shift+Tab | Toggle auto-apply / ask before each edit |
427
+ | ↑ / ↓ in the composer | Recall earlier prompts (this session, then earlier ones in the workspace) |
428
+ | Esc while replying | Stop the turn |
429
+ | Ctrl+Z (empty composer) | Undo the last turn's file changes (`/undo`) |
430
+ | Esc Esc (empty composer) | Open the rewind panel (`/rewind`): Enter / c / b / Esc |
431
+ | Enter / A / E / Esc | In review: apply / apply all from now / edit contents / decline |
432
+ | F2 or `/settings` | Open settings |
433
+ | F6 or `/theme` | Open the theme selector; choose with arrows and Enter, or cancel with Esc |
434
+ | PgUp / PgDn | Scroll |
435
+ | Ctrl+C | Quit |
436
+
437
+ Themes can be switched during a session. Pick **Neon Afterglow** in
438
+ `/theme` for the
439
+ [my-pi palette](https://github.com/spences10/my-pi/blob/main/packages/pi-themes/themes/neon-afterglow.json):
440
+ hot pink headings, laser cyan links, and acid lime inline code. The
441
+ [theme module](apps/terminal/src/theme.ts) defines semantic tokens
442
+ used by the transcript, composer, Markdown, diffs and controls. To add
443
+ a palette, add a `Theme` entry there rather than changing components.
444
+ Your choice is saved for the next launch.
445
+
446
+ ### Local settings and history
447
+
448
+ The terminal stores settings and history with Bun’s built-in
449
+ `bun:sqlite`. By default the database lives at
450
+ `${XDG_STATE_HOME:-~/.local/state}/svarness/state.db`. Set
451
+ `SVARNESS_DB_PATH` to use a different file, or `:memory:` for an
452
+ ephemeral run. Settings are global except the check command; history
453
+ is workspace-specific, and the offline demo has its own session list.
454
+ Completed conversation text is stored locally, **not encrypted**: if a
455
+ reply quotes a file, that quote is part of the saved transcript. Each
456
+ turn's file changes and check result are saved as a one-line note
457
+ (paths and exit code, not diffs). Raw tool payloads, pending reviews
458
+ and credentials are not recorded.
459
+
460
+ Open `/history` to browse the 100 most recently updated sessions in
461
+ this workspace. Type a word from a question **or an answer** to search
462
+ older sessions, even if their titles don’t match. Choose a result to
463
+ resume it; opening the picker or searching does not run a model or
464
+ restore a pending review.
465
+
466
+ There is one database. Each storage package owns its own tables in
467
+ `packages/<module>/src/schema.sql`:
468
+ [`settings`](packages/settings/src/schema.sql),
469
+ [`history`](packages/history/src/schema.sql) (sessions, ordered turns
470
+ and messages with their file changes and check result, and a full-text
471
+ index of message text for history search),
472
+ [`telemetry`](packages/telemetry/src/schema.sql) and
473
+ [`context`](packages/context/src/schema.sql). The
474
+ [`@svarness/sqlite`](packages/sqlite/src/index.ts) `apply_schema` runs
475
+ each file once and records its version in the `schema_versions` table.
476
+ If the recorded version differs from the one the build needs, launch
477
+ fails with a message naming the file: delete it to start fresh. There
478
+ are no migrations. Conversation tables store history, not tool output.
479
+
480
+ #### Telemetry
481
+
482
+ The database also records model and tool usage, as numbers only. Per
483
+ model request: provider, model, token counts (input, output, cache
484
+ read and write), cost, start and end time, and stop reason; a failed
485
+ request is recorded with a generic error. Per tool call: tool name,
486
+ start and end time, an error flag and the size of the result in bytes.
487
+ Prompts, replies, tool arguments, tool output and provider error text
488
+ are not recorded. `/usage` shows totals and the most-used tools for
489
+ the current session and for the workspace; each finished reply also
490
+ shows a one-line summary. Records are keyed by workspace, session and
491
+ turn number, with no foreign keys to history; when a save rewrites
492
+ earlier messages, the records of the discarded turns are deleted.
493
+
494
+ #### Context sidecar
495
+
496
+ When a tool result is larger than 16 KiB, the full output is stored in
497
+ the same database (`context_sources`, `context_chunks` and a full-text
498
+ index) instead of failing. The model gets a receipt (source id, size,
499
+ chunk count) and the first 2 KiB, and can call
500
+ `context_search {query}` and `context_get {id, from?, to?}` to read
501
+ the parts it needs; `context_get` returns at most 16 KiB per call. The
502
+ stored output is not encrypted, stays on this machine, is scoped to
503
+ the workspace and session, and is deleted after 7 days (checked at
504
+ launch). The `read` tool now accepts files up to 1 MiB so large files
505
+ reach the sidecar. Turn it off with the Context sidecar setting (F2);
506
+ with it off, oversized output is an error as before.
507
+
508
+ ### Settings
509
+
510
+ F2 or `/settings` opens the settings panel: ↑/↓ to move, ←/→ to change
511
+ a choice, Enter to edit text, Esc to close. Changes save immediately.
512
+
513
+ | Setting | Values | Notes |
514
+ | --------------- | --------------------- | ----------------------------------------------------------- |
515
+ | Theme | any built-in palette | Also F6 / `/theme`. |
516
+ | Edit mode | Auto-apply, Ask first | Default for new launches; Shift+Tab is session-only. |
517
+ | Check command | argv, e.g. `bun test` | Per workspace. Same as `/check`. |
518
+ | Inline diff | 6, 12, 24 lines, Full | Diff lines shown per edit in the transcript. |
519
+ | Context sidecar | On, Off | Store oversized tool output locally for search. Default On. |
520
+ | Model | provider model id | Blank uses the provider default; `OPENAI_MODEL` wins. |
521
+
522
+ ## Boundaries
523
+
524
+ | Workspace package | Responsibility |
525
+ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
526
+ | [`@svarness/core`](packages/core/src/index.ts) | The [`Conversation`](packages/core/src/conversation.svelte.ts) class: transcript, streaming, auto/ask mode, pending review, edit semantics and the post-turn check. State is Svelte 5 runes, so components read it directly. Depends only on `svelte`. |
527
+ | [`@svarness/markdown`](packages/markdown/src/index.ts) | `MarkdownDocument`: a streaming PFM tree whose nodes are updated in place (Svelte runes), the display policy for model-style Markdown, and `PFM_PROMPT`. Renderer-agnostic; depends on `svelte` and `@mdsvex/parse`. |
528
+ | [`@svarness/model`](packages/model/src/index.ts) | Adapts OpenAI Responses and Pi Codex login to `ChatModel`, and adds `PFM_PROMPT` from `@svarness/markdown` to the system prompt. Runs the tool loop: read/list/codemode, plus `edit_file`/`write_file`, which go through the conversation (and its mode) rather than touching disk. |
529
+ | [`@svarness/local`](packages/local/src/index.ts) | [Scoped read/list and the writer](packages/local/src/workspace-tools.ts), [QuickJS codemode](packages/local/src/codemode.ts) (read-only; the writer is never passed in) and the [check runner](packages/local/src/check.ts). |
530
+ | [`@svarness/sqlite`](packages/sqlite/src/index.ts) | Opens the database (path, pragmas) and applies versioned per-module schemas. No module-specific code. |
531
+ | [`@svarness/settings`](packages/settings/src/index.ts) | Key/value settings table. |
532
+ | [`@svarness/directives`](packages/directives/src/index.ts) | Renderer-agnostic specs, validation and prompt for the components a reply can contain. |
533
+ | [`@svarness/history`](packages/history/src/index.ts) | Completed chat sessions, with search. |
534
+ | [`@svarness/telemetry`](packages/telemetry/src/index.ts) | Model request and tool call records and usage totals. |
535
+ | [`@svarness/context`](packages/context/src/index.ts) | Searchable sidecar for oversized tool output. |
536
+ | [`svarness`](apps/terminal/src/main.ts) | Wires the adapters and renders the workflow using Svelte and OpenTUI, including the Markdown and code components and syntax highlighting. The components don't access files or talk to providers. |
537
+
538
+ Both renderers of a session draw from two shared packages:
539
+
540
+ - [`@svarness/view`](packages/view/src/index.ts): plain TypeScript
541
+ with no Svelte components, OpenTUI or DOM. Highlighting tokens, the
542
+ line diff (`@svarness/view/diff`, Node only), number/money/duration
543
+ text, the usage line, chart and tree shaping, widget tones, and the
544
+ themes.
545
+ - [`@svarness/ui`](packages/ui/src/primitives.ts): Svelte components
546
+ written only against `Box`, `Text`, `Span`, `Link` and `Markdown`,
547
+ which each app supplies with `set_primitives()` (OpenTUI elements in
548
+ [the terminal](apps/terminal/src/primitives/index.ts), styled DOM
549
+ elements in [the page](apps/web/src/client/primitives/index.ts)).
550
+ Sizes are terminal cells: 1 cell is `1ch` across and `1lh` down on
551
+ the page. Shared so far: `callout`, `chart`, `tree`, `progress`,
552
+ `details` and `usage`; `change`, `check`, `widget` and Markdown stay
553
+ per app. `usage` reads totals through `set_directive_data()`;
554
+ `details` keeps its open state and toggles through `Box`'s
555
+ `onclick`.
556
+
557
+ Live chat sends conversation history and tool results to the model. In
558
+ auto mode the model can change any non-private workspace file without
559
+ asking; use ask mode for workspaces you don't want edited
560
+ unsupervised. The check is **not sandboxed**: it inherits the process
561
+ environment and runs as your account. Use a trusted project and check
562
+ command. Pi manages its own login tokens; the app doesn't export them
563
+ for checks.
564
+
565
+ The writer walks pinned directory descriptors, rejects symlinks, hard
566
+ links, private names and paths outside the workspace, and re-reads the
567
+ file immediately before replacing it. That's an optimistic stale-file
568
+ check, not a lock against concurrent external writers.
569
+
570
+ The app's [`bunfig.toml`](apps/terminal/bunfig.toml) preloads the
571
+ OpenTUI adapter; its
572
+ [`svelte.config.js`](apps/terminal/svelte.config.js) enables Svelte
573
+ custom rendering. `@svarness/core` tests compile its rune module with
574
+ a small [preload](packages/core/svelte-preload.ts).
575
+
576
+ The published package has no preload: `bun run build`
577
+ ([build.ts](apps/terminal/build.ts)) bundles the app and every
578
+ `@svarness/*` package into `apps/terminal/dist/` with `.svelte` files
579
+ precompiled, and prebuilds the browser client and view frame runtime.
580
+ Svelte, `opentui-svelte` and the pi packages stay dependencies. See
581
+ [docs/releases.md](docs/releases.md) for publishing.
582
+
583
+ ## Verification and history
584
+
585
+ ```sh
586
+ bun run format # apply Vite+ formatting and lint fixes
587
+ bun run lint # check with Vite+ without changing files
588
+ bun run check # Vite+, TypeScript and Svelte checks
589
+ bun run test # offline, all workspace packages
590
+ bun run --filter @svarness/core test # just the headless workflows
591
+ ```
592
+
593
+ The original read-only Pi/Markdown prototype is preserved at
594
+ `cef146a`. Use `git show cef146a:README.md` to inspect it without
595
+ changing your checkout.
package/dist/cli.js ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bun
2
+ // The svarness bin. Svelte's default entry points are its server build; this
3
+ // plugin points them at the client build that drives OpenTUI before the app
4
+ // loads (the bunfig preload does the same when running from source).
5
+ import { plugin } from 'bun';
6
+ import { createSveltePlugin } from 'opentui-svelte/bun-plugin';
7
+
8
+ plugin(createSveltePlugin({ configFile: false }));
9
+ await import('./main.js');