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,21 +1,13 @@
1
1
  // Map OpenClaw gateway shapes into our agent-agnostic display format.
2
2
  //
3
- // OpenClaw stores one `OpenClawMessage` per role-turn: `user` (the prompt,
4
- // with AI-facing envelopes prepended — see `openclaw-strip.ts`), `assistant`
5
- // (text/reasoning/toolCall blocks + model metadata), and `toolResult` (one
6
- // per executed tool call, keyed by `toolCallId`). We turn that into:
7
- // - one Turn per user/assistant message, with tool-call parts rendered
8
- // inline on the assistant turn,
9
- // - no separate turn for toolResult rows — results are folded into the
10
- // assistant's matching tool-call part so the UI shows them as expandable
11
- // output under the call.
3
+ // OpenClaw stores one message per role-turn: `user` (the prompt, with AI-facing
4
+ // envelopes prepended — see `strip.ts`), `assistant` (text/thinking/toolCall
5
+ // blocks plus model metadata), and `toolResult` (one per executed call, keyed
6
+ // by `toolCallId`). Each user/assistant message becomes one Turn; toolResult
7
+ // rows get no turn of their own — they fold into the matching tool-call part.
12
8
  //
13
- // Two callers:
14
- // - `toStreamEvents(detail)` — static path used for cold-load (REST endpoint)
15
- // and tests.
16
- // - `messageToTurnLive(msg, sessionKey, idx, results)` — incremental path used
17
- // by the live session adapter (`openclaw-session.ts`) when a single
18
- // `session.message` frame arrives.
9
+ // `toStreamEvents` is the cold path (REST replay); `messageToTurn` is the
10
+ // per-frame path the live session uses.
19
11
  import type { Part, StreamEvent, ToolCall, ToolState, Turn, TurnMeta } from '@/lib/format'
20
12
  import type { SessionInfo } from '@/lib/types'
21
13
 
@@ -27,43 +19,88 @@ import type {
27
19
  } from './discovery'
28
20
  import { formatChatTitle } from '@/lib/chat-title'
29
21
  import { stripMoiContextLoose } from '@/lib/moi-context'
30
- import { stripUserMessageMetadata } from './strip'
22
+ import { stripSubagentEnvelope, stripUserMessageMetadata } from './strip'
23
+
24
+ // moi appends the `<moi-context>` envelope to the user's message text because
25
+ // `sessions.send` has no separate system channel — so the gateway derives
26
+ // `displayName`/`derivedTitle`/`lastMessagePreview` from a message that
27
+ // carries the envelope. Strip it (loose: truncation can cut it open) from
28
+ // every title source, not just the preview, so no title shows the envelope.
29
+ // A no-op on channel/cron labels that never contain it.
30
+ function cleanTitle(text: string | undefined): string {
31
+ return stripSubagentEnvelope(stripMoiContextLoose(text?.trim() ?? '')).trim()
32
+ }
31
33
 
32
34
  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
35
  const summary =
37
- row.label?.trim() ||
38
- row.displayName?.trim() ||
39
- row.derivedTitle?.trim() ||
40
- formatChatTitle(stripMoiContextLoose(row.lastMessagePreview ?? '')) ||
36
+ cleanTitle(row.label) ||
37
+ cleanTitle(row.displayName) ||
38
+ cleanTitle(row.derivedTitle) ||
39
+ formatChatTitle(cleanTitle(row.lastMessagePreview)) ||
41
40
  ''
41
+ // External channel provenance. 'webchat' is moi's own chat surface — only
42
+ // real external channels (telegram/irc/discord/…) get an origin badge.
43
+ const provider = row.origin?.provider
44
+ const label = row.origin?.label
45
+ const origin =
46
+ provider && provider !== 'webchat' ? { provider, ...(label ? { label } : {}) } : undefined
47
+ // Flavor from the gateway key layout: cron buckets are `…:cron:<jobId>`,
48
+ // spawned subagents carry `spawnedBy` (and live under `…:subagent:<uuid>`).
49
+ const flavor: SessionInfo['flavor'] = row.key.includes(':cron:')
50
+ ? 'cron'
51
+ : row.spawnedBy || row.key.includes(':subagent:')
52
+ ? 'subagent'
53
+ : undefined
42
54
  return {
43
55
  sessionId: row.sessionId,
44
56
  summary,
45
57
  lastModified: row.updatedAt,
46
- cwd
58
+ cwd,
59
+ ...(origin ? { origin } : {}),
60
+ ...(flavor ? { flavor } : {})
47
61
  }
48
62
  }
49
63
 
50
- export type ToolResultInfo = { output: string; isError: boolean; toolName?: string }
64
+ // `running` marks a live `session.tool` start/update frame — the call is
65
+ // executing and has no output yet. A final result (stream or durable row)
66
+ // overwrites the entry.
67
+ export type ToolResultInfo = {
68
+ output: string
69
+ isError: boolean
70
+ toolName?: string
71
+ running?: boolean
72
+ }
51
73
 
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 {
74
+ // Pull a readable `output` string out of a `toolResult` message. Rows are flat
75
+ // in practice (`content: [{ type: 'text', text: 'hello' }]`), but upstream
76
+ // types these blocks as an open `Record<string, unknown>` and says outright
77
+ // that provider SDKs spell them differently (`src/chat/tool-content.ts`), so a
78
+ // block carrying its own `content`/`text`/`output` is unwrapped one level
79
+ // rather than rendered as a bare `[toolResult]` placeholder.
80
+ export function flattenToolResultContent(content: OpenClawMessage['content'], depth = 0): string {
57
81
  if (typeof content === 'string') return content
58
82
  if (!Array.isArray(content)) return ''
59
83
  return content
60
84
  .map(block => {
61
85
  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 : ''
86
+ const b = block as {
87
+ type?: unknown
88
+ text?: unknown
89
+ content?: unknown
90
+ output?: unknown
65
91
  }
66
- return `[${block.type}]`
92
+ if (b.type === 'text') return typeof b.text === 'string' ? b.text : ''
93
+ if (b.type === 'image') return '[image]'
94
+ // Nested wrapper (e.g. a `toolResult` block): unwrap one level.
95
+ if (depth < 3) {
96
+ if (Array.isArray(b.content)) {
97
+ const inner = flattenToolResultContent(b.content as OpenClawMessage['content'], depth + 1)
98
+ if (inner) return inner
99
+ }
100
+ if (typeof b.text === 'string' && b.text) return b.text
101
+ if (typeof b.output === 'string' && b.output) return b.output
102
+ }
103
+ return typeof b.type === 'string' ? `[${b.type}]` : ''
67
104
  })
68
105
  .filter(Boolean)
69
106
  .join('\n')
@@ -98,7 +135,8 @@ function collectToolResults(messages: OpenClawMessage[]): Map<string, ToolResult
98
135
  function blockToPart(
99
136
  block: OpenClawContentBlock,
100
137
  role: OpenClawMessage['role'],
101
- results: Map<string, ToolResultInfo>
138
+ results: Map<string, ToolResultInfo>,
139
+ omitToolCallIds?: ReadonlySet<string>
102
140
  ): Part | null {
103
141
  switch (block.type) {
104
142
  case 'text': {
@@ -111,25 +149,23 @@ function blockToPart(
111
149
  return { type: 'text', text }
112
150
  }
113
151
  case 'thinking': {
114
- const text =
115
- typeof (block as { thinking?: unknown }).thinking === 'string'
116
- ? (block as { thinking: string }).thinking
117
- : ''
118
- if (!text) return null
119
- const sig = (block as { thinkingSignature?: unknown }).thinkingSignature
120
- return {
121
- type: 'reasoning',
122
- text,
123
- ...(typeof sig === 'string' ? { signature: sig } : {})
124
- }
152
+ const b = block as { thinking?: unknown; thinkingSignature?: unknown }
153
+ if (typeof b.thinking !== 'string' || !b.thinking) return null
154
+ const sig = typeof b.thinkingSignature === 'string' ? b.thinkingSignature : undefined
155
+ return { type: 'reasoning', text: b.thinking, ...(sig ? { signature: sig } : {}) }
125
156
  }
126
157
  case 'toolCall': {
127
158
  const id = (block as { id?: unknown }).id
128
159
  const name = (block as { name?: unknown }).name
129
160
  if (typeof id !== 'string' || typeof name !== 'string') return null
161
+ // This call is already on screen as its own live card (the live session
162
+ // rendered it before this row carried the block). Rendering it here too
163
+ // would show the same call twice, and a broadcast card can't be
164
+ // retracted — so the live card keeps ownership for the session's life.
165
+ if (omitToolCallIds?.has(id)) return null
130
166
  const result = results.get(id)
131
167
  let state: ToolState = 'pending'
132
- if (result) state = result.isError ? 'error' : 'success'
168
+ if (result) state = result.running ? 'running' : result.isError ? 'error' : 'success'
133
169
  const call: ToolCall = {
134
170
  toolCallId: id,
135
171
  name,
@@ -138,7 +174,7 @@ function blockToPart(
138
174
  state,
139
175
  input: (block as { arguments?: unknown }).arguments
140
176
  }
141
- if (result) {
177
+ if (result && !result.running) {
142
178
  if (result.isError) call.errorText = result.output
143
179
  else call.output = result.output
144
180
  }
@@ -179,7 +215,8 @@ export function messageToTurn(
179
215
  msg: OpenClawMessage,
180
216
  sessionKey: string,
181
217
  idx: number,
182
- results: Map<string, ToolResultInfo>
218
+ results: Map<string, ToolResultInfo>,
219
+ omitToolCallIds?: ReadonlySet<string>
183
220
  ): Turn | null {
184
221
  if (msg.role !== 'user' && msg.role !== 'assistant') return null
185
222
  const blocks: OpenClawContentBlock[] = Array.isArray(msg.content)
@@ -188,7 +225,7 @@ export function messageToTurn(
188
225
  ? [{ type: 'text', text: msg.content }]
189
226
  : []
190
227
  const parts = blocks
191
- .map(b => blockToPart(b, msg.role, results))
228
+ .map(b => blockToPart(b, msg.role, results, omitToolCallIds))
192
229
  .filter((p): p is Part => p !== null)
193
230
  if (parts.length === 0) return null
194
231
  const ocId = msg.__openclaw?.id
@@ -219,10 +256,40 @@ export function toStreamEvents(
219
256
  ): StreamEvent[] {
220
257
  if (!detail?.messages) return []
221
258
  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 }))
259
+ const events: StreamEvent[] = []
260
+ // Cold-path twin of the live model-change notice in session.ts: an
261
+ // assistant row on a different model than the previous assistant row marks
262
+ // a mid-session switch (sessions.patch from moi's picker or any other
263
+ // client) — interleave a notice before that turn instead of letting the
264
+ // switch pass silently. `prev` tracks every assistant row's model, even
265
+ // ones that render no turn.
266
+ let prevModel: string | undefined
267
+ detail.messages.forEach((msg, i) => {
268
+ if (msg.role === 'assistant') {
269
+ const model = (msg as { model?: unknown }).model
270
+ if (typeof model === 'string') {
271
+ if (prevModel !== undefined && prevModel !== model) {
272
+ events.push({
273
+ kind: 'notice',
274
+ notice: {
275
+ id: `openclaw:model-change:${msg.__openclaw?.id ?? i}`,
276
+ kind: 'model-change',
277
+ at:
278
+ typeof msg.timestamp === 'number'
279
+ ? new Date(msg.timestamp).toISOString()
280
+ : new Date().toISOString(),
281
+ model,
282
+ prev: prevModel
283
+ }
284
+ })
285
+ }
286
+ prevModel = model
287
+ }
288
+ }
289
+ const turn = messageToTurn(msg, sessionKey, i, results)
290
+ if (turn) events.push({ kind: 'turn', turn })
291
+ })
292
+ return events
226
293
  }
227
294
 
228
295
  // Find every assistant message that has a `toolCall` block with `toolCallId`.
@@ -0,0 +1,95 @@
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
+ // and UNDER-REPORT: 2026.6.33 answers `sessions.get` while omitting it from
16
+ // `features.methods`. Absence proves nothing, so nothing gates on this — the
17
+ // sets are carried for `/status` and for debugging a version mismatch.
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 type GatewayFailureKind = 'protocol-mismatch' | 'auth' | 'unreachable' | 'unknown'
44
+
45
+ export type GatewayFailure = {
46
+ kind: GatewayFailureKind
47
+ message: string
48
+ }
49
+
50
+ // Map a connect/RPC error onto a stable category the UI can explain. The
51
+ // protocol-mismatch string is the gateway's own wording (verified against a
52
+ // live 2026.4.22 gateway). `gatewayCode` (GatewayClientRequestError) is
53
+ // preferred over message sniffing when present.
54
+ export function classifyGatewayError(err: unknown): GatewayFailure {
55
+ const raw = err instanceof Error ? err.message : String(err)
56
+ const code = (err as { gatewayCode?: unknown } | undefined)?.gatewayCode
57
+ const lower = raw.toLowerCase()
58
+ if (lower.includes('protocol mismatch')) {
59
+ return {
60
+ kind: 'protocol-mismatch',
61
+ message:
62
+ 'OpenClaw gateway speaks an older protocol than this moi build. Update OpenClaw (2026.6 or newer) to reconnect.'
63
+ }
64
+ }
65
+ if (code === 'UNAUTHORIZED' || lower.includes('unauthorized')) {
66
+ return { kind: 'auth', message: `OpenClaw gateway rejected the connection: ${raw}` }
67
+ }
68
+ if (
69
+ lower.includes('refused') ||
70
+ lower.includes('timeout') ||
71
+ lower.includes('econn') ||
72
+ lower.includes('enotfound') ||
73
+ lower.includes('closed')
74
+ ) {
75
+ return { kind: 'unreachable', message: 'OpenClaw gateway is not reachable.' }
76
+ }
77
+ return { kind: 'unknown', message: raw }
78
+ }
79
+
80
+ // The durable user-echo carries `<runId>:user` so sends can be matched
81
+ // exactly. 2026.7.x nests it under `__openclaw.idempotencyKey`; 2026.6.x puts
82
+ // it on the message itself.
83
+ export function messageIdempotencyKey(msg: unknown): string | undefined {
84
+ const m = msg as
85
+ | { idempotencyKey?: unknown; __openclaw?: { idempotencyKey?: unknown } }
86
+ | undefined
87
+ const nested = m?.__openclaw?.idempotencyKey
88
+ if (typeof nested === 'string') return nested
89
+ const flat = m?.idempotencyKey
90
+ return typeof flat === 'string' ? flat : undefined
91
+ }
92
+
93
+ // Thinking levels are NOT gateway-global — they resolve per model, and the
94
+ // gateway rejects a level outside the resolved model's set. See `thinking.ts`,
95
+ // 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
+ }