moi-computer 0.0.3 → 0.1.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.
- package/bunfig.toml +4 -0
- package/client/api/workspaces.ts +277 -6
- package/client/assets/mcp/agentation.png +0 -0
- package/client/assets/mcp/airtable.png +0 -0
- package/client/assets/mcp/apollo.png +0 -0
- package/client/assets/mcp/asana.png +0 -0
- package/client/assets/mcp/box.png +0 -0
- package/client/assets/mcp/chrome.svg +33 -0
- package/client/assets/mcp/clickup.png +0 -0
- package/client/assets/mcp/cloudflare.png +0 -0
- package/client/assets/mcp/context7.png +0 -0
- package/client/assets/mcp/datadog.png +0 -0
- package/client/assets/mcp/dropbox.png +0 -0
- package/client/assets/mcp/elevenlabs.png +0 -0
- package/client/assets/mcp/exa.png +0 -0
- package/client/assets/mcp/firecrawl.png +0 -0
- package/client/assets/mcp/gmail.png +0 -0
- package/client/assets/mcp/googlecalendar.png +0 -0
- package/client/assets/mcp/googledrive.png +0 -0
- package/client/assets/mcp/grafana.png +0 -0
- package/client/assets/mcp/huggingface.png +0 -0
- package/client/assets/mcp/intercom.png +0 -0
- package/client/assets/mcp/monday.png +0 -0
- package/client/assets/mcp/mongodb.png +0 -0
- package/client/assets/mcp/paper.png +0 -0
- package/client/assets/mcp/paypal.png +0 -0
- package/client/assets/mcp/perplexity.png +0 -0
- package/client/assets/mcp/postgresql.png +0 -0
- package/client/assets/mcp/posthog.png +0 -0
- package/client/assets/mcp/puppeteer.png +0 -0
- package/client/assets/mcp/railway.png +0 -0
- package/client/assets/mcp/redis.png +0 -0
- package/client/assets/mcp/salesforce.png +0 -0
- package/client/assets/mcp/shopify.png +0 -0
- package/client/assets/mcp/snowflake.png +0 -0
- package/client/assets/mcp/telegram.png +0 -0
- package/client/assets/mcp/twilio.png +0 -0
- package/client/assets/mcp/zapier.png +0 -0
- package/client/components/App.tsx +7 -1
- package/client/components/ChatInput.tsx +194 -13
- package/client/components/ChatPanel.tsx +116 -47
- package/client/components/ChatPopup.tsx +1 -1
- package/client/components/IconMcp.tsx +21 -0
- package/client/components/McpMenu.tsx +125 -0
- package/client/components/ModelPicker.tsx +147 -0
- package/client/components/Scratchpad.tsx +775 -0
- package/client/components/ShimmerText.tsx +20 -0
- package/client/components/ThreadSelector.tsx +2 -2
- package/client/components/TurnView.tsx +111 -531
- package/client/components/WidgetShell.tsx +1 -1
- package/client/components/WorkspacesPage.tsx +12 -4
- package/client/components/layout/SidebarLayout.tsx +18 -9
- package/client/components/playground/ToolCallsPage.tsx +81 -0
- package/client/components/routes/workspace/[id].tsx +534 -141
- package/client/components/routes/workspace/create.tsx +155 -0
- package/client/components/settings/IconPicker.tsx +590 -0
- package/client/components/settings/SettingsPages.tsx +307 -0
- package/client/components/settings/WorkspaceSettings.tsx +92 -0
- package/client/components/tool-group/CodeBlock.tsx +41 -0
- package/client/components/tool-group/Collapse.tsx +28 -0
- package/client/components/tool-group/ReadImagePreview.tsx +46 -0
- package/client/components/tool-group/SubagentCard.tsx +135 -0
- package/client/components/tool-group/TimelineRow.tsx +147 -0
- package/client/components/tool-group/ToolCallGroup.tsx +231 -0
- package/client/components/tool-group/ToolOutput.tsx +139 -0
- package/client/components/tool-group/detect.ts +93 -0
- package/client/components/tool-group/fixtures.ts +315 -0
- package/client/components/tool-group/format.ts +211 -0
- package/client/components/tool-group/index.ts +9 -0
- package/client/components/ui/dialog.tsx +58 -0
- package/client/components/ui/hover-card.tsx +44 -0
- package/client/components/ui/switch.tsx +23 -0
- package/client/components/ui/tooltip.tsx +54 -0
- package/client/externalize-react.ts +6 -0
- package/client/hooks/useApplet.ts +117 -0
- package/client/hooks/useChat.ts +162 -62
- package/client/hooks/useMeiEvents.ts +9 -2
- package/client/hooks/useStickToBottom.ts +86 -0
- package/client/hooks/useWorkspaceTheme.ts +8 -2
- package/client/index.css +48 -2
- package/client/index.html +9 -5
- package/client/index.tsx +29 -2
- package/client/lib/WorkspaceContext.tsx +5 -8
- package/client/lib/WorkspaceLayoutContext.tsx +30 -10
- package/client/lib/applet-cache.ts +54 -0
- package/client/lib/connection.ts +237 -0
- package/client/lib/flags.ts +10 -0
- package/client/lib/mcp-icons.ts +142 -10
- package/client/lib/preview-turn.ts +37 -0
- package/client/lib/render-icon.ts +173 -0
- package/client/lib/scratch-executor.ts +20 -0
- package/client/lib/uploads.ts +18 -0
- package/client/main.tsx +5 -0
- package/client/store/live.ts +282 -0
- package/client/structured-clone-shim.ts +14 -0
- package/client/theme.css +2 -2
- package/client/vendor/emojibase/en/data.json +1 -0
- package/client/vendor/emojibase/en/messages.json +1 -0
- package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
- package/client/vendor/react/development/_impl/react-dom.js +223 -0
- package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
- package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
- package/client/vendor/react/development/_impl/react.js +863 -0
- package/client/vendor/react/development/react-dom-client.js +6 -0
- package/client/vendor/react/development/react-dom.js +17 -0
- package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
- package/client/vendor/react/development/react-jsx-runtime.js +6 -0
- package/client/vendor/react/development/react.js +47 -0
- package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
- package/client/vendor/react/production/_impl/react-dom.js +184 -0
- package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
- package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
- package/client/vendor/react/production/_impl/react.js +428 -0
- package/client/vendor/react/production/react-dom-client.js +6 -0
- package/client/vendor/react/production/react-dom.js +17 -0
- package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
- package/client/vendor/react/production/react-jsx-runtime.js +6 -0
- package/client/vendor/react/production/react.js +47 -0
- package/dist/agentation-4s0nn45p.png +0 -0
- package/dist/airtable-hsa66v6q.png +0 -0
- package/dist/apollo-2ed5dy2d.png +0 -0
- package/dist/asana-tvgtwbx2.png +0 -0
- package/dist/box-w3n36t5g.png +0 -0
- package/dist/chrome-tspm94rw.svg +33 -0
- package/dist/chunk-kc6e9nd4.css +1 -0
- package/dist/chunk-yf3p7qg7.js +673 -0
- package/dist/clickup-qqrqqvqb.png +0 -0
- package/dist/cloudflare-j9p931v6.png +0 -0
- package/dist/context7-8ht0xjfy.png +0 -0
- package/dist/datadog-70ne3yzt.png +0 -0
- package/dist/dropbox-4m5s9mgr.png +0 -0
- package/dist/elevenlabs-2nzzej1t.png +0 -0
- package/dist/exa-qqj3vr0x.png +0 -0
- package/dist/firecrawl-w2t8nehx.png +0 -0
- package/dist/gmail-sg6a5v3x.png +0 -0
- package/dist/googlecalendar-nqhh2v7r.png +0 -0
- package/dist/googledrive-6s8xyab7.png +0 -0
- package/dist/grafana-1yfsnwr6.png +0 -0
- package/dist/huggingface-kxzaxj83.png +0 -0
- package/dist/index.html +10 -6
- package/dist/intercom-td763jt8.png +0 -0
- package/dist/monday-jdbs4wwf.png +0 -0
- package/dist/mongodb-emzxvhd5.png +0 -0
- package/dist/paper-zbt34fab.png +0 -0
- package/dist/paypal-kwwf7xsc.png +0 -0
- package/dist/perplexity-4y63rxvj.png +0 -0
- package/dist/postgresql-qsspbsr1.png +0 -0
- package/dist/posthog-sphppc4w.png +0 -0
- package/dist/puppeteer-2xjt1a9b.png +0 -0
- package/dist/railway-834de8d2.png +0 -0
- package/dist/redis-spm6w2m1.png +0 -0
- package/dist/salesforce-1mk56v4z.png +0 -0
- package/dist/shopify-90dadaav.png +0 -0
- package/dist/snowflake-hfpykpgy.png +0 -0
- package/dist/telegram-v6tjyrs7.png +0 -0
- package/dist/twilio-dpyjdwpj.png +0 -0
- package/dist/zapier-p67qfch0.png +0 -0
- package/lib/attachment-note.ts +48 -0
- package/lib/claude-adapter.ts +219 -29
- package/lib/format.ts +32 -0
- package/lib/types.ts +314 -6
- package/package.json +10 -5
- package/server/CLAUDE.md +3 -0
- package/server/agent.ts +25 -118
- package/server/api.ts +593 -0
- package/server/applets.ts +396 -0
- package/server/build-applet.ts +580 -0
- package/server/cc-session.ts +611 -0
- package/server/cli-colors.ts +17 -0
- package/server/cli-ui.ts +52 -0
- package/server/cli.ts +964 -72
- package/server/control.ts +166 -19
- package/server/debug.ts +10 -0
- package/server/events.ts +24 -0
- package/server/functions-worker.ts +18 -2
- package/server/functions.ts +59 -12
- package/server/icon.ts +13 -0
- package/server/layout.ts +25 -3
- package/server/mcp.ts +125 -0
- package/server/moi-scaffold.ts +85 -0
- package/server/openclaw-session.ts +41 -10
- package/server/openclaw.ts +22 -0
- package/server/preview.ts +70 -0
- package/server/registry.ts +32 -2
- package/server/scratchpad-executor.ts +380 -0
- package/server/scratchpad-relay.ts +45 -0
- package/server/scratchpad.ts +171 -0
- package/server/skill-version.ts +146 -0
- package/server/skills-template.ts +6 -1
- package/server/state.ts +22 -36
- package/server/static.ts +23 -0
- package/server/status.ts +94 -0
- package/server/thread-config.ts +125 -0
- package/server/uploads.ts +0 -0
- package/server/vendor.ts +63 -0
- package/server/views.ts +0 -0
- package/server/web.ts +108 -253
- package/server/widgets.ts +52 -142
- package/server/workspace-config.ts +37 -0
- package/server/workspace-env.ts +407 -0
- package/server/workspace-init.ts +66 -0
- package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
- package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
- package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
- package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
- package/client/hooks/useWidget.ts +0 -72
- package/client/hooks/useWidgetList.ts +0 -30
- package/client/lib/ws.ts +0 -129
- package/client/store/chat.tsx +0 -162
- package/dist/chunk-4615fa69.js +0 -67
- package/dist/chunk-582xmy05.css +0 -1
- package/server/build-widget.ts +0 -343
- package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
- package/workspace/.claude/skills/widgets/SKILL.md +0 -176
package/server/api.ts
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { Hono } from 'hono'
|
|
2
|
+
import { serveStatic } from 'hono/bun'
|
|
3
|
+
import { createMiddleware } from 'hono/factory'
|
|
4
|
+
import { existsSync } from 'node:fs'
|
|
5
|
+
import { basename, join, resolve } from 'node:path'
|
|
6
|
+
|
|
7
|
+
import type {
|
|
8
|
+
EnvScope,
|
|
9
|
+
UploadInfo,
|
|
10
|
+
WorkspaceEntry,
|
|
11
|
+
WorkspaceModels,
|
|
12
|
+
WorkspaceType
|
|
13
|
+
} from '@/lib/types'
|
|
14
|
+
|
|
15
|
+
import { getClaudeModels } from './agent'
|
|
16
|
+
import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
|
|
17
|
+
import { restartWorkspaceSessions } from './cc-session'
|
|
18
|
+
import { callFunction, parseFunctionPath, restartWorker } from './functions'
|
|
19
|
+
import { processIcon } from './icon'
|
|
20
|
+
import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from './layout'
|
|
21
|
+
import { getMcpStatus } from './mcp'
|
|
22
|
+
import { publishEvent } from './events'
|
|
23
|
+
import { getOpenClawModels, getOpenClawSessionMessages, getOpenClawSessions } from './openclaw'
|
|
24
|
+
import { toSessionInfo, toStreamEvents } from './openclaw-adapter'
|
|
25
|
+
import { ensureOpenClawSessionLive, getLiveOpenClawEvents } from './openclaw-session'
|
|
26
|
+
import {
|
|
27
|
+
discoverWorkspaces,
|
|
28
|
+
getWorkspace,
|
|
29
|
+
listWorkspaces,
|
|
30
|
+
registerWorkspace,
|
|
31
|
+
removeWorkspace,
|
|
32
|
+
tildify
|
|
33
|
+
} from './registry'
|
|
34
|
+
import { loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
|
|
35
|
+
import { DIST_DIR, prebuilt } from './static'
|
|
36
|
+
import { getSessionEvents, getSessions } from './state'
|
|
37
|
+
import { getThreadConfig, saveThreadConfig } from './thread-config'
|
|
38
|
+
import type { ThreadConfigPatch } from './thread-config'
|
|
39
|
+
import { serveWorkspaceImagePreview } from './preview'
|
|
40
|
+
import { MAX_UPLOAD_BYTES, addUpload, getUpload } from './uploads'
|
|
41
|
+
import { collectViewRequiredEnv, listViews, serveView } from './views'
|
|
42
|
+
import { collectRequiredEnv, listWidgets, serveWidget } from './widgets'
|
|
43
|
+
import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
|
|
44
|
+
import {
|
|
45
|
+
CREATED_WORKSPACES_ROOT,
|
|
46
|
+
provisionWorkspace,
|
|
47
|
+
validateWorkspaceFolderName
|
|
48
|
+
} from './workspace-init'
|
|
49
|
+
import {
|
|
50
|
+
getWorkspaceEnvView,
|
|
51
|
+
isValidEnvKey,
|
|
52
|
+
isValidScope,
|
|
53
|
+
updateWorkspaceEnv
|
|
54
|
+
} from './workspace-env'
|
|
55
|
+
import type { EnvUpdate } from './workspace-env'
|
|
56
|
+
|
|
57
|
+
// The resolved workspace is stashed on the context by `withWorkspace`, so every
|
|
58
|
+
// `/api/workspaces/:id/*` handler can read it without re-querying the registry.
|
|
59
|
+
type ApiEnv = { Variables: { ws: WorkspaceEntry } }
|
|
60
|
+
|
|
61
|
+
// The env "required" view aggregates `config.requiredEnv` declared by both
|
|
62
|
+
// widgets and views, each key mapped to the bundle ids that asked for it.
|
|
63
|
+
async function requiredEnvFor(workspacePath: string): Promise<Record<string, string[]>> {
|
|
64
|
+
const [widgets, views] = await Promise.all([
|
|
65
|
+
collectRequiredEnv(workspacePath),
|
|
66
|
+
collectViewRequiredEnv(workspacePath)
|
|
67
|
+
])
|
|
68
|
+
const out: Record<string, string[]> = {}
|
|
69
|
+
for (const map of [widgets, views]) {
|
|
70
|
+
for (const [key, ids] of Object.entries(map)) {
|
|
71
|
+
out[key] = [...(out[key] ?? []), ...ids]
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return out
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function handleFunctionCall(
|
|
78
|
+
req: Request,
|
|
79
|
+
tail: string,
|
|
80
|
+
workspacePath: string
|
|
81
|
+
): Promise<Response> {
|
|
82
|
+
// Module keys may contain slashes (`widgets/hello/getWeather`), so the
|
|
83
|
+
// tail is parsed on the last slash — see parseFunctionPath.
|
|
84
|
+
const parsed = parseFunctionPath(tail)
|
|
85
|
+
if (!parsed) {
|
|
86
|
+
return new Response('Invalid module or function name', { status: 400 })
|
|
87
|
+
}
|
|
88
|
+
const { module, name } = parsed
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
const contentLength = Number(req.headers.get('content-length') ?? 0)
|
|
92
|
+
if (contentLength > 1_000_000) {
|
|
93
|
+
return new Response('Request body too large', { status: 413 })
|
|
94
|
+
}
|
|
95
|
+
const args = await req.text()
|
|
96
|
+
const result = await callFunction(module, name, args, workspacePath)
|
|
97
|
+
return new Response(result, { headers: { 'Content-Type': 'application/json' } })
|
|
98
|
+
} catch (err) {
|
|
99
|
+
const message = err instanceof Error ? err.message : 'Unknown error'
|
|
100
|
+
return new Response(message, { status: 500 })
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Resolve `:id` to a registered workspace once, 404 if unknown, and stash it on
|
|
105
|
+
// the context. Mounted on the single-workspace sub-app so every nested route
|
|
106
|
+
// shares the lookup instead of repeating `getWorkspace(...) ?? 404`.
|
|
107
|
+
const withWorkspace = createMiddleware<ApiEnv>(async (c, next) => {
|
|
108
|
+
const ws = await getWorkspace(c.req.param('id'))
|
|
109
|
+
if (!ws) return c.text('Workspace not found', 404)
|
|
110
|
+
c.set('ws', ws)
|
|
111
|
+
await next()
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
// ---- single workspace: /api/workspaces/:id/* --------------------------------
|
|
115
|
+
const one = new Hono<ApiEnv>()
|
|
116
|
+
one.use('*', withWorkspace)
|
|
117
|
+
|
|
118
|
+
one.get('/preview', async c => {
|
|
119
|
+
return c.json(await getWorkspacePreview(c.get('ws').path))
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
one.get('/widgets', c => listWidgets(c.get('ws').path))
|
|
123
|
+
|
|
124
|
+
// Widget bundle: the compiled ESM for one widget, dynamically imported by the
|
|
125
|
+
// client (useWidget). Sits beside the GET .../widgets list above — the exact
|
|
126
|
+
// path lists, `/*` serves a file from the bundle dir (`<name>/<file>`:
|
|
127
|
+
// index.js, a chunk, or a hashed asset).
|
|
128
|
+
one.get('/widgets/*', c => {
|
|
129
|
+
const id = c.req.param('id')
|
|
130
|
+
const { name, file } = parseAppletTail(c.req.url, id, 'widgets')
|
|
131
|
+
if (!name) return c.text('Not found', 404)
|
|
132
|
+
return serveWidget(name, file, c.get('ws').path, apiBaseFor(id))
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
// Views — full-screen agent apps. Mirrors the widget pair above: the exact path
|
|
136
|
+
// lists (in manifest/nav order), `/*` serves one bundle file.
|
|
137
|
+
one.get('/views', c => listViews(c.get('ws').path))
|
|
138
|
+
|
|
139
|
+
one.get('/views/*', c => {
|
|
140
|
+
const id = c.req.param('id')
|
|
141
|
+
const { name, file } = parseAppletTail(c.req.url, id, 'views')
|
|
142
|
+
if (!name) return c.text('Not found', 404)
|
|
143
|
+
return serveView(name, file, c.get('ws').path, apiBaseFor(id))
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
// Workspace file stream — an applet's `fileUrl(path)` resolves here. Streams a
|
|
147
|
+
// media file from the workspace root (range-enabled). Guarded: traversal and
|
|
148
|
+
// dotfiles (`.env`, `.moi`, `.git`) are rejected and only media/asset extensions
|
|
149
|
+
// are allowed — the workspace holds secrets, and this route is unauthenticated.
|
|
150
|
+
// localhost binding is NOT the guard.
|
|
151
|
+
one.get('/fs/*', c => {
|
|
152
|
+
const id = c.req.param('id')
|
|
153
|
+
const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${id}/fs/`)[1] ?? ''
|
|
154
|
+
return serveWorkspaceFile(c.get('ws').path, tail, c.req.header('range'))
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
// Applet RPC — the home for server-function calls from a bundle. The bundle's
|
|
158
|
+
// sentinel base resolves to `/api/workspaces/<id>`, so it POSTs to
|
|
159
|
+
// `…/rpc/<module>/<fn>`.
|
|
160
|
+
one.post('/rpc/*', c => {
|
|
161
|
+
const id = c.req.param('id')
|
|
162
|
+
const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${id}/rpc/`)[1] ?? ''
|
|
163
|
+
return handleFunctionCall(c.req.raw, tail, c.get('ws').path)
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
// Downscaled image preview of a workspace file. The chat's expanded tool rows
|
|
167
|
+
// use this to show the picture an agent `Read` — same guards as /fs/ above,
|
|
168
|
+
// images only, resized server-side (see server/preview.ts).
|
|
169
|
+
one.get('/preview/*', c => {
|
|
170
|
+
const id = c.req.param('id')
|
|
171
|
+
const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${id}/preview/`)[1] ?? ''
|
|
172
|
+
return serveWorkspaceImagePreview(c.get('ws').path, tail, c.req.header('if-none-match'))
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
// Chat attachments. The composer POSTs files here (drag/drop, paste, or the
|
|
176
|
+
// attach button) ahead of sending; we process + stash them and hand back opaque
|
|
177
|
+
// upload ids the chat WS frame references. Images are downscaled and inlined as
|
|
178
|
+
// vision blocks at send time; other files are referenced by a temp path. See
|
|
179
|
+
// server/uploads.ts and dev/file-uploads.md.
|
|
180
|
+
one.post('/uploads', async c => {
|
|
181
|
+
const id = c.req.param('id')
|
|
182
|
+
let form: FormData
|
|
183
|
+
try {
|
|
184
|
+
form = await c.req.formData()
|
|
185
|
+
} catch {
|
|
186
|
+
return c.text('Expected multipart/form-data', 400)
|
|
187
|
+
}
|
|
188
|
+
const files = form.getAll('files').filter((f): f is File => f instanceof File)
|
|
189
|
+
if (files.length === 0) return c.text('No files', 400)
|
|
190
|
+
if (files.length > 20) return c.text('Too many files (max 20)', 400)
|
|
191
|
+
|
|
192
|
+
const out: UploadInfo[] = []
|
|
193
|
+
for (const file of files) {
|
|
194
|
+
if (file.size > MAX_UPLOAD_BYTES) {
|
|
195
|
+
return c.text(`"${file.name}" is too large (max ${MAX_UPLOAD_BYTES / (1024 * 1024)} MB)`, 413)
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
const bytes = Buffer.from(await file.arrayBuffer())
|
|
199
|
+
out.push(
|
|
200
|
+
await addUpload({
|
|
201
|
+
workspaceId: id,
|
|
202
|
+
filename: file.name || 'file',
|
|
203
|
+
mediaType: file.type || 'application/octet-stream',
|
|
204
|
+
bytes
|
|
205
|
+
})
|
|
206
|
+
)
|
|
207
|
+
} catch (err) {
|
|
208
|
+
const message = err instanceof Error ? err.message : 'Failed to process upload'
|
|
209
|
+
return c.text(`"${file.name}": ${message}`, 400)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return c.json(out)
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
// Serve an upload's bytes back. Display parts reference this URL instead of a
|
|
216
|
+
// base64 data URL so the transcript broadcast / client cache stay small. The id
|
|
217
|
+
// is content-addressed (sha256), so the response is immutable while it lives —
|
|
218
|
+
// let the browser cache it for the store's TTL.
|
|
219
|
+
one.get('/uploads/:uploadId', c => {
|
|
220
|
+
const u = getUpload(c.req.param('id'), c.req.param('uploadId'))
|
|
221
|
+
if (!u) return c.text('Not found or expired', 404)
|
|
222
|
+
const body: BodyInit | null = u.data ?? (u.path ? Bun.file(u.path) : null)
|
|
223
|
+
if (!body) return c.text('Not found or expired', 404)
|
|
224
|
+
return new Response(body, {
|
|
225
|
+
headers: {
|
|
226
|
+
'Content-Type': u.mediaType,
|
|
227
|
+
'Content-Disposition': `inline; filename="${u.filename.replaceAll('"', '')}"`,
|
|
228
|
+
'Cache-Control': 'private, max-age=1800, immutable'
|
|
229
|
+
}
|
|
230
|
+
})
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
one.get('/sessions', async c => {
|
|
234
|
+
const ws = c.get('ws')
|
|
235
|
+
if (ws.type === 'openclaw') {
|
|
236
|
+
const rows = await getOpenClawSessions(ws.path, ws.agentId)
|
|
237
|
+
return c.json(rows.map(r => toSessionInfo(r, ws.path)))
|
|
238
|
+
}
|
|
239
|
+
return c.json(await getSessions(ws.path))
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
one.get('/sessions/:sessionId/events', async c => {
|
|
243
|
+
const ws = c.get('ws')
|
|
244
|
+
const id = c.req.param('id')
|
|
245
|
+
const sessionId = c.req.param('sessionId')
|
|
246
|
+
if (ws.type === 'openclaw') {
|
|
247
|
+
// Prefer the live view if we already hold one — keeps REST + WS in
|
|
248
|
+
// agreement for any reload that lands while a run is active. The first cold
|
|
249
|
+
// call also primes the live subscription so subsequent WS frames upsert into
|
|
250
|
+
// the same view.
|
|
251
|
+
const live = getLiveOpenClawEvents(id, sessionId)
|
|
252
|
+
if (live) return c.json(live)
|
|
253
|
+
if (ws.agentId) {
|
|
254
|
+
try {
|
|
255
|
+
const evs = await ensureOpenClawSessionLive({
|
|
256
|
+
workspaceId: id,
|
|
257
|
+
workspacePath: ws.path,
|
|
258
|
+
agentId: ws.agentId,
|
|
259
|
+
sessionId
|
|
260
|
+
})
|
|
261
|
+
return c.json(evs)
|
|
262
|
+
} catch {
|
|
263
|
+
// fall through to static path
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const preview = await getOpenClawSessionMessages(sessionId, ws.path, ws.agentId)
|
|
267
|
+
return c.json(toStreamEvents(preview))
|
|
268
|
+
}
|
|
269
|
+
return c.json(await getSessionEvents(sessionId, ws.path))
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
// Per-thread agent settings (model + reasoning effort). GET returns the stored
|
|
273
|
+
// config ({} for threads that never overrode the workspace defaults); PUT patches
|
|
274
|
+
// it (a field as `null` clears it, omitted leaves it). The change takes effect on
|
|
275
|
+
// the thread's next message — see ClientMessage/effort handling in cc-session.
|
|
276
|
+
one.get('/sessions/:sessionId/config', async c => {
|
|
277
|
+
return c.json(await getThreadConfig(c.get('ws').path, c.req.param('sessionId')))
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
one.put('/sessions/:sessionId/config', async c => {
|
|
281
|
+
const body = await c.req.json().catch(() => null)
|
|
282
|
+
if (typeof body !== 'object' || body === null) {
|
|
283
|
+
return c.text('Expected a JSON object', 400)
|
|
284
|
+
}
|
|
285
|
+
const patch: ThreadConfigPatch = {}
|
|
286
|
+
const record = body as Record<string, unknown>
|
|
287
|
+
for (const key of ['model', 'effort'] as const) {
|
|
288
|
+
if (!(key in record)) continue
|
|
289
|
+
const value = record[key]
|
|
290
|
+
if (value !== null && typeof value !== 'string') {
|
|
291
|
+
return c.text(`${key} must be a string or null`, 400)
|
|
292
|
+
}
|
|
293
|
+
patch[key] = value
|
|
294
|
+
}
|
|
295
|
+
return c.json(await saveThreadConfig(c.get('ws').path, c.req.param('sessionId'), patch))
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
one.get('/mcp', async c => {
|
|
299
|
+
return c.json(await getMcpStatus(c.get('ws').path))
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
// Per-workspace env vars. GET returns the effective view (discovered `.env` + UI
|
|
303
|
+
// custom secrets + scopes + declared-required keys; values masked).
|
|
304
|
+
one.get('/env', async c => {
|
|
305
|
+
const ws = c.get('ws')
|
|
306
|
+
const required = await requiredEnvFor(ws.path)
|
|
307
|
+
return c.json(await getWorkspaceEnvView(ws.path, required))
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
// PUT patches custom secrets (set/remove/scopes) and/or the inheritDotenv mode,
|
|
311
|
+
// then reaps the workspace's function worker and idle agent sessions so the next
|
|
312
|
+
// call/message picks up the change (env is frozen at spawn — a hard restart is
|
|
313
|
+
// the only way).
|
|
314
|
+
one.put('/env', async c => {
|
|
315
|
+
const ws = c.get('ws')
|
|
316
|
+
const body = await c.req.json().catch(() => null)
|
|
317
|
+
if (!body || typeof body !== 'object') {
|
|
318
|
+
return c.text('Bad request', 400)
|
|
319
|
+
}
|
|
320
|
+
const patch: EnvUpdate = {}
|
|
321
|
+
if (body.set !== undefined) {
|
|
322
|
+
if (typeof body.set !== 'object' || body.set === null) {
|
|
323
|
+
return c.text('set must be an object', 400)
|
|
324
|
+
}
|
|
325
|
+
for (const [k, v] of Object.entries(body.set)) {
|
|
326
|
+
if (!isValidEnvKey(k)) return c.text(`Invalid env key: ${k}`, 400)
|
|
327
|
+
if (typeof v !== 'string') {
|
|
328
|
+
return c.text(`Value for ${k} must be a string`, 400)
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
patch.set = body.set as Record<string, string>
|
|
332
|
+
}
|
|
333
|
+
if (body.remove !== undefined) {
|
|
334
|
+
if (!Array.isArray(body.remove) || body.remove.some((k: unknown) => typeof k !== 'string')) {
|
|
335
|
+
return c.text('remove must be an array of strings', 400)
|
|
336
|
+
}
|
|
337
|
+
patch.remove = body.remove as string[]
|
|
338
|
+
}
|
|
339
|
+
if (body.scopes !== undefined) {
|
|
340
|
+
if (typeof body.scopes !== 'object' || body.scopes === null) {
|
|
341
|
+
return c.text('scopes must be an object', 400)
|
|
342
|
+
}
|
|
343
|
+
for (const [k, s] of Object.entries(body.scopes)) {
|
|
344
|
+
if (!isValidScope(s)) return c.text(`Invalid scope for ${k}`, 400)
|
|
345
|
+
}
|
|
346
|
+
patch.scopes = body.scopes as Record<string, EnvScope>
|
|
347
|
+
}
|
|
348
|
+
if (body.inheritDotenv !== undefined) {
|
|
349
|
+
if (typeof body.inheritDotenv !== 'boolean') {
|
|
350
|
+
return c.text('inheritDotenv must be a boolean', 400)
|
|
351
|
+
}
|
|
352
|
+
patch.inheritDotenv = body.inheritDotenv
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Skip the write + reaps for a no-op PUT (no recognized fields) so an empty
|
|
356
|
+
// body doesn't needlessly kill warm workers / idle sessions.
|
|
357
|
+
const hasChange =
|
|
358
|
+
patch.set !== undefined ||
|
|
359
|
+
patch.remove !== undefined ||
|
|
360
|
+
patch.scopes !== undefined ||
|
|
361
|
+
patch.inheritDotenv !== undefined
|
|
362
|
+
if (hasChange) {
|
|
363
|
+
await updateWorkspaceEnv(ws.path, patch)
|
|
364
|
+
// Frozen-at-spawn: reap workers/idle sessions so fresh env takes effect.
|
|
365
|
+
restartWorker(ws.path)
|
|
366
|
+
restartWorkspaceSessions(ws.path)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const required = await requiredEnvFor(ws.path)
|
|
370
|
+
return c.json(await getWorkspaceEnvView(ws.path, required))
|
|
371
|
+
})
|
|
372
|
+
|
|
373
|
+
// Models the workspace's agent backend can run, normalized across providers.
|
|
374
|
+
// OpenClaw queries the gateway catalog; everything else (Claude Code) reads the
|
|
375
|
+
// account-wide Agent SDK model list.
|
|
376
|
+
one.get('/models', async c => {
|
|
377
|
+
const ws = c.get('ws')
|
|
378
|
+
const provider: WorkspaceType = ws.type ?? 'claude-code'
|
|
379
|
+
const models =
|
|
380
|
+
provider === 'openclaw' ? await getOpenClawModels() : await getClaudeModels(ws.path)
|
|
381
|
+
// Claude Code streams live tokens via `includePartialMessages`; OpenClaw
|
|
382
|
+
// uses durable rows only (no token deltas), so it opts out.
|
|
383
|
+
const supportsStreaming = provider !== 'openclaw'
|
|
384
|
+
return c.json({ provider, models, supportsStreaming } satisfies WorkspaceModels)
|
|
385
|
+
})
|
|
386
|
+
|
|
387
|
+
// Workspace identity (name). GET returns the current {name, icon}; PUT a JSON
|
|
388
|
+
// `{ name }` sets it (or `null` clears it). Broadcasts so the sidebar and header
|
|
389
|
+
// update live. Icon is handled by the binary route below.
|
|
390
|
+
one.get('/config', async c => {
|
|
391
|
+
return c.json(await getWorkspaceConfig(c.get('ws').path))
|
|
392
|
+
})
|
|
393
|
+
|
|
394
|
+
one.put('/config', async c => {
|
|
395
|
+
const ws = c.get('ws')
|
|
396
|
+
const body = await c.req.json().catch(() => null)
|
|
397
|
+
const name = body?.name
|
|
398
|
+
if (name !== null && typeof name !== 'string') {
|
|
399
|
+
return c.text('Expected { name: string | null }', 400)
|
|
400
|
+
}
|
|
401
|
+
await setWorkspaceConfig(ws.path, { name })
|
|
402
|
+
publishEvent({ type: 'workspace:updated' })
|
|
403
|
+
return c.json(await getWorkspaceConfig(ws.path))
|
|
404
|
+
})
|
|
405
|
+
|
|
406
|
+
// Scratchpad canvas. GET returns the persisted tldraw document snapshot
|
|
407
|
+
// ({ document } or { document: null } when empty) for hydration; PUT saves a new
|
|
408
|
+
// snapshot ({ document, origin }) and broadcasts so other open tabs reload.
|
|
409
|
+
// `origin` is the writing tab's id — echoed in the broadcast so that tab can
|
|
410
|
+
// ignore its own save. This is the browser's write path; the agent's draws are
|
|
411
|
+
// written server-side (see scratchpad-executor.ts). See docs/moi-scratchpad.md.
|
|
412
|
+
one.get('/scratchpad', async c => {
|
|
413
|
+
return c.json(await loadScratchpadDoc(c.get('ws').path))
|
|
414
|
+
})
|
|
415
|
+
|
|
416
|
+
one.put('/scratchpad', async c => {
|
|
417
|
+
const ws = c.get('ws')
|
|
418
|
+
const body = await c.req.json().catch(() => null)
|
|
419
|
+
if (!body || typeof body !== 'object' || !body.document) {
|
|
420
|
+
return c.text('Expected { document }', 400)
|
|
421
|
+
}
|
|
422
|
+
await saveScratchpadDoc(body.document, ws.path)
|
|
423
|
+
publishEvent({
|
|
424
|
+
type: 'scratchpad:updated',
|
|
425
|
+
workspaceId: c.req.param('id'),
|
|
426
|
+
origin: typeof body.origin === 'string' ? body.origin : undefined
|
|
427
|
+
})
|
|
428
|
+
return c.body(null, 204)
|
|
429
|
+
})
|
|
430
|
+
|
|
431
|
+
// Workspace icon. PUT a raw image body (png/jpg/gif/webp) — the server resizes
|
|
432
|
+
// it to a 128×128 transparent WebP and stores it as base64. DELETE resets to the
|
|
433
|
+
// provider default. Both broadcast for a live refresh.
|
|
434
|
+
one.put('/icon', async c => {
|
|
435
|
+
const ws = c.get('ws')
|
|
436
|
+
const bytes = new Uint8Array(await c.req.arrayBuffer())
|
|
437
|
+
if (bytes.length === 0) return c.text('Empty image body', 400)
|
|
438
|
+
let icon: string
|
|
439
|
+
try {
|
|
440
|
+
icon = await processIcon(bytes)
|
|
441
|
+
} catch (err) {
|
|
442
|
+
const msg = err instanceof Error ? err.message : String(err)
|
|
443
|
+
return c.text(`Invalid image: ${msg}`, 400)
|
|
444
|
+
}
|
|
445
|
+
await setWorkspaceConfig(ws.path, { icon })
|
|
446
|
+
publishEvent({ type: 'workspace:updated' })
|
|
447
|
+
return c.json({ icon })
|
|
448
|
+
})
|
|
449
|
+
|
|
450
|
+
one.delete('/icon', async c => {
|
|
451
|
+
await setWorkspaceConfig(c.get('ws').path, { icon: null })
|
|
452
|
+
publishEvent({ type: 'workspace:updated' })
|
|
453
|
+
return c.body(null, 204)
|
|
454
|
+
})
|
|
455
|
+
|
|
456
|
+
// All info about a single workspace: its persisted layout (widget grid, chat
|
|
457
|
+
// mode, theme) plus server-resolved metadata. GET reads, PUT writes the layout,
|
|
458
|
+
// DELETE unregisters.
|
|
459
|
+
one.get('/', async c => {
|
|
460
|
+
const ws = c.get('ws')
|
|
461
|
+
const layout = await loadLayout(ws.path)
|
|
462
|
+
return c.json({
|
|
463
|
+
...layout,
|
|
464
|
+
// Resolved display name: the settings override, or the folder name.
|
|
465
|
+
name: layout.name || basename(ws.path),
|
|
466
|
+
cwd: ws.path,
|
|
467
|
+
provider: ws.type,
|
|
468
|
+
agentId: ws.agentId
|
|
469
|
+
})
|
|
470
|
+
})
|
|
471
|
+
|
|
472
|
+
one.put('/', async c => {
|
|
473
|
+
const ws = c.get('ws')
|
|
474
|
+
const body = await c.req.json()
|
|
475
|
+
if (!body || body.version !== 1) return c.text('Bad request', 400)
|
|
476
|
+
// Preserve server-owned identity (name/icon) across a grid/theme save so the
|
|
477
|
+
// client's PUT can't erase a `moi config`-set name. See mergeLayoutForSave.
|
|
478
|
+
const existing = await loadLayout(ws.path)
|
|
479
|
+
await saveLayout(mergeLayoutForSave(existing, body), ws.path)
|
|
480
|
+
return c.body(null, 204)
|
|
481
|
+
})
|
|
482
|
+
|
|
483
|
+
one.delete('/', async c => {
|
|
484
|
+
const ok = await removeWorkspace(c.req.param('id'))
|
|
485
|
+
if (!ok) return c.text('Workspace not found', 404)
|
|
486
|
+
return c.body(null, 204)
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
// ---- workspace collection: /api/workspaces ----------------------------------
|
|
490
|
+
const workspaces = new Hono<ApiEnv>()
|
|
491
|
+
|
|
492
|
+
workspaces.get('/', async c => {
|
|
493
|
+
// Merge each workspace's live layout name/icon over the registry snapshot so
|
|
494
|
+
// the sidebar reflects `moi config` changes immediately.
|
|
495
|
+
const entries = await listWorkspaces()
|
|
496
|
+
const merged = await Promise.all(
|
|
497
|
+
entries.map(async e => {
|
|
498
|
+
const layout = await loadLayout(e.path)
|
|
499
|
+
return { ...e, name: layout.name ?? e.name, icon: layout.icon }
|
|
500
|
+
})
|
|
501
|
+
)
|
|
502
|
+
return c.json(merged)
|
|
503
|
+
})
|
|
504
|
+
|
|
505
|
+
workspaces.post('/', async c => {
|
|
506
|
+
const body = await c.req.json()
|
|
507
|
+
if (!body?.path) return c.text('Missing path', 400)
|
|
508
|
+
const rawType = body?.type
|
|
509
|
+
const type = rawType === 'claude-code' || rawType === 'openclaw' ? rawType : undefined
|
|
510
|
+
const path = resolve(String(body.path))
|
|
511
|
+
// Importing IS initializing: lay down the bundled skills (in the backend's
|
|
512
|
+
// skills dir) and the `.moi/` scaffold, exactly like `moi init` — a workspace
|
|
513
|
+
// added from the UI must be indistinguishable from one added via the CLI.
|
|
514
|
+
try {
|
|
515
|
+
await provisionWorkspace(path, type)
|
|
516
|
+
} catch (err) {
|
|
517
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
518
|
+
return c.text(`Could not initialize workspace: ${message}`, 500)
|
|
519
|
+
}
|
|
520
|
+
const entry = await registerWorkspace(path, {
|
|
521
|
+
type,
|
|
522
|
+
name: typeof body?.name === 'string' ? body.name : undefined,
|
|
523
|
+
agentId: typeof body?.agentId === 'string' ? body.agentId : undefined,
|
|
524
|
+
isDefault: typeof body?.isDefault === 'boolean' ? body.isDefault : undefined,
|
|
525
|
+
lastRunAt: typeof body?.lastRunAt === 'string' ? body.lastRunAt : undefined
|
|
526
|
+
})
|
|
527
|
+
return c.json(entry, 201)
|
|
528
|
+
})
|
|
529
|
+
|
|
530
|
+
workspaces.get('/discover', async c => c.json(await discoverWorkspaces()))
|
|
531
|
+
|
|
532
|
+
// Where `/workspace/create` places new folders — the client shows the resolved
|
|
533
|
+
// location while the user types a name.
|
|
534
|
+
workspaces.get('/create', c =>
|
|
535
|
+
c.json({ root: CREATED_WORKSPACES_ROOT, displayRoot: tildify(CREATED_WORKSPACES_ROOT) })
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
// Create a brand-new workspace: a fresh folder under CREATED_WORKSPACES_ROOT,
|
|
539
|
+
// provisioned (skills + `.moi/` scaffold) and registered. Claude Code only for
|
|
540
|
+
// now — OpenClaw workspaces belong to their agents and arrive via discovery.
|
|
541
|
+
workspaces.post('/create', async c => {
|
|
542
|
+
const body = await c.req.json()
|
|
543
|
+
const type = body?.type ?? 'claude-code'
|
|
544
|
+
if (type !== 'claude-code') {
|
|
545
|
+
return c.text('Only Claude Code workspaces can be created for now', 400)
|
|
546
|
+
}
|
|
547
|
+
const name = typeof body?.name === 'string' ? body.name.trim() : ''
|
|
548
|
+
const invalid = validateWorkspaceFolderName(name)
|
|
549
|
+
if (invalid) return c.text(invalid, 400)
|
|
550
|
+
const path = join(CREATED_WORKSPACES_ROOT, name)
|
|
551
|
+
if (existsSync(path)) return c.text('A folder with that name already exists', 409)
|
|
552
|
+
try {
|
|
553
|
+
await provisionWorkspace(path, 'claude-code')
|
|
554
|
+
} catch (err) {
|
|
555
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
556
|
+
return c.text(`Could not create workspace: ${message}`, 500)
|
|
557
|
+
}
|
|
558
|
+
const entry = await registerWorkspace(path, { type: 'claude-code' })
|
|
559
|
+
// Nudge every connected client (the sidebar list) to refetch.
|
|
560
|
+
publishEvent({ type: 'workspace:updated' })
|
|
561
|
+
return c.json(entry, 201)
|
|
562
|
+
})
|
|
563
|
+
|
|
564
|
+
// `/:id` is registered after the static `/discover` so the literal path wins.
|
|
565
|
+
// `/api/workspaces/ws` (the live-event WebSocket) is intercepted by Bun's routes
|
|
566
|
+
// table before it ever reaches Hono, so it never collides with `:id`.
|
|
567
|
+
workspaces.route('/:id', one)
|
|
568
|
+
|
|
569
|
+
// ---- top-level API ----------------------------------------------------------
|
|
570
|
+
export const api = new Hono()
|
|
571
|
+
|
|
572
|
+
api.route('/api/workspaces', workspaces)
|
|
573
|
+
|
|
574
|
+
// Everything else: in production, serve the prebuilt client from `dist/` via
|
|
575
|
+
// Hono's static handler (mime types, traversal-safe, optional precompression).
|
|
576
|
+
// Hashed assets (`/chunk-….js`, `/favicon-….png`, …) are pinned immutable; the
|
|
577
|
+
// unhashed `index.html` is not. Never mounted in dev — the live bundler serves
|
|
578
|
+
// assets via the HTML route before Bun's `fetch` ever delegates here.
|
|
579
|
+
if (prebuilt) {
|
|
580
|
+
api.get(
|
|
581
|
+
'*',
|
|
582
|
+
serveStatic({
|
|
583
|
+
root: DIST_DIR,
|
|
584
|
+
onFound: (path, c) => {
|
|
585
|
+
c.header(
|
|
586
|
+
'Cache-Control',
|
|
587
|
+
path.endsWith('index.html') ? 'no-cache' : 'public, max-age=31536000, immutable'
|
|
588
|
+
)
|
|
589
|
+
}
|
|
590
|
+
})
|
|
591
|
+
)
|
|
592
|
+
}
|
|
593
|
+
api.notFound(c => c.text('Not found', 404))
|