Skip to content

Commit 138e0ac

Browse files
Merge pull request #1900 from contour-terminal/feature/vt-screen-reader
Add Semantic Block Protocol (DEC Mode 2034) with SBQUERY
2 parents 8326da1 + 987cd24 commit 138e0ac

File tree

14 files changed

+1226
-0
lines changed

14 files changed

+1226
-0
lines changed

.github/actions/spelling/expect.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ circleval
1010
ctrled
1111
dcx
1212
DDDDD
13+
Decset
14+
DECRST
15+
DECSET
1316
ellips
17+
emantic
1418
emtpy
1519
FFFFF
1620
GGGGG
@@ -19,8 +23,12 @@ gitgraph
1923
HHHHH
2024
HTP
2125
isakbm
26+
NCommands
27+
ndrwxr
28+
nfile
2229
pseudoconsole
2330
rbong
31+
SBQUERY
2432
ULval
2533
unscroll
2634
URval
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
# Semantic Block Query (DEC Mode 2034)
2+
3+
This extension provides a discoverable, machine-readable query mechanism that returns structured
4+
JSON blocks of semantic command data from the terminal. It is designed for programmatic consumers
5+
such as AI agents, accessibility tools, and automation scripts.
6+
7+
## Prerequisites
8+
9+
This feature requires [OSC 133 shell integration](osc-133-shell-integration.md) to be active
10+
in the running shell. The shell must emit OSC 133 sequences (A, B, C, D) to mark prompt boundaries,
11+
command output regions, and command completion.
12+
13+
## Feature Discovery
14+
15+
### DEC Private Mode 2034
16+
17+
```
18+
Enable: CSI ? 2034 h (DECSM)
19+
Disable: CSI ? 2034 l (DECRM)
20+
Query: CSI ? 2034 $ p (DECRQM) -> CSI ? 2034 ; Ps $ y
21+
```
22+
23+
Where `Ps` in the DECRQM response is:
24+
- `0` = not recognized (terminal does not support this mode)
25+
- `1` = set (enabled)
26+
- `2` = reset (disabled)
27+
28+
When enabled:
29+
- The terminal tracks semantic zones from OSC 133 sequences using line flags and internal metadata.
30+
- The terminal generates a session token and replies with a DCS containing the token (see Authentication below).
31+
- The query sequence `CSI > Ps ; Pn ; T1 ; T2 ; T3 ; T4 b` becomes available.
32+
33+
When disabled:
34+
- All tracked semantic block data is discarded.
35+
- The session token is invalidated.
36+
- The query sequence returns an error response.
37+
38+
## Authentication
39+
40+
When mode 2034 is enabled via DECSM, the terminal generates a 64-bit session token and replies with:
41+
42+
```
43+
DCS > 2034 ; 1 b T1 ; T2 ; T3 ; T4 ST
44+
```
45+
46+
That is: `ESC P > 2034 ; 1 b T1 ; T2 ; T3 ; T4 ESC \`
47+
48+
The 4 integer values (`T1`..`T4`) are the session token. These same values must be included
49+
in every SBQUERY request as additional CSI parameters (see Query Syntax below). No conversion
50+
is needed — the values from the DCS reply are used directly.
51+
52+
### Token Lifecycle
53+
54+
1. **On DECSET 2034**: Terminal generates a fresh token and replies with the DCS token response.
55+
2. **On SBQUERY**: The token must be included as parameters T1..T4. Missing or invalid tokens produce error responses.
56+
3. **On DECRST 2034**: The token is invalidated along with all tracked data.
57+
4. **On re-enable**: A new token is generated; previous tokens are no longer valid.
58+
59+
### Security Note
60+
61+
DECSET normally does not produce a reply. Some terminal multiplexers (e.g. tmux, screen)
62+
may not forward the DCS token response to the application. In such environments, token-based
63+
authentication may not be usable. This is a known limitation.
64+
65+
## Query Syntax — SBQUERY
66+
67+
```
68+
CSI > Ps ; Pn ; T1 ; T2 ; T3 ; T4 b
69+
```
70+
71+
**Mnemonic:** SBQUERY — **S**emantic **B**lock **QUERY**
72+
73+
CSI with `>` leader, final character `b` (for "blocks").
74+
75+
| Parameter | Meaning |
76+
|-----------|------------------------------------------------------|
77+
| Ps | Query type (see table below) |
78+
| Pn | Count parameter (default 1) |
79+
| T1..T4 | Session token as 4 × uint16 values (from DECSET reply) |
80+
81+
| Ps | Meaning | Pn |
82+
|----|-------------------------------- |---------------------|
83+
| 1 | Last completed command block | ignored |
84+
| 2 | Last N completed command blocks | count (default 1) |
85+
| 3 | Current in-progress command | ignored |
86+
87+
## Response Syntax
88+
89+
The response is a DCS (Device Control String) with `>` leader and final character `b`.
90+
91+
**Success:**
92+
93+
```
94+
DCS > 1 b {JSON} ST
95+
```
96+
97+
That is: `ESC P > 1 b {JSON} ESC \`
98+
99+
**Error — no data or mode disabled:**
100+
101+
```
102+
DCS > 0 b ST
103+
```
104+
105+
**Error — authentication required (missing token):**
106+
107+
```
108+
DCS > 2 b ST
109+
```
110+
111+
**Error — authentication failed (wrong token):**
112+
113+
```
114+
DCS > 3 b ST
115+
```
116+
117+
### Status Codes
118+
119+
| Status | Meaning |
120+
|--------|----------------------------------|
121+
| 0 | Mode disabled or no data |
122+
| 1 | Success with JSON payload |
123+
| 2 | Authentication required (no token provided) |
124+
| 3 | Authentication failed (invalid token) |
125+
126+
## JSON Response Schema
127+
128+
```json
129+
{
130+
"version": 1,
131+
"blocks": [
132+
{
133+
"command": "ls -la",
134+
"prompt": "user@host:~$ ",
135+
"output": "total 42\ndrwxr-xr-x ...",
136+
"exitCode": 0,
137+
"finished": true,
138+
"outputLineCount": 10
139+
}
140+
]
141+
}
142+
```
143+
144+
### Fields
145+
146+
| Field | Type | Description |
147+
|-------------------|-------------------|-------------------------------------------------------------------|
148+
| `version` | integer | Schema version, currently `1`. |
149+
| `blocks` | array | Array of command block objects, ordered chronologically. |
150+
| `command` | string or null | The command line from OSC 133;C `cmdline_url` parameter. |
151+
| `prompt` | string | Text content of the prompt region (from Marked line to OutputStart). |
152+
| `output` | string | Text content of the command output region. |
153+
| `exitCode` | integer | From OSC 133;D parameter. `-1` if unknown. |
154+
| `finished` | boolean | `false` for in-progress commands (Ps=3 query), `true` otherwise. |
155+
| `outputLineCount` | integer | Number of output lines in the block. |
156+
157+
Text fields use JSON's native encoding for control characters (e.g. `\u001b` for ESC),
158+
which ensures the payload never contains a raw ST (ESC \) sequence.
159+
160+
## Example Session
161+
162+
```sh
163+
# 1. Enable the semantic block protocol and capture the token
164+
printf '\033[?2034h'
165+
# Response: DCS > 2034 ; 1 b 41394 ; 50132 ; 58870 ; 1816 ST
166+
# Token values: T1=41394 T2=50132 T3=58870 T4=1816
167+
168+
# 2. Verify it's enabled via DECRQM
169+
printf '\033[?2034$p'
170+
# Response: CSI ? 2034 ; 1 $ y
171+
172+
# 3. Run some commands (with OSC 133 shell integration active)
173+
ls -la
174+
echo hello
175+
176+
# 4. Query the last completed command (with token)
177+
printf '\033[>1;1;41394;50132;58870;1816b'
178+
# Response: DCS > 1 b {"version":1,"blocks":[{"command":"echo hello",...}]} ST
179+
180+
# 5. Query the last 3 completed commands (with token)
181+
printf '\033[>2;3;41394;50132;58870;1816b'
182+
183+
# 6. Query any in-progress command (with token)
184+
printf '\033[>3;1;41394;50132;58870;1816b'
185+
186+
# 7. Disable when done (invalidates the token)
187+
printf '\033[?2034l'
188+
```
189+
190+
## Implementation Notes
191+
192+
- **Token storage**: Terminals implementing this specification should generate the session token
193+
using a cryptographically secure random number generator and store it for the duration of the
194+
mode being enabled. The token must be regenerated on each enable.
195+
- **Terminal multiplexers**: DECSET does not normally produce a reply. Multiplexers and terminal
196+
proxies that intercept DEC mode sequences should be aware that mode 2034 produces a DCS reply
197+
and must forward it to the requesting application.
198+
- **CLI/tool integration**: Tools should capture the DCS token reply immediately after sending
199+
DECSET 2034 and parse the 16-character hex token before issuing any SBQUERY. Libraries should
200+
provide a helper to convert the hex token into the 4 integer parameters.
201+
- **Error handling**: Consumers should check the status byte in every DCS response and handle
202+
status 2 (missing token) and 3 (invalid token) gracefully, e.g. by re-enabling the mode to
203+
obtain a fresh token.
204+
- **Capacity limits**: The number of retained completed command blocks is implementation-defined.
205+
Consumers should not assume an unbounded history.
206+
- **Output encoding**: JSON text fields use standard JSON escaping for control characters
207+
(e.g. `\u001b` for ESC), ensuring the DCS payload never contains a raw ST sequence.
208+
209+
## See Also
210+
211+
- [OSC 133 - Shell Integration](osc-133-shell-integration.md)

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ nav:
124124
- vt-extensions/line-reflow-mode.md
125125
- vt-extensions/save-and-restore-sgr-attributes.md
126126
- vt-extensions/osc-133-shell-integration.md
127+
- vt-extensions/semantic-block-query.md
127128
- Internals:
128129
- internals/index.md
129130
- internals/CODING_STYLE.md

src/vtbackend/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ set(vtbackend_HEADERS
3737
RenderBuffer.h
3838
RenderBufferBuilder.h
3939
Screen.h
40+
SemanticBlockTracker.h
4041
Selector.h
4142
Sequence.h
4243
SequenceBuilder.h
@@ -71,6 +72,7 @@ set(vtbackend_SOURCES
7172
RenderBuffer.cpp
7273
RenderBufferBuilder.cpp
7374
Screen.cpp
75+
SemanticBlockTracker.cpp
7476
Selector.cpp
7577
Sequence.cpp
7678
SixelParser.cpp

src/vtbackend/Functions.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ constexpr inline auto XTCHECKSUM = FunctionDocumentation { .mnemonic = "XTCHECKS
175175
constexpr inline auto SL = FunctionDocumentation { .mnemonic = "SL", .comment = "Scroll Left" };
176176
constexpr inline auto SR = FunctionDocumentation { .mnemonic = "SR", .comment = "Scroll Right" };
177177
constexpr inline auto MODIFYOTHERKEYS = FunctionDocumentation { .mnemonic = "MODIFYOTHERKEYS", .comment = "Modify Other Keys mode" };
178+
constexpr inline auto SBQUERY = FunctionDocumentation { .mnemonic = "SBQUERY", .comment = "Query semantic command blocks." };
178179

179180
} // namespace documentation
180181

@@ -617,6 +618,7 @@ constexpr inline auto XTCHECKSUM = detail::CSI(std::nullopt, 1, 1, '#', 'y', VT
617618
constexpr inline auto XTSMGRAPHICS= detail::CSI('?', 2, 4, std::nullopt, 'S', VTExtension::XTerm, documentation::XTSMGRAPHICS);
618619
constexpr inline auto XTVERSION = detail::CSI('>', 0, 1, std::nullopt, 'q', VTExtension::XTerm, documentation::XTVERSION);
619620
constexpr inline auto MODIFYOTHERKEYS = detail::CSI('>', 0, 1, std::nullopt, 'm', VTExtension::XTerm, documentation::MODIFYOTHERKEYS);
621+
constexpr inline auto SBQUERY = detail::CSI('>', 0, 6, std::nullopt, 'b', VTExtension::Contour, documentation::SBQUERY);
620622

621623
// DCS functions
622624
constexpr inline auto DECRQSS = detail::DCS(std::nullopt, 0, 0, '$', 'q', VTType::VT420, documentation::DECRQSS);
@@ -789,6 +791,7 @@ constexpr static auto allFunctionsArray() noexcept
789791
XTSMGRAPHICS,
790792
XTVERSION,
791793
MODIFYOTHERKEYS,
794+
SBQUERY,
792795

793796
// DCS
794797
STP,

src/vtbackend/Line.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,11 @@ enum class LineFlag : uint8_t
3232
Wrappable = 0x0001,
3333
Wrapped = 0x0002,
3434
Marked = 0x0004,
35+
OutputStart = 0x0008, ///< Command output begins (from OSC 133;C)
3536
DoubleWidth = 0x0010,
3637
DoubleHeightTop = 0x0020,
3738
DoubleHeightBottom = 0x0040,
39+
CommandEnd = 0x0080, ///< Command finished (from OSC 133;D)
3840
};
3941

4042
using LineFlags = crispy::flags<LineFlag>;

0 commit comments

Comments
 (0)