dsh-stage 0.0.1 → 0.1.1

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 (4) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +200 -8
  3. package/index.js +360 -5
  4. package/package.json +27 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ - Make `undo()` topology-aware: every apply already records the `topologyHash`
6
+ it was computed against, and undo now compares it with the current topology.
7
+ If the topology changed, undo refuses with
8
+ `{ ok: false, code: 'stale_topology' }` (including `applyId`,
9
+ `recordedTopologyHash` and the current `topologyHash`) and records/marks
10
+ nothing; re-apply the layout and undo the new record instead.
11
+ - Make history append-only: undo state lives in a side table, so past history
12
+ entries are never mutated in place. `history()` still reports `undone` and
13
+ `undoneAt` for apply entries.
14
+ - Return `ok: true` on a successful undo and keep all returned history/receipt
15
+ values as defensive copies.
16
+ - Lock in zone validation with tests: `NaN`, `Infinity`, `-Infinity`,
17
+ negative values and values above `1` are rejected with `invalid_zone` (the
18
+ guard already used `Number.isFinite` plus a `0..1` range check).
19
+
20
+ ## 0.1.0
21
+
22
+ - Add the topology protocol MVP: `ctx.stage` with `setTopology()` / `topology()`
23
+ and validated display, window and space snapshots.
24
+ - Add named layouts with display-relative `0..1` zones (`setLayout()` /
25
+ `layouts()`), including normalized-zone and bounds validation.
26
+ - Add `applyLayout()`: computes focused-first window assignments in native
27
+ display units, records the intent in history and returns
28
+ `{ layout, assignments }` without calling any native window API.
29
+ - Add bounded newest-first `history(limit)` for topology, layout, apply and
30
+ undo entries, plus `undo()` for the most recent un-undone apply.
31
+ - Register the plain-object agent tools `stage_topology`, `stage_layout_set`,
32
+ `stage_layout_apply`, `stage_layout_list` and `stage_undo`.
33
+ - Document that 0.1.0 is the topology protocol MVP and that the macOS AX and
34
+ Windows Win32 adapters are planned for 0.2.0.
35
+
3
36
  ## 0.0.1
4
37
 
5
38
  - Reserve the `dsh-stage` package name.
package/README.md CHANGED
@@ -1,12 +1,17 @@
1
1
  # Stage · `dsh-stage`
2
2
 
3
- > Display, window and space topology for DeepSeek Harness agents, with reversible layouts.
3
+ > **Topology before action.** Read displays, windows and spaces, describe layouts
4
+ > as display-relative zones, and apply them as recorded, undoable intent.
4
5
 
5
- **Status: 0.0.1 name reservation.** The working design lives in the
6
- [dsh-os design notes](https://github.com/PerryLink/dsh-os#readme). A functional MVP is planned for 0.1.0.
6
+ **Status: 0.1.1 is the topology protocol MVP.** Stage validates and records
7
+ topology and layout intent only. It never calls a native window API and cannot
8
+ move a window yet. The **macOS AX adapter and Windows Win32 adapter are planned
9
+ for 0.2.0**. Until an adapter ships, a host integration supplies observations
10
+ through `ctx.stage.setTopology()`.
7
11
 
8
12
  **Not affiliated with DeepSeek.** DeepSeek and DeepSeek Harness are trademarks
9
- of their respective owners.
13
+ of their respective owners. "Stage" here means arranging windows as a stage; it
14
+ is unrelated to Apple Stage Manager.
10
15
 
11
16
  ## Install
12
17
 
@@ -14,8 +19,195 @@ of their respective owners.
14
19
  dsh plugin --profile web add dsh-stage
15
20
  ```
16
21
 
17
- ## Design
22
+ Requires Node 22.19+ (or Node 24.9+). No runtime dependencies.
18
23
 
19
- - Host seam: `ctx.stage` (planned)
20
- - Agent tools and CLI are declared in the package's design doc.
21
- - License: MIT.
24
+ ## Host seam
25
+
26
+ The bundle provides `ctx.stage`:
27
+
28
+ ```js
29
+ const stage = ctx.get('stage')
30
+
31
+ stage.setTopology({
32
+ displays: [
33
+ {
34
+ id: 'main',
35
+ bounds: { x: 0, y: 0, w: 1600, h: 1000 },
36
+ workArea: { x: 0, y: 25, w: 1600, h: 950 },
37
+ dpi: 96,
38
+ },
39
+ ],
40
+ windows: [
41
+ {
42
+ id: 'editor',
43
+ displayId: 'main',
44
+ bounds: { x: 40, y: 40, w: 900, h: 700 },
45
+ focused: true,
46
+ },
47
+ ],
48
+ spaces: [{ id: 'desk-1', displayId: 'main', current: true }],
49
+ })
50
+ ```
51
+
52
+ ### Topology
53
+
54
+ - `displays[]`: `id`, `bounds` (`{x, y, w, h}` with positive `w`/`h`) and a
55
+ positive finite `dpi` are required. `workArea` is optional and defaults to
56
+ `bounds`; it is the origin for zones.
57
+ - `windows[]`: `id`, `displayId` and `bounds` are required. `displayId` must
58
+ reference a display in the same call. `focused` is an optional boolean,
59
+ default `false`; at most one window may be focused.
60
+ - `spaces[]`: `id` and `displayId` are required; `index` is a non-negative
61
+ integer (default `0`) and `current` is a boolean (default `false`). Spaces
62
+ are best-effort metadata and do not affect layout.
63
+ - Ids are non-empty strings and unique within their collection. Bounds may
64
+ have negative `x`/`y` (multi-display global space).
65
+ - `topology()` returns the current snapshot:
66
+ `{ schema, displays, windows, spaces, topologyHash, observedAt }`.
67
+ `topologyHash` is a 16-hex-character digest of the three collections.
68
+ Before the first `setTopology()` the collections are empty and both
69
+ `topologyHash` and `observedAt` are `null`.
70
+ - Bounds and zone results stay in the adapter's native/global coordinate
71
+ units. 0.1.x reports `dpi` as metadata but does not rescale coordinates, so
72
+ mixed-DPI setups never get an implicit conversion.
73
+
74
+ Errors carry a stable `code`: `invalid_topology`, `invalid_display`,
75
+ `invalid_bounds`, `invalid_window`, `invalid_space`, `unknown_display`,
76
+ `duplicate_display`, `duplicate_window`, `duplicate_space`,
77
+ `duplicate_focus`.
78
+
79
+ ### Layouts
80
+
81
+ `setLayout(name, { displayId, zones })` creates or replaces a named layout.
82
+ Each zone is `{ x, y, w, h }` normalized to `0..1` relative to the display's
83
+ `workArea`. Every coordinate must be a finite number within `0..1` — `NaN`,
84
+ `±Infinity`, negatives and values above `1` are rejected with `invalid_zone`.
85
+ A zone needs positive `w`/`h` and must fit:
86
+ `x + w <= 1` and `y + h <= 1`. A layout holds 1 to 20 zones.
87
+
88
+ ```js
89
+ stage.setLayout('halves', {
90
+ displayId: 'main',
91
+ zones: [
92
+ { x: 0, y: 0, w: 0.5, h: 1 },
93
+ { x: 0.5, y: 0, w: 0.5, h: 1 },
94
+ ],
95
+ })
96
+ ```
97
+
98
+ `layouts()` lists definitions sorted by name. Setting an existing name
99
+ replaces it. Definitions can be created before the display is observed; the
100
+ display reference is checked again at apply time.
101
+
102
+ ### Apply, history and undo
103
+
104
+ `applyLayout(name)` requires an observed topology, a registered layout and the
105
+ layout's display. It pairs windows on that display with zones in listed order:
106
+ the focused window first, then windows in observation order. Extra zones stay
107
+ empty and extra windows are untouched. The call returns exactly
108
+ `{ layout, assignments }`:
109
+
110
+ ```json
111
+ {
112
+ "layout": {
113
+ "name": "halves",
114
+ "displayId": "main",
115
+ "zones": [
116
+ { "x": 0, "y": 0, "w": 0.5, "h": 1 },
117
+ { "x": 0.5, "y": 0, "w": 0.5, "h": 1 }
118
+ ]
119
+ },
120
+ "assignments": [
121
+ {
122
+ "windowId": "editor",
123
+ "displayId": "main",
124
+ "zone": 0,
125
+ "rect": { "x": 0, "y": 25, "w": 800, "h": 950 }
126
+ }
127
+ ]
128
+ }
129
+ ```
130
+
131
+ `zone` is the zero-based index into `layout.zones`. `rect` is in the display's
132
+ native units, relative to `workArea`, with fractional values rounded to six
133
+ decimal places. No OS call is made: the record is intent for a future adapter.
134
+
135
+ `history(limit = 20)` returns the newest entries first. Entries have an `id`,
136
+ an ISO `at` and a `type` of `topology`, `layout`, `apply` or `undo`; `limit`
137
+ must be an integer from 1 to 200, and history keeps at most 200 entries.
138
+
139
+ `undo()` reverses the most recent apply that has not already been undone. Every
140
+ apply records the `topologyHash` it was computed against; undo compares that
141
+ hash with the current topology before doing anything:
142
+
143
+ - **Same topology** — the apply's history entry is reported with `undone: true`
144
+ (history itself is append-only), an `undo` entry is appended, and the call
145
+ returns `ok: true` plus the receipt below.
146
+ - **Topology changed** — the recorded rectangles are stale, so undo does not
147
+ execute. It returns `{ ok: false, code: 'stale_topology', applyId,
148
+ recordedTopologyHash, topologyHash }`, records no `undo` entry and leaves the
149
+ apply un-undone. Re-apply the layout on the current topology and undo that
150
+ new record instead; raising a new layout definition is not required.
151
+
152
+ ```json
153
+ {
154
+ "ok": true,
155
+ "schema": "dsh.stage.undo/v1",
156
+ "undone": {
157
+ "id": "h3",
158
+ "at": "2026-11-20T12:00:00.000Z",
159
+ "layout": {
160
+ "name": "halves",
161
+ "displayId": "main",
162
+ "zones": [
163
+ { "x": 0, "y": 0, "w": 0.5, "h": 1 },
164
+ { "x": 0.5, "y": 0, "w": 0.5, "h": 1 }
165
+ ]
166
+ },
167
+ "assignments": [
168
+ {
169
+ "windowId": "editor",
170
+ "displayId": "main",
171
+ "zone": 0,
172
+ "rect": { "x": 0, "y": 25, "w": 800, "h": 950 }
173
+ }
174
+ ]
175
+ }
176
+ }
177
+ ```
178
+
179
+ With no undoable apply, `undo()` throws `nothing_to_undo`. A stale apply stays
180
+ undoable in principle (it will succeed if the topology returns to the recorded
181
+ hash), but until then it returns `stale_topology` rather than a rectangle.
182
+ Error codes for apply are `no_topology`, `unknown_layout`, `unknown_display`
183
+ and `invalid_layout` (bad name); history uses `invalid_limit`.
184
+
185
+ Because 0.1.x performs no native writes, undo is a ledger reversal only.
186
+ Restoring window rectangles, verifying placement and handling user-moved
187
+ windows are adapter concerns for 0.2.0.
188
+
189
+ ## Agent tools
190
+
191
+ | Tool | Input | Returns |
192
+ |---|---|---|
193
+ | `stage_topology` | — | `{ schema, displays, windows, spaces, topologyHash, observedAt }` |
194
+ | `stage_layout_set` | `name`, `displayId`, `zones[]` | `{ layout }` |
195
+ | `stage_layout_apply` | `name` | `{ layout, assignments }` |
196
+ | `stage_layout_list` | — | `{ layouts }` |
197
+ | `stage_undo` | — | undo receipt |
198
+
199
+ All five are plain-object tool definitions with JSON Schema parameters and text
200
+ renderers; they do not depend on `@deepseek-ai/dsh-tools`. The `StageService`
201
+ methods can be used directly without the tool registry, which is how tests and
202
+ future adapters exercise the protocol.
203
+
204
+ ## Scope
205
+
206
+ 0.1.x does **not** enumerate the real desktop, move or resize windows, request
207
+ accessibility or screen-recording permissions, read Spaces through private
208
+ APIs, persist layouts or emit events. Those belong to the macOS AX and Windows
209
+ Win32 adapters, verification and storage work scheduled for 0.2.0.
210
+
211
+ ## License
212
+
213
+ MIT.
package/index.js CHANGED
@@ -1,13 +1,368 @@
1
1
  /**
2
- * dsh-stage — Display, window and space topology for DeepSeek Harness agents, with reversible layouts.
2
+ * dsh-stage — display, window and space topology protocol for DeepSeek Harness.
3
3
  *
4
- * 0.0.1 placeholder: the bundle loads and provides a stable package name.
5
- * The functional implementation lands in 0.1.0.
4
+ * 0.1.0 is the topology protocol MVP: the `ctx.stage` service, named layouts
5
+ * made of display-relative 0..1 zones, applied-intent assignments, bounded
6
+ * history and undo. It never calls a native window API; macOS AX and Windows
7
+ * Win32 adapters are scoped for 0.2.0.
6
8
  * @module dsh-stage
7
9
  */
10
+ import { createHash } from 'node:crypto'
8
11
 
9
12
  /** Cordis plugin name. */
10
13
  export const name = 'dsh-stage'
11
14
 
12
- /** Mount the plugin. The 0.0.1 placeholder intentionally has no side effects. */
13
- export function apply() {}
15
+ /** The protocol is usable without tools; the agent tools need the registry. */
16
+ export const inject = ['tools']
17
+
18
+ /** Stable schema ids for returned values. */
19
+ export const SCHEMAS = { topology: 'dsh.stage.topology/v1', undo: 'dsh.stage.undo/v1' }
20
+
21
+ const MAX_ZONES = 20
22
+ const MAX_HISTORY = 200
23
+ const DEFAULT_HISTORY = 20
24
+ const EPSILON = 1e-9
25
+ const RECT_KEYS = ['x', 'y', 'w', 'h']
26
+
27
+ const fail = (code, message) => Object.assign(new Error(message), { code })
28
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
29
+ const clone = value => structuredClone(value)
30
+ const round = value => Math.round(value * 1e6) / 1e6
31
+ const now = () => new Date().toISOString()
32
+
33
+ function text(value, code, label) {
34
+ if (typeof value !== 'string' || value.trim() === '') throw fail(code, `${label} must be a non-empty string`)
35
+ if (value.includes('\0')) throw fail(code, `${label} must not contain NUL`)
36
+ return value
37
+ }
38
+
39
+ function rectOf(value, label) {
40
+ if (!isObject(value)) throw fail('invalid_bounds', `${label} must be an object`)
41
+ const { x, y, w, h } = value
42
+ if (![x, y, w, h].every(number => typeof number === 'number' && Number.isFinite(number))) {
43
+ throw fail('invalid_bounds', `${label}.x, .y, .w and .h must be finite numbers`)
44
+ }
45
+ if (w <= 0 || h <= 0) throw fail('invalid_bounds', `${label}.w and .h must be positive`)
46
+ return { x, y, w, h }
47
+ }
48
+
49
+ function arrayOf(value, label) {
50
+ if (value === undefined) return []
51
+ if (!Array.isArray(value)) throw fail('invalid_topology', `${label} must be an array`)
52
+ return value
53
+ }
54
+
55
+ function unique(seen, id, code, label) {
56
+ if (seen.has(id)) throw fail(code, `${label} "${id}" is repeated`)
57
+ seen.add(id)
58
+ }
59
+
60
+ function normalizeDisplay(value, index) {
61
+ if (!isObject(value)) throw fail('invalid_display', `displays[${index}] must be an object`)
62
+ const id = text(value.id, 'invalid_display', `displays[${index}].id`)
63
+ const bounds = rectOf(value.bounds, `displays[${index}].bounds`)
64
+ const workArea = value.workArea === undefined ? bounds : rectOf(value.workArea, `displays[${index}].workArea`)
65
+ if (typeof value.dpi !== 'number' || !Number.isFinite(value.dpi) || value.dpi <= 0) {
66
+ throw fail('invalid_display', `displays[${index}].dpi must be a positive finite number`)
67
+ }
68
+ return { id, bounds, workArea, dpi: value.dpi }
69
+ }
70
+
71
+ function normalizeWindow(value, index, displayIds) {
72
+ if (!isObject(value)) throw fail('invalid_window', `windows[${index}] must be an object`)
73
+ const id = text(value.id, 'invalid_window', `windows[${index}].id`)
74
+ const displayId = text(value.displayId, 'invalid_window', `windows[${index}].displayId`)
75
+ if (!displayIds.has(displayId)) throw fail('unknown_display', `windows[${index}].displayId "${displayId}" is not in displays`)
76
+ const bounds = rectOf(value.bounds, `windows[${index}].bounds`)
77
+ const focused = value.focused === undefined ? false : value.focused
78
+ if (typeof focused !== 'boolean') throw fail('invalid_window', `windows[${index}].focused must be a boolean`)
79
+ return { id, displayId, bounds, focused }
80
+ }
81
+
82
+ function normalizeSpace(value, index, displayIds) {
83
+ if (!isObject(value)) throw fail('invalid_space', `spaces[${index}] must be an object`)
84
+ const id = text(value.id, 'invalid_space', `spaces[${index}].id`)
85
+ const displayId = text(value.displayId, 'invalid_space', `spaces[${index}].displayId`)
86
+ if (!displayIds.has(displayId)) throw fail('unknown_display', `spaces[${index}].displayId "${displayId}" is not in displays`)
87
+ const spaceIndex = value.index === undefined ? 0 : value.index
88
+ if (!Number.isInteger(spaceIndex) || spaceIndex < 0) throw fail('invalid_space', `spaces[${index}].index must be a non-negative integer`)
89
+ const current = value.current === undefined ? false : value.current
90
+ if (typeof current !== 'boolean') throw fail('invalid_space', `spaces[${index}].current must be a boolean`)
91
+ return { id, displayId, index: spaceIndex, current }
92
+ }
93
+
94
+ function normalizeZones(value) {
95
+ if (!Array.isArray(value) || value.length === 0) throw fail('invalid_zone', 'zones must be a non-empty array')
96
+ if (value.length > MAX_ZONES) throw fail('invalid_zone', `zones must contain at most ${MAX_ZONES} entries`)
97
+ return value.map((zone, index) => {
98
+ if (!isObject(zone)) throw fail('invalid_zone', `zones[${index}] must be an object`)
99
+ for (const key of RECT_KEYS) {
100
+ const number = zone[key]
101
+ if (typeof number !== 'number' || !Number.isFinite(number) || number < 0 || number > 1) {
102
+ throw fail('invalid_zone', `zones[${index}].${key} must be a finite number within 0..1`)
103
+ }
104
+ }
105
+ if (zone.w === 0 || zone.h === 0) throw fail('invalid_zone', `zones[${index}].w and .h must be positive`)
106
+ if (zone.x + zone.w > 1 + EPSILON || zone.y + zone.h > 1 + EPSILON) {
107
+ throw fail('invalid_zone', `zones[${index}] must fit inside 0..1`)
108
+ }
109
+ return { x: zone.x, y: zone.y, w: zone.w, h: zone.h }
110
+ })
111
+ }
112
+
113
+ const hashTopology = (displays, windows, spaces) => createHash('sha256')
114
+ .update(JSON.stringify({ displays, windows, spaces })).digest('hex').slice(0, 16)
115
+
116
+ const placeZone = (zone, area) => ({
117
+ x: round(area.x + zone.x * area.w), y: round(area.y + zone.y * area.h),
118
+ w: round(zone.w * area.w), h: round(zone.h * area.h),
119
+ })
120
+
121
+ /** Host seam exposed as `ctx.stage`. */
122
+ export class StageService {
123
+ constructor() {
124
+ this._topology = null
125
+ this._layouts = new Map()
126
+ this._history = []
127
+ this._undone = new Map()
128
+ this._sequence = 0
129
+ }
130
+
131
+ _record(entry) {
132
+ const record = { id: `h${++this._sequence}`, at: now(), ...entry }
133
+ this._history.push(record)
134
+ if (this._history.length > MAX_HISTORY) {
135
+ for (const dropped of this._history.splice(0, this._history.length - MAX_HISTORY)) {
136
+ this._undone.delete(dropped.id)
137
+ }
138
+ }
139
+ return record
140
+ }
141
+
142
+ /**
143
+ * Validate and replace the observed topology snapshot. Displays need `id`,
144
+ * `bounds` and a positive `dpi`; windows need `id`, a known `displayId`,
145
+ * `bounds` and an optional boolean `focused`. Spaces are best-effort.
146
+ */
147
+ setTopology(input) {
148
+ if (!isObject(input)) throw fail('invalid_topology', 'topology must be an object')
149
+ const displayIds = new Set()
150
+ const displays = arrayOf(input.displays, 'displays').map((value, index) => {
151
+ const display = normalizeDisplay(value, index)
152
+ unique(displayIds, display.id, 'duplicate_display', 'display id')
153
+ return display
154
+ })
155
+ const windowIds = new Set()
156
+ let focused = 0
157
+ const windows = arrayOf(input.windows, 'windows').map((value, index) => {
158
+ const window = normalizeWindow(value, index, displayIds)
159
+ unique(windowIds, window.id, 'duplicate_window', 'window id')
160
+ if (window.focused) focused += 1
161
+ return window
162
+ })
163
+ if (focused > 1) throw fail('duplicate_focus', 'at most one window may be focused')
164
+ const spaceIds = new Set()
165
+ const spaces = arrayOf(input.spaces, 'spaces').map((value, index) => {
166
+ const space = normalizeSpace(value, index, displayIds)
167
+ unique(spaceIds, space.id, 'duplicate_space', 'space id')
168
+ return space
169
+ })
170
+ const snapshot = {
171
+ schema: SCHEMAS.topology, displays, windows, spaces,
172
+ topologyHash: hashTopology(displays, windows, spaces), observedAt: now(),
173
+ }
174
+ this._topology = snapshot
175
+ this._record({
176
+ type: 'topology', displays: displays.length, windows: windows.length,
177
+ spaces: spaces.length, topologyHash: snapshot.topologyHash,
178
+ })
179
+ return clone(snapshot)
180
+ }
181
+
182
+ /** Read the latest snapshot; an unobserved topology is empty with null hash. */
183
+ topology() {
184
+ return this._topology === null
185
+ ? { schema: SCHEMAS.topology, displays: [], windows: [], spaces: [], topologyHash: null, observedAt: null }
186
+ : clone(this._topology)
187
+ }
188
+
189
+ /** Create or replace a named layout definition. Does not touch topology. */
190
+ setLayout(name, spec) {
191
+ const layoutName = text(name, 'invalid_layout', 'layout name')
192
+ if (!isObject(spec)) throw fail('invalid_layout', 'layout spec must be an object')
193
+ const displayId = text(spec.displayId, 'invalid_layout', 'layout displayId')
194
+ const layout = { name: layoutName, displayId, zones: normalizeZones(spec.zones) }
195
+ this._layouts.set(layoutName, layout)
196
+ this._record({ type: 'layout', name: layoutName, displayId, zones: layout.zones.length })
197
+ return clone(layout)
198
+ }
199
+
200
+ /** All layouts, sorted by name. */
201
+ layouts() {
202
+ return [...this._layouts.values()]
203
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
204
+ .map(item => clone(item))
205
+ }
206
+
207
+ /**
208
+ * Compute and record the intent to place windows of the layout's display.
209
+ * The focused window comes first, then windows in observation order; zones
210
+ * are consumed in listed order. No native API is called.
211
+ */
212
+ applyLayout(name) {
213
+ const layoutName = text(name, 'invalid_layout', 'layout name')
214
+ if (this._topology === null) throw fail('no_topology', 'setTopology() must be called before applyLayout()')
215
+ const layout = this._layouts.get(layoutName)
216
+ if (layout === undefined) throw fail('unknown_layout', `layout "${layoutName}" is not registered`)
217
+ const display = this._topology.displays.find(item => item.id === layout.displayId)
218
+ if (display === undefined) throw fail('unknown_display', `layout display "${layout.displayId}" is not in the current topology`)
219
+ const windows = this._topology.windows
220
+ .map((window, index) => ({ window, index }))
221
+ .filter(item => item.window.displayId === display.id)
222
+ .sort((a, b) => Number(b.window.focused) - Number(a.window.focused) || a.index - b.index)
223
+ .map(item => item.window)
224
+ const assignments = layout.zones.slice(0, windows.length).map((zone, index) => ({
225
+ windowId: windows[index].id, displayId: display.id, zone: index, rect: placeZone(zone, display.workArea),
226
+ }))
227
+ this._record({
228
+ type: 'apply', name: layout.name, displayId: display.id, layout: clone(layout),
229
+ assignments: clone(assignments), topologyHash: this._topology.topologyHash,
230
+ })
231
+ return { layout: clone(layout), assignments: clone(assignments) }
232
+ }
233
+
234
+ /** Newest-first history entries, capped by `limit` (default 20, max 200). */
235
+ history(limit = DEFAULT_HISTORY) {
236
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_HISTORY) {
237
+ throw fail('invalid_limit', `history limit must be an integer from 1 to ${MAX_HISTORY}`)
238
+ }
239
+ return clone(this._history.slice(-limit).reverse().map(entry => (
240
+ entry.type === 'apply' && this._undone.has(entry.id)
241
+ ? { ...entry, undone: true, undoneAt: this._undone.get(entry.id) }
242
+ : entry.type === 'apply' ? { ...entry, undone: false } : entry
243
+ )))
244
+ }
245
+
246
+ /**
247
+ * Mark the latest not-yet-undone apply as undone and return its receipt.
248
+ *
249
+ * The apply records the topology hash it was computed against. If the
250
+ * topology has changed since, the recorded rectangles are stale, so undo
251
+ * refuses with `{ ok: false, code: 'stale_topology' }` and changes nothing;
252
+ * re-apply the layout on the current topology and undo that record instead.
253
+ */
254
+ undo() {
255
+ const entry = [...this._history].reverse()
256
+ .find(item => item.type === 'apply' && !this._undone.has(item.id))
257
+ if (entry === undefined) throw fail('nothing_to_undo', 'no applied layout is available to undo')
258
+ const topologyHash = this._topology === null ? null : this._topology.topologyHash
259
+ if (entry.topologyHash !== topologyHash) {
260
+ return {
261
+ ok: false,
262
+ code: 'stale_topology',
263
+ message: 'the topology changed after this layout was applied; re-apply the layout and undo the new record',
264
+ applyId: entry.id,
265
+ recordedTopologyHash: entry.topologyHash,
266
+ topologyHash,
267
+ }
268
+ }
269
+ this._undone.set(entry.id, now())
270
+ this._record({
271
+ type: 'undo', applyId: entry.id, name: entry.name, displayId: entry.displayId, topologyHash,
272
+ })
273
+ return {
274
+ ok: true,
275
+ schema: SCHEMAS.undo,
276
+ undone: { id: entry.id, at: entry.at, layout: clone(entry.layout), assignments: clone(entry.assignments) },
277
+ }
278
+ }
279
+ }
280
+
281
+ const TOOL_OUTPUT = {
282
+ schema: { type: 'object', additionalProperties: true },
283
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
284
+ }
285
+
286
+ const objectSchema = (properties, required) => ({
287
+ type: 'object', additionalProperties: false, properties,
288
+ ...(required === undefined ? {} : { required }),
289
+ })
290
+
291
+ const ZONE_SCHEMA = {
292
+ type: 'object', additionalProperties: false,
293
+ properties: Object.fromEntries(RECT_KEYS.map(key => [key, { type: 'number', minimum: 0, maximum: 1 }])),
294
+ required: RECT_KEYS,
295
+ }
296
+
297
+ const tool = (name, description, parameters, execute) => ({
298
+ name, description, parameters, output: TOOL_OUTPUT,
299
+ async execute(args) {
300
+ return execute(args ?? {})
301
+ },
302
+ })
303
+
304
+ /** Plain-object ToolDefinitions; no `@deepseek-ai/dsh-tools` dependency. */
305
+ export function createTools(service) {
306
+ return [
307
+ tool(
308
+ 'stage_topology',
309
+ 'Read the current display/window/space topology snapshot. Topology is supplied '
310
+ + 'by a platform adapter; 0.1.0 ships no native adapter.',
311
+ objectSchema({}),
312
+ () => service.topology(),
313
+ ),
314
+ tool(
315
+ 'stage_layout_set',
316
+ 'Create or replace a named layout of display-relative 0..1 zones. '
317
+ + 'Records a definition only; it does not move windows.',
318
+ objectSchema({
319
+ name: { type: 'string', description: 'Layout name, e.g. "left-right".' },
320
+ displayId: { type: 'string', description: 'Target display id from stage_topology.' },
321
+ zones: {
322
+ type: 'array',
323
+ items: ZONE_SCHEMA,
324
+ minItems: 1,
325
+ maxItems: MAX_ZONES,
326
+ description: 'Normalized zones in application order.',
327
+ },
328
+ }, ['name', 'displayId', 'zones']),
329
+ args => ({
330
+ layout: service.setLayout(args?.name, {
331
+ displayId: args?.displayId,
332
+ zones: args?.zones,
333
+ }),
334
+ }),
335
+ ),
336
+ tool(
337
+ 'stage_layout_apply',
338
+ 'Record a layout application: pair windows on the target display (focused '
339
+ + 'first) with zones, append it to history and return { layout, assignments }. '
340
+ + 'No native window API is called.',
341
+ objectSchema({ name: { type: 'string' } }, ['name']),
342
+ args => service.applyLayout(args?.name),
343
+ ),
344
+ tool(
345
+ 'stage_layout_list',
346
+ 'List every registered layout, sorted by name.',
347
+ objectSchema({}),
348
+ () => ({ layouts: service.layouts() }),
349
+ ),
350
+ tool(
351
+ 'stage_undo',
352
+ 'Undo the most recent applied layout in the Stage ledger. Reverses recorded '
353
+ + 'intent only; native window restore is an adapter concern.',
354
+ objectSchema({}),
355
+ () => service.undo(),
356
+ ),
357
+ ]
358
+ }
359
+
360
+ /** Mount dsh-stage: provide `ctx.stage` and the five `stage_*` tools. */
361
+ export function apply(ctx, _config = {}) {
362
+ const stage = new StageService()
363
+ ctx.provide('stage', stage)
364
+ if (ctx.tools && typeof ctx.tools.register === 'function') {
365
+ for (const item of createTools(stage)) ctx.tools.register(item)
366
+ }
367
+ return stage
368
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-stage",
3
- "version": "0.0.1",
4
- "description": "Display, window and space topology for DeepSeek Harness agents, with reversible layouts.",
3
+ "version": "0.1.1",
4
+ "description": "Display, window and space topology protocol for DeepSeek Harness agents, with normalized, reversible layouts.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "exports": {
@@ -34,15 +34,38 @@
34
34
  },
35
35
  "engines": {
36
36
  "node": "^22.19.0 || >=24.9.0",
37
- "dsh": ">=0.2.1-rc.2 <0.3.0 || >=0.2.2-0 <0.3.0"
37
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0"
38
38
  },
39
39
  "dsh": {
40
40
  "manifestVersion": 1,
41
41
  "bundle": {
42
42
  "patch": "./cordis.patch.yml"
43
+ },
44
+ "os": {
45
+ "service": "stage",
46
+ "provides": [
47
+ "stage"
48
+ ],
49
+ "capabilities": [
50
+ "ui"
51
+ ],
52
+ "tools": [
53
+ "stage_topology",
54
+ "stage_layout_set",
55
+ "stage_layout_apply",
56
+ "stage_layout_list",
57
+ "stage_undo"
58
+ ],
59
+ "ui": null,
60
+ "stability": "experimental",
61
+ "since": "0.1.0"
43
62
  }
44
63
  },
64
+ "scripts": {
65
+ "test": "node --test"
66
+ },
45
67
  "publishConfig": {
46
- "access": "public"
68
+ "access": "public",
69
+ "registry": "https://registry.npmjs.org/"
47
70
  }
48
71
  }