moi-computer 0.8.0 → 0.9.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 (110) 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/MarkdownContent.tsx +1 -1
  19. package/client/features/chat/ModelPicker.tsx +5 -4
  20. package/client/features/chat/TurnView.tsx +108 -13
  21. package/client/features/chat/api.ts +1 -18
  22. package/client/features/chat/chat-send.ts +2 -2
  23. package/client/features/chat/{ChatComposer.tsx → composer/ChatComposer.tsx} +6 -5
  24. package/client/features/chat/composer/banners/ChatErrorBanner.tsx +28 -0
  25. package/client/features/chat/composer/banners/ComposerBanner.tsx +30 -0
  26. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +91 -0
  27. package/client/features/{workspace → chat/composer/banners}/WorkspaceSkillUpdateBanner.tsx +9 -7
  28. package/client/features/chat/composer/useWorkspaceComposerState.tsx +74 -0
  29. package/client/features/{workspace → chat/composer}/useWorkspaceSkillUpdates.ts +1 -1
  30. package/client/features/chat/group-turns.ts +46 -28
  31. package/client/features/chat/interleave-notices.ts +84 -0
  32. package/client/features/chat/model-order.ts +9 -3
  33. package/client/features/chat/tool-group/TimelineRow.tsx +23 -11
  34. package/client/features/chat/tool-group/ToolCallGroup.tsx +38 -3
  35. package/client/features/chat/tool-group/format.ts +51 -10
  36. package/client/features/chat/useAppletChatMessage.ts +11 -16
  37. package/client/features/chat/useChat.ts +3 -7
  38. package/client/features/dev/ChatStatesPage.tsx +466 -0
  39. package/client/features/dev/DevIndexPage.tsx +52 -0
  40. package/client/features/dev/DevRoutes.tsx +6 -3
  41. package/client/features/dev/HarnessDebugPage.tsx +3 -3
  42. package/client/features/dev/chat-states-fixtures.ts +744 -0
  43. package/client/features/scratchpad/Scratchpad.tsx +4 -0
  44. package/client/features/scratchpad/scratch-session.ts +71 -0
  45. package/client/features/views/ViewBuilderTab.tsx +5 -4
  46. package/client/features/views/useViewBuilderActions.ts +2 -2
  47. package/client/features/workspace/WorkspaceLayoutContext.tsx +4 -2
  48. package/client/features/workspace/WorkspaceScreen.tsx +128 -146
  49. package/client/features/workspace/WorkspaceSplitLayout.tsx +111 -0
  50. package/client/features/workspace/api.ts +33 -8
  51. package/client/features/workspace/useFitsSplitLayout.ts +31 -5
  52. package/client/index.css +1 -1
  53. package/client/lib/flags.ts +4 -3
  54. package/client/runtime/useWorkspaceEvents.ts +18 -1
  55. package/client/store/ui.ts +5 -1
  56. package/dist/{chunk-0pcdwjkp.js → chunk-2vaafjp4.js} +1 -1
  57. package/dist/{chunk-9y2zbzqz.js → chunk-35fq49qa.js} +1 -1
  58. package/dist/{chunk-h9h8f176.js → chunk-3b3rkjet.js} +1 -1
  59. package/dist/chunk-gt7n06ef.js +1 -0
  60. package/dist/{chunk-r5ce5cdg.js → chunk-kkj86722.js} +75 -75
  61. package/dist/chunk-ty1sqbmn.js +80 -0
  62. package/dist/chunk-xeyxk7ep.js +10 -0
  63. package/dist/chunk-yz6wd5vc.css +1 -0
  64. package/dist/index.html +1 -1
  65. package/lib/format.ts +37 -7
  66. package/lib/themes.ts +2 -2
  67. package/lib/types.ts +38 -8
  68. package/lib/workspace-layout.ts +2 -2
  69. package/package.json +6 -4
  70. package/server/agent.ts +199 -0
  71. package/server/api.ts +36 -17
  72. package/server/bundler/build-applet.ts +35 -44
  73. package/server/cli-env.ts +2 -2
  74. package/server/cli.ts +39 -53
  75. package/server/constants.ts +8 -0
  76. package/server/control-client.ts +124 -0
  77. package/server/control.ts +2 -2
  78. package/server/env-apply.ts +4 -0
  79. package/server/harness/README.md +32 -12
  80. package/server/harness/claude-code/auth.ts +54 -0
  81. package/server/harness/claude-code/index.ts +6 -1
  82. package/server/harness/codex/adapter.ts +9 -1
  83. package/server/harness/codex/auth.ts +50 -0
  84. package/server/harness/codex/index.ts +6 -1
  85. package/server/harness/codex/session.ts +33 -14
  86. package/server/harness/openclaw/NOTES.md +619 -186
  87. package/server/harness/openclaw/adapter.ts +121 -54
  88. package/server/harness/openclaw/compat.ts +95 -0
  89. package/server/harness/openclaw/cron-view.ts +78 -0
  90. package/server/harness/openclaw/discovery.ts +145 -52
  91. package/server/harness/openclaw/gateway.ts +224 -36
  92. package/server/harness/openclaw/index.ts +56 -21
  93. package/server/harness/openclaw/session.ts +1002 -67
  94. package/server/harness/openclaw/strip.ts +71 -23
  95. package/server/harness/openclaw/thinking.ts +150 -0
  96. package/server/harness/types.ts +10 -5
  97. package/server/layout.ts +5 -2
  98. package/server/service.ts +2 -2
  99. package/workspace/.claude/skills/moi-workspace/SKILL.md +6 -6
  100. package/workspace/.claude/skills/moi-workspace/{DESIGN.md → references/DESIGN.md} +19 -9
  101. package/client/features/dev/PixelPainter.tsx +0 -94
  102. package/client/features/dev/PlaygroundPage.tsx +0 -69
  103. package/dist/chunk-0k7brsms.js +0 -9
  104. package/dist/chunk-dfs36zgc.js +0 -1
  105. package/dist/chunk-dtwxpxbg.js +0 -51
  106. package/dist/chunk-ga7t9qsk.js +0 -2
  107. package/dist/chunk-tey2nq7c.js +0 -31
  108. package/dist/chunk-z73xpsa0.js +0 -50
  109. package/dist/chunk-zzgredta.css +0 -1
  110. /package/workspace/.claude/skills/moi-workspace/{SCRATCHPAD.md → references/SCRATCHPAD.md} +0 -0
@@ -1,12 +1,17 @@
1
- import { readFile } from 'node:fs/promises'
2
- import { homedir } from 'node:os'
3
- import { join, resolve } from 'node:path'
1
+ import { resolve } from 'node:path'
4
2
 
5
3
  import type { Model } from '@/lib/types'
6
4
 
7
- import { getGateway } from './gateway'
5
+ import type { OpenClawCronRunEntry } from './cron-view'
6
+ import { getGateway, withOneShotGateway } from './gateway'
8
7
  import type { GatewayHandle } from './gateway'
9
8
  import { stripUserMessageMetadata } from './strip'
9
+ import {
10
+ OPENCLAW_FALLBACK_THINKING_LEVELS,
11
+ hasOpenClawThinkingProfiles,
12
+ openClawThinkingProfile,
13
+ recordOpenClawThinkingProfiles
14
+ } from './thinking'
10
15
 
11
16
  export type OpenClawAgent = {
12
17
  path: string
@@ -16,6 +21,20 @@ export type OpenClawAgent = {
16
21
  lastRunAt?: string
17
22
  }
18
23
 
24
+ // Channel-routing metadata on a session row. Deliberately loose: the gateway
25
+ // ships more fields than these (chatType, accountId, …) and the exact set
26
+ // varies by channel plugin — we read only what we surface. `provider` is the
27
+ // channel id ('telegram', 'irc', 'discord', …); moi's own chats come back as
28
+ // 'webchat'.
29
+ export type OpenClawSessionOrigin = {
30
+ provider?: string
31
+ surface?: string
32
+ label?: string
33
+ from?: string
34
+ to?: string
35
+ [k: string]: unknown
36
+ }
37
+
19
38
  // Subset of the session row returned by `sessions.list`. The gateway ships
20
39
  // more fields, but these are the ones we map to our SessionInfo/StreamEvent.
21
40
  export type OpenClawSessionRow = {
@@ -29,6 +48,15 @@ export type OpenClawSessionRow = {
29
48
  model?: string
30
49
  modelProvider?: string
31
50
  status?: string
51
+ origin?: OpenClawSessionOrigin
52
+ kind?: string
53
+ // Parent session key for gateway-spawned subagent sessions.
54
+ spawnedBy?: string
55
+ // The thinking menu the gateway resolved for this row's model. Per-model, not
56
+ // global — harvested into `thinking.ts` so the picker offers a valid set.
57
+ thinkingOptions?: string[]
58
+ thinkingLevels?: { id: string; label?: string }[]
59
+ thinkingDefault?: string
32
60
  }
33
61
 
34
62
  // Shape returned by `sessions.get({ key })` — the full transcript, unlike
@@ -97,53 +125,10 @@ function parseIdentityName(md: string | undefined): string | undefined {
97
125
  type Rpc = <T>(method: string, params?: Record<string, unknown>) => Promise<T>
98
126
 
99
127
  // Connect, hand the scoped `rpc(method, params)` to `fn`, then stop the client.
100
- // Any connect/auth/timeout failure → returns `null` silently (caller's choice).
128
+ // Any connect/auth/timeout failure → returns `null` silently (caller's choice);
129
+ // the failure category still lands in gateway.ts's status for /status lines.
101
130
  async function withGatewayClient<T>(fn: (rpc: Rpc) => Promise<T>): Promise<T | null> {
102
- let cfg: { gateway?: { port?: number; auth?: { token?: string } } }
103
- try {
104
- const raw = await readFile(join(homedir(), '.openclaw/openclaw.json'), 'utf8')
105
- cfg = JSON.parse(raw)
106
- } catch {
107
- return null
108
- }
109
- const port = cfg.gateway?.port
110
- const token = cfg.gateway?.auth?.token
111
- if (!port || !token) return null
112
-
113
- let GatewayClient: typeof import('openclaw/plugin-sdk/gateway-runtime').GatewayClient
114
- try {
115
- ;({ GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime'))
116
- } catch {
117
- return null
118
- }
119
-
120
- // The SDK's `opts` is private since 2026.7.x — connect callbacks must be
121
- // handed to the constructor, so wire them to a deferred promise up front.
122
- let settleConnect!: { res: () => void; rej: (err: Error) => void }
123
- const connect = new Promise<void>((res, rej) => {
124
- settleConnect = { res, rej }
125
- })
126
- const client = new GatewayClient({
127
- url: `ws://127.0.0.1:${port}`,
128
- token,
129
- role: 'operator',
130
- scopes: ['operator.admin', 'operator.read', 'operator.write'],
131
- requestTimeoutMs: TIMEOUT_MS,
132
- onHelloOk: () => settleConnect.res(),
133
- onConnectError: err => settleConnect.rej(err)
134
- })
135
-
136
- try {
137
- client.start()
138
- await withTimeout(connect, TIMEOUT_MS, 'connect')
139
- const rpc: Rpc = (method, params = {}) =>
140
- withTimeout(client.request(method, params), TIMEOUT_MS, method)
141
- return await fn(rpc)
142
- } catch {
143
- return null
144
- } finally {
145
- client.stop()
146
- }
131
+ return withOneShotGateway(fn)
147
132
  }
148
133
 
149
134
  export async function discoverOpenClawAgents(): Promise<OpenClawAgent[]> {
@@ -200,6 +185,8 @@ export async function getOpenClawSessions(
200
185
  includeDerivedTitles: true,
201
186
  includeLastMessage: true
202
187
  })
188
+ // Rows are the only carrier of each model's thinking menu (thinking.ts).
189
+ recordOpenClawThinkingProfiles(res.sessions)
203
190
  return res.sessions
204
191
  })
205
192
  return out ?? []
@@ -227,6 +214,77 @@ export async function getOpenClawSessionMessages(
227
214
  return out ?? null
228
215
  }
229
216
 
217
+ // sessionId → gateway session key, or null when the gateway is down or the
218
+ // session is unknown. Used to recognize cron bucket keys (`…:cron:<jobId>`)
219
+ // when the transcript comes back empty.
220
+ export async function resolveOpenClawSessionKey(
221
+ sessionId: string,
222
+ workspacePath: string,
223
+ agentId?: string
224
+ ): Promise<string | null> {
225
+ const out = await withGatewayClient(async rpc => {
226
+ const id = agentId ?? (await resolveAgentIdForPath(rpc, workspacePath))
227
+ if (!id) return null
228
+ const resolved = await rpc<{ key?: string }>('sessions.resolve', {
229
+ sessionId,
230
+ agentId: id
231
+ }).catch(() => null)
232
+ return resolved?.key ?? null
233
+ })
234
+ return out ?? null
235
+ }
236
+
237
+ // Recorded run history for one cron job (`cron.runs`, identical params and
238
+ // page shape on both supported lines — verified live on 2026.7.1 and
239
+ // 2026.6.33). Default sort is newest-first, so a limit keeps the most recent
240
+ // runs; cron-view.ts re-sorts ascending for display.
241
+ export async function getOpenClawCronRuns(
242
+ jobId: string,
243
+ limit = 50
244
+ ): Promise<OpenClawCronRunEntry[]> {
245
+ const out = await withGatewayClient(async rpc => {
246
+ const res = await rpc<{ entries?: OpenClawCronRunEntry[] }>('cron.runs', { jobId, limit })
247
+ return res.entries ?? []
248
+ })
249
+ return out ?? []
250
+ }
251
+
252
+ // Archive a session: resolve to its key, then `sessions.patch
253
+ // { archived: true }`. Rides the persistent gateway handle so failures THROW
254
+ // (unlike the silent one-shot helpers) — the API layer maps them to a failed
255
+ // archive. Version note: `archived` exists on SessionsPatchParamsSchema only
256
+ // on 2026.7.x; 2026.6.x validates patch params with `additionalProperties:
257
+ // false` and rejects the field, so archiving against a 6.x gateway fails
258
+ // loudly instead of silently doing nothing.
259
+ export async function archiveOpenClawSession(
260
+ sessionId: string,
261
+ workspacePath: string,
262
+ agentId?: string
263
+ ): Promise<void> {
264
+ const gateway = await getGateway()
265
+ const rpc: Rpc = (method, params = {}) =>
266
+ withTimeout(gateway.rpc(method, params), TIMEOUT_MS, method)
267
+ const id = agentId ?? (await resolveAgentIdForPath(rpc, workspacePath))
268
+ if (!id) throw new Error('openclaw agent not found for workspace')
269
+ const resolved = await rpc<{ key?: string }>('sessions.resolve', { sessionId, agentId: id })
270
+ if (!resolved?.key) throw new Error(`openclaw session not found: ${sessionId}`)
271
+ try {
272
+ await rpc('sessions.patch', { key: resolved.key, archived: true })
273
+ } catch (err) {
274
+ const raw = err instanceof Error ? err.message : String(err)
275
+ // 2026.6.x has no `archived` patch field (additionalProperties: false →
276
+ // "unexpected property"); the gateway also refuses archiving the agent's
277
+ // main session on every line. Translate both to actionable messages.
278
+ if (raw.includes("unexpected property 'archived'")) {
279
+ throw new Error('Archiving chats needs OpenClaw 2026.7 or newer')
280
+ }
281
+ if (raw.toLowerCase().includes('main session')) {
282
+ throw new Error("The agent's main chat can't be archived")
283
+ }
284
+ throw err
285
+ }
286
+ }
287
+
230
288
  function firstUserMessageText(detail: OpenClawSessionDetail | null): string | undefined {
231
289
  const message = detail?.messages.find(candidate => candidate.role === 'user')
232
290
  if (!message) return undefined
@@ -356,8 +414,43 @@ type OpenClawModelChoice = {
356
414
  export async function getOpenClawModels(): Promise<Model[]> {
357
415
  const out = await withGatewayClient(async rpc => {
358
416
  const res = await rpc<{ models: OpenClawModelChoice[] }>('models.list')
417
+ // `models.list` reports only `reasoning: boolean` — never the level menu,
418
+ // and no RPC exposes it. Session rows do, so prime the profile map from
419
+ // one aggregate list when it's still cold (first picker open on a fresh
420
+ // server). Later calls read the map discovery/live ingest keep warm.
421
+ if (!hasOpenClawThinkingProfiles()) {
422
+ const sessions = await rpc<{ sessions: OpenClawSessionRow[] }>('sessions.list', {
423
+ includeGlobal: true
424
+ }).catch(() => null)
425
+ if (sessions) recordOpenClawThinkingProfiles(sessions.sessions)
426
+ }
359
427
  return res.models
360
428
  })
361
- // Map the gateway catalog onto the raw Model shape (value/displayName).
362
- return (out ?? []).map(m => ({ value: m.id, displayName: m.name }))
429
+ // Map the gateway catalog onto the Model shape. The picker value is the
430
+ // full `provider/id` ref — the exact form `sessions.patch {model}` accepts
431
+ // and the form session rows report back (`modelProvider`/`model`), so both
432
+ // the applied-model cache comparison and the thinking-profile lookup hold.
433
+ return (out ?? []).map(m => {
434
+ const value = m.provider && !m.id.includes('/') ? `${m.provider}/${m.id}` : m.id
435
+ const model: Model = { value, displayName: m.name }
436
+ // Per-model menu (thinking.ts). A learned menu with a real choice in it is
437
+ // itself proof the model reasons, and it outranks the catalog flag: on
438
+ // 2026.7.2-beta.7 `models.list` stopped setting `reasoning` for the OpenAI
439
+ // models (verified live) while their session rows still advertise the full
440
+ // `off…ultra` menu, so trusting the flag alone silently drops the effort
441
+ // picker for every GPT model.
442
+ const profile = openClawThinkingProfile(value)
443
+ if (!m.reasoning && !(profile && profile.levels.length > 1)) return model
444
+ // Falling back to the cross-provider intersection offers fewer levels than
445
+ // the model has rather than levels it would reject — a rejection silently
446
+ // drops the user's pick.
447
+ model.supportsEffort = true
448
+ model.supportedEffortLevels = profile
449
+ ? [...profile.levels]
450
+ : [...OPENCLAW_FALLBACK_THINKING_LEVELS]
451
+ if (profile?.default && profile.levels.includes(profile.default)) {
452
+ model.defaultEffort = profile.default
453
+ }
454
+ return model
455
+ })
363
456
  }
@@ -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) => {