paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# UI Protocol

**Status:** Definition only — transport-agnostic specification. Transport bindings (stdin/stdout, WebSocket, in-process) are future appendices; this document defines only the message format, the rules both sides follow, and the full message taxonomy with examples.

**Scope:** This document defines how any User Interface (a terminal app today, a web app later) talks to the PaperOS core. It does not change terminal behavior, does not implement an event bus in core, does not add dependencies, and does not pick a concrete transport. Concrete wire framing is deferred to transport appendices named below.

---

## Introduction

PaperOS follows a *minimal core + extensions* architecture (see `docs/architecture.md`). The core provides the runtime, command routing, and event bus; extensions provide commands, actors, views, and I/O.

The UI protocol is the contract between the UI bridge and any UI client. It is a **message-based** protocol:

- The UI is a **projection** — it renders state pushed from the core and sends commands/actions back. (architecture.md §18)
- The **same core** supports Web UI, Desktop WebView, Terminal, and Remote Web UI. The core does not know which UI connects. (architecture.md §20)
- The protocol is **transport-agnostic** — it works over a pipe, a TCP connection with WebSocket framing, or an in-process channel. Only the framing of individual messages (how bytes are split into messages) is transport-specific; the message shapes are not.
- Messages are **JSON** — the project already uses `serde`/`serde_json`, and any future web UI can natively parse it.

### Message taxonomy

```text
UI → Core   (requests — client-initiated, expect a correlated reply or event)
  hello           handshake / version negotiation
  command         invoke a named command (mirrors run_command)
  input           keyboard / text input
  focus           view gained keyboard focus
  resize          terminal / viewport resize
  view.action     view-specific action
  view.subscribe  subscribe to state updates for a view
  view.unsubscribe  stop receiving updates for a view

Core → UI   (responses / unsolicited updates)
  reply           result of a request
  error           error reply (machine-readable code + message)
  event           state-change event (see §10 catalog)
  state           full state snapshot for a view
  notification    unsolicited human-facing message
  layout          view tree arrangement (see §33)
```

(architecture.md §19–20)

### How to read this document

Each message in sections 3–5 has: a purpose paragraph, a JSON schema, and one or more ```json examples. Every ```json block is a complete envelope message. The acceptance test (`tests/acceptance/ui_protocol_tests.rs`) parses every fenced example and enforces envelope invariants, so the document is machine-checked.

---

## Envelope

This protocol uses **JSON Lines framing**: each message is a single complete JSON object on one line. There are no interior newlines within a payload (string values are escaped via standard JSON string escaping). Each line is independently parseable.

```text
{"v":1,"id":"req-1","type":"hello","payload":{"version":1}}
{"v":1,"seq":1,"type":"reply","id":"req-1","payload":{"ok":true,"result":{"version":1}}}
```

### Envelope fields

| Field   | Type    | Direction        | Required | Description |
|---------|---------|------------------|----------|-------------|
| `v`     | integer | Both             | Yes      | Protocol version (see versioning policy, §6). |
| `id`    | string  | UI → Core (req)  | Yes (req)| Client-side unique identifier for request/reply correlation. The server echoes this in the matching `reply` or `error`. |
| `seq`   | integer | Core → UI        | Yes (resp)| Monotonic-per-connection sequence number for Core→UI messages, starting at 1. Used for ordering on the client. Absent on UI→Core messages. |
| `type`  | string  | Both             | Yes      | Message type — one of the catalog values in sections 3–5. |
| `payload`| object | Both             | Yes      | Structured body of the message. Always a JSON object (possibly empty). |

### Request vs. response

- **UI → Core** messages (section 3 catalog) MUST include `id` and MUST NOT include `seq`.
- **Core → UI** messages (section 4 catalog) MUST include `seq`. The `reply` and `error` types MUST also include `id` (echoing the request they answer). `event`, `state`, `notification`, and `layout` are unsolicited and may omit `id`.

```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```

### Transport properties

The byte stream carrying JSON Lines MUST be:

- **Bidirectional** — both sides can send.
- **Ordered** — messages arrive in the order sent on a given direction.
- **Reliable** — no message loss (TCP semantics).
- **Message-boundary preserving** — the transport preserves line/message boundaries so the receiver can split on `\n`.

Transport bindings (named for future appendices — NOT specified here):

- `stdin/stdout` — newline-delimited JSON over the process stdio pipe.
- `WebSocket` — one text frame per JSON line, `ws://<host>:4017/ws`.
- `in-process` — direct channel send, no framing needed.

### Version negotiation

The protocol version is an integer in the `v` envelope field. The client declares its highest supported version in the `hello` payload (`version` field). The server replies with the negotiated version (the minimum of what both sides support). A major-version mismatch terminates the session with an `unsupported_version` error (§6).

```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```

---

## Session

### Hello / version handshake

When a connection is established, the client MUST send `hello` as its first message. The server responds with `reply` (echoing the `id`) containing the negotiated version, or `error` with code `unsupported_version` if the client's requested version is incompatible.

```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```

```json
{"v":1,"seq":1,"type":"reply","id":"h-001","payload":{"ok":true,"result":{"version":1}}}
```

```json
{"v":1,"seq":1,"type":"error","id":"h-001","code":"unsupported_version","payload":{"message":"client version 2 not supported; server supports 1"}}
```

### View subscriptions

The client subscribes to views (see §7 for view addressing and registry) by sending `view.subscribe` with a `view:<id>` target. The server replies with `reply`, then begins pushing `state` snapshots and `event` messages for that view.

```json
{"v":1,"id":"sub-001","type":"view.subscribe","payload":{"view":"view:buffer"}}
```

```json
{"v":1,"seq":2,"type":"reply","id":"sub-001","payload":{"ok":true,"result":null}}
```

Unsubscribing stops state/event delivery for that view:

```json
{"v":1,"id":"unsub-001","type":"view.unsubscribe","payload":{"view":"view:buffer"}}
```

If a client subscribes to an unknown view, the server responds with `error` / `unknown_view`:

```json
{"v":1,"seq":3,"type":"error","id":"sub-002","code":"unknown_view","payload":{"message":"unknown view: view:nonexistent"}}
```

### Disconnect

The client closes the transport stream. The server cleans up all subscriptions and session state for that connection. No explicit logout message is required.

### Reconnection

On disconnect, the server treats each connection as fresh — there is no session continuity in this version. A reconnecting client sends a new `hello` with new `id`s and re-subscribes to the views it wants. The server does not persist subscriptions across disconnects.

---

## UI to Core messages

### hello

**Purpose:** The first message after connection. Negotiates protocol version and announces the client's capabilities.

**Payload fields:**

| Field       | Type    | Description |
|-------------|---------|-------------|
| `version`   | integer | Highest protocol version the client supports. |

```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```

### command

**Purpose:** Invokes a named command on the core's command bus. This mirrors `runtime.run_command("name args")` with the `Option<ActorId>` target model (see `src/core/runtime.rs`). The args are split with `splitn(2)` semantics: the first whitespace-delimited token is the command name, the remainder is a single argument string.

**Payload fields:**

| Field    | Type             | Description |
|----------|------------------|-------------|
| `name`   | string           | Command name (e.g. `"open"`, `"write"`, `"undo"`). |
| `args`   | array[string]    | Command arguments. |
| `target` | `"buffer:<id>"` \| `"view:<id>"` \| null | Optional execution target. When targeting a buffer, maps to `Option<ActorId>` in `run_command`. |

```json
{"v":1,"id":"cmd-001","type":"command","payload":{"name":"open","args":["README.md"],"target":null}}
```

```json
{"v":1,"id":"cmd-002","type":"command","payload":{"name":"save","args":["/tmp/example.txt"],"target":"buffer:buf-1"}}
```

### input

**Purpose:** Sends a keyboard or text input event to the core for dispatch to the active input extension (`InputExtension` or `ViInputExtension`).

**Payload fields:**

| Field   | Type                   | Description |
|---------|------------------------|-------------|
| `kind`  | `"key"` \| `"text"` \| `"ping"` | Input kind. `"key"` for a named key, `"text"` for an inserted character/string, `"ping"` for heartbeat. |
| `value` | string                 | The key name (e.g. `"arrow_down"`, `"enter"`, `"ctrl-s"`) or text content. |

```json
{"v":1,"id":"in-001","type":"input","payload":{"kind":"text","value":"x"}}
```

```json
{"v":1,"id":"in-002","type":"input","payload":{"kind":"key","value":"arrow_down"}}
```

### focus

**Purpose:** Notifies the core that a view has gained keyboard focus.

**Payload fields:**

| Field  | Type             | Description |
|--------|------------------|-------------|
| `view` | `"view:<id>"`    | The view that received focus. |

```json
{"v":1,"id":"f-001","type":"focus","payload":{"view":"view:buffer"}}
```

### resize

**Purpose:** Notifies the core of a viewport / terminal resize.

**Payload fields:**

| Field  | Type    | Description |
|--------|---------|-------------|
| `rows` | integer | New viewport height in rows. |
| `cols` | integer | New viewport width in columns. |

```json
{"v":1,"id":"r-001","type":"resize","payload":{"rows":24,"cols":80}}
```

### view.action

**Purpose:** A view-specific action invocation. The view handles the action via its extension-provided handler.

**Payload fields:**

| Field    | Type          | Description |
|----------|---------------|-------------|
| `view`   | `"view:<id>"` | Target view. |
| `action` | string        | Action name. |
| `args`   | object        | Action arguments (arbitrary JSON object). |

```json
{"v":1,"id":"va-001","type":"view.action","payload":{"view":"view:buffer-list","action":"open","args":{"file":"main.rs"}}}
```

### view.subscribe

**Purpose:** Subscribes to state and event updates for a view. See §2 (Session).

**Payload fields:**

| Field  | Type            | Description |
|--------|-----------------|-------------|
| `view` | `"view:<id>"`   | View to subscribe to. |

```json
{"v":1,"id":"sub-001","type":"view.subscribe","payload":{"view":"view:buffer"}}
```

### view.unsubscribe

**Purpose:** Stops receiving state and event updates for a previously-subscribed view.

**Payload fields:**

| Field  | Type            | Description |
|--------|-----------------|-------------|
| `view` | `"view:<id>"`   | View to unsubscribe from. |

```json
{"v":1,"id":"unsub-001","type":"view.unsubscribe","payload":{"view":"view:buffer"}}
```

---

## Core to UI messages

### reply

**Purpose:** The result of a request. `ok` is true on success; the `result` field carries the return value (which may be `null`). On error, use `error` instead.

**Payload fields:**

| Field   | Type           | Description |
|---------|----------------|-------------|
| `ok`    | boolean        | Success flag. |
| `result`| object \| null | Result data. |

```json
{"v":1,"seq":1,"type":"reply","id":"h-001","payload":{"ok":true,"result":{"version":1}}}
```

```json
{"v":1,"seq":1,"type":"reply","id":"sub-001","payload":{"ok":true,"result":null}}
```

```json
{"v":1,"seq":2,"type":"reply","id":"cmd-001","payload":{"ok":true,"result":{"buffer_id":"buf-1"}}}
```

### error

**Purpose:** An error reply to a request. Always echoes the request `id`.

**Payload fields:**

| Field     | Type   | Description |
|-----------|--------|-------------|
| `code`    | string | Machine-readable error code (see §6 error catalog). |
| `message` | string | Human-readable error message. |

```json
{"v":1,"seq":3,"type":"error","id":"cmd-002","code":"unknown_command","payload":{"message":"Unknown command: savv"}}
```

```json
{"v":1,"seq":3,"type":"error","id":"sub-002","code":"unknown_view","payload":{"message":"unknown view: view:nonexistent"}}
```

### event

**Purpose:** A state-change event published on the event bus (architecture.md §10). The `name` is drawn from the §10 event catalog. Unsolicited — not tied to a specific request.

**Payload fields:**

| Field  | Type    | Description |
|--------|---------|-------------|
| `name` | string  | Event name (see §10 catalog). |
| `data` | object  | Event payload. |

```json
{"v":1,"seq":4,"type":"event","payload":{"name":"BufferChanged","data":{"buffer_id":"buf-1","row":0,"col":1}}}
```

```json
{"v":1,"seq":5,"type":"event","payload":{"name":"BufferSaved","data":{"buffer_id":"buf-1","file_path":"/tmp/example.txt"}}}
```

```json
{"v":1,"seq":6,"type":"event","payload":{"name":"CursorMoved","data":{"buffer_id":"buf-1","row":0,"col":5}}}
```

```json
{"v":1,"seq":7,"type":"event","payload":{"name":"FileOpened","data":{"buffer_id":"buf-2","file_path":"README.md"}}}
```

### state

**Purpose:** Full state snapshot for a subscribed view. Sent after each `view.subscribe` reply and after each event that changes the view's state. This is a *projection* of core state — the UI is authoritative only over its own transient rendering.

**Buffer view payload** (the default editor buffer view):

| Field      | Type            | Description |
|------------|-----------------|-------------|
| `view`     | `"view:<id>"`   | View identifier. |
| `lines`    | array[string]   | Buffer content, one string per line. |
| `cursor`   | object          | `{ "row": int, "col": int }` — 0-indexed, matching `BufferActor`'s `GetCursorPosition` reply. |
| `file_path`| string \| null  | Current file association, or null for unnamed buffers. |
| `mode`     | string          | Editor mode (e.g. `"insert"`, `"normal"`). |

```json
{"v":1,"seq":8,"type":"state","payload":{"view":"view:buffer","lines":["hello world","second line"],"cursor":{"row":0,"col":11},"file_path":"README.md","mode":"normal"}}
```

### notification

**Purpose:** An unsolicited human-facing message (info/warning/error). Does not require a request.

**Payload fields:**

| Field    | Type             | Description |
|----------|------------------|-------------|
| `level`  | `"info"` \| `"warning"` \| `"error"` | Severity. |
| `message`| string           | Human-readable text. |

```json
{"v":1,"seq":9,"type":"notification","payload":{"level":"info","message":"File saved successfully"}}
```

```json
{"v":1,"seq":10,"type":"notification","payload":{"level":"warning","message":"Buffer has unsaved changes"}}
```

### layout

**Purpose:** Describes the arrangement of views in the workspace (architecture.md §33). Sent at session start and whenever the layout changes.

**Payload:** a layout tree object:

| Field     | Type            | Description |
|-----------|-----------------|-------------|
| `root`    | string          | Root container id (e.g. `"workspace"`). |
| `children`| array[string]   | Ordered child region ids (e.g. `["sidebar","main","bottom"]`). |

```json
{"v":1,"seq":11,"type":"layout","payload":{"root":"workspace","children":["sidebar","main","bottom"]}}
```

```json
{"v":1,"seq":12,"type":"layout","payload":{"root":"workspace","children":["main"]}}
```

---

## Error model and versioning policy

### Error reply shape

```json
{"v":1,"seq":3,"type":"error","id":"cmd-002","code":"unknown_command","payload":{"message":"Unknown command: savv"}}
```

An error reply echoes the request `id` (if applicable) and carries a `code` (machine-readable) and a `message` (human-readable) inside the payload.

### Error code catalog

| Code                   | Meaning |
|------------------------|---------|
| `invalid_message`      | The JSON could not be parsed, or did not conform to the envelope shape (missing `v`, `type`, or `payload`). |
| `unknown_type`         | The `type` field is not a recognized message type. |
| `unsupported_version`  | The client's requested protocol version is not supported by the server. |
| `bad_request`          | The request was well-formed but invalid (e.g. missing required payload fields). |
| `unknown_view`         | A `view.subscribe` / `view.unsubscribe` / `focus` / `view.action` referenced an unknown view id. |
| `unknown_command`      | A `command` message named a command that is not registered. |
| `capability_denied`    | The command or action was syntactically valid but the client lacks the capability to perform it. |
| `internal`             | An unexpected internal error occurred. |

### Versioning policy

- The protocol version is an integer in the `v` envelope field.
- **Additive-only evolution**: new message types, new payload fields, and new error codes may be added without incrementing `v`. Existing types are never renumbered or repurposed.
- **Unknown event types are ignored** by clients — a client receiving an event `name` it does not recognize should skip it (forward-compatible).
- **Unknown request `type` values** produce an `unknown_type` error reply carrying the echoed `id`.
- **Unknown error codes** are treated as `internal` by clients (clients should not hard-fail on an unrecognized code).
- **Major version negotiation**: client `hello` declares its version; if the server cannot support at least a compatible major version, it replies with `unsupported_version` and closes the connection. Minor/patch evolution is fully backward-compatible.

```json
{"v":1,"seq":1,"type":"error","id":"h-001","code":"unsupported_version","payload":{"message":"client version 2 not supported; server supports 1"}}
```

---

## Views and wire types

### View addressing

View identifiers follow the rule `view:<id>` where `<id>` is a lowercase-kebab string. The `view:` prefix distinguishes view targets from buffer targets (`buffer:<id>`).

```text
view:buffer
view:status
view:buffer-list
view:problems
```

### View registry

A view is described by six dimensions (architecture.md §32) — **View ID, State, Commands, Events, Layout, Rendering**. The core does not implement every view; extensions provide views and register them in a client-side view registry. Known default view ids are: `buffer` (the editor content), `status` (status bar), `buffer-list` (open buffers), and `problems` (diagnostics). This list is NOT an exhaustive contract — extensions may contribute additional views.

```json
{"v":1,"seq":2,"type":"reply","id":"sub-001","payload":{"ok":true,"result":null}}
```

### Wire types

- **Content** is an array of strings — one element per line. A buffer with no trailing newline has `lines` of length equal to the line count. An empty buffer has `lines: [""]` (one empty string).
- **Cursor** is `{ "row": int, "col": int }`, **0-indexed**, matching the `(usize, usize)` returned by `BufferActor::GetCursorPosition`. Display conversion (1-indexing for status bar, etc.) is client-side.
- **State** is delivered as a full snapshot per view after each event. No diff/patch protocol exists in this version — the client re-renders from the full line array.
- **File path** is a UTF-8 string or null (untitled buffer).

```json
{"v":1,"seq":8,"type":"state","payload":{"view":"view:buffer","lines":["hello","world"],"cursor":{"row":0,"col":5},"file_path":null,"mode":"insert"}}
```

### Layout model

Layouts form a tree (architecture.md §33). The workspace root has children regions. The default three-region layout is:

```text
Workspace
├── Sidebar
├── Main Area
└── Bottom Panel
```

```json
{"v":1,"seq":11,"type":"layout","payload":{"root":"workspace","children":["sidebar","main","bottom"]}}
```

An extension may contribute additional regions. Users customize the layout programmatically via the layout message stream.

### State ↔ events flow

Per architecture.md §18, the flow is:

```text
state → events → UI state → DOM
DOM interaction → command → core
```

The core pushes `state` (full snapshot) and `event` (change notification) messages. The UI applies both and re-renders. DOM interaction (keystrokes, clicks) generates `command`, `input`, or `view.action` messages back to the core.