@deepseek-insight/dsi 0.11.0 → 0.11.2

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 (47) hide show
  1. package/README.md +118 -30
  2. package/bin/dsi-chassis.mjs +371 -0
  3. package/bin/dsi.mjs +22 -5
  4. package/build/client/_app/immutable/chunks/{e-3PBXxJ.js → BXbGQv0I.js} +1 -1
  5. package/build/client/_app/immutable/chunks/{UPlr67N1.js → CLf6wcwo.js} +2 -2
  6. package/build/client/_app/immutable/chunks/DXwjOJ3W.js +1 -0
  7. package/build/client/_app/immutable/chunks/FP3OKgFQ.js +1 -0
  8. package/build/client/_app/immutable/entry/{app.ezxtVZch.js → app.wTcqn7d3.js} +2 -2
  9. package/build/client/_app/immutable/entry/start.Bo2gqLX-.js +1 -0
  10. package/build/client/_app/immutable/nodes/{1.CGppLUrN.js → 1.5Yu0dCHp.js} +1 -1
  11. package/build/client/_app/immutable/nodes/{2.9BE7-E5x.js → 2.DAzLHFNq.js} +107 -107
  12. package/build/client/_app/version.json +1 -1
  13. package/build/handler.js +4 -4
  14. package/build/index.js +4 -4
  15. package/build/server/chunks/chunks/{internal2.js-Cu5N8_4R.js → internal2.js-D_dNqBcA.js} +2 -2
  16. package/build/server/chunks/chunks/{registry.js-Bwc2MNSZ.js → registry.js-Cnmd1vW3.js} +194 -19
  17. package/build/server/chunks/chunks/{state.js-CRPhnJJH.js → state.js-BIGPexgb.js} +2 -2
  18. package/build/server/chunks/entries/endpoints/api/browser/_id_/activate/{_server.ts.js-BxfB-QXT.js → _server.ts.js-DlbbO3RF.js} +2 -2
  19. package/build/server/chunks/entries/endpoints/api/browser/_id_/close/{_server.ts.js-DT6rU-EU.js → _server.ts.js-B85bLw4w.js} +2 -2
  20. package/build/server/chunks/entries/endpoints/api/browser/_id_/closetab/{_server.ts.js-Cwu4C98Y.js → _server.ts.js-Dt5Bxv2-.js} +2 -2
  21. package/build/server/chunks/entries/endpoints/api/browser/_id_/element/{_server.ts.js-B55tx3-S.js → _server.ts.js-uJ5BnGUA.js} +2 -2
  22. package/build/server/chunks/entries/endpoints/api/browser/_id_/history/{_server.ts.js-D2ft7u0s.js → _server.ts.js-CVCoWk2n.js} +2 -2
  23. package/build/server/chunks/entries/endpoints/api/browser/_id_/input/{_server.ts.js-BO1uO6i3.js → _server.ts.js-CmhQ7zGO.js} +2 -2
  24. package/build/server/chunks/entries/endpoints/api/browser/_id_/mcp/{_server.ts.js-zOccgfJZ.js → _server.ts.js-CFtpmSCd.js} +2 -2
  25. package/build/server/chunks/entries/endpoints/api/browser/_id_/navigate/{_server.ts.js-DgyR0sLf.js → _server.ts.js-BH8MNt9W.js} +2 -2
  26. package/build/server/chunks/entries/endpoints/api/browser/_id_/opentab/{_server.ts.js-CPCIL2MG.js → _server.ts.js-uIrK0T8h.js} +2 -2
  27. package/build/server/chunks/entries/endpoints/api/browser/_id_/page/{_server.ts.js-Cjvr5nEt.js → _server.ts.js-Bg5yHS9F.js} +2 -2
  28. package/build/server/chunks/entries/endpoints/api/browser/_id_/stream/{_server.ts.js-Bb3DkB-H.js → _server.ts.js-DG6xvUsm.js} +2 -2
  29. package/build/server/chunks/entries/endpoints/api/browser/_id_/tabs/{_server.ts.js-DVcq1pYf.js → _server.ts.js-RiXP45mV.js} +2 -2
  30. package/build/server/chunks/entries/endpoints/api/browser/_id_/viewport/{_server.ts.js-D1xgkwTO.js → _server.ts.js-w9MNQddQ.js} +2 -2
  31. package/build/server/chunks/entries/endpoints/api/browser/_id_/zoom/{_server.ts.js-DFo94fTq.js → _server.ts.js-BoXDoshV.js} +2 -2
  32. package/build/server/chunks/entries/endpoints/api/browser/{_server.ts.js-0Gye8oLN.js → _server.ts.js-pQmJm_Io.js} +2 -2
  33. package/build/server/chunks/entries/pages/{_error.svelte.js-CJ9RHd_3.js → _error.svelte.js-MpJVAPPn.js} +3 -3
  34. package/build/server/chunks/entries/pages/{_page.svelte.js-DlLAziUY.js → _page.svelte.js-tSeYvTqX.js} +111 -10
  35. package/build/server/chunks/{handler-BRlzTcii.js → handler-CdfDULha.js} +3 -3
  36. package/build/server/chunks/{index.js-D2umW-Cg.js → index.js-CAZuEVlJ.js} +2 -2
  37. package/build/server/chunks/{manifest.js-CaT4HRXz.js → manifest.js-Bq-QTetg.js} +19 -19
  38. package/build/server/chunks/nodes/1.js-CKR9qKW9.js +9 -0
  39. package/build/server/chunks/nodes/{2.js-CF_m1q-z.js → 2.js-BuwXpGsh.js} +3 -3
  40. package/package.json +1 -1
  41. package/skills/dsi-host-drive/SKILL.md +96 -0
  42. package/template/.dsi/prompts.sqlite-shm +0 -0
  43. package/template/.dsi/prompts.sqlite-wal +0 -0
  44. package/build/client/_app/immutable/chunks/Dj8AK3pr.js +0 -1
  45. package/build/client/_app/immutable/chunks/WySTHi46.js +0 -1
  46. package/build/client/_app/immutable/entry/start.DdPLwPDt.js +0 -1
  47. package/build/server/chunks/nodes/1.js-cXTCbvze.js +0 -9
package/README.md CHANGED
@@ -5,85 +5,120 @@
5
5
  <p align="center">
6
6
  A different style opinionate <strong>DSH web client</strong> - aka <strong>DSI</strong>
7
7
  <p>
8
+
8
9
  <p align="center">
9
10
  Screenshot: Sidebar, Workspace-explorer, Agent, Glass-browser, Subagent
10
11
  <p>
12
+ <p align="center">
13
+ <strong>Where you can see mulltiple agent / sub-agent plus+ non conversation panels:</strong>
14
+ </p>
11
15
 
12
- #### Where you can see mulltiple **agent** / **sub-agent**, plus+ non conversation panels:
13
- - keys panel: `Agent`, `Subagent`, `Workspace Explorer`, `Glass Browser`, `Terminal`,
14
- - management panel: `Prompt`, `Skill`, `Plugins` and `Configs` Manager`
16
+ - keys panel: **Agent**, **Sub-agent**, **Workspace-explorer**, **Glass-browser**, **Terminal**,
17
+ - management panel: **Prompt**, **Skill**, **Plugins** and **Configs** Manager
15
18
 
16
19
  > [!NOTE]
17
- > ["in a nutshell" - DSI](https://github.com/mitmplay/dsh-insight) make `Harness` present multiple conversations (`agent` or `sub-agent`), `keys` and `management` panels **side-by-side** `INSIDE Container` that can be **re-size** or **scale**.
20
+ > ["in a nutshell" - DSI](https://github.com/mitmplay/dsh-insight) make `Harness` present multiple conversations (**Agent** or **Sub-agent**), **keys** and **management** panels **side-by-side** `INSIDE Container` that can be **re-size** or **scale**.
18
21
 
19
- ## Quick Start
22
+ # Quick Start
20
23
 
21
24
  ```bash
22
- npx @deepseek-insight/dsi@latest dsh --sync --zai
23
- # Open http://localhost:5174
25
+ npx @deepseek-insight/dsi@latest dsh --sync --zai # open http://localhost:5174
24
26
  ```
25
-
27
+ <details><summary>**CLI Params**</strong></summary>
26
28
  | Argument | What it does |
27
29
  |---|---|
28
30
  | `dsh` | starts **DSH** (`dsh web`) and **DSI** together, as one pair and runs it |
29
31
  | `--sync` | copies DSH token to DSI config — **one window, one Ctrl-C stops both** |
30
32
  | `--zai` | **optional.** It bootstraps the GLM (Z.AI) provider into the harness settings (`~/.dsh/settings.yaml`). **If you do not have a GLM account, simply leave it off** — DSI will use whatever provider your harness is already configured with |
31
33
 
34
+ </details>
35
+
32
36
  When it is up, your browser opens the page by itself (default `http://127.0.0.1:5174`).
33
37
 
34
38
  ## Various operations can be Enter in Composer:
35
- - `/dsi-terminal` — Open a terminal session
36
- - `/dsi-prompts` — Open prompt manager
37
- - `/dsi-plugins` — Open plugin manager
38
- - `/dsi-skills` — Open skill manager
39
39
 
40
- ### Autocomplete (`?`)
40
+ <details><summary><strong>Autocomplete (`?`)</strong></summary>
41
41
 
42
- Type `?` followed by a few letters, for example `?deploy`, and a small list appears showing the prompts you have saved before, best match first. Choosing one puts its text into the input, so you can read it and change a detail before sending. It keeps you from typing the same long prompts over and over, and from trying to remember where you saved them.
42
+ Type `?` followed by a few letters, for example `?commit`, and a small list appears showing the prompts you have saved before, best match first. Choosing one puts its text into the input, so you can read it and change a detail before sending. It keeps you from typing the same long prompts over and over, and from trying to remember where you saved them.
43
+ <img src="https://raw.githubusercontent.com/mitmplay/dsh-insight/refs/heads/main/docs/images/dsi-insight-8.ac-complete.png"/>
44
+
45
+ </details>
43
46
 
44
- ### Macros (`!`)
47
+ <details><summary><strong>Macros (`!`)</strong></summary>
45
48
 
46
49
  `!` works the same way, but choosing a prompt runs it right away instead of filling the input. Save the prompts you use every day as macros, and routines like a code review or a session summary become a single short line. Use `?` when you want to look first, and `!` when you already know what you want.
50
+ <img src="https://github.com/mitmplay/dsh-insight/blob/main/docs/images/dsi-insight-8.ac-macro.png?raw=true"/>
51
+
52
+ </details>
53
+
54
+ <details><summary><strong>Prompt Manager (`/dsi-prompts`)</strong></summary>
55
+ - `/dsi-prompts` — Open prompt manager
47
56
 
48
- ### Prompt Manager (`/dsi-prompts`)
49
57
  The prompt manager is where your saved prompts live, so the `?` and `!` tricks above always have something to find. Search across everything you have kept, open a prompt to tweak its wording, flag the ones you use daily as macros, and send a keeper straight back into the input with one click. A prompt you were proud of today becomes a shortcut tomorrow.
58
+ <img src="https://github.com/mitmplay/dsh-insight/blob/main/docs/images/dsi-insight-7.prompt-manager.png?raw=true"/>
59
+
60
+ </details>
61
+
62
+ <details><summary><strong>Plugin Manager (`/dsi-plugins`)</strong></summary>
63
+ - `/dsi-plugins` — Open plugin manager
50
64
 
51
- ### Plugin Manager (`/dsi-plugins`)
52
65
  Plugins add whole features to DSI — the plugin manager shows what is on the rack. A simple install tab lists what you can add, uninstall lists what is already on, and each row shows the plugin's state so you always know what is running. You never touch a config file to add or remove one.
66
+ <img src="https://github.com/mitmplay/dsh-insight/blob/main/docs/images/dsi-insight-7.plugin-rack.png?raw=true"/>
67
+
68
+ </details>
69
+
70
+ <details><summary><strong>Skill Manager (`/dsi-skills`)</strong></summary>
71
+ - `/dsi-skills` — Open skill manager
53
72
 
54
- ### Skill Manager (`/dsi-skills`)
55
73
  Skills are the instructions your agents can follow, and this panel is their shelf. Browse what is installed group by group, tick the ones you want gone, and anything you remove can come back later. If a skill stopped being useful, it is two clicks away from being off the shelf.
74
+ <img src="https://github.com/mitmplay/dsh-insight/blob/main/docs/images/dsi-insight-7.skill-shelf.png?raw=true"/>
75
+
76
+ </details>
77
+
78
+ <details><summary><strong>Terminal (`/dsi-terminal`)</strong></summary>
79
+ - `/dsi-terminal` — Open a terminal session
56
80
 
57
- ### Terminal (`/dsi-terminal`)
58
81
  One terminal is rarely enough when agents are working, so this one opens several, each in its own tab. Open a tab per task, keep a long build running in the background, and your tabs survive a page refresh — come back and they are still there. When a session has ended, the tab tells you instead of leaving you to guess.
82
+ <img src="https://github.com/mitmplay/dsh-insight/blob/main/docs/images/dsi-insight-9.terminall.png?raw=true"/>
83
+
84
+ </details>
85
+
86
+ <details><summary><strong>Workspace explorer</strong></summary>
59
87
 
60
- ### Workspace explorer
61
88
  The workspace explorer is DSI's window into the folder your agents are working in. Click the workspace chip at the top of a conversation — or a file name in one of the assistant's replies — and the panel opens with that file ready. A directory tree shows the whole project, every opened file keeps its own tab so several can sit side by side, and files your agents have changed are marked in the tree, so the work is visible at a glance. One click turns any tab into a before-and-after diff when you want to see exactly what was edited.
89
+ <img src="https://github.com/mitmplay/dsh-insight/blob/main/docs/images/dsi-insight-5.ws-explorer.png?raw=true"/>
90
+
91
+ </details>
62
92
 
63
93
  ## Included skills for:
64
94
  - Coding agents: `/dsi-adr`, `/dsi-spec`, `/dsi-task`
65
95
  - Integration helper for [OpenViking](https://openviking.ai/): `/dsi-ov-setup`
66
96
 
67
- **Your language.** The interface speaks English, Chinese, Indonesian & Spanish.
68
-
69
- <details>
70
- <summary>Deepseek-insight-panels</summary>
97
+ <details><summary>Deepseek-insight-panels</summary>
71
98
  <img src="https://raw.githubusercontent.com/mitmplay/dsh-insight/refs/heads/main/docs/images/dsi-panels.png"/>
72
99
  </details>
73
100
 
74
- ---
101
+ # Ports & the browser brain, in plain words
75
102
 
76
- ### Ports & the browser brain, in plain words
103
+ **Floor** is a pair: **DSI** (the page you watch), **DSH** (the harness host). Each sits on its own port, and ports can be moved — handy when you want **next floor** tobe running.
77
104
 
78
- One "floor" is a pair: **DSH** (the harness host) and **DSI** (the page you watch). Each sits on its own port, and each port can be moved — handy when you want a second floor beside one that is already running.
105
+ ```bash
106
+ npx @deepseek-insight/dsi@latest dsh --sync --zai
107
+ # similar commands with detail of env vars within default values
108
+ DSI_PORT=5174 DSH_PORT=3080 GLASS_PORT=9515 npx @deepseek-insight/dsi@latest dsh --sync --zai
109
+ ```
110
+ <details><summary><strong>Env vars</strong></summary>
79
111
 
80
112
  | What | Default | How to move it | Plain meaning |
81
113
  |---|---|---|---|
82
- | DSH host | `3080` | `--port <n>` or `DSH_PORT=<n>` env var (flag wins) | the harness brain of the floor |
83
114
  | DSI page | `5174` | `DSI_PORT=<n>` env var | the page you open in the browser |
115
+ | DSH host | `3080` | `--port <n>` or `DSH_PORT=<n>` env var (flag wins) | the harness brain of the floor |
84
116
  | Browser brain | `9515` | `GLASS_PORT=<n>` env var | the MCP endpoint agents use to drive the glass browser |
117
+ | Glass chassis | *(this machine)* | `GLASS_CHASSIS_URL=<url>` env var | where Shift+click births its visible window — unset means right here |
118
+ </details>
85
119
 
86
- **The browser brain.** By default the glass browser's assistant (the MCP brain that lets an agent click and type in the browser) runs as its **own separate helper process** — if it fails, you lose only the glass panel. Adding `--playwright-mcp` moves that brain **inside the DSI page server**: one less background process and a faster start, but a brain failure can now touch the page server itself. DSI prints a banner saying so whenever you use the flag — drop the flag to go back to the helper process.
120
+ <details><summary>**The browser brain.**</summary>
121
+ By default the glass browser's assistant (the MCP brain that lets an agent click and type in the browser) runs as its **own separate helper process** — if it fails, you lose only the glass panel. Adding `--playwright-mcp` moves that brain **inside the DSI page server**: one less background process and a faster start, but a brain failure can now touch the page server itself. DSI prints a banner saying so whenever you use the flag — drop the flag to go back to the helper process.
87
122
 
88
123
  **Example — a second, self-contained floor beside a live one** (nothing on the running floor is touched):
89
124
 
@@ -92,9 +127,62 @@ DSI_PORT=5176 DSH_PORT=3081 GLASS_PORT=19515 npx @deepseek-insight/dsi@latest ds
92
127
  # Page: http://localhost:5176 · host: 3081 · brain: http://127.0.0.1:19515/sse
93
128
  ```
94
129
 
95
- **Second floors are fully drivable.** At boot, a floor stamps its own addresses (`DSI_UI`, `DSI_MCP_URL`) into everything it starts — so agents in *that* floor's conversations drive *that* floor's glass automatically, and the preset brain entry follows the stamped port. Nothing on the primary floor changes: without a stamp (a bare `dsh web` boot), the brain falls back to `9515` and the drivers probe `5175` → `5174` exactly as before. One conversation = one glass owner; the driver refuses to touch another conversation's glass, and a session busy in the live floor shows `writer-held` if you try to prompt it from the second window (watch it there, prompt it on its own floor).
130
+ </details>
131
+
132
+ <details><summary>**DSI in a VM, Glass on the host.**</summary>
133
+ Run DSI/DSH inside OrbStack (or any VM) while
134
+ the Glass brain stays on your Mac — that is where the headed glass can be seen
135
+ (Shift+Click opens a visible Playwright window, and only the host display can
136
+ show one). The VM floor boots **brain-less** (no brain flag — never spawn a
137
+ second, invisible brain) and exports `GLASS_BRAIN_URL` pointing at the host;
138
+ OrbStack exposes the Mac to its VMs at `host.internal`:
139
+
140
+ ```bash
141
+ # inside the VM — floor lives here, brain dials the host
142
+ DSI_PORT=5171 DSH_PORT=3081 GLASS_BRAIN_URL=http://host.internal:9515/sse npx @deepseek-insight/dsi@latest dsh --sync
143
+ ```
144
+
145
+ ```mermaid
146
+ sequenceDiagram
147
+ participant M as host Mac
148
+ participant V as VM floor (OrbStack)
149
+ participant G as Glass brain (host 9515)
150
+ M->>M: dsi dsh --sync with the brain flag — Glass lives here
151
+ V->>V: dsi dsh --sync brain-less with GLASS_BRAIN_URL exported
152
+ V->>G: preset dials the host stamp
153
+ G->>G: Shift+Click opens a HEADED window on the host display
154
+ V->>G: tabs, panels, viewport — driven over the wire
155
+ ```
156
+
157
+ ```mermaid
158
+ flowchart TD
159
+ A[floor boots] --> B{GLASS_BRAIN_URL exported?}
160
+ B -- yes --> C[dial that address — VM floor, host brain]
161
+ B -- no --> D[dial 127.0.0.1:GLASS_PORT — same machine]
162
+ C --> E[headed glass opens where the brain runs]
163
+ D --> E
164
+ ```
165
+
166
+ **Second floors are fully drivable.** At boot, a floor stamps its own addresses (`DSI_UI`, `GLASS_BRAIN_URL`) into everything it starts — so agents in *that* floor's conversations drive *that* floor's glass automatically, and the preset brain entry follows the stamped port. Nothing on the primary floor changes: without a stamp (a bare `dsh web` boot), the brain falls back to `9515` and the drivers probe `5175` → `5174` exactly as before. One conversation = one glass owner; the driver refuses to touch another conversation's glass, and a session busy in the live floor shows `writer-held` if you try to prompt it from the second window (watch it there, prompt it on its own floor).
167
+
168
+ </details>
169
+
170
+ <details><summary>**Two glass addresses: brain vs chassis.**</summary>
171
+ The glass has two halves and each has its own stamp. The **brain** (`GLASS_BRAIN_URL`) is where *agents* dial in — the MCP endpoint. The **chassis** (`GLASS_CHASSIS_URL`) is where a Shift+click's *visible window* is born. By default both are "this machine" and nothing changes. When DSI runs on a machine with no screen (a VM) but your screens live on the host, stamp the chassis at the host and the window opens where you are looking:
172
+
173
+ ```bash
174
+ # in the VM — the window is born on the host, the panel mirrors it
175
+ node bin/dsi-chassis.mjs --bind 192.168.1.9 --port 9525 # on the HOST: the chassis companion
176
+ DSI_PORT=5171 DSH_PORT=3081 GLASS_CHASSIS_URL=http://192.168.1.9:9525 pnpm dsi dsh --sync
177
+ ```
178
+
179
+ The host-side **companion** (`dsi-chassis`) births each Shift+click glass on a fresh disposable profile — never your real Chrome profile — enforces the same one-conversation-one-glass rule on its side, binds only the address you name (never all interfaces), and bridges CDP back to the floor. When the stamp is set and the companion is down, the panel says so honestly instead of silently falling back to a screenless local launch; unset the stamp and every floor behaves exactly as before.
180
+
181
+ </details>
96
182
 
97
183
  ## License
98
184
 
99
185
  [Apache-2.0](LICENSE) — Copyright © 2026 [Widi Harsojo](https://www.linkedin.com/in/wharsojo/)
100
186
  > OPEN TO WORK (SG_PR)
187
+
188
+ **Your language.** The interface speaks English, Chinese, Indonesian & Spanish.
@@ -0,0 +1,371 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsi-chassis — the host companion (ADR-0054 D3/D4, spec 2026-11-08 Glass
4
+ * Chassis Remote CDP task 1.1).
5
+ *
6
+ * A small helper that runs on the machine the operator's SCREENS are on.
7
+ * A floor whose launcher stamped GLASS_CHASSIS_URL at this process asks it
8
+ * to birth the headed glass THERE, by the house rules:
9
+ * - disposable profiles only (the Borrowed Chrome posture — the host's
10
+ * real Chrome profile is never mounted, read, or deletable);
11
+ * - one conversation = one glass, enforced HERE (ownership survives the
12
+ * machine boundary; a busy owner is refused with the writer-held
13
+ * contract);
14
+ * - it binds ONLY the interface address given via the required --bind
15
+ * flag, never 0.0.0.0 (D4);
16
+ * - it owns Chrome's debugging port and speaks clean CDP to the floor —
17
+ * HTTP endpoints are proxied with the Host header rewritten, JSON
18
+ * responses have their webSocketDebuggerUrl rewritten to route back
19
+ * through the companion, and websocket upgrades are raw-piped (this
20
+ * is the loopback/Host-header hop, ADR fact 7).
21
+ *
22
+ * The birth rules (profile naming, owner marker, pid-of-port) come from
23
+ * src/lib/server/browser/chassis-shared.ts — the SAME module the floor's
24
+ * registry imports; plain node strips the types natively (Node >= 23.6).
25
+ *
26
+ * Wire:
27
+ * POST /open { width, height, ownerSessionId } -> { id, cdpTarget, pid, profileDir }
28
+ * 409 { error: 'BUSY' } when ownerSessionId already holds a glass
29
+ * POST /close { id } (or { pid } / { profileDir }) -> { ok }
30
+ * GET /status -> { bind, port, glasses: [...] }
31
+ * /cdp/<id>/... CDP bridge (HTTP + websocket upgrade) to that glass
32
+ *
33
+ * Run: node bin/dsi-chassis.mjs --bind 192.168.1.9 [--port 9560]
34
+ */
35
+ import { createServer, request as httpRequest } from 'node:http';
36
+ import { connect as netConnect } from 'node:net';
37
+ import { homedir } from 'node:os';
38
+ import { join } from 'node:path';
39
+ import { mkdirSync, rmSync } from 'node:fs';
40
+ import { pathToFileURL } from 'node:url';
41
+
42
+ import {
43
+ disposableProfilePath,
44
+ pidOfPort,
45
+ writeOwnerMarker
46
+ } from '../src/lib/server/browser/chassis-shared.ts';
47
+
48
+ /** The companion's disposable root — the same default the floor config
49
+ * ships (insight-config). The companion runs on the host and answers to
50
+ * the Borrowed Chrome posture, so deletes are GUARDED to this root. */
51
+ const PROFILE_ROOT = join(homedir(), '.dsi', 'browser-profiles');
52
+
53
+ /** D4 — the bind verdict. Pure: `--bind` is REQUIRED and 0.0.0.0 (and the
54
+ * IPv6 all-interfaces '::') are refused. The stamp already names the
55
+ * exact interface; bind-all buys nothing and invites every device. */
56
+ export function resolveBind(bind) {
57
+ if (bind === undefined || bind === '') {
58
+ return { ok: false, error: 'dsi-chassis: --bind <addr> is required (the private interface from the GLASS_CHASSIS_URL stamp); refusing to guess' };
59
+ }
60
+ if (bind === '0.0.0.0' || bind === '::' || bind === '[::]') {
61
+ return { ok: false, error: 'dsi-chassis: refusing 0.0.0.0 — bind the ONE private interface from the stamp (ADR-0054 D4)' };
62
+ }
63
+ return { ok: true, addr: bind };
64
+ }
65
+
66
+ /** CLI arg parsing — pure, so the pins drive it directly. */
67
+ export function parseArgs(argv) {
68
+ const out = { bind: undefined, port: undefined };
69
+ for (let i = 0; i < argv.length; i += 1) {
70
+ const a = argv[i];
71
+ if (a === '--bind') { out.bind = argv[i + 1]; i += 1; }
72
+ else if (a.startsWith('--bind=')) out.bind = a.slice('--bind='.length);
73
+ else if (a === '--port') { out.port = Number(argv[i + 1]); i += 1; }
74
+ else if (a.startsWith('--port=')) out.port = Number(a.slice('--port='.length));
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /** A free port for Chrome's debugging listener — net probe, no lsof
80
+ * dependency, same behavior on macOS and Linux hosts. */
81
+ async function freeChassisPort(preferred) {
82
+ const { createServer: probeServer } = await import('node:net');
83
+ const tryBind = (port) =>
84
+ new Promise((resolve) => {
85
+ const s = probeServer();
86
+ s.once('error', () => resolve(false));
87
+ s.once('listening', () => s.close(() => resolve(true)));
88
+ s.listen(port, '127.0.0.1');
89
+ });
90
+ if (preferred && (await tryBind(preferred))) return preferred;
91
+ for (let p = 9520; p < 9620; p += 1) if (await tryBind(p)) return p;
92
+ throw new Error('dsi-chassis: no free debugging port in 9520..9619');
93
+ }
94
+
95
+ /** The REAL launcher: headed Chromium on a disposable profile via the
96
+ * repo's pinned playwright-core, channel 'chrome' with the bundled
97
+ * chromium fallback — the same posture registry.open() births with. */
98
+ async function defaultLaunch({ profileDir, args, headless, width, height }) {
99
+ const { chromium } = await import('playwright-core');
100
+ const ignoreDefaultArgs = ['--enable-automation', '--mute-audio', '--hide-scrollbars'];
101
+ // headless honors the floor's plain-click contract (no OS window); only
102
+ // the Shift+click headed open passes false (ADR-0054 D2 — the chassis
103
+ // exists so a HEADED glass can be born where the screens are).
104
+ // Anti-bot parity (registry's PLAIN_IDENTITY posture): a headless birth
105
+ // must not advertise HeadlessChrome — Google captcha'd the first VM-floor
106
+ // plain click on 2026-11-08 while the host floor's spoofed glass passed.
107
+ const identity = headless === true
108
+ ? { userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' }
109
+ : {};
110
+ // Viewport parity (ADR-0041's local contract, carried across the machine
111
+ // boundary): HEADED is window-driven — viewport null so the page tracks
112
+ // Browser.setWindowBounds. HEADLESS has no OS window: pin the viewport to
113
+ // the requested box (no +6/+70 chassis padding — that pads OS title bars,
114
+ // and a headless glass has none) or the mirror is cut off at the bottom
115
+ // (live witness 2026-11-08: VM plain click vs host panel box).
116
+ const viewport = headless === true
117
+ ? { defaultViewport: { width: Number(width) || 730, height: Number(height) || 830 } }
118
+ : { defaultViewport: null };
119
+ let context;
120
+ try {
121
+ context = await chromium.launchPersistentContext(profileDir, { channel: 'chrome', headless: headless === true, ignoreDefaultArgs, ...identity, ...viewport, args });
122
+ } catch {
123
+ context = await chromium.launchPersistentContext(profileDir, { headless: headless === true, ignoreDefaultArgs, ...identity, ...viewport, args });
124
+ }
125
+ const port = Number(args.find((a) => a.startsWith('--remote-debugging-port='))?.split('=')[1]);
126
+ const pid = pidOfPort(port);
127
+ return {
128
+ pid,
129
+ port,
130
+ close: async () => { await context.close(); }
131
+ };
132
+ }
133
+
134
+ /**
135
+ * Start the companion. `launch` is injectable so the pins can drive the
136
+ * whole open/close/ownership/bridge contract without a real Chromium.
137
+ * Returns { server, port, glasses, stop }.
138
+ */
139
+ export async function startChassisCompanion(opts = {}) {
140
+ const bindVerdict = resolveBind(opts.bind);
141
+ if (!bindVerdict.ok) throw new Error(bindVerdict.error);
142
+ const bind = bindVerdict.ok ? bindVerdict.addr : undefined;
143
+ const launch = opts.launch ?? defaultLaunch;
144
+ const portFor = opts.portFor ?? freeChassisPort;
145
+ // Injectable for the pins (and a VM host may relocate the root); the
146
+ // default stays the Borrowed Chrome root. Deletes are GUARDED to THIS
147
+ // root — the guard is a PATH check, never a flag (the borrowed-wipe RCA).
148
+ const profileRoot = opts.profileRoot ?? PROFILE_ROOT;
149
+
150
+ // The ownership registry lives IN this process: one conversation = one
151
+ // glass, keyed by the requesting floor's ownerSessionId (karpathy edge
152
+ // case: two floors stamping the same companion each carry their own id).
153
+ const glasses = new Map(); // id -> glass
154
+ const byOwner = new Map(); // ownerSessionId -> id
155
+
156
+ const server = createServer(async (req, res) => {
157
+ try {
158
+ const url = new URL(req.url ?? '/', 'http://' + (req.headers.host ?? bind));
159
+ // --- the CDP bridge: /cdp/<id>/... proxies to that glass's port ---
160
+ const cdp = url.pathname.match(/^\/cdp\/([^/]+)(\/.*)$/);
161
+ if (cdp) {
162
+ const glass = glasses.get(cdp[1]);
163
+ if (!glass) { res.statusCode = 404; res.end('unknown glass'); return; }
164
+ const headers = { ...req.headers, host: '127.0.0.1:' + glass.debugPort };
165
+ const preq = httpRequest({ host: '127.0.0.1', port: glass.debugPort, path: cdp[2] + url.search, method: req.method, headers }, (pres) => {
166
+ const ctype = String(pres.headers['content-type'] ?? '');
167
+ if (ctype.includes('json')) {
168
+ const chunks = [];
169
+ pres.on('data', (c) => chunks.push(c));
170
+ pres.on('end', () => {
171
+ // Rewrite the advertised debugger urls to route back
172
+ // through THIS companion — the floor never needs to know
173
+ // Chrome's loopback port (ADR fact 7, the Host hop).
174
+ const body = Buffer.concat(chunks).toString('utf8')
175
+ .split('ws://127.0.0.1:' + glass.debugPort).join('ws://' + (req.headers.host ?? bind + ':' + glass.boundPort) + '/cdp/' + glass.id);
176
+ const headers = { ...pres.headers };
177
+ delete headers['transfer-encoding'];
178
+ res.writeHead(pres.statusCode ?? 200, { ...headers, 'content-length': Buffer.byteLength(body) });
179
+ res.end(body);
180
+ });
181
+ return;
182
+ }
183
+ res.writeHead(pres.statusCode ?? 200, pres.headers);
184
+ pres.pipe(res);
185
+ });
186
+ preq.on('error', () => { try { res.statusCode = 502; res.end('cdp bridge down'); } catch { /* gone */ } });
187
+ req.pipe(preq);
188
+ return;
189
+ }
190
+ if (req.method === 'GET' && url.pathname === '/status') {
191
+ res.writeHead(200, { 'content-type': 'application/json' });
192
+ res.end(JSON.stringify({
193
+ bind,
194
+ port: glassPort(server),
195
+ glasses: [...glasses.values()].map((g) => ({ id: g.id, ownerSessionId: g.ownerSessionId, pid: g.pid, profileDir: g.profileDir }))
196
+ }));
197
+ return;
198
+ }
199
+ if (req.method === 'POST' && url.pathname === '/open') {
200
+ const chunks = [];
201
+ for await (const c of req) chunks.push(c);
202
+ let body;
203
+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch { body = {}; }
204
+ const ownerSessionId = typeof body.ownerSessionId === 'string' ? body.ownerSessionId : '';
205
+ if (!ownerSessionId) {
206
+ res.writeHead(400, { 'content-type': 'application/json' });
207
+ res.end(JSON.stringify({ error: 'BAD_REQUEST', message: 'ownerSessionId is required — ownership is keyed by the requesting conversation' }));
208
+ return;
209
+ }
210
+ // Writer-held, enforced HERE (D3): a busy owner is refused, and
211
+ // the refusal is HONEST — the floor surfaces it, no fallback.
212
+ if (byOwner.has(ownerSessionId)) {
213
+ res.writeHead(409, { 'content-type': 'application/json' });
214
+ res.end(JSON.stringify({ error: 'BUSY', message: 'writer-held: owner session ' + ownerSessionId + ' already holds a glass on this chassis' }));
215
+ return;
216
+ }
217
+ const id = crypto.randomUUID();
218
+ const profileDir = disposableProfilePath(profileRoot, id);
219
+ mkdirSync(profileDir, { recursive: true });
220
+ writeOwnerMarker(profileDir); // shared birth rule — the sweep contract holds on the host too
221
+ const debugPort = await portFor(opts.debugPort);
222
+ const width = Math.max(200, Math.min(1920, Number(body.width) || 730));
223
+ const height = Math.max(120, Math.min(1080, Number(body.height) || 830));
224
+ const args = [
225
+ '--no-first-run',
226
+ '--remote-debugging-port=' + debugPort,
227
+ '--disable-dev-shm-usage',
228
+ '--disable-renderer-backgrounding',
229
+ '--disable-background-timer-throttling',
230
+ '--disable-backgrounding-occluded-windows',
231
+ '--disable-blink-features=AutomationControlled',
232
+ '--autoplay-policy=no-user-gesture-required',
233
+ '--window-size=' + (width + 6) + ',' + (height + 70)
234
+ ];
235
+ const born = await launch({ profileDir, args, headless: body.headless === true, width, height }).catch((e) => {
236
+ // a failed birth must not leave a profile dir behind (and the
237
+ // error rides the honest 500 to the floor's panel)
238
+ try { if (profileDir.startsWith(profileRoot)) rmSync(profileDir, { recursive: true, force: true }); } catch { /* best-effort */ }
239
+ throw e;
240
+ });
241
+ const glass = {
242
+ id,
243
+ ownerSessionId,
244
+ debugPort,
245
+ pid: born.pid ?? null,
246
+ profileDir,
247
+ close: born.close
248
+ };
249
+ glasses.set(id, glass);
250
+ byOwner.set(ownerSessionId, id);
251
+ res.writeHead(200, { 'content-type': 'application/json' });
252
+ // The cdpTarget routes THROUGH this companion (the bridge above) —
253
+ // the floor attaches its relay to this URL, never to Chrome raw.
254
+ // Root it at the address the floor DIALED (the request's Host
255
+ // header — same idiom as the ws rewrite in the bridge): `bind`
256
+ // is often 127.0.0.1, which only means "this machine" to the
257
+ // HOST — to a remote floor (VM over the OrbStack bridge) it is
258
+ // the wrong machine and connectOverCDP dials itself (witness
259
+ // 2026-11-08: ECONNREFUSED 127.0.0.1:9525 from the VM floor).
260
+ const dialHost = req.headers.host ?? (bind + ':' + glassPort(server));
261
+ res.end(JSON.stringify({ id, cdpTarget: 'http://' + dialHost + '/cdp/' + id, pid: glass.pid, profileDir }));
262
+ return;
263
+ }
264
+ if (req.method === 'POST' && url.pathname === '/close') {
265
+ const chunks = [];
266
+ for await (const c of req) chunks.push(c);
267
+ let body;
268
+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch { body = {}; }
269
+ // Karpathy edge case: the companion may have restarted, so a
270
+ // glass is closable by id, pid, or profileDir — not id alone.
271
+ const glass = glasses.get(String(body.id ?? ''))
272
+ ?? [...glasses.values()].find((g) => (body.pid !== undefined && g.pid === body.pid) || (body.profileDir !== undefined && g.profileDir === body.profileDir));
273
+ if (!glass) {
274
+ res.writeHead(404, { 'content-type': 'application/json' });
275
+ res.end(JSON.stringify({ error: 'NO_GLASS', message: 'no such glass on this chassis' }));
276
+ return;
277
+ }
278
+ await releaseGlass(glass);
279
+ res.writeHead(200, { 'content-type': 'application/json' });
280
+ res.end(JSON.stringify({ ok: true }));
281
+ return;
282
+ }
283
+ res.statusCode = 404;
284
+ res.end();
285
+ } catch (e) {
286
+ // Honest failure: a birth or close that throws is a 500 with the
287
+ // reason — the floor's panel surfaces it verbatim (no fallback).
288
+ try {
289
+ res.writeHead(500, { 'content-type': 'application/json' });
290
+ res.end(JSON.stringify({ error: 'CHASSIS_FAILED', message: e instanceof Error ? e.message : String(e) }));
291
+ } catch { /* client gone */ }
292
+ }
293
+ });
294
+
295
+ function releaseGlass(glass) {
296
+ glasses.delete(glass.id);
297
+ if (byOwner.get(glass.ownerSessionId) === glass.id) byOwner.delete(glass.ownerSessionId);
298
+ return (async () => {
299
+ try { await glass.close(); } catch { /* already dead */ }
300
+ try { if (glass.pid) process.kill(glass.pid, 'SIGKILL'); } catch { /* already dead */ }
301
+ // Borrowed Chrome: deletes are GUARDED to the disposable root.
302
+ if (glass.profileDir.startsWith(profileRoot)) rmSync(glass.profileDir, { recursive: true, force: true });
303
+ })();
304
+ }
305
+
306
+ const upgrade = (req, socket, head) => {
307
+ const m = (req.url ?? '').match(/^\/cdp\/([^/]+)(\/devtools\/.*)$/);
308
+ if (!m) { socket.destroy(); return; }
309
+ const glass = glasses.get(m[1]);
310
+ if (!glass) { socket.destroy(); return; }
311
+ // Raw pipe to Chrome's loopback port; the Host header is rewritten —
312
+ // recent Chrome validates it (ADR fact 7) and the companion is the hop.
313
+ const headers = [];
314
+ const raw = req.rawHeaders;
315
+ for (let i = 0; i < raw.length; i += 2) {
316
+ headers.push(raw[i] + ': ' + (raw[i].toLowerCase() === 'host' ? '127.0.0.1:' + glass.debugPort : raw[i + 1]));
317
+ }
318
+ const upstream = netConnect(glass.debugPort, '127.0.0.1', () => {
319
+ upstream.write(req.method + ' ' + m[2] + ' HTTP/1.1\r\n' + headers.join('\r\n') + '\r\n\r\n');
320
+ if (head?.length) upstream.write(head);
321
+ socket.pipe(upstream);
322
+ upstream.pipe(socket);
323
+ });
324
+ const fail = () => { socket.destroy(); upstream.destroy(); };
325
+ upstream.on('error', fail);
326
+ socket.on('error', fail);
327
+ };
328
+ server.on('upgrade', upgrade);
329
+
330
+ const wanted = opts.port ?? 9560;
331
+ const boundPort = await new Promise((res, rej) => {
332
+ server.once('error', rej);
333
+ server.listen(wanted, bind, () => {
334
+ const a = server.address();
335
+ res(typeof a === 'object' && a ? a.port : wanted);
336
+ });
337
+ });
338
+ return {
339
+ server,
340
+ port: boundPort,
341
+ glasses,
342
+ stop: async () => {
343
+ server.removeAllListeners('upgrade');
344
+ for (const g of [...glasses.values()]) await releaseGlass(g);
345
+ await new Promise((res) => server.close(() => res()));
346
+ }
347
+ };
348
+ }
349
+
350
+ function glassPort(server) {
351
+ const a = server.address();
352
+ return typeof a === 'object' && a ? a.port : 0;
353
+ }
354
+
355
+ // ---- direct run: parse CLI, resolve bind, start, stay up --------------------
356
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
357
+ const { bind, port } = parseArgs(process.argv.slice(2));
358
+ const verdict = resolveBind(bind);
359
+ if (!verdict.ok) {
360
+ console.error(verdict.error);
361
+ process.exit(1);
362
+ }
363
+ startChassisCompanion({ bind: verdict.addr, port })
364
+ .then((c) => {
365
+ console.log('dsi-chassis: listening on ' + verdict.addr + ':' + c.port + ' (stamp me as GLASS_CHASSIS_URL=http://' + verdict.addr + ':' + c.port + ')');
366
+ })
367
+ .catch((e) => {
368
+ console.error('dsi-chassis: ' + (e instanceof Error ? e.message : String(e)));
369
+ process.exit(1);
370
+ });
371
+ }
package/bin/dsi.mjs CHANGED
@@ -88,7 +88,11 @@ const USAGE = [
88
88
  ' must keep running (another conversation floor), forward',
89
89
  ' --port <n> (or DSH_PORT=<n>; the flag wins) — it goes to `dsh web`',
90
90
  ' and DSI follows it automatically. GLASS_PORT=<n> moves the brain',
91
- ' (the glass browser MCP, default 9515).',
91
+ ' (the glass browser MCP, default 9515). A pre-set GLASS_BRAIN_URL',
92
+ ' overrides the computed brain address byte-for-byte. On a VM floor,',
93
+ ' stamp GLASS_CHASSIS_URL=http://<host>:<port> (run `node bin/dsi-chassis.mjs --bind <host>`',
94
+ ' there) and Shift+click births the visible glass window on THAT',
95
+ ' machine; unset, the window is born locally exactly as always.',
92
96
  '',
93
97
  ' All commands (flags — see above):',
94
98
  '',
@@ -389,13 +393,26 @@ function setDshAuthToken(token) {
389
393
  /** The Stamped Floor (ADR 2026-11-05, D1): every floor announces its own
390
394
  * addresses into the env it gives its children — the UI base (the Floor
391
395
  * Seam D1a seam, finally with a writer) and the brain URL (the preset's
392
- * !!js expression reads DSI_MCP_URL with a 9515 bare-boot fallback). The
393
- * launcher is the only party that knows both ports at spawn time. */
396
+ * !!js expression reads GLASS_BRAIN_URL with a 9515 bare-boot fallback).
397
+ * The launcher is the only party that knows both ports at spawn time.
398
+ * D2 (ADR 2026-11-08): an operator pre-set GLASS_BRAIN_URL passes through
399
+ * byte-for-byte — no validation, no trim; the computed URL is only the
400
+ * default.
401
+ * GLASS_CHASSIS_URL (ADR-0054, 2026-11-08): the SECOND stamp — where the
402
+ * glass WINDOW is born. Same ladder: an operator-exported value passes
403
+ * through byte-for-byte; unset stamps nothing and the registry keeps its
404
+ * local launch exactly as today (D5). It points at the host companion
405
+ * (`node bin/dsi-chassis.mjs --bind <addr>`), not at raw Chrome. */
394
406
  function stampedFloorEnv(uiPort) {
395
- return {
407
+ const env = {
396
408
  DSI_UI: 'http://127.0.0.1:' + uiPort,
397
- DSI_MCP_URL: 'http://127.0.0.1:' + (process.env.GLASS_PORT ?? 9515) + '/sse'
409
+ GLASS_BRAIN_URL: process.env.GLASS_BRAIN_URL ?? 'http://127.0.0.1:' + (process.env.GLASS_PORT ?? 9515) + '/sse'
398
410
  };
411
+ // Unset means NOTHING is stamped (D5): byte-for-byte today's env shape.
412
+ if (process.env.GLASS_CHASSIS_URL !== undefined) {
413
+ env.GLASS_CHASSIS_URL = process.env.GLASS_CHASSIS_URL;
414
+ }
415
+ return env;
399
416
  }
400
417
 
401
418
  function dshWebVersion() {