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
@@ -27,43 +27,91 @@ import type {
27
27
  } from './discovery'
28
28
  import { formatChatTitle } from '@/lib/chat-title'
29
29
  import { stripMoiContextLoose } from '@/lib/moi-context'
30
- import { stripUserMessageMetadata } from './strip'
30
+ import { stripSubagentEnvelope, stripUserMessageMetadata } from './strip'
31
+
32
+ // moi appends the `<moi-context>` envelope to the user's message text because
33
+ // `sessions.send` has no separate system channel — so the gateway derives
34
+ // `displayName`/`derivedTitle`/`lastMessagePreview` from a message that
35
+ // carries the envelope. Strip it (loose: truncation can cut it open) from
36
+ // every title source, not just the preview, so no title shows the envelope.
37
+ // A no-op on channel/cron labels that never contain it.
38
+ function cleanTitle(text: string | undefined): string {
39
+ return stripSubagentEnvelope(stripMoiContextLoose(text?.trim() ?? '')).trim()
40
+ }
31
41
 
32
42
  export function toSessionInfo(row: OpenClawSessionRow, cwd: string): SessionInfo {
33
- // Gateway previews carry the raw stored message — for a user send that
34
- // includes the appended context envelope, and truncation can cut it open,
35
- // so clean with the loose strip like the Codex previews do.
36
43
  const summary =
37
- row.label?.trim() ||
38
- row.displayName?.trim() ||
39
- row.derivedTitle?.trim() ||
40
- formatChatTitle(stripMoiContextLoose(row.lastMessagePreview ?? '')) ||
44
+ cleanTitle(row.label) ||
45
+ cleanTitle(row.displayName) ||
46
+ cleanTitle(row.derivedTitle) ||
47
+ formatChatTitle(cleanTitle(row.lastMessagePreview)) ||
41
48
  ''
49
+ // External channel provenance. 'webchat' is moi's own chat surface — only
50
+ // real external channels (telegram/irc/discord/…) get an origin badge.
51
+ const provider = row.origin?.provider
52
+ const label = row.origin?.label
53
+ const origin =
54
+ provider && provider !== 'webchat' ? { provider, ...(label ? { label } : {}) } : undefined
55
+ // Flavor from the gateway key layout: cron buckets are `…:cron:<jobId>`,
56
+ // spawned subagents carry `spawnedBy` (and live under `…:subagent:<uuid>`).
57
+ const flavor: SessionInfo['flavor'] = row.key.includes(':cron:')
58
+ ? 'cron'
59
+ : row.spawnedBy || row.key.includes(':subagent:')
60
+ ? 'subagent'
61
+ : undefined
42
62
  return {
43
63
  sessionId: row.sessionId,
44
64
  summary,
45
65
  lastModified: row.updatedAt,
46
- cwd
66
+ cwd,
67
+ ...(origin ? { origin } : {}),
68
+ ...(flavor ? { flavor } : {})
47
69
  }
48
70
  }
49
71
 
50
- export type ToolResultInfo = { output: string; isError: boolean; toolName?: string }
72
+ // `running` marks a live `session.tool` start/update frame — the call is
73
+ // executing and has no output yet. A final result (stream or durable row)
74
+ // overwrites the entry.
75
+ export type ToolResultInfo = {
76
+ output: string
77
+ isError: boolean
78
+ toolName?: string
79
+ running?: boolean
80
+ }
51
81
 
52
- // Pull a readable `output` string out of a `toolResult` message. OpenClaw
53
- // ships content as blocks; in practice tool output is one or more text
54
- // blocks, so we concatenate them. Non-text blocks (images, etc.) are
55
- // represented as a `[type]` placeholder so we don't silently drop them.
56
- function flattenToolResultContent(content: OpenClawMessage['content']): string {
82
+ // Pull a readable `output` string out of a `toolResult` message. The tool
83
+ // result wire shape has drifted across OpenClaw lines (verified live):
84
+ // - 2026.7.1 — `content: [{ type: 'text', text: 'hello' }]` (flat text)
85
+ // - 2026.7.2+ — the exec sandbox nests the result as `[{ type: 'text',
86
+ // text: '<json>' }]` or wraps it in a `{ type: 'toolResult', content: […] }`
87
+ // block (which rendered as a bare `[toolResult]` placeholder before this).
88
+ // So recurse: text/image blocks resolve directly, any other block that
89
+ // carries its own `content` array or `text`/`output` string is unwrapped one
90
+ // level, and only a truly opaque block falls back to `[type]`.
91
+ export function flattenToolResultContent(content: OpenClawMessage['content'], depth = 0): string {
57
92
  if (typeof content === 'string') return content
58
93
  if (!Array.isArray(content)) return ''
59
94
  return content
60
95
  .map(block => {
61
96
  if (!block || typeof block !== 'object') return ''
62
- if (block.type === 'text') {
63
- const v = (block as { text?: unknown }).text
64
- return typeof v === 'string' ? v : ''
97
+ const b = block as {
98
+ type?: unknown
99
+ text?: unknown
100
+ content?: unknown
101
+ output?: unknown
102
+ }
103
+ if (b.type === 'text') return typeof b.text === 'string' ? b.text : ''
104
+ if (b.type === 'image') return '[image]'
105
+ // Nested wrapper (e.g. a `toolResult` block): unwrap one level.
106
+ if (depth < 3) {
107
+ if (Array.isArray(b.content)) {
108
+ const inner = flattenToolResultContent(b.content as OpenClawMessage['content'], depth + 1)
109
+ if (inner) return inner
110
+ }
111
+ if (typeof b.text === 'string' && b.text) return b.text
112
+ if (typeof b.output === 'string' && b.output) return b.output
65
113
  }
66
- return `[${block.type}]`
114
+ return typeof b.type === 'string' ? `[${b.type}]` : ''
67
115
  })
68
116
  .filter(Boolean)
69
117
  .join('\n')
@@ -110,17 +158,33 @@ function blockToPart(
110
158
  if (!text) return null
111
159
  return { type: 'text', text }
112
160
  }
113
- case 'thinking': {
161
+ case 'thinking':
162
+ case 'reasoning': {
163
+ // Field drift across OpenClaw lines: 2026.7.1 ships `{ type: 'thinking',
164
+ // thinking, thinkingSignature }`; newer lines emit `reasoning` and/or
165
+ // carry the text in `text`. Read whichever is present so the Thought row
166
+ // never silently vanishes.
167
+ const b = block as {
168
+ thinking?: unknown
169
+ reasoning?: unknown
170
+ text?: unknown
171
+ thinkingSignature?: unknown
172
+ signature?: unknown
173
+ }
114
174
  const text =
115
- typeof (block as { thinking?: unknown }).thinking === 'string'
116
- ? (block as { thinking: string }).thinking
117
- : ''
175
+ (typeof b.thinking === 'string' && b.thinking) ||
176
+ (typeof b.reasoning === 'string' && b.reasoning) ||
177
+ (typeof b.text === 'string' && b.text) ||
178
+ ''
118
179
  if (!text) return null
119
- const sig = (block as { thinkingSignature?: unknown }).thinkingSignature
180
+ const sig =
181
+ (typeof b.thinkingSignature === 'string' && b.thinkingSignature) ||
182
+ (typeof b.signature === 'string' && b.signature) ||
183
+ undefined
120
184
  return {
121
185
  type: 'reasoning',
122
186
  text,
123
- ...(typeof sig === 'string' ? { signature: sig } : {})
187
+ ...(sig ? { signature: sig } : {})
124
188
  }
125
189
  }
126
190
  case 'toolCall': {
@@ -129,7 +193,7 @@ function blockToPart(
129
193
  if (typeof id !== 'string' || typeof name !== 'string') return null
130
194
  const result = results.get(id)
131
195
  let state: ToolState = 'pending'
132
- if (result) state = result.isError ? 'error' : 'success'
196
+ if (result) state = result.running ? 'running' : result.isError ? 'error' : 'success'
133
197
  const call: ToolCall = {
134
198
  toolCallId: id,
135
199
  name,
@@ -138,7 +202,7 @@ function blockToPart(
138
202
  state,
139
203
  input: (block as { arguments?: unknown }).arguments
140
204
  }
141
- if (result) {
205
+ if (result && !result.running) {
142
206
  if (result.isError) call.errorText = result.output
143
207
  else call.output = result.output
144
208
  }
@@ -219,10 +283,40 @@ export function toStreamEvents(
219
283
  ): StreamEvent[] {
220
284
  if (!detail?.messages) return []
221
285
  const results = collectToolResults(detail.messages)
222
- const turns = detail.messages
223
- .map((m, i) => messageToTurn(m, sessionKey, i, results))
224
- .filter((t): t is Turn => t !== null)
225
- return turns.map(turn => ({ kind: 'turn', turn }))
286
+ const events: StreamEvent[] = []
287
+ // Cold-path twin of the live model-change notice in session.ts: an
288
+ // assistant row on a different model than the previous assistant row marks
289
+ // a mid-session switch (sessions.patch from moi's picker or any other
290
+ // client) — interleave a notice before that turn instead of letting the
291
+ // switch pass silently. `prev` tracks every assistant row's model, even
292
+ // ones that render no turn.
293
+ let prevModel: string | undefined
294
+ detail.messages.forEach((msg, i) => {
295
+ if (msg.role === 'assistant') {
296
+ const model = (msg as { model?: unknown }).model
297
+ if (typeof model === 'string') {
298
+ if (prevModel !== undefined && prevModel !== model) {
299
+ events.push({
300
+ kind: 'notice',
301
+ notice: {
302
+ id: `openclaw:model-change:${msg.__openclaw?.id ?? i}`,
303
+ kind: 'model-change',
304
+ at:
305
+ typeof msg.timestamp === 'number'
306
+ ? new Date(msg.timestamp).toISOString()
307
+ : new Date().toISOString(),
308
+ model,
309
+ prev: prevModel
310
+ }
311
+ })
312
+ }
313
+ prevModel = model
314
+ }
315
+ }
316
+ const turn = messageToTurn(msg, sessionKey, i, results)
317
+ if (turn) events.push({ kind: 'turn', turn })
318
+ })
319
+ return events
226
320
  }
227
321
 
228
322
  // Find every assistant message that has a `toolCall` block with `toolCallId`.
@@ -0,0 +1,99 @@
1
+ // Version/feature tolerance for the OpenClaw gateway.
2
+ //
3
+ // moi speaks gateway wire protocol 4 — the protocol of the current line
4
+ // (2026.7.x) and the previous still-maintained line (2026.6.x). The two lines
5
+ // differ only in small field placements, handled by the helpers here (all
6
+ // verified against live gateways: 2026.7.1 and 2026.6.33). Protocol-3
7
+ // gateways (≤ 2026.5.x) refuse the handshake with "protocol mismatch"; those
8
+ // are detected and surfaced as a status, never silently swallowed.
9
+ //
10
+ // Rule for future params: old gateways validate params with
11
+ // `additionalProperties: false` and reject unknown fields outright — never
12
+ // send a param that only newer schemas know without gating on `GatewayInfo`.
13
+
14
+ // What the gateway announced in `hello-ok`. `methods`/`events` are advisory:
15
+ // 2026.6.33 answers `sessions.get` while omitting it from `features.methods`,
16
+ // so absence must never disable an essential call — use `advertisesMethod`
17
+ // only to unlock optional niceties.
18
+ export type GatewayInfo = {
19
+ protocol?: number
20
+ serverVersion?: string
21
+ methods: Set<string>
22
+ events: Set<string>
23
+ }
24
+
25
+ export function parseHelloOk(hello: unknown): GatewayInfo {
26
+ const h = hello as
27
+ | {
28
+ protocol?: unknown
29
+ server?: { version?: unknown }
30
+ features?: { methods?: unknown; events?: unknown }
31
+ }
32
+ | undefined
33
+ const strings = (v: unknown): string[] =>
34
+ Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
35
+ return {
36
+ protocol: typeof h?.protocol === 'number' ? h.protocol : undefined,
37
+ serverVersion: typeof h?.server?.version === 'string' ? h.server.version : undefined,
38
+ methods: new Set(strings(h?.features?.methods)),
39
+ events: new Set(strings(h?.features?.events))
40
+ }
41
+ }
42
+
43
+ export function advertisesMethod(info: GatewayInfo | null, method: string): boolean {
44
+ return info?.methods.has(method) ?? false
45
+ }
46
+
47
+ export type GatewayFailureKind = 'protocol-mismatch' | 'auth' | 'unreachable' | 'unknown'
48
+
49
+ export type GatewayFailure = {
50
+ kind: GatewayFailureKind
51
+ message: string
52
+ }
53
+
54
+ // Map a connect/RPC error onto a stable category the UI can explain. The
55
+ // protocol-mismatch string is the gateway's own wording (verified against a
56
+ // live 2026.4.22 gateway). `gatewayCode` (GatewayClientRequestError) is
57
+ // preferred over message sniffing when present.
58
+ export function classifyGatewayError(err: unknown): GatewayFailure {
59
+ const raw = err instanceof Error ? err.message : String(err)
60
+ const code = (err as { gatewayCode?: unknown } | undefined)?.gatewayCode
61
+ const lower = raw.toLowerCase()
62
+ if (lower.includes('protocol mismatch')) {
63
+ return {
64
+ kind: 'protocol-mismatch',
65
+ message:
66
+ 'OpenClaw gateway speaks an older protocol than this moi build. Update OpenClaw (2026.6 or newer) to reconnect.'
67
+ }
68
+ }
69
+ if (code === 'UNAUTHORIZED' || lower.includes('unauthorized')) {
70
+ return { kind: 'auth', message: `OpenClaw gateway rejected the connection: ${raw}` }
71
+ }
72
+ if (
73
+ lower.includes('refused') ||
74
+ lower.includes('timeout') ||
75
+ lower.includes('econn') ||
76
+ lower.includes('enotfound') ||
77
+ lower.includes('closed')
78
+ ) {
79
+ return { kind: 'unreachable', message: 'OpenClaw gateway is not reachable.' }
80
+ }
81
+ return { kind: 'unknown', message: raw }
82
+ }
83
+
84
+ // The durable user-echo carries `<runId>:user` so sends can be matched
85
+ // exactly. 2026.7.x nests it under `__openclaw.idempotencyKey`; 2026.6.x puts
86
+ // it on the message itself.
87
+ export function messageIdempotencyKey(msg: unknown): string | undefined {
88
+ const m = msg as
89
+ | { idempotencyKey?: unknown; __openclaw?: { idempotencyKey?: unknown } }
90
+ | undefined
91
+ const nested = m?.__openclaw?.idempotencyKey
92
+ if (typeof nested === 'string') return nested
93
+ const flat = m?.idempotencyKey
94
+ return typeof flat === 'string' ? flat : undefined
95
+ }
96
+
97
+ // Thinking levels are NOT gateway-global — they resolve per model, and the
98
+ // gateway rejects a level outside the resolved model's set. See `thinking.ts`,
99
+ // which learns each model's menu from the session rows that carry it.
@@ -0,0 +1,78 @@
1
+ // Cold-path view synthesis for isolated cron sessions.
2
+ //
3
+ // Why this exists: `sessions.list` shows a cron job under its bucket key
4
+ // (`agent:<id>:cron:<jobId>`), but each scheduled run executes in a per-run
5
+ // session (`…:cron:<jobId>:run:<uuid>`) and the gateway's post-run session
6
+ // reset orphans that per-run transcript file. `sessions.get` on the listed
7
+ // bucket key therefore returns ZERO messages (verified live on 2026.7.1), so
8
+ // opening a cron chat would render empty. The run-history RPC (`cron.runs`,
9
+ // present with identical params/response on both supported lines, 2026.7.x
10
+ // and 2026.6.x) still records each run's outcome — we synthesize one
11
+ // assistant turn per recorded run from it.
12
+ import type { StreamEvent, Turn, TurnMeta } from '@/lib/format'
13
+
14
+ // One `cron.runs` entry (subset). Shape verified against a live 2026.7.1
15
+ // gateway; note usage keys are snake_case here, unlike session-message usage.
16
+ export type OpenClawCronRunEntry = {
17
+ ts: number
18
+ jobId: string
19
+ status?: string
20
+ error?: string
21
+ summary?: string
22
+ runId?: string
23
+ runAtMs?: number
24
+ durationMs?: number
25
+ model?: string
26
+ provider?: string
27
+ usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number }
28
+ sessionId?: string
29
+ sessionKey?: string
30
+ jobName?: string
31
+ }
32
+
33
+ // `agent:main:cron:<jobId>` (bucket) or `…:cron:<jobId>:run:<uuid>` → jobId.
34
+ export function openClawCronJobIdFromKey(key: string): string | null {
35
+ const m = /:cron:([^:]+)/.exec(key)
36
+ return m ? m[1] : null
37
+ }
38
+
39
+ // One assistant turn per recorded run, ascending by run time. An errored run
40
+ // shows its error even when a reply summary exists (delivery failures record
41
+ // both — the summary alone would render indistinguishable from success);
42
+ // clean runs show the summary, and runs with neither (skipped, timed out
43
+ // before output) still get a status line so the chat never renders empty
44
+ // while runs exist.
45
+ export function cronRunsToStreamEvents(entries: OpenClawCronRunEntry[]): StreamEvent[] {
46
+ const events: StreamEvent[] = []
47
+ for (const entry of [...entries].sort((a, b) => a.ts - b.ts)) {
48
+ const summary = entry.summary?.trim()
49
+ const failed = entry.status === 'error' && entry.error
50
+ const text = failed
51
+ ? `⚠ ${entry.error}${summary ? `\n\n${summary}` : ''}`
52
+ : summary || (entry.error ? `⚠ ${entry.error}` : entry.status ? `(run ${entry.status})` : '')
53
+ if (!text) continue
54
+ const meta: TurnMeta = {}
55
+ if (entry.model) meta.model = entry.model
56
+ if (entry.provider) meta.provider = entry.provider
57
+ if (entry.status) meta.stopReason = entry.status
58
+ if (entry.usage) {
59
+ const usage: NonNullable<TurnMeta['usage']> = {}
60
+ if (typeof entry.usage.input_tokens === 'number') usage.inputTokens = entry.usage.input_tokens
61
+ if (typeof entry.usage.output_tokens === 'number') {
62
+ usage.outputTokens = entry.usage.output_tokens
63
+ }
64
+ if (typeof entry.usage.total_tokens === 'number') usage.totalTokens = entry.usage.total_tokens
65
+ if (Object.keys(usage).length > 0) meta.usage = usage
66
+ }
67
+ const turn: Turn = {
68
+ id: `openclaw:cron:${entry.jobId}:${entry.runId ?? entry.ts}`,
69
+ role: 'assistant',
70
+ origin: { kind: 'user-input' },
71
+ parts: [{ type: 'text', text }],
72
+ timestamp: new Date(entry.ts).toISOString(),
73
+ ...(Object.keys(meta).length > 0 ? { meta } : {})
74
+ }
75
+ events.push({ kind: 'turn', turn })
76
+ }
77
+ return events
78
+ }
@@ -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
  }