moi-computer 0.8.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 (100) hide show
  1. package/client/api/workspace-keys.ts +1 -2
  2. package/client/app/AppRouter.tsx +10 -3
  3. package/client/app/routes/HomeRoute.tsx +1 -1
  4. package/client/app/shell/SidebarLayout.tsx +2 -14
  5. package/client/components/shared/Composer.tsx +20 -7
  6. package/client/components/shared/PanelHeader.tsx +8 -1
  7. package/client/components/ui/button.tsx +3 -3
  8. package/client/components/ui/dialog.tsx +1 -1
  9. package/client/components/ui/dropdown-menu.tsx +2 -2
  10. package/client/components/ui/hover-card.tsx +1 -1
  11. package/client/components/ui/popover.tsx +1 -1
  12. package/client/components/ui/resizable.tsx +40 -0
  13. package/client/features/chat/ChatEmptyState.tsx +9 -11
  14. package/client/features/chat/ChatPanel.tsx +76 -48
  15. package/client/features/chat/ChatPopup.tsx +16 -2
  16. package/client/features/chat/ChatPromptBubbles.tsx +6 -8
  17. package/client/features/chat/ChatSelector.tsx +24 -7
  18. package/client/features/chat/ModelPicker.tsx +5 -4
  19. package/client/features/chat/TurnView.tsx +108 -13
  20. package/client/features/chat/api.ts +1 -18
  21. package/client/features/chat/chat-send.ts +2 -2
  22. package/client/features/chat/{ChatComposer.tsx → composer/ChatComposer.tsx} +6 -5
  23. package/client/features/chat/composer/banners/ChatErrorBanner.tsx +28 -0
  24. package/client/features/chat/composer/banners/ComposerBanner.tsx +30 -0
  25. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +91 -0
  26. package/client/features/{workspace → chat/composer/banners}/WorkspaceSkillUpdateBanner.tsx +9 -7
  27. package/client/features/chat/composer/useWorkspaceComposerState.tsx +74 -0
  28. package/client/features/{workspace → chat/composer}/useWorkspaceSkillUpdates.ts +1 -1
  29. package/client/features/chat/group-turns.ts +46 -28
  30. package/client/features/chat/interleave-notices.ts +84 -0
  31. package/client/features/chat/model-order.ts +9 -3
  32. package/client/features/chat/tool-group/TimelineRow.tsx +23 -11
  33. package/client/features/chat/tool-group/ToolCallGroup.tsx +38 -3
  34. package/client/features/chat/tool-group/format.ts +23 -7
  35. package/client/features/chat/useAppletChatMessage.ts +11 -16
  36. package/client/features/chat/useChat.ts +3 -7
  37. package/client/features/dev/ChatStatesPage.tsx +428 -0
  38. package/client/features/dev/DevIndexPage.tsx +52 -0
  39. package/client/features/dev/DevRoutes.tsx +6 -3
  40. package/client/features/dev/HarnessDebugPage.tsx +3 -3
  41. package/client/features/dev/chat-states-fixtures.ts +744 -0
  42. package/client/features/scratchpad/Scratchpad.tsx +4 -0
  43. package/client/features/scratchpad/scratch-session.ts +71 -0
  44. package/client/features/views/ViewBuilderTab.tsx +5 -4
  45. package/client/features/views/useViewBuilderActions.ts +2 -2
  46. package/client/features/workspace/WorkspaceLayoutContext.tsx +4 -2
  47. package/client/features/workspace/WorkspaceScreen.tsx +128 -146
  48. package/client/features/workspace/WorkspaceSplitLayout.tsx +111 -0
  49. package/client/features/workspace/api.ts +33 -8
  50. package/client/features/workspace/useFitsSplitLayout.ts +31 -5
  51. package/client/index.css +1 -1
  52. package/client/lib/flags.ts +4 -3
  53. package/client/runtime/useWorkspaceEvents.ts +18 -1
  54. package/client/store/ui.ts +5 -1
  55. package/dist/{chunk-0pcdwjkp.js → chunk-2vaafjp4.js} +1 -1
  56. package/dist/{chunk-9y2zbzqz.js → chunk-35fq49qa.js} +1 -1
  57. package/dist/chunk-gny990qx.css +1 -0
  58. package/dist/chunk-gt7n06ef.js +1 -0
  59. package/dist/{chunk-r5ce5cdg.js → chunk-kkj86722.js} +75 -75
  60. package/dist/chunk-n7pga5x3.js +80 -0
  61. package/dist/chunk-xeyxk7ep.js +10 -0
  62. package/dist/{chunk-h9h8f176.js → chunk-xzx7c9hq.js} +1 -1
  63. package/dist/index.html +1 -1
  64. package/lib/format.ts +17 -1
  65. package/lib/themes.ts +2 -2
  66. package/lib/types.ts +38 -8
  67. package/lib/workspace-layout.ts +2 -2
  68. package/package.json +2 -1
  69. package/server/agent.ts +199 -0
  70. package/server/api.ts +36 -17
  71. package/server/env-apply.ts +4 -0
  72. package/server/harness/README.md +28 -12
  73. package/server/harness/claude-code/auth.ts +54 -0
  74. package/server/harness/claude-code/index.ts +6 -1
  75. package/server/harness/codex/adapter.ts +9 -1
  76. package/server/harness/codex/auth.ts +50 -0
  77. package/server/harness/codex/index.ts +6 -1
  78. package/server/harness/codex/session.ts +33 -14
  79. package/server/harness/openclaw/NOTES.md +518 -187
  80. package/server/harness/openclaw/adapter.ts +125 -31
  81. package/server/harness/openclaw/compat.ts +99 -0
  82. package/server/harness/openclaw/cron-view.ts +78 -0
  83. package/server/harness/openclaw/discovery.ts +145 -52
  84. package/server/harness/openclaw/gateway.ts +224 -36
  85. package/server/harness/openclaw/index.ts +56 -21
  86. package/server/harness/openclaw/session.ts +971 -55
  87. package/server/harness/openclaw/strip.ts +87 -15
  88. package/server/harness/openclaw/thinking.ts +198 -0
  89. package/server/harness/types.ts +10 -5
  90. package/server/layout.ts +5 -2
  91. package/workspace/.claude/skills/moi-workspace/DESIGN.md +19 -9
  92. package/client/features/dev/PixelPainter.tsx +0 -94
  93. package/client/features/dev/PlaygroundPage.tsx +0 -69
  94. package/dist/chunk-0k7brsms.js +0 -9
  95. package/dist/chunk-dfs36zgc.js +0 -1
  96. package/dist/chunk-dtwxpxbg.js +0 -51
  97. package/dist/chunk-ga7t9qsk.js +0 -2
  98. package/dist/chunk-tey2nq7c.js +0 -31
  99. package/dist/chunk-z73xpsa0.js +0 -50
  100. package/dist/chunk-zzgredta.css +0 -1
@@ -17,22 +17,117 @@ import { readFile } from 'node:fs/promises'
17
17
  import { homedir } from 'node:os'
18
18
  import { join } from 'node:path'
19
19
 
20
+ import { type GatewayFailure, type GatewayInfo, classifyGatewayError, parseHelloOk } from './compat'
21
+ import { tapWire } from '../debug'
22
+
20
23
  type Rpc = <T>(method: string, params?: Record<string, unknown>) => Promise<T>
21
24
  type Listener = (event: string, payload: Record<string, unknown>) => void
22
25
 
26
+ // All openclaw wire frames are tapped under one scope: the gateway connection
27
+ // is process-global, not per-workspace (index.ts `wireScope` returns this).
28
+ export const OPENCLAW_WIRE_SCOPE = 'openclaw'
29
+
30
+ // Last connect outcome, for /status lines and user-facing errors — a
31
+ // protocol-3 gateway (≤ 2026.5.x) must surface "too old", never silent
32
+ // empty lists. Cleared on the next successful hello.
33
+ let lastFailure: GatewayFailure | null = null
34
+ let lastInfo: GatewayInfo | null = null
35
+
36
+ export function getOpenClawGatewayStatus(): {
37
+ connected: boolean
38
+ info: GatewayInfo | null
39
+ failure: GatewayFailure | null
40
+ } {
41
+ return { connected: current !== null, info: lastInfo, failure: lastFailure }
42
+ }
43
+
23
44
  type ClientCtor = typeof import('openclaw/plugin-sdk/gateway-runtime').GatewayClient
24
45
  type GatewayInstance = InstanceType<ClientCtor>
25
46
 
26
47
  const CONNECT_TIMEOUT_MS = 5_000
27
48
  const REQUEST_TIMEOUT_MS = 30_000
28
49
 
50
+ // Capabilities moi advertises to the gateway on connect. OpenClaw registers a
51
+ // connection as a live tool-event recipient only when it advertises the
52
+ // `tool-events` capability; the SDK sends `caps: []` by default, so without
53
+ // this the `session.tool` frames that drive our live tool cards
54
+ // (session.ts `handleToolFrame`) never reach our socket. BOTH the persistent
55
+ // streaming client and the one-shot discovery client must advertise it.
56
+ export const OPENCLAW_CLIENT_CAPS = ['tool-events'] as const
57
+
58
+ // The connect options shared by the persistent streaming client and the
59
+ // one-shot discovery client: identity (role/scopes), the advertised caps, and
60
+ // the pinned wire-protocol window. moi speaks protocol 4 (compat.ts); the SDK
61
+ // already defaults minProtocol/maxProtocol to 4, so pinning them is
62
+ // self-documenting rather than a behavior change. Each caller layers its own
63
+ // timeouts and event callbacks on top. Exported as a pure builder so the caps
64
+ // contract is unit-testable without opening a socket.
65
+ export function gatewayClientBaseOptions(
66
+ url: string,
67
+ token: string
68
+ ): Pick<
69
+ ConstructorParameters<ClientCtor>[0],
70
+ 'url' | 'token' | 'role' | 'scopes' | 'caps' | 'minProtocol' | 'maxProtocol'
71
+ > {
72
+ return {
73
+ url,
74
+ token,
75
+ role: 'operator',
76
+ scopes: ['operator.admin', 'operator.read', 'operator.write'],
77
+ caps: [...OPENCLAW_CLIENT_CAPS],
78
+ minProtocol: 4,
79
+ maxProtocol: 4
80
+ }
81
+ }
82
+
29
83
  let pending: Promise<GatewayHandle> | null = null
30
84
  let current: { handle: GatewayHandle; client: GatewayInstance } | null = null
31
85
 
32
86
  const listeners = new Set<Listener>()
33
- const sessionSubscriptions = new Set<string>() // sessionKeys we hold open
87
+ // Wire state: sessionKeys with a live `sessions.messages.subscribe` on the
88
+ // CURRENT socket. Cleared on disconnect, re-issued on reconnect. Separate from
89
+ // demand (refcounts) so a reconnect can re-subscribe without disturbing counts.
90
+ const sessionSubscriptions = new Set<string>()
91
+ // Demand: how many live session records depend on each key. Survives
92
+ // disconnects (the records are still alive), so it is the source of truth for
93
+ // what to re-subscribe on reconnect and when it is safe to unsubscribe. We
94
+ // subscribe on the wire on the 0→1 transition and unsubscribe on the 1→0 one.
95
+ const sessionSubscriptionRefcounts = new Map<string, number>()
34
96
  let topLevelSubscribed = false
35
97
 
98
+ // Refcount bookkeeping split out (and exported) so the demand logic is
99
+ // unit-testable without opening a socket; the handle methods below wrap these
100
+ // with the actual subscribe/unsubscribe wire calls.
101
+
102
+ // Record a new holder for a key. Returns true when this is the FIRST holder —
103
+ // the caller should then issue the wire `sessions.messages.subscribe`.
104
+ export function acquireSessionSubscriptionRef(sessionKey: string): boolean {
105
+ const next = (sessionSubscriptionRefcounts.get(sessionKey) ?? 0) + 1
106
+ sessionSubscriptionRefcounts.set(sessionKey, next)
107
+ return next === 1
108
+ }
109
+
110
+ // Drop a holder for a key. Returns true when that was the LAST holder — the
111
+ // caller should then `sessions.messages.unsubscribe`; the key is also dropped
112
+ // from the wire set so a reconnect won't replay it. Releasing an unheld key
113
+ // returns false (idempotent), so a double teardown is safe.
114
+ export function releaseSessionSubscriptionRef(sessionKey: string): boolean {
115
+ const cur = sessionSubscriptionRefcounts.get(sessionKey)
116
+ if (!cur) return false
117
+ if (cur > 1) {
118
+ sessionSubscriptionRefcounts.set(sessionKey, cur - 1)
119
+ return false
120
+ }
121
+ sessionSubscriptionRefcounts.delete(sessionKey)
122
+ sessionSubscriptions.delete(sessionKey)
123
+ return true
124
+ }
125
+
126
+ // Current holder count for a key (0 when none). Exported for tests.
127
+ export function sessionSubscriptionRefcount(sessionKey: string): number {
128
+ return sessionSubscriptionRefcounts.get(sessionKey) ?? 0
129
+ }
130
+
36
131
  // Side-effect hook: callers (the live session module) register a one-time
37
132
  // callback that fires after the gateway has reconnected and re-issued every
38
133
  // previously-held subscription. Used to run a transcript reconcile so any
@@ -45,7 +140,6 @@ export function onGatewayReconnected(cb: ReconnectCallback): () => void {
45
140
  }
46
141
 
47
142
  let reconnectTimer: ReturnType<typeof setTimeout> | null = null
48
- let droppedSessionKeys: string[] = []
49
143
  const RECONNECT_DELAY_MS = 1500
50
144
 
51
145
  function scheduleReconnect() {
@@ -55,11 +149,12 @@ function scheduleReconnect() {
55
149
  if (current) return // someone else already reconnected via getGateway()
56
150
  try {
57
151
  const gw = await getGateway()
58
- // Replay any keys that were held before the drop.
59
- const keys = droppedSessionKeys
60
- droppedSessionKeys = []
61
- for (const key of keys) {
62
- await gw.ensureSessionSubscribed(key).catch(() => {})
152
+ // Re-subscribe every key that still has a live holder (demand survived
153
+ // the disconnect; the wire set was cleared). Wire-only re-issue — leaves
154
+ // the refcounts untouched, and a key released during the disconnect
155
+ // (refcount 0) is simply not replayed.
156
+ for (const key of sessionSubscriptionRefcounts.keys()) {
157
+ await gw.resubscribeSessionKey(key).catch(() => {})
63
158
  }
64
159
  // Notify session-level holders so they can run a transcript reconcile.
65
160
  for (const cb of reconnectCallbacks) {
@@ -71,7 +166,6 @@ function scheduleReconnect() {
71
166
  }
72
167
  } catch {
73
168
  // Connect still failing — schedule another attempt.
74
- droppedSessionKeys = droppedSessionKeys.length ? droppedSessionKeys : []
75
169
  scheduleReconnect()
76
170
  }
77
171
  }, RECONNECT_DELAY_MS)
@@ -79,15 +173,46 @@ function scheduleReconnect() {
79
173
 
80
174
  export type GatewayHandle = {
81
175
  rpc: Rpc
176
+ // hello-ok metadata of the live connection (protocol, server version,
177
+ // advertised methods/events); null before the first successful hello.
178
+ info: () => GatewayInfo | null
82
179
  on: (l: Listener) => () => void
180
+ // Acquire a live-holder reference on a session key: subscribes on the wire on
181
+ // the first holder (refcount 0→1), then increments. Idempotent per holder.
83
182
  ensureSessionSubscribed: (sessionKey: string) => Promise<void>
183
+ // Release a live-holder reference: decrements; on the last holder (1→0) it
184
+ // best-effort `sessions.messages.unsubscribe`s and drops the key from the
185
+ // wire set so a reconnect won't replay it. Never unsubscribes while other
186
+ // holders remain.
187
+ releaseSessionSubscription: (sessionKey: string) => Promise<void>
188
+ // Wire-only re-subscribe, used by the reconnect replay to re-issue a key
189
+ // whose demand outlived the dropped socket. Does not touch refcounts.
190
+ resubscribeSessionKey: (sessionKey: string) => Promise<void>
84
191
  ensureTopLevelSubscribed: () => Promise<void>
85
192
  isConnected: () => boolean
86
193
  }
87
194
 
88
- async function readGatewayConfig(): Promise<{ port: number; token: string } | null> {
195
+ // The live handle if the gateway is currently connected, else null. Non-
196
+ // connecting (unlike getGateway) so callers on a teardown path — session idle
197
+ // eviction, shutdown, tests without a gateway — can release a subscription
198
+ // without forcing a connect or awaiting a reconnect.
199
+ export function currentGatewayHandle(): GatewayHandle | null {
200
+ return current?.handle ?? null
201
+ }
202
+
203
+ // Config resolution mirrors the OpenClaw CLI: explicit OPENCLAW_CONFIG_PATH
204
+ // wins, then OPENCLAW_STATE_DIR (profile runs), then the default state root.
205
+ export function openClawConfigPath(): string {
206
+ const explicit = process.env.OPENCLAW_CONFIG_PATH
207
+ if (explicit) return explicit
208
+ const stateDir = process.env.OPENCLAW_STATE_DIR
209
+ if (stateDir) return join(stateDir, 'openclaw.json')
210
+ return join(homedir(), '.openclaw/openclaw.json')
211
+ }
212
+
213
+ export async function readGatewayConfig(): Promise<{ port: number; token: string } | null> {
89
214
  try {
90
- const raw = await readFile(join(homedir(), '.openclaw/openclaw.json'), 'utf8')
215
+ const raw = await readFile(openClawConfigPath(), 'utf8')
91
216
  const cfg = JSON.parse(raw) as {
92
217
  gateway?: { port?: number; auth?: { token?: string } }
93
218
  }
@@ -113,7 +238,16 @@ function fanout(event: string, payload: Record<string, unknown>) {
113
238
  async function startClient(): Promise<{ handle: GatewayHandle; client: GatewayInstance }> {
114
239
  const cfg = await readGatewayConfig()
115
240
  if (!cfg) throw new Error('openclaw config missing or invalid')
116
- const { GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime')
241
+ let GatewayClient: typeof import('openclaw/plugin-sdk/gateway-runtime').GatewayClient
242
+ try {
243
+ ;({ GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime'))
244
+ } catch {
245
+ // Optional dependency absent — callers surface the rejection as a chat
246
+ // error; keep the category visible in /status.
247
+ const err = new Error('openclaw package is not installed')
248
+ lastFailure = { kind: 'unreachable', message: err.message }
249
+ throw err
250
+ }
117
251
 
118
252
  let connected = false
119
253
  // The SDK's `opts` is private since 2026.7.x — connect callbacks must be
@@ -123,22 +257,23 @@ async function startClient(): Promise<{ handle: GatewayHandle; client: GatewayIn
123
257
  settleConnect = { res, rej }
124
258
  })
125
259
  const client = new GatewayClient({
126
- url: `ws://127.0.0.1:${cfg.port}`,
127
- token: cfg.token,
128
- role: 'operator',
129
- scopes: ['operator.admin', 'operator.read', 'operator.write'],
260
+ ...gatewayClientBaseOptions(`ws://127.0.0.1:${cfg.port}`, cfg.token),
130
261
  requestTimeoutMs: REQUEST_TIMEOUT_MS,
131
- onHelloOk: () => {
262
+ onHelloOk: (hello: unknown) => {
132
263
  connected = true
264
+ lastInfo = parseHelloOk(hello)
265
+ lastFailure = null
133
266
  settleConnect.res()
134
267
  },
135
268
  onConnectError: err => {
269
+ lastFailure = classifyGatewayError(err)
136
270
  settleConnect.rej(err)
137
271
  },
138
272
  onEvent: evt => {
139
273
  const event = (evt as unknown as { event?: unknown }).event
140
274
  const payload = (evt as unknown as { payload?: unknown }).payload
141
275
  if (typeof event !== 'string') return
276
+ tapWire(OPENCLAW_WIRE_SCOPE, 'recv', evt)
142
277
  fanout(
143
278
  event,
144
279
  (payload && typeof payload === 'object' ? payload : {}) as Record<string, unknown>
@@ -148,21 +283,21 @@ async function startClient(): Promise<{ handle: GatewayHandle; client: GatewayIn
148
283
  connected = false
149
284
  current = null
150
285
  pending = null
151
- // Mark every held subscription as needing re-issue after the next
152
- // connect. The Set entries themselves stay so we know what to re-issue.
286
+ // The socket is gone: clear the wire state (top-level + per-session
287
+ // subscriptions). Demand (refcounts) is untouched — the reconnect replay
288
+ // re-subscribes every key that still has a live holder.
153
289
  topLevelSubscribed = false
154
- const dropped = [...sessionSubscriptions]
155
290
  sessionSubscriptions.clear()
156
- droppedSessionKeys = dropped
157
291
  scheduleReconnect()
158
292
  }
159
293
  })
160
294
 
161
295
  await new Promise<void>((res, rej) => {
162
- const t = setTimeout(
163
- () => rej(new Error(`openclaw connect timeout after ${CONNECT_TIMEOUT_MS}ms`)),
164
- CONNECT_TIMEOUT_MS
165
- )
296
+ const t = setTimeout(() => {
297
+ const err = new Error(`openclaw connect timeout after ${CONNECT_TIMEOUT_MS}ms`)
298
+ lastFailure = classifyGatewayError(err)
299
+ rej(err)
300
+ }, CONNECT_TIMEOUT_MS)
166
301
  connectPromise.then(
167
302
  () => {
168
303
  clearTimeout(t)
@@ -176,24 +311,63 @@ async function startClient(): Promise<{ handle: GatewayHandle; client: GatewayIn
176
311
  client.start()
177
312
  })
178
313
 
179
- const rpc: Rpc = (method, params = {}) => client.request(method, params) as Promise<never>
314
+ const rpc: Rpc = (method, params = {}) => {
315
+ tapWire(OPENCLAW_WIRE_SCOPE, 'send', { method, params })
316
+ const p = client.request(method, params) as Promise<never>
317
+ p.then(
318
+ result => tapWire(OPENCLAW_WIRE_SCOPE, 'recv', { method, result }),
319
+ (err: unknown) =>
320
+ tapWire(OPENCLAW_WIRE_SCOPE, 'recv', {
321
+ method,
322
+ error: err instanceof Error ? err.message : String(err)
323
+ })
324
+ )
325
+ return p
326
+ }
327
+
328
+ // Issue the `sessions.messages.subscribe` RPC once per socket for a key,
329
+ // tracked by the wire set. Shared by the first-holder path and the reconnect
330
+ // replay; touches no refcounts.
331
+ async function subscribeWire(sessionKey: string): Promise<void> {
332
+ if (sessionSubscriptions.has(sessionKey)) return
333
+ sessionSubscriptions.add(sessionKey)
334
+ try {
335
+ await rpc('sessions.messages.subscribe', { key: sessionKey })
336
+ } catch (err) {
337
+ sessionSubscriptions.delete(sessionKey)
338
+ throw err
339
+ }
340
+ }
180
341
 
181
342
  const handle: GatewayHandle = {
182
343
  rpc,
344
+ info: () => lastInfo,
183
345
  on(l) {
184
346
  listeners.add(l)
185
347
  return () => listeners.delete(l)
186
348
  },
187
349
  async ensureSessionSubscribed(sessionKey: string) {
188
- if (sessionSubscriptions.has(sessionKey)) return
189
- sessionSubscriptions.add(sessionKey)
350
+ if (!acquireSessionSubscriptionRef(sessionKey)) return // a holder has it
190
351
  try {
191
- await rpc('sessions.messages.subscribe', { key: sessionKey })
352
+ await subscribeWire(sessionKey)
192
353
  } catch (err) {
193
- sessionSubscriptions.delete(sessionKey)
354
+ releaseSessionSubscriptionRef(sessionKey) // roll back the demand bump
194
355
  throw err
195
356
  }
196
357
  },
358
+ async releaseSessionSubscription(sessionKey: string) {
359
+ if (!releaseSessionSubscriptionRef(sessionKey)) return // holders remain
360
+ try {
361
+ await rpc('sessions.messages.unsubscribe', { key: sessionKey })
362
+ } catch (err) {
363
+ // Best-effort — the run may already be gone, or the socket dropping is
364
+ // itself an unsubscribe. Log and move on; never throw from teardown.
365
+ console.error('[openclaw-gateway] unsubscribe failed', sessionKey, err)
366
+ }
367
+ },
368
+ resubscribeSessionKey(sessionKey: string) {
369
+ return subscribeWire(sessionKey)
370
+ },
197
371
  async ensureTopLevelSubscribed() {
198
372
  if (topLevelSubscribed) return
199
373
  topLevelSubscribed = true
@@ -239,19 +413,33 @@ export async function getGateway(): Promise<GatewayHandle> {
239
413
  export async function withOneShotGateway<T>(fn: (rpc: Rpc) => Promise<T>): Promise<T | null> {
240
414
  const cfg = await readGatewayConfig()
241
415
  if (!cfg) return null
242
- const { GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime')
416
+ // `openclaw` is an optionalDependency — a missing package must degrade to
417
+ // the silent-null path (no agents discovered), never a rejected promise.
418
+ let GatewayClient: typeof import('openclaw/plugin-sdk/gateway-runtime').GatewayClient
419
+ try {
420
+ ;({ GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime'))
421
+ } catch {
422
+ return null
423
+ }
243
424
  let settleConnect!: { res: () => void; rej: (err: Error) => void }
244
425
  const connectPromise = new Promise<void>((res, rej) => {
245
426
  settleConnect = { res, rej }
246
427
  })
247
428
  const client = new GatewayClient({
248
- url: `ws://127.0.0.1:${cfg.port}`,
249
- token: cfg.token,
250
- role: 'operator',
251
- scopes: ['operator.admin', 'operator.read', 'operator.write'],
429
+ ...gatewayClientBaseOptions(`ws://127.0.0.1:${cfg.port}`, cfg.token),
252
430
  requestTimeoutMs: 2000,
253
- onHelloOk: () => settleConnect.res(),
254
- onConnectError: err => settleConnect.rej(err)
431
+ onHelloOk: (hello: unknown) => {
432
+ lastInfo = parseHelloOk(hello)
433
+ lastFailure = null
434
+ settleConnect.res()
435
+ },
436
+ onConnectError: err => {
437
+ // One-shot callers stay silent by design, but the failure category must
438
+ // still reach /status — a too-old gateway looks like "no agents"
439
+ // otherwise.
440
+ lastFailure = classifyGatewayError(err)
441
+ settleConnect.rej(err)
442
+ }
255
443
  })
256
444
  try {
257
445
  await new Promise<void>((res, rej) => {
@@ -1,30 +1,36 @@
1
1
  // OpenClaw as a Harness. Thin wiring over this folder's modules — see
2
2
  // ../types.ts for the contract and ../README.md for the architecture.
3
3
  import type { DiscoveredWorkspaceCandidate, Harness } from '../types'
4
+ import { OPENCLAW_WIRE_SCOPE, getOpenClawGatewayStatus } from './gateway'
4
5
  import { toSessionInfo, toStreamEvents } from './adapter'
6
+ import { cronRunsToStreamEvents, openClawCronJobIdFromKey } from './cron-view'
5
7
  import {
8
+ archiveOpenClawSession,
6
9
  discoverOpenClawAgents,
10
+ getOpenClawCronRuns,
7
11
  getOpenClawModels,
8
12
  getOpenClawSessionMessages,
9
13
  getOpenClawSessions,
10
- getOpenClawWorkspacePreview
14
+ getOpenClawWorkspacePreview,
15
+ resolveOpenClawSessionKey
11
16
  } from './discovery'
12
17
  import {
13
18
  abortOpenClawRun,
14
19
  ensureOpenClawSessionLive,
15
20
  getLiveOpenClawEvents,
16
21
  getOpenClawActiveSessions,
22
+ killAllOpenClawSessions,
17
23
  sendOpenClawMessage
18
24
  } from './session'
19
25
 
20
26
  export const openclawHarness: Harness = {
21
27
  id: 'openclaw',
22
28
  capabilities: {
23
- supportsStreaming: false, // durable message rows only — deliberate v2 cut
29
+ supportsStreaming: true, // `chat` delta frames → StreamPreview
24
30
  imagesInline: 'path-note',
25
- liveModelSwitch: false,
26
- liveEffortSwitch: false,
27
- nativeUserEcho: true // gateway echoes sends (lagged); matched by text
31
+ liveModelSwitch: true, // sessions.patch { model } before each send
32
+ liveEffortSwitch: true, // sessions.patch { thinkingLevel }
33
+ nativeUserEcho: true // echo matched by `<runId>:user` idempotency key, text fallback
28
34
  },
29
35
 
30
36
  sendMessage: async input => {
@@ -34,6 +40,11 @@ export const openclawHarness: Harness = {
34
40
  return sendOpenClawMessage({ ...input, agentId: input.agentId })
35
41
  },
36
42
  interrupt: (workspaceId, sessionId) => abortOpenClawRun({ workspaceId, sessionId }),
43
+ // `sessions.patch { archived: true }`. 2026.6.x gateways reject the field
44
+ // (their patch schema predates it and validates with
45
+ // `additionalProperties: false`) — the RPC error propagates and the API
46
+ // layer reports the archive as failed.
47
+ archiveSession: (ws, sessionId) => archiveOpenClawSession(sessionId, ws.path, ws.agentId),
37
48
  activeSessions: () => getOpenClawActiveSessions(),
38
49
 
39
50
  listSessions: async ws => {
@@ -45,24 +56,34 @@ export const openclawHarness: Harness = {
45
56
  // Prefer the live view if we already hold one — keeps REST + WS in
46
57
  // agreement for any reload that lands while a run is active. The first cold
47
58
  // call also primes the live subscription so subsequent WS frames upsert
48
- // into the same view; the static transcript is the last resort.
59
+ // into the same view; the static transcript is the last resort. A session
60
+ // that still comes back empty may be an isolated cron bucket — its per-run
61
+ // transcripts are orphaned by the gateway's post-run session reset (see
62
+ // cron-view.ts), so fall back to synthesizing turns from `cron.runs`.
49
63
  sessionEvents: async (ws, sessionId) => {
50
- const live = getLiveOpenClawEvents(ws.id, sessionId)
51
- if (live) return live
52
- if (ws.agentId) {
53
- try {
54
- return await ensureOpenClawSessionLive({
55
- workspaceId: ws.id,
56
- workspacePath: ws.path,
57
- agentId: ws.agentId,
58
- sessionId
59
- })
60
- } catch {
61
- // fall through to static path
64
+ const events = await (async () => {
65
+ const live = getLiveOpenClawEvents(ws.id, sessionId)
66
+ if (live) return live
67
+ if (ws.agentId) {
68
+ try {
69
+ return await ensureOpenClawSessionLive({
70
+ workspaceId: ws.id,
71
+ workspacePath: ws.path,
72
+ agentId: ws.agentId,
73
+ sessionId
74
+ })
75
+ } catch {
76
+ // fall through to static path
77
+ }
62
78
  }
63
- }
64
- const preview = await getOpenClawSessionMessages(sessionId, ws.path, ws.agentId)
65
- return toStreamEvents(preview)
79
+ const preview = await getOpenClawSessionMessages(sessionId, ws.path, ws.agentId)
80
+ return toStreamEvents(preview)
81
+ })()
82
+ if (events.length > 0) return events
83
+ const key = await resolveOpenClawSessionKey(sessionId, ws.path, ws.agentId)
84
+ const jobId = key ? openClawCronJobIdFromKey(key) : null
85
+ if (!jobId) return events
86
+ return cronRunsToStreamEvents(await getOpenClawCronRuns(jobId))
66
87
  },
67
88
  listModels: () => getOpenClawModels(),
68
89
 
@@ -78,11 +99,25 @@ export const openclawHarness: Harness = {
78
99
  )
79
100
  },
80
101
 
102
+ // Server shutdown: tear down every live session (unsubscribe + stop ingest).
103
+ // The shared gateway client is left running — process exit drops it. Invoked
104
+ // from web.ts's SIGTERM/SIGINT handler via allHarnesses().shutdown().
105
+ shutdown: () => killAllOpenClawSessions(),
81
106
  skillsDir: workspaceRoot => `${workspaceRoot}/skills`,
82
107
 
108
+ // One process-global gateway connection → one shared wire-tap scope.
109
+ wireScope: () => OPENCLAW_WIRE_SCOPE,
110
+
83
111
  statusLines: () => {
84
112
  const active = getOpenClawActiveSessions()
113
+ const status = getOpenClawGatewayStatus()
114
+ const gateway = status.connected
115
+ ? `gateway connected · protocol ${status.info?.protocol ?? '?'} · server ${status.info?.serverVersion ?? '?'}`
116
+ : status.failure
117
+ ? `gateway ${status.failure.kind}: ${status.failure.message}`
118
+ : 'gateway not connected yet'
85
119
  return [
120
+ gateway,
86
121
  `live OpenClaw runs ${active.length}`,
87
122
  ...active.map(r => ` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
88
123
  ]