moi-computer 0.0.1

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 (106) hide show
  1. package/LICENSE +95 -0
  2. package/README.md +71 -0
  3. package/bin/moi.mjs +25 -0
  4. package/bunfig.toml +3 -0
  5. package/client/CLAUDE.md +12 -0
  6. package/client/api/workspaces.ts +158 -0
  7. package/client/assets/claude.svg +3 -0
  8. package/client/assets/favicon.png +0 -0
  9. package/client/assets/hermes-nous.png +0 -0
  10. package/client/assets/mcp/.gitkeep +0 -0
  11. package/client/assets/mcp/atlassian.png +0 -0
  12. package/client/assets/mcp/discord.png +0 -0
  13. package/client/assets/mcp/figma.png +0 -0
  14. package/client/assets/mcp/github.png +0 -0
  15. package/client/assets/mcp/gitlab.png +0 -0
  16. package/client/assets/mcp/granola.png +0 -0
  17. package/client/assets/mcp/hubspot.png +0 -0
  18. package/client/assets/mcp/linear.png +0 -0
  19. package/client/assets/mcp/neon.png +0 -0
  20. package/client/assets/mcp/notion.png +0 -0
  21. package/client/assets/mcp/sentry.png +0 -0
  22. package/client/assets/mcp/slack.png +0 -0
  23. package/client/assets/mcp/stripe.png +0 -0
  24. package/client/assets/mcp/supabase.png +0 -0
  25. package/client/assets/mcp/vercel.png +0 -0
  26. package/client/assets/moi-logo.svg +11 -0
  27. package/client/assets/openclaw.svg +22 -0
  28. package/client/components/App.tsx +35 -0
  29. package/client/components/BottomPanel.tsx +33 -0
  30. package/client/components/ChatInput.tsx +62 -0
  31. package/client/components/ChatPanel.tsx +206 -0
  32. package/client/components/ChatPopup.tsx +60 -0
  33. package/client/components/CustomizePanel.tsx +117 -0
  34. package/client/components/HiddenPanel.tsx +79 -0
  35. package/client/components/HomePage.tsx +17 -0
  36. package/client/components/MarkdownContent.tsx +41 -0
  37. package/client/components/ThreadSelector.tsx +88 -0
  38. package/client/components/TurnView.tsx +618 -0
  39. package/client/components/WidgetErrorBoundary.tsx +46 -0
  40. package/client/components/WidgetFrame.tsx +66 -0
  41. package/client/components/WidgetGrid.tsx +113 -0
  42. package/client/components/WidgetShell.tsx +44 -0
  43. package/client/components/Widgets.tsx +132 -0
  44. package/client/components/WorkspacePreview.tsx +48 -0
  45. package/client/components/WorkspacesPage.tsx +237 -0
  46. package/client/components/layout/SidebarLayout.tsx +260 -0
  47. package/client/components/playground/LedLogo.tsx +181 -0
  48. package/client/components/playground/PixelPainter.tsx +105 -0
  49. package/client/components/playground/PlaygroundPage.tsx +71 -0
  50. package/client/components/routes/workspace/[id].tsx +282 -0
  51. package/client/components/ui/button.tsx +48 -0
  52. package/client/components/ui/dropdown-menu.tsx +257 -0
  53. package/client/components/ui/input.tsx +21 -0
  54. package/client/components/ui/popover.tsx +79 -0
  55. package/client/components/ui/textarea.tsx +18 -0
  56. package/client/externalize-react.ts +29 -0
  57. package/client/hooks/useChat.ts +88 -0
  58. package/client/hooks/useFitsSidebar.ts +34 -0
  59. package/client/hooks/useGridReconcile.ts +73 -0
  60. package/client/hooks/useMeiEvents.ts +66 -0
  61. package/client/hooks/useScrollFade.ts +38 -0
  62. package/client/hooks/useWidget.ts +72 -0
  63. package/client/hooks/useWidgetList.ts +30 -0
  64. package/client/hooks/useWorkspaceTheme.ts +76 -0
  65. package/client/index.css +182 -0
  66. package/client/index.html +43 -0
  67. package/client/index.tsx +19 -0
  68. package/client/lib/WorkspaceContext.tsx +24 -0
  69. package/client/lib/WorkspaceLayoutContext.tsx +92 -0
  70. package/client/lib/cn.ts +6 -0
  71. package/client/lib/grid-pack.ts +35 -0
  72. package/client/lib/group-turns.ts +44 -0
  73. package/client/lib/mcp-icons.ts +53 -0
  74. package/client/lib/ws.ts +129 -0
  75. package/client/main.tsx +23 -0
  76. package/client/store/chat.tsx +162 -0
  77. package/client/store/ui.ts +21 -0
  78. package/client/theme.css +66 -0
  79. package/lib/claude-adapter.ts +602 -0
  80. package/lib/format.ts +212 -0
  81. package/lib/themes.ts +89 -0
  82. package/lib/types.ts +144 -0
  83. package/package.json +117 -0
  84. package/server/CLAUDE.md +6 -0
  85. package/server/agent.ts +132 -0
  86. package/server/build-widget.ts +343 -0
  87. package/server/cli.ts +632 -0
  88. package/server/constants.ts +3 -0
  89. package/server/control.ts +98 -0
  90. package/server/functions-worker.ts +89 -0
  91. package/server/functions.ts +171 -0
  92. package/server/layout.ts +83 -0
  93. package/server/openclaw-adapter.ts +242 -0
  94. package/server/openclaw-gateway.ts +255 -0
  95. package/server/openclaw-session.ts +485 -0
  96. package/server/openclaw-strip.ts +134 -0
  97. package/server/openclaw.ts +206 -0
  98. package/server/registry.ts +150 -0
  99. package/server/skills-template.ts +21 -0
  100. package/server/state.ts +87 -0
  101. package/server/theme.ts +55 -0
  102. package/server/web.ts +321 -0
  103. package/server/widgets.ts +254 -0
  104. package/tsconfig.json +21 -0
  105. package/workspace/.claude/skills/widgets/DESIGN.md +630 -0
  106. package/workspace/.claude/skills/widgets/SKILL.md +176 -0
@@ -0,0 +1,98 @@
1
+ import { resolve } from 'path'
2
+
3
+ import { CONTROL_PORT } from './constants'
4
+ import { loadLayout, saveLayout } from './layout'
5
+ import { listWorkspaces, registerWorkspace } from './registry'
6
+ import { broadcastAll } from './state'
7
+ import { applyThemeUpdate, matchColorTheme } from './theme'
8
+ import { publishMei } from './web'
9
+ import { handleBundle } from './widgets'
10
+
11
+ export const control = Bun.serve({
12
+ port: CONTROL_PORT,
13
+ hostname: '127.0.0.1',
14
+ fetch(req, server) {
15
+ return server.upgrade(req)
16
+ ? new Response(null, { status: 101 })
17
+ : new Response('Control WebSocket only', { status: 426 })
18
+ },
19
+ websocket: {
20
+ async message(ws, message) {
21
+ try {
22
+ const data = JSON.parse(String(message))
23
+
24
+ if (data.type === 'workspace:register') {
25
+ const absPath = resolve(String(data.path))
26
+ const entry = await registerWorkspace(absPath)
27
+ broadcastAll({ type: 'workspace:switch', workspaceId: entry.id })
28
+ ws.send(JSON.stringify({ id: entry.id, path: entry.path }))
29
+ return
30
+ }
31
+
32
+ if (data.type === 'workspace:list') {
33
+ const workspaces = await listWorkspaces()
34
+ ws.send(JSON.stringify({ workspaces }))
35
+ return
36
+ }
37
+
38
+ if (data.type === 'bundle') {
39
+ // Bundle needs a workspace path — default to first registered workspace
40
+ const workspaces = await listWorkspaces()
41
+ if (workspaces.length === 0) {
42
+ ws.send(JSON.stringify({ error: 'No workspaces registered' }))
43
+ return
44
+ }
45
+ const workspacePath = String(data.path ?? workspaces[0].path)
46
+ const results = await handleBundle(publishMei, workspacePath, !!data.force)
47
+ ws.send(JSON.stringify(results))
48
+ return
49
+ }
50
+
51
+ if (data.type === 'widget:refresh') {
52
+ // Tell every connected widget to re-import its module (cache-bust)
53
+ // and re-run its data fetches. No rebuild, no page reload — the
54
+ // existing `useWidget` hook handles `widgets:refresh` identically
55
+ // to `widget:updated` (load with bust=true).
56
+ publishMei({ type: 'widgets:refresh' })
57
+ ws.send(JSON.stringify({ ok: true }))
58
+ return
59
+ }
60
+
61
+ if (data.type === 'theme') {
62
+ // Theme is per-workspace
63
+ const workspaces = await listWorkspaces()
64
+ if (workspaces.length === 0) {
65
+ ws.send(JSON.stringify({ error: 'No workspaces registered' }))
66
+ return
67
+ }
68
+ const workspacePath = String(data.path ?? workspaces[0].path)
69
+ const layout = await loadLayout(workspacePath)
70
+
71
+ // Listing mode — neither axis requested
72
+ if (!data.font && !data.color) {
73
+ ws.send(
74
+ JSON.stringify({
75
+ currentFont: layout.theme?.font ?? 'default',
76
+ currentColor: matchColorTheme(layout.theme?.background, layout.theme?.foreground)
77
+ })
78
+ )
79
+ return
80
+ }
81
+
82
+ const result = applyThemeUpdate(layout.theme, { font: data.font, color: data.color })
83
+ if (!result.ok) {
84
+ ws.send(JSON.stringify({ error: result.error }))
85
+ return
86
+ }
87
+
88
+ await saveLayout({ ...layout, theme: result.theme }, workspacePath)
89
+ publishMei({ type: 'theme:updated' })
90
+ ws.send(JSON.stringify({ ok: true, ...result.applied }))
91
+ }
92
+ } catch (err) {
93
+ console.error('[control]', err)
94
+ ws.send(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }))
95
+ }
96
+ }
97
+ }
98
+ })
@@ -0,0 +1,89 @@
1
+ // MEI Functions Worker — child process that loads and executes .server.ts modules.
2
+ // Spawned by the main process with IPC. Receives call/reload messages.
3
+ import { parse, stringify } from 'devalue'
4
+ import { join } from 'path'
5
+
6
+ const MEI_DIR =
7
+ process.env.MEI_FUNCTIONS_DIR ?? join(import.meta.dir, '..', 'test-workspace', '.widgets')
8
+
9
+ const moduleCache = new Map<string, Record<string, unknown>>()
10
+
11
+ function send(msg: unknown) {
12
+ try {
13
+ process.send!(msg)
14
+ } catch {
15
+ // IPC channel closed — parent died
16
+ }
17
+ }
18
+
19
+ async function loadModule(name: string): Promise<Record<string, unknown>> {
20
+ const cached = moduleCache.get(name)
21
+ if (cached) return cached
22
+
23
+ const filePath = join(MEI_DIR, `${name}.server.ts`)
24
+ const file = Bun.file(filePath)
25
+
26
+ if (!(await file.exists())) {
27
+ throw new Error(`Server module "${name}" not found`)
28
+ }
29
+
30
+ const mod = (await import(filePath + `?t=${file.lastModified}`)) as Record<string, unknown>
31
+ moduleCache.set(name, mod)
32
+ return mod
33
+ }
34
+
35
+ async function evictModule(name: string) {
36
+ const mod = moduleCache.get(name)
37
+ if (!mod) return
38
+
39
+ if (typeof mod.dispose === 'function') {
40
+ try {
41
+ await (mod.dispose as () => Promise<void>)()
42
+ } catch (err) {
43
+ console.error(`[mei] dispose error in ${name}.server.ts:`, err)
44
+ }
45
+ }
46
+
47
+ moduleCache.delete(name)
48
+ }
49
+
50
+ type CallMessage = { id: string; type: 'call'; module: string; name: string; args: string }
51
+ type ReloadMessage = { type: 'reload'; modules: string[] }
52
+ type IncomingMessage = CallMessage | ReloadMessage
53
+
54
+ process.on('message', async (raw: IncomingMessage) => {
55
+ if (raw.type === 'reload') {
56
+ for (const name of raw.modules) {
57
+ await evictModule(name)
58
+ }
59
+ return
60
+ }
61
+
62
+ if (raw.type === 'call') {
63
+ const { id, module: moduleName, name, args } = raw
64
+
65
+ if (!id || !moduleName || !name) {
66
+ send({ id, type: 'error', message: 'Malformed call message' })
67
+ return
68
+ }
69
+
70
+ try {
71
+ const mod = await loadModule(moduleName)
72
+ const fn = mod[name]
73
+
74
+ if (typeof fn !== 'function') {
75
+ throw new Error(`"${name}" in ${moduleName}.server.ts is not a function`)
76
+ }
77
+
78
+ const parsedArgs = parse(args) as unknown[]
79
+ const result = await fn(...parsedArgs)
80
+
81
+ send({ id, type: 'result', data: stringify(result) })
82
+ } catch (err) {
83
+ const message = err instanceof Error ? err.message : 'Unknown error'
84
+ send({ id, type: 'error', message })
85
+ }
86
+ }
87
+ })
88
+
89
+ send({ type: 'ready' })
@@ -0,0 +1,171 @@
1
+ // Per-workspace pool of functions worker subprocesses.
2
+ //
3
+ // Each entry in the LRU cache owns one child process running
4
+ // `functions-worker.ts`, scoped to a single workspace. Workers are spawned
5
+ // lazily on first call, kept warm for `WORKER_IDLE_TTL_MS`, then reaped by
6
+ // the LRU TTL. Up to `MAX_WORKERS` slots coexist; an LRU eviction kills the
7
+ // oldest. Switching workspaces no longer kills anything — multiple tabs
8
+ // against multiple workspaces stay isolated.
9
+ //
10
+ // CWD contract: workers run with `cwd = workspacePath` (the workspace root,
11
+ // where the agent works), NOT `.widgets/`. The `.widgets/` location is
12
+ // passed to the worker as `MEI_FUNCTIONS_DIR` so it can locate `.server.ts`
13
+ // files. This is the contract documented in the widgets SKILL.
14
+ import { LRUCache } from 'lru-cache'
15
+ import { join } from 'path'
16
+
17
+ const WORKER_PATH = join(import.meta.dir, 'functions-worker.ts')
18
+ const CALL_TIMEOUT_MS = 30_000
19
+ const WORKER_IDLE_TTL_MS = 10 * 60_000
20
+ const MAX_WORKERS = 8
21
+
22
+ type Pending = {
23
+ resolve: (data: string) => void
24
+ reject: (err: Error) => void
25
+ timer: ReturnType<typeof setTimeout>
26
+ }
27
+
28
+ type Slot = {
29
+ workspacePath: string
30
+ worker: ReturnType<typeof Bun.spawn>
31
+ readyPromise: Promise<void>
32
+ pending: Map<string, Pending>
33
+ killed: boolean
34
+ }
35
+
36
+ function rejectAndClearPending(slot: Slot, reason: string) {
37
+ for (const { reject, timer } of slot.pending.values()) {
38
+ clearTimeout(timer)
39
+ reject(new Error(reason))
40
+ }
41
+ slot.pending.clear()
42
+ }
43
+
44
+ function killSlot(slot: Slot, reason: string) {
45
+ if (slot.killed) return
46
+ slot.killed = true
47
+ rejectAndClearPending(slot, reason)
48
+ try {
49
+ slot.worker.kill()
50
+ } catch {}
51
+ }
52
+
53
+ const slots = new LRUCache<string, Slot>({
54
+ max: MAX_WORKERS,
55
+ ttl: WORKER_IDLE_TTL_MS,
56
+ ttlAutopurge: true,
57
+ updateAgeOnGet: true,
58
+ dispose: slot => killSlot(slot, 'Functions worker idle-evicted')
59
+ })
60
+
61
+ function spawnSlot(workspacePath: string): Slot {
62
+ const meiDir = join(workspacePath, '.widgets')
63
+
64
+ let readyResolve: () => void = () => {}
65
+ const readyPromise = new Promise<void>(r => (readyResolve = r))
66
+
67
+ const slot: Slot = {
68
+ workspacePath,
69
+ worker: undefined as never,
70
+ readyPromise,
71
+ pending: new Map(),
72
+ killed: false
73
+ }
74
+
75
+ slot.worker = Bun.spawn([process.execPath, WORKER_PATH], {
76
+ cwd: workspacePath,
77
+ // Default to the workspace's built functions dir, but let an explicitly-set
78
+ // MEI_FUNCTIONS_DIR win (used by tests to point the worker at fixtures).
79
+ env: { ...process.env, MEI_FUNCTIONS_DIR: process.env.MEI_FUNCTIONS_DIR ?? meiDir },
80
+ stderr: 'inherit',
81
+ onExit(_proc, code) {
82
+ if (code !== 0 && code !== null) {
83
+ console.error(`[mei] functions worker for ${workspacePath} exited with code ${code}`)
84
+ }
85
+ // Mark slot dead and reject pending. Then drop from cache without
86
+ // re-disposing (the worker is already gone).
87
+ slot.killed = true
88
+ rejectAndClearPending(slot, 'Functions worker exited')
89
+ if (slots.peek(workspacePath) === slot) slots.delete(workspacePath)
90
+ },
91
+ ipc(message) {
92
+ const msg = message as { type: string; id?: string; data?: string; message?: string }
93
+
94
+ if (msg.type === 'ready') {
95
+ readyResolve()
96
+ return
97
+ }
98
+
99
+ if (msg.id) {
100
+ const p = slot.pending.get(msg.id)
101
+ if (!p) return
102
+ slot.pending.delete(msg.id)
103
+ clearTimeout(p.timer)
104
+
105
+ if (msg.type === 'result') {
106
+ p.resolve(msg.data!)
107
+ } else if (msg.type === 'error') {
108
+ p.reject(new Error(msg.message ?? 'Unknown error'))
109
+ }
110
+ }
111
+ }
112
+ })
113
+
114
+ return slot
115
+ }
116
+
117
+ function getOrSpawn(workspacePath: string): Slot {
118
+ const existing = slots.get(workspacePath)
119
+ if (existing && !existing.killed) return existing
120
+
121
+ const fresh = spawnSlot(workspacePath)
122
+ slots.set(workspacePath, fresh)
123
+ return fresh
124
+ }
125
+
126
+ export async function callFunction(
127
+ module: string,
128
+ name: string,
129
+ args: string,
130
+ workspacePath: string
131
+ ): Promise<string> {
132
+ const slot = getOrSpawn(workspacePath)
133
+ await slot.readyPromise
134
+
135
+ const id = crypto.randomUUID()
136
+ return new Promise((resolve, reject) => {
137
+ const timer = setTimeout(() => {
138
+ slot.pending.delete(id)
139
+ reject(new Error(`Function call timed out: ${module}/${name}`))
140
+ }, CALL_TIMEOUT_MS)
141
+
142
+ slot.pending.set(id, { resolve, reject, timer })
143
+
144
+ try {
145
+ slot.worker.send({ id, type: 'call', module, name, args })
146
+ } catch (err) {
147
+ slot.pending.delete(id)
148
+ clearTimeout(timer)
149
+ reject(err instanceof Error ? err : new Error('Failed to send to worker'))
150
+ }
151
+ })
152
+ }
153
+
154
+ // Kill every live worker. Called from the server's shutdown handler so a
155
+ // dev-supervisor restart (or Ctrl-C) never orphans worker child processes.
156
+ // killSlot is idempotent, so a dispose() racing in via clear() is harmless.
157
+ export function killAllWorkers() {
158
+ for (const slot of slots.values()) killSlot(slot, 'Server shutting down')
159
+ slots.clear()
160
+ }
161
+
162
+ export function reloadModules(modules: string[], workspacePath: string) {
163
+ if (modules.length === 0) return
164
+ // peek: don't refresh TTL just because files changed. If the worker was
165
+ // already idle-evicted, the next callFunction will re-spawn fresh anyway.
166
+ const slot = slots.peek(workspacePath)
167
+ if (!slot || slot.killed) return
168
+ try {
169
+ slot.worker.send({ type: 'reload', modules })
170
+ } catch {}
171
+ }
@@ -0,0 +1,83 @@
1
+ import { readdir } from 'node:fs/promises'
2
+ import { join } from 'path'
3
+
4
+ import type { WidgetConfig, WorkspaceLayout, WorkspacePreview } from '@/lib/types'
5
+
6
+ const DEFAULT: WorkspaceLayout = {
7
+ version: 1,
8
+ widgetGrid: [],
9
+ chatMode: 'sidebar'
10
+ }
11
+
12
+ const DEFAULT_WIDGET_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
13
+ const PREVIEW_COLS = 4
14
+ const EMPTY_PREVIEW: WorkspacePreview = { cols: PREVIEW_COLS, items: [] }
15
+
16
+ export function getLayoutPath(workspacePath: string): string {
17
+ return join(workspacePath, '.widgets', '.workspace.json')
18
+ }
19
+
20
+ export async function loadLayout(workspacePath: string): Promise<WorkspaceLayout> {
21
+ try {
22
+ const text = await Bun.file(getLayoutPath(workspacePath)).text()
23
+ const parsed = JSON.parse(text)
24
+ if (parsed?.version === 1) return parsed as WorkspaceLayout
25
+ } catch {}
26
+ return { ...DEFAULT }
27
+ }
28
+
29
+ export async function saveLayout(layout: WorkspaceLayout, workspacePath: string): Promise<void> {
30
+ await Bun.write(getLayoutPath(workspacePath), JSON.stringify(layout, null, 2))
31
+ }
32
+
33
+ async function scanWidgetIds(workspacePath: string): Promise<Set<string>> {
34
+ try {
35
+ const entries = await readdir(join(workspacePath, '.widgets'))
36
+ return new Set(
37
+ entries
38
+ .filter(f => /\.(tsx|ts)$/.test(f) && !f.endsWith('.server.ts'))
39
+ .map(f => f.replace(/\.tsx?$/, ''))
40
+ )
41
+ } catch {
42
+ return new Set()
43
+ }
44
+ }
45
+
46
+ export async function getWorkspacePreview(workspacePath: string): Promise<WorkspacePreview> {
47
+ try {
48
+ const layout = await loadLayout(workspacePath)
49
+ if (!Array.isArray(layout.widgetGrid) || layout.widgetGrid.length === 0) return EMPTY_PREVIEW
50
+
51
+ const validIds = await scanWidgetIds(workspacePath)
52
+ if (validIds.size === 0) return EMPTY_PREVIEW
53
+
54
+ let manifest: Record<string, WidgetConfig> = {}
55
+ try {
56
+ const manifestPath = join(workspacePath, '.widgets', '.build', 'widgets', 'manifest.json')
57
+ const parsed = JSON.parse(await Bun.file(manifestPath).text())
58
+ if (parsed && typeof parsed.config === 'object' && parsed.config !== null) {
59
+ manifest = parsed.config as Record<string, WidgetConfig>
60
+ }
61
+ } catch {}
62
+
63
+ const items = layout.widgetGrid
64
+ .map(({ i, x, y }) => {
65
+ if (!validIds.has(i)) return null
66
+ const cfg = manifest[i] ?? DEFAULT_WIDGET_CONFIG
67
+ if (
68
+ typeof x !== 'number' ||
69
+ typeof y !== 'number' ||
70
+ typeof cfg.colSpan !== 'number' ||
71
+ typeof cfg.rowSpan !== 'number'
72
+ ) {
73
+ return null
74
+ }
75
+ return { x, y, w: cfg.colSpan, h: cfg.rowSpan }
76
+ })
77
+ .filter((v): v is { x: number; y: number; w: number; h: number } => v !== null)
78
+
79
+ return { cols: PREVIEW_COLS, items }
80
+ } catch {
81
+ return EMPTY_PREVIEW
82
+ }
83
+ }
@@ -0,0 +1,242 @@
1
+ // Map OpenClaw gateway shapes into our agent-agnostic display format.
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.
12
+ //
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.
19
+ import type { Part, StreamEvent, ToolCall, ToolState, Turn, TurnMeta } from '@/lib/format'
20
+ import type { SessionInfo } from '@/lib/types'
21
+
22
+ import type {
23
+ OpenClawContentBlock,
24
+ OpenClawMessage,
25
+ OpenClawSessionDetail,
26
+ OpenClawSessionRow
27
+ } from './openclaw'
28
+ import { stripUserMessageMetadata } from './openclaw-strip'
29
+
30
+ export function toSessionInfo(row: OpenClawSessionRow, cwd: string): SessionInfo {
31
+ const summary =
32
+ row.lastMessagePreview?.trim() || row.displayName?.trim() || row.label?.trim() || ''
33
+ return {
34
+ sessionId: row.sessionId,
35
+ summary,
36
+ lastModified: row.updatedAt,
37
+ cwd
38
+ }
39
+ }
40
+
41
+ export type ToolResultInfo = { output: string; isError: boolean; toolName?: string }
42
+
43
+ // Pull a readable `output` string out of a `toolResult` message. OpenClaw
44
+ // ships content as blocks; in practice tool output is one or more text
45
+ // blocks, so we concatenate them. Non-text blocks (images, etc.) are
46
+ // represented as a `[type]` placeholder so we don't silently drop them.
47
+ function flattenToolResultContent(content: OpenClawMessage['content']): string {
48
+ if (typeof content === 'string') return content
49
+ if (!Array.isArray(content)) return ''
50
+ return content
51
+ .map(block => {
52
+ if (!block || typeof block !== 'object') return ''
53
+ if (block.type === 'text') {
54
+ const v = (block as { text?: unknown }).text
55
+ return typeof v === 'string' ? v : ''
56
+ }
57
+ return `[${block.type}]`
58
+ })
59
+ .filter(Boolean)
60
+ .join('\n')
61
+ }
62
+
63
+ export function toolResultFromMessage(
64
+ msg: OpenClawMessage
65
+ ): { id: string; info: ToolResultInfo } | null {
66
+ if (msg.role !== 'toolResult') return null
67
+ const id = (msg as { toolCallId?: unknown }).toolCallId
68
+ if (typeof id !== 'string') return null
69
+ const toolName = (msg as { toolName?: unknown }).toolName
70
+ return {
71
+ id,
72
+ info: {
73
+ output: flattenToolResultContent(msg.content),
74
+ isError: (msg as { isError?: unknown }).isError === true,
75
+ ...(typeof toolName === 'string' ? { toolName } : {})
76
+ }
77
+ }
78
+ }
79
+
80
+ function collectToolResults(messages: OpenClawMessage[]): Map<string, ToolResultInfo> {
81
+ const map = new Map<string, ToolResultInfo>()
82
+ for (const msg of messages) {
83
+ const r = toolResultFromMessage(msg)
84
+ if (r) map.set(r.id, r.info)
85
+ }
86
+ return map
87
+ }
88
+
89
+ function blockToPart(
90
+ block: OpenClawContentBlock,
91
+ role: OpenClawMessage['role'],
92
+ results: Map<string, ToolResultInfo>
93
+ ): Part | null {
94
+ switch (block.type) {
95
+ case 'text': {
96
+ const raw =
97
+ typeof (block as { text?: unknown }).text === 'string'
98
+ ? (block as { text: string }).text
99
+ : ''
100
+ const text = role === 'user' ? stripUserMessageMetadata(raw) : raw
101
+ if (!text) return null
102
+ return { type: 'text', text }
103
+ }
104
+ case 'thinking': {
105
+ const text =
106
+ typeof (block as { thinking?: unknown }).thinking === 'string'
107
+ ? (block as { thinking: string }).thinking
108
+ : ''
109
+ if (!text) return null
110
+ const sig = (block as { thinkingSignature?: unknown }).thinkingSignature
111
+ return {
112
+ type: 'reasoning',
113
+ text,
114
+ ...(typeof sig === 'string' ? { signature: sig } : {})
115
+ }
116
+ }
117
+ case 'toolCall': {
118
+ const id = (block as { id?: unknown }).id
119
+ const name = (block as { name?: unknown }).name
120
+ if (typeof id !== 'string' || typeof name !== 'string') return null
121
+ const result = results.get(id)
122
+ let state: ToolState = 'pending'
123
+ if (result) state = result.isError ? 'error' : 'success'
124
+ const call: ToolCall = {
125
+ toolCallId: id,
126
+ name,
127
+ caller: 'model',
128
+ provider: 'openclaw',
129
+ state,
130
+ input: (block as { arguments?: unknown }).arguments
131
+ }
132
+ if (result) {
133
+ if (result.isError) call.errorText = result.output
134
+ else call.output = result.output
135
+ }
136
+ return { type: 'tool-call', call }
137
+ }
138
+ default:
139
+ return null
140
+ }
141
+ }
142
+
143
+ // Pull assistant-side metadata (model, provider, usage, stopReason) into our
144
+ // per-turn meta slot. OpenClaw only ships these on assistant rows.
145
+ function extractTurnMeta(msg: OpenClawMessage): TurnMeta | undefined {
146
+ if (msg.role !== 'assistant') return undefined
147
+ const m = msg as Record<string, unknown>
148
+ const meta: TurnMeta = {}
149
+ if (typeof m.model === 'string') meta.model = m.model
150
+ if (typeof m.provider === 'string') meta.provider = m.provider
151
+ if (typeof m.stopReason === 'string') meta.stopReason = m.stopReason
152
+ if (m.usage && typeof m.usage === 'object') {
153
+ const u = m.usage as Record<string, unknown>
154
+ const usage: NonNullable<TurnMeta['usage']> = {}
155
+ if (typeof u.input === 'number') usage.inputTokens = u.input
156
+ if (typeof u.output === 'number') usage.outputTokens = u.output
157
+ if (typeof u.totalTokens === 'number') usage.totalTokens = u.totalTokens
158
+ const cost = u.cost as Record<string, unknown> | undefined
159
+ if (cost && typeof cost.total === 'number') usage.costUsd = cost.total
160
+ if (Object.keys(usage).length > 0) meta.usage = usage
161
+ }
162
+ return Object.keys(meta).length > 0 ? meta : undefined
163
+ }
164
+
165
+ // Build a Turn from one OpenClaw message. `idx` is only used as a fallback
166
+ // suffix when the message lacks `__openclaw.id` (rare — the gateway emits it
167
+ // on durable rows). For streaming we reject id-less messages upstream so we
168
+ // never see that case live.
169
+ export function messageToTurn(
170
+ msg: OpenClawMessage,
171
+ sessionKey: string,
172
+ idx: number,
173
+ results: Map<string, ToolResultInfo>
174
+ ): Turn | null {
175
+ if (msg.role !== 'user' && msg.role !== 'assistant') return null
176
+ const blocks: OpenClawContentBlock[] = Array.isArray(msg.content)
177
+ ? msg.content
178
+ : typeof msg.content === 'string'
179
+ ? [{ type: 'text', text: msg.content }]
180
+ : []
181
+ const parts = blocks
182
+ .map(b => blockToPart(b, msg.role, results))
183
+ .filter((p): p is Part => p !== null)
184
+ if (parts.length === 0) return null
185
+ const ocId = msg.__openclaw?.id
186
+ const seq = msg.__openclaw?.seq
187
+ const meta = extractTurnMeta(msg)
188
+ // Inter-session provenance — exposed on the wire so the UI can render or
189
+ // collapse agent-to-agent prompts differently from human input.
190
+ const provenance = (msg as { provenance?: unknown }).provenance
191
+ const isInterSession =
192
+ provenance &&
193
+ typeof provenance === 'object' &&
194
+ (provenance as { kind?: unknown }).kind === 'inter_session'
195
+ return {
196
+ id: ocId != null ? `openclaw:${sessionKey}:${ocId}` : `openclaw:${sessionKey}:${idx}`,
197
+ role: msg.role,
198
+ origin: { kind: msg.role === 'user' && isInterSession ? 'inter-session' : 'user-input' },
199
+ parts,
200
+ timestamp:
201
+ typeof msg.timestamp === 'number' ? new Date(msg.timestamp).toISOString() : undefined,
202
+ ...(typeof seq === 'number' ? { seq } : {}),
203
+ ...(meta ? { meta } : {})
204
+ }
205
+ }
206
+
207
+ export function toStreamEvents(
208
+ detail: OpenClawSessionDetail | null,
209
+ sessionKey = ''
210
+ ): StreamEvent[] {
211
+ if (!detail?.messages) return []
212
+ const results = collectToolResults(detail.messages)
213
+ const turns = detail.messages
214
+ .map((m, i) => messageToTurn(m, sessionKey, i, results))
215
+ .filter((t): t is Turn => t !== null)
216
+ return turns.map(turn => ({ kind: 'turn', turn }))
217
+ }
218
+
219
+ // Find every assistant message that has a `toolCall` block with `toolCallId`.
220
+ // Used by the live session: when a `toolResult` lands, we re-emit the prior
221
+ // assistant turns that referenced that id, so the result folds into the card.
222
+ export function findToolCallOwners(
223
+ messages: Iterable<OpenClawMessage>,
224
+ toolCallId: string
225
+ ): OpenClawMessage[] {
226
+ const owners: OpenClawMessage[] = []
227
+ for (const m of messages) {
228
+ if (m.role !== 'assistant' || !Array.isArray(m.content)) continue
229
+ for (const b of m.content) {
230
+ if (
231
+ b &&
232
+ typeof b === 'object' &&
233
+ b.type === 'toolCall' &&
234
+ (b as { id?: unknown }).id === toolCallId
235
+ ) {
236
+ owners.push(m)
237
+ break
238
+ }
239
+ }
240
+ }
241
+ return owners
242
+ }