moi-computer 0.7.0 → 0.8.1-next.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 (123) hide show
  1. package/README.md +2 -2
  2. package/client/api/workspace-keys.ts +1 -2
  3. package/client/app/AppRouter.tsx +10 -3
  4. package/client/app/routes/HomeRoute.tsx +1 -1
  5. package/client/app/shell/SidebarLayout.tsx +2 -14
  6. package/client/components/shared/BottomPanel.tsx +2 -1
  7. package/client/components/shared/Composer.tsx +20 -7
  8. package/client/components/shared/PanelHeader.tsx +8 -1
  9. package/client/components/ui/button.tsx +3 -3
  10. package/client/components/ui/dialog.tsx +1 -1
  11. package/client/components/ui/dropdown-menu.tsx +2 -2
  12. package/client/components/ui/hover-card.tsx +1 -1
  13. package/client/components/ui/popover.tsx +1 -1
  14. package/client/components/ui/resizable.tsx +40 -0
  15. package/client/features/applets/AppletMount.tsx +9 -22
  16. package/client/features/applets/applet-cache.ts +7 -0
  17. package/client/features/applets/applet-styles.ts +21 -1
  18. package/client/features/applets/useApplet.ts +1 -1
  19. package/client/features/chat/ChatEmptyState.tsx +9 -11
  20. package/client/features/chat/ChatPanel.tsx +76 -48
  21. package/client/features/chat/ChatPopup.tsx +16 -2
  22. package/client/features/chat/ChatPromptBubbles.tsx +6 -8
  23. package/client/features/chat/ChatSelector.tsx +25 -8
  24. package/client/features/chat/ModelPicker.tsx +5 -4
  25. package/client/features/chat/TurnView.tsx +108 -13
  26. package/client/features/chat/api.ts +1 -18
  27. package/client/features/chat/chat-send.ts +2 -2
  28. package/client/features/chat/{ChatComposer.tsx → composer/ChatComposer.tsx} +24 -9
  29. package/client/features/chat/composer/banners/ChatErrorBanner.tsx +28 -0
  30. package/client/features/chat/composer/banners/ComposerBanner.tsx +30 -0
  31. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +91 -0
  32. package/client/features/{workspace → chat/composer/banners}/WorkspaceSkillUpdateBanner.tsx +9 -7
  33. package/client/features/chat/composer/useWorkspaceComposerState.tsx +74 -0
  34. package/client/features/{workspace → chat/composer}/useWorkspaceSkillUpdates.ts +1 -1
  35. package/client/features/chat/group-turns.ts +46 -28
  36. package/client/features/chat/interleave-notices.ts +84 -0
  37. package/client/features/chat/model-order.ts +9 -3
  38. package/client/features/chat/tool-group/TimelineRow.tsx +23 -11
  39. package/client/features/chat/tool-group/ToolCallGroup.tsx +38 -3
  40. package/client/features/chat/tool-group/format.ts +23 -7
  41. package/client/features/chat/useAppletChatMessage.ts +11 -16
  42. package/client/features/chat/useChat.ts +3 -7
  43. package/client/features/dev/ChatStatesPage.tsx +428 -0
  44. package/client/features/dev/DevIndexPage.tsx +52 -0
  45. package/client/features/dev/DevRoutes.tsx +6 -3
  46. package/client/features/dev/HarnessDebugPage.tsx +3 -3
  47. package/client/features/dev/chat-states-fixtures.ts +744 -0
  48. package/client/features/home/api.ts +0 -10
  49. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +21 -64
  50. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +1 -1
  51. package/client/features/scratchpad/Scratchpad.tsx +5 -3
  52. package/client/features/scratchpad/scratch-session.ts +71 -0
  53. package/client/features/views/ViewBuilderTab.tsx +5 -4
  54. package/client/features/views/ViewManager.tsx +258 -0
  55. package/client/features/views/useViewBuilderActions.ts +2 -2
  56. package/client/features/views/view-residency.ts +77 -0
  57. package/client/features/widgets/WidgetFrame.tsx +6 -2
  58. package/client/features/workspace/CustomizePanel.tsx +40 -24
  59. package/client/features/workspace/WorkspaceLayoutContext.tsx +12 -2
  60. package/client/features/workspace/WorkspaceScreen.tsx +131 -201
  61. package/client/features/workspace/WorkspaceSplitLayout.tsx +111 -0
  62. package/client/features/workspace/WorkspaceTabs.tsx +1 -1
  63. package/client/features/workspace/api.ts +33 -8
  64. package/client/features/workspace/useFitsSplitLayout.ts +31 -5
  65. package/client/index.css +5 -2
  66. package/client/lib/flags.ts +4 -3
  67. package/client/runtime/useWorkspaceEvents.ts +18 -1
  68. package/client/runtime/workspace-theme.ts +29 -10
  69. package/client/store/ui.ts +5 -1
  70. package/client/theme.css +96 -6
  71. package/dist/{chunk-0pcdwjkp.js → chunk-2vaafjp4.js} +1 -1
  72. package/dist/{chunk-9y2zbzqz.js → chunk-35fq49qa.js} +1 -1
  73. package/dist/chunk-gny990qx.css +1 -0
  74. package/dist/chunk-gt7n06ef.js +1 -0
  75. package/dist/{chunk-rxvx4ta9.js → chunk-kkj86722.js} +75 -75
  76. package/dist/chunk-n7pga5x3.js +80 -0
  77. package/dist/chunk-xeyxk7ep.js +10 -0
  78. package/dist/{chunk-w3tnv51j.js → chunk-xzx7c9hq.js} +1 -1
  79. package/dist/index.html +1 -1
  80. package/lib/format.ts +17 -1
  81. package/lib/themes.ts +123 -51
  82. package/lib/types.ts +40 -13
  83. package/lib/workspace-layout.ts +2 -2
  84. package/package.json +6 -4
  85. package/server/agent.ts +199 -0
  86. package/server/api.ts +38 -90
  87. package/server/bundler/build-applet.ts +7 -4
  88. package/server/cli.ts +46 -15
  89. package/server/control.ts +13 -6
  90. package/server/env-apply.ts +4 -0
  91. package/server/harness/README.md +28 -12
  92. package/server/harness/claude-code/auth.ts +54 -0
  93. package/server/harness/claude-code/index.ts +6 -1
  94. package/server/harness/codex/adapter.ts +9 -1
  95. package/server/harness/codex/auth.ts +50 -0
  96. package/server/harness/codex/index.ts +6 -1
  97. package/server/harness/codex/session.ts +33 -14
  98. package/server/harness/openclaw/NOTES.md +518 -187
  99. package/server/harness/openclaw/adapter.ts +125 -31
  100. package/server/harness/openclaw/compat.ts +99 -0
  101. package/server/harness/openclaw/cron-view.ts +78 -0
  102. package/server/harness/openclaw/discovery.ts +145 -52
  103. package/server/harness/openclaw/gateway.ts +224 -36
  104. package/server/harness/openclaw/index.ts +56 -21
  105. package/server/harness/openclaw/session.ts +971 -55
  106. package/server/harness/openclaw/strip.ts +87 -15
  107. package/server/harness/openclaw/thinking.ts +198 -0
  108. package/server/harness/types.ts +10 -5
  109. package/server/layout.ts +5 -2
  110. package/server/moi-scaffold.ts +1 -1
  111. package/server/registry.ts +0 -20
  112. package/server/theme.ts +24 -27
  113. package/workspace/.claude/skills/moi-workspace/DESIGN.md +100 -53
  114. package/workspace/.claude/skills/moi-workspace/SKILL.md +10 -12
  115. package/client/features/dev/PixelPainter.tsx +0 -94
  116. package/client/features/dev/PlaygroundPage.tsx +0 -69
  117. package/dist/chunk-175bm057.js +0 -27
  118. package/dist/chunk-55sh4dty.js +0 -2
  119. package/dist/chunk-afgbg75t.js +0 -50
  120. package/dist/chunk-agtetn7n.css +0 -1
  121. package/dist/chunk-dfs36zgc.js +0 -1
  122. package/dist/chunk-exj6hr30.js +0 -9
  123. package/dist/chunk-m11ckkxd.js +0 -51
@@ -1,11 +1,16 @@
1
1
  # OpenClaw — integration notes
2
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.
3
+ Everything we learned wiring moi to OpenClaw's local gateway. Covers on-disk
4
+ layout, the WebSocket protocol, auth, the RPC surface, the live event stream,
5
+ per-version drift, the things that bit us, and how to use it from Bun.
6
+
7
+ Pinned dep: **`openclaw@2026.7.1`**. Compatibility: moi speaks gateway **wire
8
+ protocol 4**, the protocol of both the 2026.7.x and 2026.6.x lines — verified
9
+ identical for everything moi uses against live 2026.7.1 and 2026.6.33
10
+ gateways. Protocol-3 gateways (≤ 2026.5.x) reject the handshake with
11
+ `protocol mismatch` (verified live against 2026.4.22, WS close 1002); those
12
+ are detect-and-surface only (`compat.ts` → `classifyGatewayError`), never
13
+ silently degraded into empty lists.
9
14
 
10
15
  ## 1. What OpenClaw is
11
16
 
@@ -15,8 +20,8 @@ two components that matter:
15
20
 
16
21
  - **The gateway** — a local service exposing a WebSocket JSON-RPC API at
17
22
  `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.
23
+ approvals, memory, logs, skills, cron) is reachable through it. It's the
24
+ single control plane.
20
25
  - **The `openclaw` CLI** — a thin wrapper over the gateway's RPC methods. Most
21
26
  subcommands (`openclaw sessions`, `openclaw agents list`, `openclaw logs`)
22
27
  just open a WS connection, call one method, and format the result.
@@ -26,7 +31,10 @@ Control UI SPA and a tiny `/health` endpoint. Everything else is WebSocket.
26
31
 
27
32
  ## 2. On-disk layout
28
33
 
29
- State root: `~/.openclaw/`.
34
+ State root: `~/.openclaw/` by default. moi resolves the config the way the
35
+ CLI does: `OPENCLAW_CONFIG_PATH` wins, then `OPENCLAW_STATE_DIR/openclaw.json`
36
+ (profile runs), then `~/.openclaw/openclaw.json` (`gateway.ts →
37
+ openClawConfigPath`).
30
38
 
31
39
  | What | Path |
32
40
  | ----------------------------------------------------------------- | ---------------------------------------------------------- |
@@ -43,28 +51,17 @@ State root: `~/.openclaw/`.
43
51
  | Paired devices (control-UI, CLI, health) | `~/.openclaw/devices/paired.json` |
44
52
  | Pending pairing requests | `~/.openclaw/devices/pending.json` |
45
53
 
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):
54
+ Each agent has its **own workspace dir** (override with `openclaw agents add
55
+ --workspace`) and its own agent-state dir. The default `~/.openclaw/workspace/`
56
+ is only the fallback when an agent doesn't specify one — don't assume it's
57
+ global. If you're enumerating per-agent data, **always resolve the workspace
58
+ per agent from `agents.list`**.
55
59
 
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`.
60
+ The session `.jsonl` record vocabulary is identical across 2026.4.x → 2026.7.x
61
+ (diffed in dist): `session`/`session_info`, `message` (roles
62
+ `user`/`assistant`/`toolResult`), `compaction`, `custom`, `custom_message`,
63
+ `model_change`, `thinking_level_change`, `branch_summary`, `label`. Content
64
+ blocks: `text`, `thinking` (+`thinkingSignature`), `toolCall`.
68
65
 
69
66
  ## 3. Auth & device pairing — the part that breaks you
70
67
 
@@ -80,11 +77,12 @@ Three auth concepts stack on the gateway:
80
77
  approved scope set (`operator.read`, `operator.write`, `operator.admin`,
81
78
  `operator.approvals`, `operator.pairing`, `operator.talk.secrets`).
82
79
 
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:
80
+ A loopback `gateway-client` in `backend` mode holding a valid gateway token
81
+ skips pairing entirely — this is moi's path, and on a fresh install it gets
82
+ full operator scopes immediately (verified in the cloud sandbox,
83
+ `docs/openclaw-sandbox.md`). The pairing dance below bites shared/remote
84
+ setups where devices start with **`operator.read` only**. When the CLI
85
+ connects with insufficient scopes the gateway emits:
88
86
 
89
87
  ```
90
88
  GatewayClientRequestError: scope upgrade pending approval (requestId: <uuid>)
@@ -103,208 +101,541 @@ requestId`.
103
101
  Resolution paths, in order of practicality:
104
102
 
105
103
  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.
104
+ usually already paired with full operator scopes. One click in the Devices
105
+ panel approves the latest pending request.
106
+ 2. **Approve from another already-paired device** holding admin scopes.
107
+ 3. **Revoke the current read-only CLI pairing** so it re-pairs from scratch.
113
108
 
114
- Once approved, the role token in `device-auth.json` gets upgraded in place. No
115
- config changes needed.
109
+ Once approved, the role token in `device-auth.json` is upgraded in place.
116
110
 
117
111
  ### Fallback behavior of the CLI
118
112
 
119
113
  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.
114
+ gateway refuses the connection, they read `~/.openclaw/…` directly (`openclaw
115
+ sessions`, `openclaw status`, `openclaw agents list`, `openclaw logs`). Watch
116
+ for the "Direct scope access failed; using local fallback" banner when
117
+ debugging — those commands may never have hit the gateway.
118
+
119
+ ## 4. Handshake and hello-ok
120
+
121
+ The server pushes `connect.challenge {nonce, ts}` on socket open; the client's
122
+ first frame must be a `connect` request. On success the response payload is
123
+ (observed live on both lines):
124
+
125
+ ```jsonc
126
+ {
127
+ "type": "hello-ok",
128
+ "protocol": 4,
129
+ "server": { "version": "2026.7.1", "connId": "<uuid>" },
130
+ "features": {
131
+ "methods": ["..."], // 218 on 2026.7.1, 193 on 2026.6.33
132
+ "events": ["..."], // 30 / 27
133
+ "capabilities": ["chat-send-routing-contract"] // 2026.7.x only
134
+ },
135
+ "snapshot": {
136
+ "presence": [],
137
+ "health": {},
138
+ "uptimeMs": 0,
139
+ "sessionDefaults": {},
140
+ "authMode": "token"
141
+ },
142
+ "auth": { "role": "operator", "scopes": ["..."] },
143
+ "policy": { "maxPayload": 26214400, "maxBufferedBytes": 52428800, "tickIntervalMs": 30000 }
144
+ }
145
+ ```
126
146
 
127
- ## 4. RPC surface
147
+ **`features.methods` UNDER-REPORTS.** Methods registered with
148
+ `advertise:false` (`sessions.get`, `sessions.resolve`, `sessions.usage*`) are
149
+ omitted yet fully callable — both live gateways omit `sessions.get` from
150
+ `features.methods` and still answer it (verified live against 2026.7.1 /
151
+ 2026.6.33). Treat the list as advisory: gate optional niceties on it, never an
152
+ essential call (`compat.ts → advertisesMethod`).
153
+
154
+ Rule for params in the other direction: gateways validate with
155
+ `additionalProperties: false` and hard-reject unknown fields, so never send a
156
+ param that only newer schemas know without gating on the announced version
157
+ (e.g. `sessions.list {archived}` and `sessions.create {fork, worktree}` are
158
+ 2026.7.x-only).
159
+
160
+ ## 5. RPC surface
161
+
162
+ Methods moi uses, all present and shape-identical on both supported lines:
163
+ `agents.list` · `agents.files.get` · `models.list` · `sessions.list` ·
164
+ `sessions.get` · `sessions.resolve` · `sessions.create` · `sessions.send` ·
165
+ `sessions.steer` · `sessions.abort` · `sessions.patch` ·
166
+ `sessions.subscribe`/`unsubscribe` · `sessions.messages.subscribe`/
167
+ `unsubscribe`. Also there: `sessions.preview`, `sessions.compact`,
168
+ `chat.history`, `cron.list`, `cron.runs`, and many more.
128
169
 
129
- Full method list (surfaced from `method-scopes-*.js` but verified by calling
130
- them live):
170
+ ### Gotchas in params
131
171
 
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}`.
172
+ - **`sessions.list`** accepts `limit`, `offset`, `activeMinutes`,
173
+ `includeGlobal`, `includeUnknown`, `configuredAgentsOnly`,
174
+ `includeDerivedTitles`, `includeLastMessage`, `label`, `spawnedBy`,
175
+ `agentId`, `search` (+`archived` on 2026.7.x) — **not** `allAgents` (the CLI
176
+ flag is client-side aggregation). Pass `includeGlobal: true` to aggregate.
177
+ - **`sessions.get`** takes `{ key | sessionKey, limit?, agentId? }` (no strict
178
+ schema) → `{ messages }`; unknown keys return `{ messages: [] }`, not an
179
+ error. `sessions.preview({ keys, limit, maxChars })` returns `{ role, text }`
180
+ items but caps around 11 — use `sessions.get` for transcripts.
181
+ - **`agents.list`** accepts **no** extra params. The row is richer than it
182
+ used to be — `{ id, workspace, workspaceGit, agentRuntime, thinkingLevels,
183
+ thinkingOptions, thinkingDefault, model }` (verified live) — but identity
184
+ (`identityName`, emoji, bindings) is still CLI-enriched; fetch
185
+ `agents.files.get({ agentId, name: 'IDENTITY.md' })` yourself.
186
+ - **`agents.files.get`** uses `{ agentId, name }` — not `{ id, path }`.
187
+ - Scope errors return `INVALID_REQUEST` or `scope upgrade pending approval`
188
+ depending on the method's required scope.
139
189
 
140
- **Agents.** `agents.list` · `agents.create` · `agents.update` · `agents.delete` ·
141
- `agents.files.{list,get,set}`.
190
+ ### sessions.patch
142
191
 
143
- **Config/logs.** `config.get` · `config.schema.lookup` · `logs.tail`.
192
+ Params (`additionalProperties: false`): `key` (+`agentId`) plus any of
193
+ `label`, `category`, `archived`, `pinned`, `unread`, `thinkingLevel`,
194
+ `fastMode`, `verboseLevel`, `traceLevel`, `reasoningLevel`, `responseUsage`,
195
+ `elevatedLevel`, `execHost`/`execSecurity`/`execAsk`/`execNode`, `model`,
196
+ `spawnedBy`, `spawnedWorkspaceDir`, `spawnedCwd`, `spawnDepth`,
197
+ `subagentRole`, `subagentControlScope`, `inheritedToolAllow`/`Deny`,
198
+ `sendPolicy`, `groupActivation`. Write scope covers the organizational fields
199
+ (`label`, `category`, `pinned`, `archived`, `unread`); the rest needs admin.
144
200
 
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.
201
+ `{ model, thinkingLevel }` is how moi applies the picker before each send
202
+ (both lines, verified live). The config's `agents.defaults.models` map is a
203
+ **model allowlist**: patching to a model outside it is rejected with
204
+ `INVALID_REQUEST` `model not allowed: <provider>/<model>` (verified live
205
+ against 2026.6.33).
148
206
 
149
- ### Gotchas in params
207
+ #### Never patch the model straight into a send
150
208
 
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.
209
+ `sessions.patch { model }` is **not** a session-local write: OpenClaw persists
210
+ the pick into the agent's effective `model.primary`, and that config write
211
+ bumps the prepared-model-runtime generation. A run admitted inside that window
212
+ is superseded and dies **during admission** — `sessions.send` still answers
213
+ `status: 'started'` with a runId, and the only thing that follows is
214
+ `sessions.changed { reason: 'chat.dispatch-error' }` (no runId to match on).
168
215
 
169
- ### Detecting running sessions
216
+ Captured on the wire against 2026.7.2-beta.7, first message of a new chat:
170
217
 
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
218
+ ```
219
+ 14:49:47.901 SEND sessions.patch { model, thinkingLevel, reasoningLevel }
220
+ 14:49:47.930 RESP patch ok
221
+ 14:49:47.930 SEND sessions.send ← same millisecond
222
+ 14:49:47.946 RESP send status=started runId=88a7701d
223
+ 14:49:49.959 EVT sessions.changed reason=chat.dispatch-error ← run dead, 2.0s later
224
+ 14:49:58.641 SEND sessions.send (user resent) → ran fine
225
+ ```
178
226
 
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.
227
+ The resend works because the model is already applied, so there is no second
228
+ config write. That is the whole shape of the bug: **first message of a new
229
+ chat fails, second always works.**
184
230
 
185
- ### Stopping a run
231
+ So moi carries the model **in `sessions.create`** instead (`session.ts →
232
+ sendOpenClawMessageImpl`) and marks it applied on the record so
233
+ `applySessionSettings` skips the model patch. Note the asymmetry that decides
234
+ what may ride along on create:
186
235
 
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' }`.
236
+ | create param | 2026.6.x | 2026.7.x |
237
+ | --------------- | -------- | -------- |
238
+ | `model` | yes | yes |
239
+ | `thinkingLevel` | **no** | yes |
190
240
 
191
- ## 5. Using the `openclaw` npm package
241
+ Both lines validate create with `additionalProperties: false`, so passing
242
+ `thinkingLevel` there would hard-reject **every new chat** on 2026.6.x. Effort
243
+ stays a patch — it is session-scoped, writes no config, and so cannot supersede
244
+ a run. Only the model ever needed moving.
192
245
 
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:
246
+ **Thinking levels are per model, not gateway-global** (an earlier version of
247
+ this doc claimed otherwise and moi shipped one static list because of it).
248
+ The gateway resolves the menu from per-provider policies in the dist
249
+ (`provider-claude-thinking`, `moonshot-thinking`, …) and validates
250
+ `thinkingLevel` against the session's _resolved_ model, rejecting by name:
196
251
 
197
- ```ts
198
- import { GatewayClient } from 'openclaw/plugin-sdk/gateway-runtime'
252
+ ```
253
+ thinkingLevel "adaptive" is not supported for openai/gpt-5.6-sol
254
+ (use off|minimal|low|medium|high|xhigh|max|ultra)
255
+ thinkingLevel "minimal" is not supported for ollama/deepseek-v4-flash:cloud
256
+ (use off|low|medium|high|max)
199
257
  ```
200
258
 
201
- Also available at the same path: `createOperatorApprovalsGatewayClient`,
202
- `withOperatorApprovalsGatewayClient`, the `EventFrame` protocol type.
203
-
204
- `GatewayClient` handles:
259
+ Menus captured live from `sessions.list` rows on 2026.7.1-2:
260
+
261
+ | model | thinkingOptions | default |
262
+ | ------------------------------ | -------------------------------------------------- | ------- |
263
+ | openai/gpt-5.6-sol | off minimal low medium high xhigh max **ultra** | low |
264
+ | openai/gpt-5.6-terra | off minimal low medium high xhigh max **ultra** | medium |
265
+ | openai/gpt-5.6-luna | off minimal low medium high xhigh max | medium |
266
+ | anthropic/claude-opus-4-8 | off minimal low medium **adaptive** high xhigh max | off |
267
+ | ollama/kimi-k3:cloud | off low medium high max | off |
268
+ | ollama/deepseek-v4-flash:cloud | off low medium high max | off |
269
+ | openai/kimi-k3:cloud | off minimal low medium high | off |
270
+
271
+ So `adaptive` is Claude-only, `ultra` is OpenAI-only (and absent from luna),
272
+ the ollama models drop `minimal`/`xhigh`, and the same model id under two
273
+ providers gets two different menus. `thinkingDefault` varies too.
274
+
275
+ `models.list` carries only `reasoning: boolean` — no levels — **and even that
276
+ flag is not dependable**: on 2026.7.2-beta.7 the OpenAI rows come back with
277
+ `reasoning: undefined` while their session rows still advertise the full
278
+ `off…ultra` menu (verified live). Gating the effort picker on the flag alone
279
+ therefore makes it vanish for every GPT model on that line, so
280
+ `getOpenClawModels` also accepts a learned menu with more than one level as
281
+ proof the model reasons. There is no per-model thinking RPC either (`models.get`/`models.capabilities` don't exist;
282
+ `models.list` hard-rejects an `agentId` param). Every **session row** does
283
+ carry the resolved menu, so `thinking.ts` harvests rows (discovery
284
+ `sessions.list` + the row embedded in every live frame) into a per-model map
285
+ that feeds the picker, and relearns a model's menu from a rejection message
286
+ when one slips through. Models with no row yet fall back to the
287
+ cross-provider intersection `off low medium high`.
288
+
289
+ ### reasoningLevel — the gate on reasoning output
290
+
291
+ `sessions.patch { reasoningLevel: 'off' | 'on' | 'stream' }`, **default
292
+ `off`**. In the dist, `reasoningMode = reasoningLevel ?? 'off'` and then
293
+ `includeReasoning: reasoningMode === 'on'`, `streamReasoning: reasoningMode
294
+ === 'stream'`, both further gated on `canShowReasoning = thinkingLevel !==
295
+ 'off'`. moi patches `reasoningLevel: 'stream'` whenever the picked effort is
296
+ not `off`, so a provider that can surface reasoning does.
297
+
298
+ Necessary but not sufficient — see §6 for which backends actually carry the
299
+ text. Note the side effect on a session that also serves a channel (a
300
+ Telegram-routed `agent:<a>:main`): reasoning mode is a session property, so
301
+ raising it changes what that channel streams too.
302
+
303
+ Config edits hot-reload where possible: the gateway watches `openclaw.json`
304
+ and logs `config hot reload applied (…)` vs `requires gateway restart (…)`
305
+ per key; CLI config writes print `Gateway restart required` when a key
306
+ doesn't hot-apply. Don't assume every config write needs a restart anymore —
307
+ but model-auth changes still resolve at startup.
205
308
 
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`)
309
+ ### Detecting running sessions
213
310
 
214
- Minimal client (what `server/openclaw.ts` uses):
311
+ `sessions.list` rows include `status` + `startedAt` / `endedAt` / `runtimeMs`
312
+ once a session has had at least one gateway run. `status === 'running'` is
313
+ the live discriminator; `abortedLastRun: true` means the last run was killed.
314
+ Rows for never-run sessions omit these fields entirely.
215
315
 
216
- ```ts
217
- import { GatewayClient } from 'openclaw/plugin-sdk/gateway-runtime'
316
+ ### Stopping a run
218
317
 
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
- })
318
+ `sessions.abort({ key, runId? })`. Pass the specific `runId` to kill a
319
+ particular run; omit it to kill whatever's active. Returns `{ ok: true,
320
+ abortedRunId, status: 'aborted' | 'no-active-run' }`. `sessions.steer` is
321
+ `sessions.send` that interrupts the active run first (response carries
322
+ `interruptedActiveRun`).
323
+
324
+ ## 6. Live events
325
+
326
+ One WebSocket connection: `sessions.subscribe({})` for the agent-wide
327
+ firehose, `sessions.messages.subscribe({ key })` per session. Events arrive
328
+ as `{ type: 'event', event, payload, seq? }` frames. moi refcounts the
329
+ per-session subscriptions (`gateway.ts`): the first live record subscribes a
330
+ key, later records reuse it, and the last one to tear down (idle eviction or
331
+ shutdown) `sessions.messages.unsubscribe({ key })`s it — best-effort, since a
332
+ dropped socket already unsubscribes server-side. On reconnect it re-subscribes
333
+ every key that still has a live holder. **Every session-scoped
334
+ event embeds a fresh session row** (`payload.session` and/or flattened
335
+ fields): `model`/`modelProvider`, `thinkingLevel` (+`thinkingLevels`),
336
+ `inputTokens`/`outputTokens`/`totalTokens`, `estimatedCostUsd`, `status`,
337
+ `origin`, `contextTokens`, `contextBudgetStatus.shouldCompact` — a free
338
+ state sync on every frame.
339
+
340
+ Families we consume (skeletons from live captures; wire shapes identical on
341
+ 2026.7.1 and 2026.6.33 unless noted):
342
+
343
+ **`chat`** — token streaming. `message` is the cumulative partial (full
344
+ content blocks), `deltaText` just the increment:
345
+
346
+ ```jsonc
347
+ {
348
+ "runId": "…",
349
+ "sessionKey": "agent:main:main",
350
+ "seq": 6,
351
+ "state": "delta", // delta | final | error | aborted
352
+ "deltaText": " moon is …",
353
+ "message": {
354
+ "role": "assistant",
355
+ "content": [{ "type": "text", "text": "The moon is …" }],
356
+ "timestamp": 0
357
+ },
358
+ "stopReason": "stop", // final/aborted ("rpc" on a steer interrupt)
359
+ "errorMessage": "…"
360
+ } // error only
361
+ ```
226
362
 
227
- await new Promise<void>((res, rej) => {
228
- client.opts.onHelloOk = () => res()
229
- client.opts.onConnectError = rej
230
- client.start()
231
- })
363
+ **`session.message`** — durable transcript rows, pushed as they commit. The
364
+ `message` carries `__openclaw` meta (see §7). Rows without `__openclaw.id`
365
+ are transient pre-envelope echoes — skip them; the durable row follows
366
+ seconds later. **`toolResult` rows DO stream here** on both lines (an earlier
367
+ version of this doc claimed they didn't); `session.tool` additionally carries
368
+ the same output live, and the run-end `sessions.get` reconcile is now just
369
+ the safety net.
370
+
371
+ **`session.tool`** — live tool state, `data.phase` `start`/`update`/`result`,
372
+ with the **full output inline on both lines**:
373
+
374
+ ```jsonc
375
+ {
376
+ "runId": "…",
377
+ "stream": "tool",
378
+ "sessionKey": "agent:main:main",
379
+ "data": {
380
+ "phase": "result", // start: name/toolCallId/args · update: +partialResult
381
+ "name": "exec",
382
+ "toolCallId": "toolu_01…",
383
+ "isError": false,
384
+ "result": {
385
+ "content": [{ "type": "text", "text": "8" }],
386
+ "details": { "status": "completed", "exitCode": 0, "durationMs": 255, "cwd": "/…" }
387
+ }
388
+ },
389
+ "session": {
390
+ /* fresh row */
391
+ }
392
+ }
393
+ ```
232
394
 
233
- const result = await client.request('sessions.list', { includeGlobal: true })
234
- client.stop()
395
+ **`agent`** — the raw run stream `{ runId, stream, seq, ts, data }`;
396
+ `stream` values: `assistant` (`{ text, delta }`, cumulative + increment;
397
+ `thinking` likewise), `item` (tool/item lifecycle `{ itemId, phase:
398
+ start|update|end, kind, status, name, toolCallId }`), `command_output`
399
+ (`{ output, phase: delta|end, exitCode?, durationMs?, cwd? }`), `lifecycle`
400
+ (phases `start` → `finishing` `{ stopReason, aborted }` → `end`, or `error`
401
+ `{ error }`).
402
+
403
+ **codex-app-server tool output is run-end only.** On the codex backend
404
+ (OpenAI models — the `agent`/`tool` + `codex_app_server.*` streams, not
405
+ `session.tool`; `codex_app_server.item` frames are present and no
406
+ `command_output` frames are), the live `agent`/`tool` `phase:'result'` frame
407
+ carries only `{ status, exitCode, durationMs }` — **never the stdout**.
408
+ Verified on the wire (result frame at t≈16.2s has no `content`; the command's
409
+ output first appears in the run-end `session.message` `toolResult` at t≈20.0s)
410
+ and in the plugin: `@openclaw/codex` `itemToolResult(commandExecution)`
411
+ returns exactly those three fields. A turn's assistant/`toolCall`/`toolResult`
412
+ rows all commit together when the turn ends, so the durable `toolResult` (the
413
+ only frame that carries stdout **with** a `toolCallId`) is run-end-gated. The
414
+ one live-stdout path — the plugin's `handleOutputDelta`/`emitToolResultOutput`
415
+ → `onToolResult` — is gated behind the agent's `verboseLevel:'full'` and
416
+ arrives as formatted channel-progress text with no `toolCallId`, so it can't
417
+ attach to a card. Net: moi renders a codex tool running and flips it to
418
+ success/error (from `isError`/exitCode) live at the result frame, but the
419
+ **output body only fills when the run ends**. This is a backend property, not
420
+ a moi gap — `session.tool` (Anthropic) carries output live, which is why the
421
+ two backends feel different.
422
+
423
+ **Live tool synthesis is codex-only.** Because codex batches its durable rows
424
+ at run end, tools would otherwise pop in all at once after the streamed text,
425
+ so moi synthesizes an ephemeral `livetool:<toolCallId>` turn from the
426
+ `agent`/`tool` `start` frame and merges the durable owner onto it by re-id
427
+ (`session.ts` → `emitLiveToolTurn`/`emitTurn`). This is gated on a
428
+ `codex_app_server.*` frame having been seen this session (`rec.codexBackend`).
429
+ Native-loop providers (Anthropic, **ollama** — e.g. deepseek-v4-flash) are NOT
430
+ gated in: their durable rows arrive during the run, so `session.tool` +
431
+ `reemitToolCallOwners` already render tools live, and their `start`-frame
432
+ `toolCallId` need not match the `result`/durable id (ollama uses a provisional
433
+ start id, a final result id) — synthesizing there stranded the live card as a
434
+ permanent duplicate (`○` stuck running beside the durable `●`), and broadcast
435
+ turns can't be retracted (`applyEvent` only upserts by id). So synthesis stays
436
+ off unless the positive codex signal fires.
437
+
438
+ **Thinking blocks: who actually emits them.** The wire shape exists and moi
439
+ renders it — durable rows carry `{ type: 'thinking', thinking,
440
+ thinkingSignature }` and `adapter.ts` maps it to a `reasoning` part. What
441
+ varies is whether a backend ever produces one. Measured live (2026.7.1-2, one
442
+ send per backend, full frame capture):
443
+
444
+ | backend (`agentRuntime`) | reasoning on the wire | text? |
445
+ | ---------------------------------- | --------------------------------------------------------------------------------------------------------- | ----- |
446
+ | codex app-server (`codex`) | `agent`/item `kind:'analysis' title:'Reasoning'` start→end, plus `codex_app_server.item type:'reasoning'` | no |
447
+ | claude CLI (`claude-cli`) | `agent`/thinking `{ progressTokens: 50 }` | no |
448
+ | native loop (`auto`, ollama) | nothing — the model writes its reasoning as plain text | n/a |
449
+ | `openai-codex` responses transport | durable `thinking` blocks with full text | YES |
450
+
451
+ Only the last one delivers text, and it is the path the current default config
452
+ no longer takes: OpenAI models resolve to `agentRuntime: codex` (implicitly, or
453
+ pinned per model in `agents.defaults.models`), which routes through the codex
454
+ app-server. Its `appendCodexAcpConfigOverrides` forwards
455
+ `model_reasoning_effort` but never `model_reasoning_summary`, and its item
456
+ frames carry no payload; the plugin's one text-bearing reasoning path
457
+ (`onReasoningStream`) is channel-progress formatting with no item id, so it
458
+ can't attach to a row. Selecting `openai-codex/<model>` directly is blocked by
459
+ the `agents.defaults.models` allowlist unless the user adds that ref.
460
+
461
+ Setting `reasoningLevel` (§5) does not change any of the three "no" rows —
462
+ verified with `on` and `stream`, each paired with `thinkingLevel: high` so
463
+ `canShowReasoning` held. It is still set, because it is the documented gate and
464
+ the one path that does carry text needs it.
465
+
466
+ Given that, moi renders what the codex backend _does_ report: `session.ts →
467
+ handleReasoningItemFrame` turns the analysis item into a textless
468
+ `{ type: 'reasoning', text: '', redacted: true, durationMs }` part, so a codex
469
+ run shows "Thinking" → "Thought for 1.1s" instead of a silent gap before the
470
+ first token. Like the live tool cards it is not durable — nothing in the
471
+ transcript backs it, so a cold reload drops the row.
472
+
473
+ **`task`** — subagent runs (2026.7.x; the event family is new there):
474
+
475
+ ```jsonc
476
+ {
477
+ "action": "upserted",
478
+ "task": {
479
+ "kind": "subagent",
480
+ "status": "running", // → completed
481
+ "title": "…",
482
+ "sessionKey": "agent:main:main",
483
+ "childSessionKey": "agent:main:subagent:<uuid>",
484
+ "runId": "…"
485
+ }
486
+ }
235
487
  ```
236
488
 
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.
489
+ **`session.operation`** — compaction:
490
+ `{ operationId, operation: 'compact', phase: 'start' | 'end', sessionKey,
491
+ completed?, ts }`.
492
+
493
+ **`presence` / `health`** — connected-device roster and a rich gateway
494
+ health blob (`eventLoop`, `plugins`, `channels`, `sessions`); useful for
495
+ liveness, ignored otherwise. `tick` is the heartbeat.
496
+
497
+ ### `sessions.changed`
498
+
499
+ Two flavors share the event name (both lines, verified live):
500
+
501
+ - **Run lifecycle**: `{ phase: 'start' | 'end' | 'error', runId, …row }` —
502
+ drives the busy flag.
503
+ - **Mutations**: `{ reason, …row }`. Observed live: `send`, `steer`,
504
+ `create`, `patch`, `compact`, `subagent-status`; the dist also emits
505
+ `new`, `delete`, `abort`, `cleanup` and friends — treat the set as open.
506
+ **`chat.title` is 2026.7.x-only** — zero emit sites in the 2026.6.33 dist,
507
+ so title refreshes on 6.x ride the other reasons.
240
508
 
241
- ### The dependency footprint
509
+ ## 7. Durable-row drift between the lines
242
510
 
243
- The `openclaw` package is **big** (~300+ transitive deps — it includes channel
244
- plugins, provider SDKs, the full CLI). If that's a dealbreaker:
511
+ Where 2026.7.x and 2026.6.x rows actually differ for us (all verified live
512
+ via `sessions.get` + `session.message` frames on both gateways):
245
513
 
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.
514
+ | Field | 2026.7.x | 2026.6.x |
515
+ | ------------------------------------------ | ------------------------------------------------------- | ------------------------------------------------------------ |
516
+ | `<runId>:user` send idempotency key | `__openclaw.idempotencyKey` (+ mirrored on the message) | message-level `idempotencyKey` only |
517
+ | `__openclaw.senderIsOwner` | on user rows (`false` = channel inbound) | absent |
518
+ | `__openclaw.id` | 8-hex short hash | short hash on agent rows, uuid seen on gateway-injected rows |
519
+ | assistant `responseId` (`msg_…`) + `model` | both | both |
251
520
 
252
- For our case (the server already has lots of deps), the subpath import wins.
521
+ Treat `__openclaw.id` as an opaque string. `compat.ts →
522
+ messageIdempotencyKey` reads nested-then-flat so the user-echo rendezvous
523
+ matches on either line; text matching stays as the fallback.
253
524
 
254
- ## 6. Security hardening in 2026.4.22
525
+ ## 8. Cron sessions
255
526
 
256
- Notable items in the CHANGELOG relevant to anyone integrating:
527
+ Anatomy (verified live against 2026.7.1): the job's session key is
528
+ `agent:<a>:cron:<jobId>` with label/displayName `Cron: <name>`; every firing
529
+ runs under a per-run key `agent:<a>:cron:<jobId>:run:<uuid>` with its own
530
+ `sessionId` (visible in `cron.runs` entries). The post-run session reset
531
+ **orphans the per-run transcript file** — `sessions.get` AND `chat.history`
532
+ return 0 messages for both the job key and the run key (verified live). The
533
+ readable record is `cron.runs`: entries carry `{ ts, jobId, action, status:
534
+ 'ok' | 'error', summary, runId, durationMs, model, usage, sessionKey,
535
+ error? }`. Don't build cron transcript views on the session APIs.
257
536
 
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
537
+ ## 9. Channel routing
270
538
 
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.
539
+ With default routing an inbound channel DM (IRC, Telegram, …) lands in the
540
+ agent's **main** session `agent:<a>:main` — no new session. Verified live
541
+ against 2026.7.1 with a loopback IRC channel:
275
542
 
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.
543
+ - The session row's `channel`/`lastChannel` flip to the provider and `origin`
544
+ absorbs the peer identity: `{ label: 'mole!mole@127.0.0.1', from:
545
+ 'irc:mole!mole@127.0.0.1', to: 'irc:mole' }`; `deliveryContext` records the
546
+ reply route.
547
+ - `displayName` becomes the peer identity string — which **hijacks title
548
+ precedence** (label > displayName > derivedTitle > preview), so the chat
549
+ list suddenly shows `mole!mole@127.0.0.1` instead of the derived title.
550
+ - Per-message provenance is minimal: the inbound user row carries only
551
+ `__openclaw.senderIsOwner: false` (2026.7.x; 6.x rows have no marker), plus
552
+ the strippable inbound-metadata envelope in the text (see `strip.ts`).
279
553
 
280
- ## 7. What our code does
554
+ ## 10. Using the `openclaw` npm package
281
555
 
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.
556
+ **Don't roll your own WS client.** The `openclaw` package publishes a
557
+ supported subpath export:
286
558
 
287
- Pipeline:
559
+ ```ts
560
+ import { GatewayClient } from 'openclaw/plugin-sdk/gateway-runtime'
561
+ ```
562
+
563
+ `GatewayClient` handles device-identity loading & signing, token auth, the
564
+ challenge-response handshake, reconnect backoff, heartbeat watch, and per-RPC
565
+ timeouts. `opts` is private — connect callbacks go to the constructor
566
+ (that's true on every version we support, not just 2026.7.x):
288
567
 
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
568
+ ```ts
569
+ const client = new GatewayClient({
570
+ url: `ws://127.0.0.1:${port}`,
571
+ token, // from openclaw.json gateway.auth.token
572
+ role: 'operator',
573
+ scopes: ['operator.admin', 'operator.read', 'operator.write'],
574
+ // REQUIRED for live tool cards: the gateway registers a connection as a
575
+ // tool-event recipient only when it advertises this cap. Omit it and
576
+ // `session.tool` frames never arrive (the SDK defaults `caps` to `[]`).
577
+ caps: ['tool-events'],
578
+ // moi speaks wire protocol 4 (compat.ts). The SDK already defaults both to 4,
579
+ // so pinning them is self-documenting, not a behavior change.
580
+ minProtocol: 4,
581
+ maxProtocol: 4,
582
+ requestTimeoutMs: 2000,
583
+ onHelloOk: hello => {
584
+ /* parseHelloOk(hello) → GatewayInfo */
585
+ },
586
+ onConnectError: err => {
587
+ /* classifyGatewayError(err) */
588
+ },
589
+ onEvent: evt => {
590
+ /* { event, payload } frames */
591
+ }
592
+ })
593
+ client.start()
594
+ const result = await client.request('sessions.list', { includeGlobal: true })
595
+ client.stop()
596
+ ```
298
597
 
299
- That's it — 2 round-trips to get everything we show on `/`.
598
+ moi builds these shared options once in `gateway.ts → gatewayClientBaseOptions`
599
+ and spreads them into both the persistent streaming client and the one-shot
600
+ discovery client, so both advertise `caps: ['tool-events']`.
300
601
 
301
- ## 8. Commands worth knowing
602
+ Important: **always wrap `connect` in your own timeout**. `GatewayClient`
603
+ doesn't enforce one on the initial handshake (only on individual RPCs), so a
604
+ silent gateway will hang forever. We race a 2–5 s timer.
605
+
606
+ The package is **big** (~300+ transitive deps — channel plugins, provider
607
+ SDKs, the full CLI). For our case (the server already has lots of deps) the
608
+ subpath import wins over rolling a minimal client.
609
+
610
+ ## 11. What our code does
611
+
612
+ `server/harness/openclaw/` — the harness. Module map:
613
+
614
+ - `gateway.ts` — one process-global `GatewayClient` (reconnect, subscription
615
+ replay, wire tap), config-path resolution, one-shot client for discovery,
616
+ and the last connect outcome for `/status` (`getOpenClawGatewayStatus`).
617
+ - `compat.ts` — protocol-4 tolerance layer: `parseHelloOk`,
618
+ `advertisesMethod`, `classifyGatewayError`, `messageIdempotencyKey`. Read
619
+ its header before sending any new param to the gateway.
620
+ - `thinking.ts` — per-model thinking menus learned from session rows, plus the
621
+ relearn-from-rejection path. The effort picker reads it (§5).
622
+ - `discovery.ts` — agents → workspace candidates, models catalog, transcript
623
+ seeds (2 round-trips: `agents.list` + `sessions.list`, then per-agent
624
+ `agents.files.get(IDENTITY.md)`).
625
+ - `session.ts` — live session records: `sessions.get` seed, `session.message`
626
+ ingest, `chat` → StreamPreview, `session.tool` → live tool cards,
627
+ `sessions.patch` before sends, echo rendezvous, run-end reconcile.
628
+ - `adapter.ts` — gateway rows/messages → moi turns; `strip.ts` — mirror of
629
+ upstream `strip-inbound-meta` (re-diff on every bump, see its header).
630
+
631
+ ## 12. Commands worth knowing
302
632
 
303
633
  ```
304
634
  openclaw status # overview (gateway, agents, sessions, security)
305
635
  openclaw agents list [--json] # agents + workspaces + bindings (CLI-enriched)
306
636
  openclaw sessions --all-agents --json # aggregate sessions across agents (uses RPC)
307
637
  openclaw logs --follow --json # tail gateway logs (WS if scoped, else /tmp file)
638
+ openclaw cron list --all # cron jobs incl. disabled; `cron runs` for history
308
639
  openclaw devices list # pending + paired devices
309
640
  openclaw devices approve <requestId> # needs admin scope (chicken-and-egg, see §3)
310
641
  openclaw doctor # lint config, flag risky dm policies
@@ -312,5 +643,5 @@ openclaw dashboard # open Control UI with token in URL
312
643
  ```
313
644
 
314
645
  `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>/`).
646
+ on port `19001`. Same for `--profile <name>` (`~/.openclaw-<name>/`) — the
647
+ multi-version test rig in `docs/openclaw-sandbox.md` is built on profiles.