moi-computer 0.3.0-next.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +1 -1
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/http.ts +1 -1
  4. package/client/api/workspace-keys.ts +1 -0
  5. package/client/app/AppRouter.tsx +14 -5
  6. package/client/app/routes/HomeRoute.tsx +1 -1
  7. package/client/app/routes/WorkspaceRoute.tsx +8 -2
  8. package/client/app/shell/SidebarLayout.tsx +10 -5
  9. package/client/assets/openai.svg +3 -0
  10. package/client/components/shared/BottomPanel.tsx +2 -2
  11. package/client/components/ui/button.tsx +3 -2
  12. package/client/components/ui/input.tsx +1 -1
  13. package/client/features/applets/AppletMount.tsx +44 -0
  14. package/client/features/applets/WidgetShell.tsx +4 -1
  15. package/client/features/applets/applet-cache.ts +8 -0
  16. package/client/features/applets/applet-styles.ts +61 -0
  17. package/client/features/chat/ChatComposer.tsx +2 -2
  18. package/client/features/chat/ChatPanel.tsx +8 -25
  19. package/client/features/chat/ChatPopup.tsx +3 -3
  20. package/client/features/chat/{ThreadSelector.tsx → ChatSelector.tsx} +4 -4
  21. package/client/features/chat/TurnView.tsx +8 -9
  22. package/client/features/chat/api.ts +1 -1
  23. package/client/features/chat/chat-send.ts +57 -0
  24. package/client/features/chat/tool-group/ToolCallGroup.tsx +2 -1
  25. package/client/features/chat/tool-group/format.ts +117 -0
  26. package/client/features/chat/useChat.ts +10 -34
  27. package/client/features/connectors/McpMenu.tsx +4 -21
  28. package/client/features/dev/DevRoutes.tsx +18 -0
  29. package/client/features/dev/HarnessDebugPage.tsx +468 -0
  30. package/client/{components/playground → features/dev}/PlaygroundPage.tsx +1 -1
  31. package/client/features/home/CreateWorkspaceDialog.tsx +64 -158
  32. package/client/features/home/CreateWorkspaceDialogSteps.tsx +234 -0
  33. package/client/features/home/HomeLogo.tsx +344 -0
  34. package/client/features/home/HomePage.tsx +15 -21
  35. package/client/features/home/WorkspacePreview.tsx +12 -5
  36. package/client/features/home/api.ts +11 -3
  37. package/client/features/home/workspace-presentation.tsx +4 -4
  38. package/client/features/settings/GeneralSettings.tsx +3 -3
  39. package/client/features/settings/IconPicker.tsx +4 -3
  40. package/client/features/settings/icon-picker-options.ts +0 -131
  41. package/client/features/views/ViewBuilderTab.tsx +153 -0
  42. package/client/features/views/api.ts +124 -0
  43. package/client/features/views/useViewBuilderActions.ts +72 -0
  44. package/client/features/widgets/WidgetGrid.tsx +36 -20
  45. package/client/features/widgets/Widgets.tsx +140 -90
  46. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -9
  47. package/client/features/workspace/WorkspaceScreen.tsx +179 -40
  48. package/client/features/workspace/WorkspaceTabs.tsx +4 -4
  49. package/client/index.css +0 -35
  50. package/client/index.html +1 -1
  51. package/client/lib/app-icon-registry.ts +145 -0
  52. package/client/runtime/useWorkspaceEvents.ts +3 -1
  53. package/client/theme.css +1 -1
  54. package/dist/chunk-4vf1t6v1.js +10 -0
  55. package/dist/chunk-4z52b2av.css +1 -0
  56. package/dist/chunk-6c8cwpzc.js +1 -0
  57. package/dist/chunk-b4b276wx.js +15 -0
  58. package/dist/{chunk-c4j722at.js → chunk-cs8vbert.js} +2 -2
  59. package/dist/chunk-fjksw6xf.js +1 -0
  60. package/dist/chunk-kxmvv1ax.js +48 -0
  61. package/dist/{chunk-p68fnz3q.js → chunk-vkvb3hjm.js} +1 -1
  62. package/dist/chunk-y82s1jxm.js +61 -0
  63. package/dist/chunk-zpxrb1ce.js +2 -0
  64. package/dist/index.html +2 -2
  65. package/dist/openai-h13pza4b.svg +3 -0
  66. package/lib/format.ts +2 -2
  67. package/lib/types.ts +38 -2
  68. package/lib/view-builder-meta.ts +35 -0
  69. package/lib/workspace-layout.ts +14 -0
  70. package/package.json +2 -1
  71. package/server/AGENTS.md +3 -3
  72. package/server/api.ts +165 -51
  73. package/server/applets.ts +1 -1
  74. package/server/bundle-queue.ts +19 -0
  75. package/server/bundler/applet-css.ts +50 -0
  76. package/server/{build-applet.ts → bundler/build-applet.ts} +36 -26
  77. package/server/cli.ts +79 -2
  78. package/server/control.ts +106 -8
  79. package/server/env-apply.ts +2 -2
  80. package/server/harness/README.md +228 -0
  81. package/server/harness/claude-code/NOTES.md +578 -0
  82. package/{lib/claude-adapter.ts → server/harness/claude-code/adapter.ts} +67 -5
  83. package/server/harness/claude-code/index.ts +124 -0
  84. package/server/{mcp.ts → harness/claude-code/mcp.ts} +1 -1
  85. package/server/{cc-session.ts → harness/claude-code/session.ts} +42 -14
  86. package/server/harness/claude-code/sessions.ts +42 -0
  87. package/server/harness/codex/NOTES.md +326 -0
  88. package/server/harness/codex/adapter.ts +414 -0
  89. package/server/harness/codex/client.ts +343 -0
  90. package/server/harness/codex/index.ts +68 -0
  91. package/server/harness/codex/probe.ts +186 -0
  92. package/server/harness/codex/session.ts +617 -0
  93. package/server/harness/debug.ts +57 -0
  94. package/server/harness/openclaw/NOTES.md +316 -0
  95. package/server/{openclaw-adapter.ts → harness/openclaw/adapter.ts} +2 -2
  96. package/server/harness/openclaw/index.ts +93 -0
  97. package/server/{openclaw-session.ts → harness/openclaw/session.ts} +44 -9
  98. package/server/{openclaw-strip.ts → harness/openclaw/strip.ts} +3 -1
  99. package/server/harness/registry.ts +36 -0
  100. package/server/harness/types.ts +87 -0
  101. package/server/layout.ts +6 -12
  102. package/server/moi-scaffold.ts +1 -1
  103. package/server/registry.ts +14 -52
  104. package/server/state.ts +5 -38
  105. package/server/status.ts +7 -46
  106. package/server/vendor.ts +1 -1
  107. package/server/view-builders.ts +428 -0
  108. package/server/views.ts +0 -0
  109. package/server/web.ts +18 -40
  110. package/server/workspace-init.ts +6 -6
  111. package/workspace/.claude/skills/moi-workspace/DESIGN.md +1 -0
  112. package/workspace/.claude/skills/moi-workspace/SKILL.md +28 -7
  113. package/client/assets/hermes-nous.png +0 -0
  114. package/client/hooks/useScrollFade.ts +0 -38
  115. package/dist/chunk-23cgr1tz.css +0 -1
  116. package/dist/chunk-3hy3qy6d.js +0 -10
  117. package/dist/chunk-dyfaffyz.js +0 -119
  118. package/dist/chunk-kpe40hm8.js +0 -1
  119. package/dist/chunk-ty6dvda0.js +0 -1
  120. package/dist/hermes-nous-pznd63x9.png +0 -0
  121. /package/client/{components/playground → features/dev}/PixelPainter.tsx +0 -0
  122. /package/client/{components/playground → features/dev}/ToolCallsPage.tsx +0 -0
  123. /package/server/{agent.ts → harness/claude-code/models.ts} +0 -0
  124. /package/server/{openclaw.ts → harness/openclaw/discovery.ts} +0 -0
  125. /package/server/{openclaw-gateway.ts → harness/openclaw/gateway.ts} +0 -0
@@ -0,0 +1,316 @@
1
+ # OpenClaw — integration notes
2
+
3
+ Everything we learned wiring the workspace-discovery flow to OpenClaw's local
4
+ gateway. Covers on-disk layout, the WebSocket protocol, auth, the RPC surface,
5
+ the things that bit us, and how to use it from Bun.
6
+
7
+ Pinned version (known good): **`openclaw@2026.4.22`** — this is the one our
8
+ code and these notes were verified against.
9
+
10
+ ## 1. What OpenClaw is
11
+
12
+ A personal multi-channel AI assistant that runs on your own machine. The
13
+ product has several surfaces, but from an integrator's perspective there are
14
+ two components that matter:
15
+
16
+ - **The gateway** — a local service exposing a WebSocket JSON-RPC API at
17
+ `ws://127.0.0.1:18789`. Every feature (sessions, agents, channels, config,
18
+ approvals, memory, logs, skills) is reachable through it. It's the single
19
+ control plane.
20
+ - **The `openclaw` CLI** — a thin wrapper over the gateway's RPC methods. Most
21
+ subcommands (`openclaw sessions`, `openclaw agents list`, `openclaw logs`)
22
+ just open a WS connection, call one method, and format the result.
23
+
24
+ The HTTP surface at the same port (`http://127.0.0.1:18789/`) serves the
25
+ Control UI SPA and a tiny `/health` endpoint. Everything else is WebSocket.
26
+
27
+ ## 2. On-disk layout
28
+
29
+ State root: `~/.openclaw/`.
30
+
31
+ | What | Path |
32
+ | ----------------------------------------------------------------- | ---------------------------------------------------------- |
33
+ | Config (gateway port, auth token, agent defaults, hooks, plugins) | `~/.openclaw/openclaw.json` |
34
+ | Gateway HTTP+WS service | launchd `ai.openclaw.gateway`, loopback |
35
+ | Agents (per-agent state, auth profiles, per-agent model catalog) | `~/.openclaw/agents/<id>/agent/` |
36
+ | Per-agent session index | `~/.openclaw/agents/<id>/sessions/sessions.json` |
37
+ | Per-session raw event log | `~/.openclaw/agents/<id>/sessions/<uuid>.jsonl` |
38
+ | Sibling trajectory log | `~/.openclaw/agents/<id>/sessions/<uuid>.trajectory.jsonl` |
39
+ | Default workspace (if agents share) | `~/.openclaw/workspace/` |
40
+ | Memory DB | `~/.openclaw/memory/<id>.sqlite` |
41
+ | Device keypair (handshake signing) | `~/.openclaw/identity/device.json` |
42
+ | Issued device-auth role tokens | `~/.openclaw/identity/device-auth.json` |
43
+ | Paired devices (control-UI, CLI, health) | `~/.openclaw/devices/paired.json` |
44
+ | Pending pairing requests | `~/.openclaw/devices/pending.json` |
45
+
46
+ Each agent has its **own workspace dir** (override with `openclaw agents add --workspace`)
47
+ and its own agent-state dir. The default `~/.openclaw/workspace/` is only the
48
+ fallback when an agent doesn't specify one — don't assume it's global. If you're
49
+ enumerating per-agent data (widgets, local files), **always resolve the workspace
50
+ per agent from `agents.list`**, not from the default.
51
+
52
+ ### Session `.jsonl` schema
53
+
54
+ Each line is one event. Types seen in the wild (from a fresh agent run):
55
+
56
+ ```
57
+ session { version, id, cwd, timestamp }
58
+ model_change { provider, modelId }
59
+ thinking_level_change{ thinkingLevel }
60
+ custom { customType, data } ← OpenClaw's synthetic-event channel
61
+ message { role: 'user'|'assistant', content: [...] }
62
+ toolResult message-shaped with tool output
63
+ ```
64
+
65
+ The sibling `<uuid>.trajectory.jsonl` carries lifecycle events:
66
+ `session.started`, `context.compiled`, `prompt.submitted`, `model.completed`,
67
+ `trace.metadata`, `trace.artifacts`, `session.ended`.
68
+
69
+ ## 3. Auth & device pairing — the part that breaks you
70
+
71
+ Three auth concepts stack on the gateway:
72
+
73
+ 1. **Gateway token** — shared secret from `openclaw.json → gateway.auth.token`.
74
+ Required on every WebSocket connect; fail-closed by default.
75
+ 2. **Device identity** — an Ed25519 keypair in `~/.openclaw/identity/device.json`.
76
+ Signed in the `connect` handshake so the gateway knows _which_ device is
77
+ connecting (the token is shared, the key isn't).
78
+ 3. **Per-device role tokens & scopes** — each paired device holds its own
79
+ operator-role token (`~/.openclaw/identity/device-auth.json`) with an
80
+ approved scope set (`operator.read`, `operator.write`, `operator.admin`,
81
+ `operator.approvals`, `operator.pairing`, `operator.talk.secrets`).
82
+
83
+ A fresh CLI device starts with **`operator.read` only**. Almost every useful
84
+ method (`sessions.list`, `sessions.subscribe`, `logs.tail`, `agents.files.get`,
85
+ admin actions) needs at least `operator.read` + `operator.write`, and most of
86
+ them need `operator.admin`. When the CLI connects with insufficient scopes the
87
+ gateway emits:
88
+
89
+ ```
90
+ GatewayClientRequestError: scope upgrade pending approval (requestId: <uuid>)
91
+ ```
92
+
93
+ and writes a record to `~/.openclaw/devices/pending.json`.
94
+
95
+ ### The approval dance (chicken-and-egg)
96
+
97
+ You **cannot approve a scope upgrade from the same CLI device that's asking
98
+ for it** — `openclaw devices approve <id>` itself needs `operator.admin`, which
99
+ you don't have yet, so it spawns another pending request with a new ID. Each
100
+ retry generates a fresh ID, so copy-pasting an old one returns `unknown
101
+ requestId`.
102
+
103
+ Resolution paths, in order of practicality:
104
+
105
+ 1. **Approve from the Control UI** (`http://127.0.0.1:18789/`). The browser is
106
+ usually already paired as `openclaw-control-ui / webchat` with full
107
+ operator scopes — its keypair lives in the browser's IndexedDB. One click
108
+ in the Devices panel approves the latest pending request.
109
+ 2. **Approve from another already-paired device** holding admin scopes, using
110
+ its device token.
111
+ 3. **Revoke the current read-only CLI pairing** so it re-pairs from scratch;
112
+ the fresh pairing shows up as a new request the browser can approve.
113
+
114
+ Once approved, the role token in `device-auth.json` gets upgraded in place. No
115
+ config changes needed.
116
+
117
+ ### Fallback behavior of the CLI
118
+
119
+ Most `openclaw` subcommands that need RPC have a local-file fallback: if the
120
+ gateway refuses the connection, they read `~/.openclaw/…` directly. `openclaw
121
+ sessions`, `openclaw status`, `openclaw agents list`, `openclaw logs` all do
122
+ this. That's why those commands kept working for us before the scope upgrade
123
+ was approved — they were never hitting the gateway, they were scraping disk.
124
+ Useful to know when you're debugging: see the "Direct scope access failed;
125
+ using local fallback" banner.
126
+
127
+ ## 4. RPC surface
128
+
129
+ Full method list (surfaced from `method-scopes-*.js` but verified by calling
130
+ them live):
131
+
132
+ **Sessions.** `sessions.list` · `sessions.resolve` · `sessions.preview` ·
133
+ `sessions.get` · `sessions.messages.subscribe` / `unsubscribe` ·
134
+ `sessions.subscribe` / `unsubscribe` · `sessions.send` · `sessions.patch` ·
135
+ `sessions.abort` · `sessions.steer` · `sessions.create` · `sessions.reset` ·
136
+ `sessions.delete` · `sessions.compact` ·
137
+ `sessions.compaction.{list,get,branch,restore}` · `sessions.usage` ·
138
+ `sessions.usage.{logs,timeseries}`.
139
+
140
+ **Agents.** `agents.list` · `agents.create` · `agents.update` · `agents.delete` ·
141
+ `agents.files.{list,get,set}`.
142
+
143
+ **Config/logs.** `config.get` · `config.schema.lookup` · `logs.tail`.
144
+
145
+ Live over the `openclaw.control-ui` webchat device we also observed
146
+ `channels.status`, `skills.status`, `sessions.usage` — there are many more
147
+ outside the integration surface we touched.
148
+
149
+ ### Gotchas in params
150
+
151
+ - **`sessions.list`** accepts `limit`, `activeMinutes`, `includeGlobal`,
152
+ `includeUnknown`, `includeDerivedTitles`, `includeLastMessage`, `label`,
153
+ `spawnedBy`, `agentId`, `search` — **not** `allAgents` (the CLI flag is
154
+ client-side aggregation). Pass `includeGlobal: true` to aggregate.
155
+ - **`sessions.get`** exists in the method list, but for reading _messages_
156
+ what you want is `sessions.preview({ keys: [...], limit, maxChars })` which
157
+ returns structured `{ role, text }` items, or `sessions.messages.subscribe`
158
+ for a live stream.
159
+ - **`agents.list`** accepts **no** extra params. All the identity enrichment
160
+ you see in `openclaw agents list --json` (`identityName`, `identityEmoji`,
161
+ `agentDir`, `bindings`, `isDefault`, `routes`) is computed client-side by
162
+ the CLI — the gateway returns `{ defaultId, mainKey, scope, agents: [{ id,
163
+ workspace, model }] }`. Short response.
164
+ - **`agents.files.get`** uses `{ agentId, name }` — not `{ id, path }`. Easy
165
+ to get wrong.
166
+ - Scope errors return `INVALID_REQUEST` or `scope upgrade pending approval`
167
+ depending on the method's required scope.
168
+
169
+ ### Detecting running sessions
170
+
171
+ `sessions.list` rows include `status` + `startedAt` / `endedAt` / `runtimeMs`
172
+ once a session has had at least one gateway run. `status === 'running'` is
173
+ the live discriminator; `abortedLastRun: true` means the last run was killed.
174
+ Rows for never-run sessions (`tui-...`) omit these fields entirely — don't
175
+ assume they're present.
176
+
177
+ ### Live updates
178
+
179
+ One WebSocket connection, `sessions.subscribe({})` for top-level session
180
+ events, `sessions.messages.subscribe({ key })` for per-thread message events.
181
+ Events arrive on the same socket as pushed `event` frames of shape
182
+ `{ type: 'event', event: '<name>', payload: {...} }`. Unsubscribe symmetrically.
183
+ No long-polling, no second connection.
184
+
185
+ ### Stopping a run
186
+
187
+ `sessions.abort({ key, runId? })`. Pass the specific `runId` from a subscribe
188
+ frame to kill a particular run; omit it to kill whatever's active. Returns
189
+ `{ ok: true, abortedRunId, status: 'aborted'|'no-active-run' }`.
190
+
191
+ ## 5. Using the `openclaw` npm package
192
+
193
+ **Don't roll your own WS client** unless you have a reason. The `openclaw`
194
+ package publishes a supported subpath export that's declared in its
195
+ `package.json` `exports` map:
196
+
197
+ ```ts
198
+ import { GatewayClient } from 'openclaw/plugin-sdk/gateway-runtime'
199
+ ```
200
+
201
+ Also available at the same path: `createOperatorApprovalsGatewayClient`,
202
+ `withOperatorApprovalsGatewayClient`, the `EventFrame` protocol type.
203
+
204
+ `GatewayClient` handles:
205
+
206
+ - Ed25519 device-identity loading & challenge signing
207
+ - Token / password / deviceToken auth resolution
208
+ - Challenge-response handshake with nonce
209
+ - Reconnect with exponential backoff
210
+ - Heartbeat tick watch
211
+ - TLS fingerprint pinning (for `wss://`)
212
+ - Request timeout (`requestTimeoutMs`)
213
+
214
+ Minimal client (what `server/openclaw.ts` uses):
215
+
216
+ ```ts
217
+ import { GatewayClient } from 'openclaw/plugin-sdk/gateway-runtime'
218
+
219
+ const client = new GatewayClient({
220
+ url: `ws://127.0.0.1:${port}`,
221
+ token, // from openclaw.json gateway.auth.token
222
+ role: 'operator',
223
+ scopes: ['operator.admin', 'operator.read', 'operator.write'],
224
+ requestTimeoutMs: 2000
225
+ })
226
+
227
+ await new Promise<void>((res, rej) => {
228
+ client.opts.onHelloOk = () => res()
229
+ client.opts.onConnectError = rej
230
+ client.start()
231
+ })
232
+
233
+ const result = await client.request('sessions.list', { includeGlobal: true })
234
+ client.stop()
235
+ ```
236
+
237
+ Important: **always wrap `connect` in your own timeout**. `GatewayClient`
238
+ doesn't enforce one on the initial handshake (only on individual RPCs), so a
239
+ silent gateway will hang forever. We use `Promise.race` with a 2 s timer.
240
+
241
+ ### The dependency footprint
242
+
243
+ The `openclaw` package is **big** (~300+ transitive deps — it includes channel
244
+ plugins, provider SDKs, the full CLI). If that's a dealbreaker:
245
+
246
+ - `@paperclipai/adapter-openclaw-gateway` publishes a minimal WS client (3
247
+ deps: `ws`, `picocolors`, its own utils) implementing the same handshake. Use
248
+ it as a reference for rolling your own, but note its shape is Paperclip-specific.
249
+ - Rolling your own with `ws` + `@noble/ed25519` is doable; the connect frame
250
+ shape is covered in the `GatewayClient.sendConnect()` source.
251
+
252
+ For our case (the server already has lots of deps), the subpath import wins.
253
+
254
+ ## 6. Security hardening in 2026.4.22
255
+
256
+ Notable items in the CHANGELOG relevant to anyone integrating:
257
+
258
+ - `Auth/commands` — require owner identity for owner-enforced commands
259
+ - `Agents/gateway tool` — expanded config-mutation guard so models can't
260
+ rewrite operator-trusted paths (sandbox, plugin trust, gateway auth/TLS,
261
+ hook routing/tokens, SSRF policy, MCP servers, per-agent overrides)
262
+ - `Security/dotenv` — block `OPENCLAW_*` keys and Matrix/Mattermost/IRC/Synology
263
+ endpoint overrides from workspace `.env` injection
264
+ - `Security/external content` — strip Qwen/ChatML/Llama/Gemma/Mistral/Phi/GPT-OSS
265
+ chat-template special tokens (role-boundary spoofing defense)
266
+ - `Security/update` — fail closed on plugin / hook-pack integrity drift
267
+ - `Plugins/discovery` — reject plugin entries that escape their package dir
268
+ - `Control UI/CSP` — tightened `img-src 'self' data:`; remote avatar URLs dropped
269
+ - `Sessions/Maintenance` — bounded session store prevents gateway OOM
270
+
271
+ No public CVE/RCE exists against the package in the CHANGELOG or GitHub
272
+ security advisories as of this date. Previous AI-authored claims about a
273
+ "CSWSH 1-click RCE fixed in 2026.2.25+" are not corroborated by the actual
274
+ changelog — treat them as hallucinated.
275
+
276
+ `bun audit` will flag transitive advisories in `hono`, `picomatch`,
277
+ `path-to-regexp`, but those come from unrelated dependencies (MCP SDK,
278
+ shadcn, lint-staged), not from `openclaw` itself.
279
+
280
+ ## 7. What our code does
281
+
282
+ `server/openclaw.ts` — discovery helper with a 2 s timeout wrapper around both
283
+ connect and every RPC. Returns `OpenClawAgent[]` = `{ path, agentId, name?,
284
+ isDefault, lastRunAt? }`. Any failure (missing config, gateway down, timeout,
285
+ malformed response) → empty array, silently.
286
+
287
+ Pipeline:
288
+
289
+ 1. Read `~/.openclaw/openclaw.json` for port + token (sync filesystem)
290
+ 2. Lazy-import `GatewayClient` (keeps startup cost off the critical path if
291
+ the feature's unused)
292
+ 3. Open one WS connection; wait for `onHelloOk` or 2 s timeout
293
+ 4. **Round-trip 1** (parallel): `agents.list` + `sessions.list({ includeGlobal })`
294
+ 5. **Round-trip 2** (parallel per agent): `agents.files.get(IDENTITY.md)`
295
+ 6. Parse `- **Name:** ...` from the identity markdown; group
296
+ `sessions.list` rows by the `agent:<id>:…` key prefix for `lastRunAt`
297
+ 7. Map to the `OpenClawAgent` shape; `stop()` the client
298
+
299
+ That's it — 2 round-trips to get everything we show on `/`.
300
+
301
+ ## 8. Commands worth knowing
302
+
303
+ ```
304
+ openclaw status # overview (gateway, agents, sessions, security)
305
+ openclaw agents list [--json] # agents + workspaces + bindings (CLI-enriched)
306
+ openclaw sessions --all-agents --json # aggregate sessions across agents (uses RPC)
307
+ openclaw logs --follow --json # tail gateway logs (WS if scoped, else /tmp file)
308
+ openclaw devices list # pending + paired devices
309
+ openclaw devices approve <requestId> # needs admin scope (chicken-and-egg, see §3)
310
+ openclaw doctor # lint config, flag risky dm policies
311
+ openclaw dashboard # open Control UI with token in URL
312
+ ```
313
+
314
+ `openclaw --dev` runs a completely isolated instance under `~/.openclaw-dev/`
315
+ on port `19001` — useful if you're hacking integrations and don't want to
316
+ touch your real gateway. Same for `--profile <name>` (`~/.openclaw-<name>/`).
@@ -24,8 +24,8 @@ import type {
24
24
  OpenClawMessage,
25
25
  OpenClawSessionDetail,
26
26
  OpenClawSessionRow
27
- } from './openclaw'
28
- import { stripUserMessageMetadata } from './openclaw-strip'
27
+ } from './discovery'
28
+ import { stripUserMessageMetadata } from './strip'
29
29
 
30
30
  export function toSessionInfo(row: OpenClawSessionRow, cwd: string): SessionInfo {
31
31
  const summary =
@@ -0,0 +1,93 @@
1
+ // OpenClaw as a Harness. Thin wiring over this folder's modules — see
2
+ // ../types.ts for the contract and ../README.md for the architecture.
3
+ import type { DiscoveredWorkspace } from '@/lib/types'
4
+
5
+ import type { Harness } from '../types'
6
+ import { toSessionInfo, toStreamEvents } from './adapter'
7
+ import {
8
+ discoverOpenClawAgents,
9
+ getOpenClawModels,
10
+ getOpenClawSessionMessages,
11
+ getOpenClawSessions
12
+ } from './discovery'
13
+ import {
14
+ abortOpenClawRun,
15
+ ensureOpenClawSessionLive,
16
+ getLiveOpenClawEvents,
17
+ getOpenClawRunningSessions,
18
+ sendOpenClawMessage
19
+ } from './session'
20
+
21
+ export const openclawHarness: Harness = {
22
+ id: 'openclaw',
23
+ capabilities: {
24
+ supportsStreaming: false, // durable message rows only — deliberate v2 cut
25
+ imagesInline: 'path-note',
26
+ liveModelSwitch: false,
27
+ liveEffortSwitch: false,
28
+ nativeUserEcho: true // gateway echoes sends (lagged); matched by text
29
+ },
30
+
31
+ sendMessage: async input => {
32
+ if (!input.agentId) {
33
+ throw new Error('OpenClaw workspace has no agentId — re-add it via discovery')
34
+ }
35
+ return sendOpenClawMessage({ ...input, agentId: input.agentId })
36
+ },
37
+ interrupt: (workspaceId, sessionId) => abortOpenClawRun({ workspaceId, sessionId }),
38
+ runningSessions: () => getOpenClawRunningSessions(),
39
+
40
+ listSessions: async ws => {
41
+ const rows = await getOpenClawSessions(ws.path, ws.agentId)
42
+ return rows.map(r => toSessionInfo(r, ws.path))
43
+ },
44
+ // Prefer the live view if we already hold one — keeps REST + WS in
45
+ // agreement for any reload that lands while a run is active. The first cold
46
+ // call also primes the live subscription so subsequent WS frames upsert
47
+ // into the same view; the static transcript is the last resort.
48
+ sessionEvents: async (ws, sessionId) => {
49
+ const live = getLiveOpenClawEvents(ws.id, sessionId)
50
+ if (live) return live
51
+ if (ws.agentId) {
52
+ try {
53
+ return await ensureOpenClawSessionLive({
54
+ workspaceId: ws.id,
55
+ workspacePath: ws.path,
56
+ agentId: ws.agentId,
57
+ sessionId
58
+ })
59
+ } catch {
60
+ // fall through to static path
61
+ }
62
+ }
63
+ const preview = await getOpenClawSessionMessages(sessionId, ws.path, ws.agentId)
64
+ return toStreamEvents(preview)
65
+ },
66
+ listModels: () => getOpenClawModels(),
67
+
68
+ discoverWorkspaces: async registeredPaths => {
69
+ const agents = await discoverOpenClawAgents()
70
+ return agents
71
+ .filter(a => !registeredPaths.has(a.path))
72
+ .map(
73
+ (a): DiscoveredWorkspace => ({
74
+ path: a.path,
75
+ type: 'openclaw',
76
+ ...(a.name ? { name: a.name } : {}),
77
+ ...(a.agentId ? { agentId: a.agentId } : {}),
78
+ ...(a.isDefault ? { isDefault: a.isDefault } : {}),
79
+ ...(a.lastRunAt ? { lastRunAt: a.lastRunAt } : {})
80
+ })
81
+ )
82
+ },
83
+
84
+ skillsDir: workspaceRoot => `${workspaceRoot}/skills`,
85
+
86
+ statusLines: () => {
87
+ const running = getOpenClawRunningSessions()
88
+ return [
89
+ `live OpenClaw runs ${running.length}`,
90
+ ...running.map(r => ` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
91
+ ]
92
+ }
93
+ }
@@ -12,6 +12,7 @@
12
12
  // - Disk persistence — the gateway is the source of truth; we re-seed from
13
13
  // `sessions.get` on cold start.
14
14
  import { appendAttachmentNote } from '@/lib/attachment-note'
15
+ import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
15
16
  import { applyEvent, emptyViewState } from '@/lib/format'
16
17
  import type { StreamEvent, ViewState } from '@/lib/types'
17
18
 
@@ -19,16 +20,21 @@ import {
19
20
  type OpenClawMessage,
20
21
  type OpenClawSessionDetail,
21
22
  getOpenClawSessionMessages
22
- } from './openclaw'
23
+ } from './discovery'
23
24
  import {
24
25
  type ToolResultInfo,
25
26
  findToolCallOwners,
26
27
  messageToTurn,
27
28
  toolResultFromMessage
28
- } from './openclaw-adapter'
29
- import { getGateway, onGatewayReconnected } from './openclaw-gateway'
30
- import { broadcast } from './state'
31
- import { materializeToPath, resolveUploads } from './uploads'
29
+ } from './adapter'
30
+ import { getGateway, onGatewayReconnected } from './gateway'
31
+ import { broadcast } from '../../state'
32
+ import { materializeToPath, resolveUploads } from '../../uploads'
33
+ import {
34
+ markViewBuilderBuildingBySession,
35
+ markViewBuilderWaitingBySession,
36
+ renameViewBuilderSession
37
+ } from '../../view-builders'
32
38
 
33
39
  type OpenClawSessionKey = string // the gateway-side composite key, e.g. `agent:main:main`
34
40
 
@@ -108,6 +114,11 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
108
114
  })
109
115
  if (existing?.processing === processing) return
110
116
  broadcast(rec.workspaceId, { type: 'status', sessionId: rec.sessionId, processing })
117
+ if (processing) {
118
+ void markViewBuilderBuildingBySession(rec.workspaceId, rec.workspacePath, rec.sessionId)
119
+ } else {
120
+ void markViewBuilderWaitingBySession(rec.workspaceId, rec.workspacePath, rec.sessionId)
121
+ }
111
122
  }
112
123
 
113
124
  // On run end the gateway has flushed every durable row — including
@@ -419,6 +430,12 @@ async function sendOpenClawMessageImpl(input: {
419
430
  to: created.sessionId
420
431
  })
421
432
  realSessionId = created.sessionId
433
+ await renameViewBuilderSession(
434
+ input.workspaceId,
435
+ input.workspacePath,
436
+ input.sessionId,
437
+ realSessionId
438
+ )
422
439
  }
423
440
  }
424
441
  rec = await getOrCreateOpenClawSession({
@@ -428,16 +445,26 @@ async function sendOpenClawMessageImpl(input: {
428
445
  sessionId: realSessionId
429
446
  })
430
447
  } catch (err) {
448
+ const message = err instanceof Error ? err.message : 'failed to start session'
431
449
  broadcast(input.workspaceId, {
432
450
  kind: 'error',
433
451
  sessionId: realSessionId,
434
- content: err instanceof Error ? err.message : 'failed to start session'
452
+ content: message
435
453
  })
436
- return
454
+ await markViewBuilderWaitingBySession(
455
+ input.workspaceId,
456
+ input.workspacePath,
457
+ realSessionId,
458
+ message
459
+ )
460
+ throw err
437
461
  }
438
462
 
439
463
  if (input.optimisticId) {
440
- rec.pendingUserEchoes.push({ optimisticId: input.optimisticId, text: input.content })
464
+ rec.pendingUserEchoes.push({
465
+ optimisticId: input.optimisticId,
466
+ text: stripViewBuilderMeta(input.content)
467
+ })
441
468
  if (rec.pendingUserEchoes.length > MAX_PENDING_USER_ECHOES) {
442
469
  rec.pendingUserEchoes.shift()
443
470
  }
@@ -459,11 +486,19 @@ async function sendOpenClawMessageImpl(input: {
459
486
  const idx = rec.pendingUserEchoes.findIndex(e => e.optimisticId === input.optimisticId)
460
487
  if (idx >= 0) rec.pendingUserEchoes.splice(idx, 1)
461
488
  }
489
+ const message = err instanceof Error ? err.message : 'send failed'
462
490
  broadcast(rec.workspaceId, {
463
491
  kind: 'error',
464
492
  sessionId: rec.sessionId,
465
- content: err instanceof Error ? err.message : 'send failed'
493
+ content: message
466
494
  })
495
+ await markViewBuilderWaitingBySession(
496
+ rec.workspaceId,
497
+ rec.workspacePath,
498
+ rec.sessionId,
499
+ message
500
+ )
501
+ throw err
467
502
  }
468
503
  }
469
504
 
@@ -1,3 +1,5 @@
1
+ import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
2
+
1
3
  // Strip OpenClaw-injected inbound metadata from user-role message text.
2
4
  //
3
5
  // The gateway prepends AI-facing envelopes to every user message before storing
@@ -130,5 +132,5 @@ export function stripBootstrapPreamble(text: string): string {
130
132
  }
131
133
 
132
134
  export function stripUserMessageMetadata(text: string): string {
133
- return stripInboundMetadata(stripBootstrapPreamble(text))
135
+ return stripViewBuilderMeta(stripInboundMetadata(stripBootstrapPreamble(text)))
134
136
  }
@@ -0,0 +1,36 @@
1
+ // WorkspaceType → Harness lookup. This is the single import surface for the
2
+ // rest of the server: web.ts/api.ts/etc. dispatch through harnessFor()
3
+ // instead of branching on workspace.type (documented exceptions: cli.ts
4
+ // provisioning and tests import harness internals directly).
5
+ import type { WorkspaceEntry, WorkspaceType } from '@/lib/types'
6
+
7
+ import { claudeCodeHarness } from './claude-code'
8
+ import { codexHarness } from './codex'
9
+ import { openclawHarness } from './openclaw'
10
+ import type { Harness } from './types'
11
+
12
+ export type { Harness, HarnessCapabilities, SendMessageInput } from './types'
13
+
14
+ const harnesses = {
15
+ 'claude-code': claudeCodeHarness,
16
+ openclaw: openclawHarness,
17
+ codex: codexHarness
18
+ } satisfies Partial<Record<WorkspaceType, Harness>>
19
+
20
+ // An untyped registry entry is a Claude Code workspace (pre-typing legacy).
21
+ export function harnessFor(ws: Pick<WorkspaceEntry, 'type'> | WorkspaceType | undefined): Harness {
22
+ const type = typeof ws === 'string' ? ws : ws?.type
23
+ return (
24
+ (type && type in harnesses && harnesses[type as keyof typeof harnesses]) || claudeCodeHarness
25
+ )
26
+ }
27
+
28
+ export function allHarnesses(): Harness[] {
29
+ return Object.values(harnesses)
30
+ }
31
+
32
+ // Is this string a workspace type moi can actually drive? (Validates the
33
+ // `type` field on workspace registration.)
34
+ export function isHarnessType(value: unknown): value is keyof typeof harnesses {
35
+ return typeof value === 'string' && value in harnesses
36
+ }
@@ -0,0 +1,87 @@
1
+ // The harness contract: what an agent backend must implement to be drivable
2
+ // by moi. See README.md in this folder for the full checklist and the
3
+ // message-type layers; each harness's index.ts exports one Harness object
4
+ // wrapping its session/adapter/transport modules.
5
+ import type {
6
+ DiscoveredWorkspace,
7
+ McpServer,
8
+ Model,
9
+ SessionInfo,
10
+ StreamEvent,
11
+ WorkspaceEntry,
12
+ WorkspaceType
13
+ } from '@/lib/types'
14
+
15
+ // The superset of what any backend needs to accept a user message; harnesses
16
+ // ignore fields they don't support (e.g. OpenClaw ignores model/effort/stream,
17
+ // only OpenClaw reads agentId).
18
+ export type SendMessageInput = {
19
+ workspaceId: string
20
+ workspacePath: string
21
+ sessionId: string
22
+ isNew: boolean
23
+ content: string
24
+ // Upload ids from POST .../uploads, resolved by the harness into its input
25
+ // capability (base64 blocks / data URLs / temp-file path notes).
26
+ attachments?: string[]
27
+ optimisticId?: string
28
+ model?: string
29
+ effort?: string
30
+ stream?: boolean
31
+ // OpenClaw: the gateway agent that owns the workspace.
32
+ agentId?: string
33
+ }
34
+
35
+ // Static, per-harness feature flags. These let orchestration code stay
36
+ // generic instead of special-casing providers (e.g. the models endpoint's
37
+ // streaming toggle). An entry describes what the BACKEND can do — partial
38
+ // support/workarounds are documented in README.md's capability matrix.
39
+ export type HarnessCapabilities = {
40
+ // Can the UI offer live token-by-token streaming for this backend?
41
+ supportsStreaming: boolean
42
+ // How image attachments reach the agent.
43
+ imagesInline: 'base64' | 'data-url' | 'path-note'
44
+ // Model/effort can change mid-session without a rebuild dance.
45
+ liveModelSwitch: boolean
46
+ liveEffortSwitch: boolean
47
+ // Does the backend echo the sent user message back (with our optimistic id)?
48
+ nativeUserEcho: boolean
49
+ }
50
+
51
+ export type Harness = {
52
+ id: WorkspaceType
53
+ capabilities: HarnessCapabilities
54
+
55
+ // -- chat lifecycle ---------------------------------------------------------
56
+ sendMessage(input: SendMessageInput): Promise<void>
57
+ interrupt(workspaceId: string, sessionId: string): Promise<void>
58
+ // Sessions currently processing a turn, across all workspaces (drives the
59
+ // connect-time status snapshot and view-builder reconciliation).
60
+ runningSessions(): { workspaceId: string; sessionId: string }[]
61
+
62
+ // -- discovery / metadata ---------------------------------------------------
63
+ listSessions(ws: WorkspaceEntry): Promise<SessionInfo[]>
64
+ sessionEvents(ws: WorkspaceEntry, sessionId: string): Promise<StreamEvent[]>
65
+ listModels(ws: WorkspaceEntry): Promise<Model[]>
66
+ // MCP server status for the connectors UI; absent = backend has no MCP story.
67
+ mcpStatus?(ws: WorkspaceEntry): Promise<McpServer[]>
68
+ // Workspaces this backend knows about that aren't registered yet.
69
+ discoverWorkspaces?(registeredPaths: Set<string>): Promise<DiscoveredWorkspace[]>
70
+
71
+ // -- host integration hooks -------------------------------------------------
72
+ // Env is frozen at spawn everywhere; this reaps idle sessions/processes so
73
+ // the next message picks up fresh env.
74
+ onEnvChanged?(workspacePath: string): void
75
+ // Server shutdown: kill child processes so nothing is orphaned.
76
+ shutdown?(): void
77
+ // Where this backend loads workspace skills from (workspace provisioning).
78
+ skillsDir?(workspaceRoot: string): string
79
+ // Extra payload for the /dev/harness debug page (e.g. codex process info).
80
+ debugInfo?(ws: WorkspaceEntry): Promise<unknown>
81
+ // Key this harness taps its wire frames under in debug.ts (defaults to the
82
+ // workspace id; codex taps by workspacePath — its process client doesn't
83
+ // know workspace ids).
84
+ wireScope?(ws: WorkspaceEntry): string
85
+ // Lines for the /status introspection page.
86
+ statusLines?(now: number): string[]
87
+ }