import { resolveWorkspaceEnv } from '../workspaces/env' import { changeWorkspaceHarness } from '../workspaces/change-harness' import { HarnessTransitionError, reserveWorkspaceOperation } from '../workspaces/harness-transition' import { onboarding } from './onboarding' import type { SpeedMode } from '@/lib/types' import { isSpeedMode } from '@/lib/speed-mode' import { isMessageAttachments } from '@/lib/message-attachments' import { Hono } from 'hono' import { serveStatic } from 'hono/bun' import { createMiddleware } from 'hono/factory' import { existsSync } from 'node:fs' import { basename, resolve } from 'node:path' import { UPDATE_ACTIVE_AGENT_MESSAGE } from '@/lib/update' import { resolveWorkspaceTheme } from '@/lib/themes' import { isWorkspaceIcon } from '@/lib/workspace-icon' import type { AppletKind, AppletThumbnailBatch, AppSettings, HarnessAvailability, SelectedSessionScope, UploadInfo, WorkspaceHarness, WorkspaceEntry, WorkspaceType } from '@/lib/types' import { isWorkspaceTabId } from '@/lib/workspace-tabs' import { proxyUserState } from '../collab/cloudflare-access' import { collabManager } from '../collab/manager' import { harnessStore } from '../harness/auth' import { harnesses } from './harnesses' import { clientAppConfig, createdWorkspacesRoot, getAppConfig } from '../app-config' import { getAppSettings, pickAppSettingsPatch, saveAppSettings } from '../app-settings' import { appletForModule, recordAppletError } from '../applets/log' import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from '../applets' import { applyEnvChanged } from '../workspaces/env-apply' import { publishEvent } from '../events' import { callFunction, parseFunctionPath } from '../applets/functions' import { processIcon } from '../workspaces/icon' import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from '../workspaces/layout' import { getAppletThumbnailRecords, isValidAppletId, saveAppletThumbnails, serveAppletThumbnail } from '../applets/thumbnails' import { getClientFrameLog, getWireLog } from '../harness/debug' import { loginShellPath } from '../harness/shell-path' import { allHarnesses, harnessFor, isHarnessType } from '../harness/registry' import { discoverWorkspaces, getWorkspace, listWorkspaces, registerWorkspace, removeWorkspace, reorderWorkspaces } from '../workspaces/registry' import { loadScratchpadDoc, saveScratchpadDoc } from '../scratchpad/document' import { MAX_ASSET_BYTES, scratchpadAssetFile, storeScratchpadAsset } from '../scratchpad/assets' import { deselectSession, getPinnedSession, pinSession, saveSelectedSession, unpinSession } from '../sessions/selected' import { saveSessionConfig } from '../sessions/config' import type { SessionConfigPatch } from '../sessions/config' import { archiveWorkspaceSession } from '../sessions/archive' import { getWorkspaceState } from '../workspace-state' import { DIST_DIR, prebuilt } from '../static' import { getWorkspaceSkillsStatus, updateWorkspaceSkills } from '../skills/update' import { serveWorkspaceImagePreview } from '../workspaces/preview' import { MAX_UPLOAD_BYTES, addUpload, addWorkspaceFileUpload, getUpload } from '../uploads' import { requiredEnvFor } from '../workspaces/required-env' import { deleteView, listCompiledViews, listViews, serveView, updateViewTitle, ViewMutationError } from '../applets/views' import { createPendingView, discardPendingView, getPendingView, updatePendingView, PendingViewError } from '../sessions/pending-views' import { submitView, ViewStartupError } from '../sessions/view-sessions' import { listWidgets, serveWidget } from '../applets/widgets' import { getWorkspaceConfig, setWorkspaceConfig } from '../workspaces/config' import { createWorkspaceDirectory, provisionWorkspace } from '../workspaces/init' import { validateWorkspaceName } from '@/lib/workspace-name' import { resolveWorkspaceImportMetadata } from '../workspaces/import' import type { WorkspaceImportMetadata } from '../workspaces/import' import { getWorkspaceEnvView, parseEnvUpdate, updateWorkspaceEnv } from '../workspaces/env' import { getCachedUpdateStatus, hasRunningAgentSessions, installUpdate, restartPendingForUpdate, scheduleRestartForUpdate, updateInProgress } from '../update' // The resolved workspace is stashed on the context by `withWorkspace`, so every // `/api/workspaces/:id/*` handler can read it without re-querying the registry. type ApiEnv = { Variables: { ws: WorkspaceEntry } } // The writing browser tab's id from a request body, echoed on the resulting // event so that tab can skip it. See client/lib/browser-tab-id.ts. function eventOrigin(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined } async function handleFunctionCall( req: Request, tail: string, workspacePath: string ): Promise { // Module keys may contain slashes (`widgets/hello/getWeather`), so the // tail is parsed on the last slash — see parseFunctionPath. const parsed = parseFunctionPath(tail) if (!parsed) { return new Response('Invalid module or function name', { status: 400 }) } const { module, name } = parsed try { const contentLength = Number(req.headers.get('content-length') ?? 0) if (contentLength > 1_000_000) { return new Response('Request body too large', { status: 413 }) } const args = await req.text() const result = await callFunction(module, name, args, workspacePath) return new Response(result, { headers: { 'Content-Type': 'application/json' } }) } catch (err) { const message = err instanceof Error ? err.message : 'Unknown error' // Journal the failure so the agent can find it via `moi debug logs` — the // 500 body below only reaches the browser (see docs/self-correction.md). recordAppletError(workspacePath, { source: 'rpc', ...(appletForModule(module) ?? {}), module, fn: name, message }) return new Response(message, { status: 500 }) } } // Resolve `:id` to a registered workspace once, 404 if unknown, and stash it on // the context. Mounted on the single-workspace sub-app so every nested route // shares the lookup instead of repeating `getWorkspace(...) ?? 404`. const withWorkspace = createMiddleware(async (c, next) => { const id = c.req.param('id') if (!id) return c.text('Workspace not found', 404) let release: (() => void) | undefined try { if (c.req.method !== 'GET' && !c.req.path.endsWith('/harness')) release = reserveWorkspaceOperation(id) const ws = await getWorkspace(id) if (!ws) return c.text('Workspace not found', 404) c.set('ws', ws) await next() } catch (error) { if (error instanceof HarnessTransitionError) return c.text(error.message, 409) throw error } finally { release?.() } }) // ---- single workspace: /api/workspaces/:id/* -------------------------------- const one = new Hono() one.use('*', withWorkspace) one.patch('/harness', async c => { if (getAppConfig().demo) return c.text('Changing agents is unavailable in the demo', 403) const body = await c.req.json().catch(() => null) if (!body || !['claude-code', 'codex'].includes(body.type)) return c.text('Invalid agent selection', 400) try { return c.json(await changeWorkspaceHarness(c.get('ws'), body.type)) } catch (error) { if (error instanceof HarnessTransitionError) return c.text(error.message, 409) throw error } }) one.get('/widgets', c => listWidgets(c.get('ws').path)) // Widget bundle: the compiled ESM for one widget, dynamically imported by the // client (useWidget). Sits beside the GET .../widgets list above — the exact // path lists, `/*` serves a file from the bundle dir (`/`: // index.js, a chunk, or a hashed asset). one.get('/widgets/*', c => { const ws = c.get('ws') const { name, file } = parseAppletTail(c.req.url, ws.id, 'widgets') if (!name) return c.text('Not found', 404) return serveWidget(name, file, ws.path, apiBaseFor(ws.id), c.req.header('if-none-match')) }) // Views — full-screen agent apps. Mirrors the widget pair above: the exact path // lists (in manifest/nav order), `/*` serves one bundle file. one.get('/views', c => listViews(c.get('ws').path)) one.patch('/views/:viewId', async c => { const ws = c.get('ws') const body = await c.req.json().catch(() => null) if (await getPendingView(ws, c.req.param('viewId'))) { try { if ( typeof body?.requirements !== 'string' && typeof body?.title !== 'string' && typeof body?.icon !== 'string' ) return c.text('Expected requirements, title, or icon', 400) return c.json( await updatePendingView(ws, c.req.param('viewId'), { requirements: typeof body.requirements === 'string' ? body.requirements : undefined, title: typeof body.title === 'string' ? body.title.trim() : undefined, icon: typeof body.icon === 'string' ? body.icon : undefined }) ) } catch (error) { if (error instanceof PendingViewError) return c.text(error.message, error.status) throw error } } const title = typeof body?.title === 'string' ? body.title.trim() : '' if (!title) return c.text('Expected { title: string }', 400) try { return c.json(await updateViewTitle(publishEvent, ws.id, ws.path, c.req.param('viewId'), title)) } catch (error) { if (error instanceof ViewMutationError || error instanceof PendingViewError) return c.text(error.message, error.status) throw error } }) one.delete('/views/:viewId', async c => { const ws = c.get('ws') try { const viewId = c.req.param('viewId') if (await getPendingView(ws, viewId)) { const active = new Set( harnessFor(ws) .activeSessions() .filter(session => session.workspaceId === ws.id) .map(session => session.sessionId) ) await discardPendingView(ws, viewId, active) } else await deleteView(publishEvent, ws, viewId) return c.body(null, 204) } catch (error) { if (error instanceof ViewMutationError || error instanceof PendingViewError) return c.text(error.message, error.status) throw error } }) one.get('/views/*', c => { const ws = c.get('ws') const { name, file } = parseAppletTail(c.req.url, ws.id, 'views') if (!name) return c.text('Not found', 404) return serveView(name, file, ws.path, apiBaseFor(ws.id), c.req.header('if-none-match')) }) one.post('/views', async c => { const ws = c.get('ws') return c.json(await createPendingView(ws), 201) }) one.post('/views/:viewId/submit', async c => { const ws = c.get('ws') const body = await c.req.json<{ requirements?: string sessionId?: string optimisticId?: string selectedSessionScope?: SelectedSessionScope model?: string effort?: string speedMode?: SpeedMode stream?: boolean attachments?: unknown }>() if (typeof body?.requirements !== 'string') { return c.text('Expected { requirements: string }', 400) } if (body.optimisticId !== undefined && typeof body.optimisticId !== 'string') { return c.text('Invalid optimisticId', 400) } if ( body.selectedSessionScope !== undefined && body.selectedSessionScope !== 'shared' && body.selectedSessionScope !== 'browser-tab' ) { return c.text('Invalid selectedSessionScope', 400) } const attachments = body.attachments ?? [] if (!isMessageAttachments(attachments)) return c.text('Invalid attachments', 400) for (const attachment of attachments) { if (attachment.type !== 'upload') continue if (!/^[a-f0-9]{64}$/.test(attachment.uploadId)) return c.text('Invalid upload id', 400) if (!getUpload(ws.id, attachment.uploadId)) return c.text('Attachment not found or expired', 400) } const availability = await workspaceTypeAvailability(ws.type ?? 'claude-code') if (availability.status !== 'available') return c.text(availability.reason, 400) try { const result = await submitView(ws, c.req.param('viewId'), { requirements: body.requirements, sessionId: typeof body.sessionId === 'string' ? body.sessionId : undefined, selectedSessionScope: body.selectedSessionScope, attachments, optimisticId: body.optimisticId, model: typeof body.model === 'string' ? body.model : undefined, effort: typeof body.effort === 'string' ? body.effort : undefined, speedMode: isSpeedMode(body.speedMode) ? body.speedMode : undefined, stream: body.stream === true ? true : undefined }) return c.json(result) } catch (err) { if (err instanceof PendingViewError) return c.text(err.message, err.status) if (err instanceof ViewStartupError) return c.json({ error: err.message, viewId: err.viewId, sessionId: err.sessionId }, 500) throw err } }) // Workspace file stream — `resolveUrl('moi:/files/...')` resolves here. Streams a // media file from the workspace root (range-enabled). Guarded: traversal and // dotfiles (`.env`, `.moi`, `.git`) are rejected and only media/asset extensions // are allowed — the workspace holds secrets, and this route is unauthenticated. // localhost binding is NOT the guard. one.get('/files/*', c => { const ws = c.get('ws') const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/files/`)[1] ?? '' return serveWorkspaceFile(ws.path, tail, c.req.header('range'), c.req.header('if-none-match')) }) // Applet RPC — the home for server-function calls from a bundle. The bundle's // sentinel base resolves to `/api/workspaces/`, so it POSTs to // `…/rpc//`. one.post('/rpc/*', c => { const ws = c.get('ws') const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/rpc/`)[1] ?? '' return handleFunctionCall(c.req.raw, tail, ws.path) }) // Browser-side applet errors (module load failures, render crashes, window // errors attributed to a bundle) reported into the workspace's error journal — // `moi debug logs` reads it back (docs/self-correction.md). Unauthenticated // localhost route, so treat the payload as hostile: whitelist the browser-only // sources (`build`/`rpc` are server-recorded and can't be spoofed by a tab), // pattern-check the applet name, cap the batch size; applets/log.ts caps string // lengths. one.post('/applet-log', async c => { let body: { events?: unknown } try { body = await c.req.json() } catch { return c.text('Invalid JSON', 400) } const events = Array.isArray(body.events) ? body.events.slice(0, 10) : [] for (const raw of events) { const e = raw as { source?: unknown kind?: unknown name?: unknown message?: unknown stack?: unknown } if ( e.source !== 'load' && e.source !== 'render' && e.source !== 'window' && e.source !== 'runtime' ) continue // `runtime` entries may be unattributed (a stale link to a deleted view // names no applet), so attribution is optional there and dropped when // malformed — every other source must name the applet that broke. const attributed = (e.kind === 'widget' || e.kind === 'view') && typeof e.name === 'string' const named = attributed && /^[a-zA-Z0-9_-]+$/.test(e.name as string) if (!named && e.source !== 'runtime') continue if (typeof e.message !== 'string' || !e.message) continue recordAppletError(c.get('ws').path, { source: e.source, ...(named ? { kind: e.kind as AppletKind, name: e.name as string } : {}), message: e.message, ...(typeof e.stack === 'string' ? { stack: e.stack } : {}) }) } return c.body(null, 204) }) // Downscaled image preview of a workspace file. The chat's expanded tool rows // use this to show the picture an agent `Read` — same guards as /files/ above, // images only, resized server-side (see server/workspaces/preview.ts). one.get('/preview/*', c => { const ws = c.get('ws') const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/preview/`)[1] ?? '' return serveWorkspaceImagePreview(ws.path, tail, c.req.header('if-none-match')) }) // Chat attachments. The composer POSTs files here (drag/drop, paste, or the // attach button) ahead of sending; we process + stash them and hand back opaque // upload ids the chat WS frame references. Images are downscaled and inlined as // vision blocks at send time; other files are referenced by a temp path. See // server/uploads.ts and dev/file-uploads.md. one.post('/uploads', async c => { const ws = c.get('ws') let form: FormData try { form = await c.req.formData() } catch { return c.text('Choose a file to upload', 400) } const files = form.getAll('files').filter((f): f is File => f instanceof File) if (files.length === 0) return c.text('Choose a file to upload', 400) if (files.length > 20) return c.text('You can upload up to 20 files at a time', 400) const out: UploadInfo[] = [] for (const file of files) { if (file.size > MAX_UPLOAD_BYTES) { return c.text(`Files can be up to ${MAX_UPLOAD_BYTES / (1024 * 1024)} MB`, 413) } try { const bytes = Buffer.from(await file.arrayBuffer()) out.push( await addUpload({ workspaceId: ws.id, filename: file.name || 'file', mediaType: file.type || 'application/octet-stream', bytes }) ) } catch { return c.text(`Couldn’t process "${file.name}"`, 400) } } return c.json(out) }) // Existing workspace documents enter the same upload pipeline without a browser round trip. one.post('/uploads/from-path', async c => { const body: unknown = await c.req.json().catch(() => null) if (!body || typeof body !== 'object' || !('path' in body) || typeof body.path !== 'string') { return c.text('Choose a file from this workspace', 400) } const ws = c.get('ws') try { return c.json(await addWorkspaceFileUpload(ws.id, ws.path, body.path)) } catch (error) { if (error instanceof Error && 'code' in error) { if (error.code === 'ENOENT') return c.text('This file no longer exists', 400) if (error.code === 'EACCES' || error.code === 'EPERM') return c.text('This file can’t be read by Moi', 400) return c.text('Something went wrong while adding this file', 400) } return c.text( error instanceof Error ? error.message : 'Something went wrong while adding this file', 400 ) } }) // Serve an upload's bytes back. Display parts reference this URL instead of a // base64 data URL so the transcript broadcast / client cache stay small. The id // is content-addressed (sha256), so the response is immutable while it lives — // let the browser cache it for the store's TTL. one.get('/uploads/:uploadId', c => { const u = getUpload(c.get('ws').id, c.req.param('uploadId')) if (!u) return c.text('Not found or expired', 404) const body = u.data ? new Uint8Array(u.data) : u.path ? Bun.file(u.path) : null if (!body) return c.text('Not found or expired', 404) return new Response(body, { headers: { 'Content-Type': u.mediaType, 'Content-Disposition': `inline; filename="${u.filename.replaceAll('"', '')}"`, 'Cache-Control': 'private, max-age=1800, immutable' } }) }) // Per-user chat state: pin, the chat each tab shows, per-chat settings and // fork history, and views being built. Every write below answers with the new // state; other clients get it as `state:changed`. one.get('/state', async c => c.json(await getWorkspaceState(c.get('ws')))) // The agent's chats. Tab ownership and settings come from `/state`. one.get('/sessions', async c => { const ws = c.get('ws') return c.json(await harnessFor(ws).listSessions(ws)) }) one.put('/sessions/:sessionId/pin', async c => { const ws = c.get('ws') const sessionId = c.req.param('sessionId') const harness = harnessFor(ws) const found = (await harness.listSessions(ws)).some(session => session.sessionId === sessionId) const active = harness .activeSessions() .some(session => session.workspaceId === ws.id && session.sessionId === sessionId) if (!found && !active) return c.text('Chat not found', 404) await pinSession(ws, sessionId) return c.json(await getWorkspaceState(ws)) }) one.delete('/sessions/:sessionId/pin', async c => { const ws = c.get('ws') await unpinSession(ws, c.req.param('sessionId')) return c.json(await getWorkspaceState(ws)) }) // Show the chat in a tab. `ifMatch` (a chat id, or null for none) applies the // change only while the tab still shows that chat. one.put('/sessions/:sessionId/selection', async c => { const ws = c.get('ws') const body: unknown = await c.req.json().catch(() => null) if (!body || typeof body !== 'object') return c.text('Bad request', 400) const input = body as { tabId?: unknown; ifMatch?: unknown } if (!isWorkspaceTabId(input.tabId)) return c.text('Invalid chat tab', 400) const hasIfMatch = Object.prototype.hasOwnProperty.call(input, 'ifMatch') if (hasIfMatch && input.ifMatch !== null && typeof input.ifMatch !== 'string') return c.text('ifMatch must be a chat id or null', 400) if (await getPinnedSession(ws)) return c.text('Unpin chat before switching', 409) await saveSelectedSession( ws, c.req.param('sessionId'), input.tabId, hasIfMatch ? (input.ifMatch as string | null) : undefined ) return c.json(await getWorkspaceState(ws)) }) // Stop showing the chat in a tab, which then opens a new chat. A tab showing // another chat is left alone. one.delete('/sessions/:sessionId/selection', async c => { const ws = c.get('ws') const body: unknown = await c.req.json().catch(() => null) const tabId = (body as { tabId?: unknown } | null)?.tabId if (!isWorkspaceTabId(tabId)) return c.text('Invalid chat tab', 400) await deselectSession(ws, c.req.param('sessionId'), tabId) return c.json(await getWorkspaceState(ws)) }) // Change run settings. Omitted fields stay; null clears one. one.patch('/sessions/:sessionId/config', async c => { const body = await c.req.json().catch(() => null) if (typeof body !== 'object' || body === null) { return c.text('Expected a JSON object', 400) } const patch: SessionConfigPatch = {} const record = body as Record for (const key of ['model', 'effort'] as const) { if (!(key in record)) continue const value = record[key] if (value !== null && typeof value !== 'string') { return c.text(`${key} must be a string or null`, 400) } patch[key] = value } if ('speedMode' in record) { const value = record.speedMode if (value !== null && !isSpeedMode(value)) { return c.text('speedMode must be "normal", "fast", "ultrafast", or null', 400) } patch.speedMode = value } const ws = c.get('ws') await saveSessionConfig(ws, c.req.param('sessionId'), patch) return c.json(await getWorkspaceState(ws)) }) one.post('/sessions/:sessionId/archive', async c => { const ws = c.get('ws') const harness = harnessFor(ws) const sessionId = c.req.param('sessionId') if (!harness.archiveSession) return c.text('Chat archiving is not supported', 501) try { await archiveWorkspaceSession(ws, sessionId) return c.json(await getWorkspaceState(ws)) } catch (error) { console.error(`[api] archive chat failed for ${harness.id}`, error) // Harnesses translate backend refusals into actionable one-liners (e.g. // OpenClaw: main chat not archivable, gateway too old) — surface them. const message = error instanceof Error && error.message ? error.message : 'Couldn’t archive chat' return c.text(message, 500) } }) one.get('/sessions/:sessionId/events', async c => { const ws = c.get('ws') const sessionId = c.req.param('sessionId') return c.json(await harnessFor(ws).sessionEvents(ws, sessionId)) }) one.get('/mcp', async c => { const ws = c.get('ws') const harness = harnessFor(ws) if (c.req.query('stream') !== 'true') return c.json((await harness.mcpStatus?.(ws)) ?? []) let cancelled = false const encoder = new TextEncoder() return new Response( new ReadableStream({ async start(controller) { const emit = (frame: unknown) => { if (!cancelled) controller.enqueue(encoder.encode(JSON.stringify(frame) + '\n')) } try { const connectors = (await harness.mcpStatus?.(ws, connectors => emit({ connectors }))) ?? [] emit({ connectors, done: true }) } catch { emit({ error: 'Could not load connectors' }) } finally { if (!cancelled) controller.close() } }, cancel() { cancelled = true } }), { headers: { 'Content-Type': 'application/x-ndjson', 'Cache-Control': 'no-store' } } ) }) // Harness debug tap for /dev/harness: the backend's native wire frames // (Codex: app-server JSON-RPC, both directions; Claude Code: raw SDK messages // + enqueued inputs) and the exact frames the server pushed to chat clients. // `sinceWire`/`sinceBroadcast` are seq cursors so the page can poll deltas. one.get('/harness/debug', async c => { const ws = c.get('ws') const harness = harnessFor(ws) const sinceWire = Number(c.req.query('sinceWire') ?? 0) || 0 const sinceBroadcast = Number(c.req.query('sinceBroadcast') ?? 0) || 0 return c.json({ provider: harness.id, process: (await harness.debugInfo?.(ws)) ?? null, wire: getWireLog(harness.wireScope?.(ws) ?? ws.id, sinceWire), broadcasts: getClientFrameLog(ws.id, sinceBroadcast) }) }) // Per-workspace env vars. GET returns the effective view (discovered `.env` + UI // custom secrets + scopes + declared-required keys; values masked). one.get('/env', async c => { const ws = c.get('ws') // Unawaited on purpose: getWorkspaceEnvView loads it in parallel with the // env stores (manifest reads and env reads are independent). return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path))) }) // PUT patches custom secrets (set/remove) and/or the inheritDotenv mode, // then reaps the workspace's function worker and idle agent sessions so the next // call/message picks up the change (env is frozen at spawn — a hard restart is // the only way). one.put('/env', async c => { const ws = c.get('ws') const patch = parseEnvUpdate(await c.req.json().catch(() => null)) if (typeof patch === 'string') return c.text(patch, 400) // Skip the write + reaps for a no-op PUT (no recognized fields) so an empty // body doesn't needlessly kill warm workers / idle sessions. const hasChange = patch.set !== undefined || patch.remove !== undefined || patch.inheritDotenv !== undefined if (hasChange) { await updateWorkspaceEnv(ws.path, patch) // Frozen-at-spawn: reap workers/idle sessions and tell other clients. applyEnvChanged(ws) } return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path))) }) one.get('/skills', async c => { const ws = c.get('ws') return c.json(await getWorkspaceSkillsStatus(ws.path, ws.type)) }) one.post('/skills/update', async c => { const ws = c.get('ws') const result = await updateWorkspaceSkills(ws.path, ws.type ?? 'claude-code') return c.json(result.status) }) // Workspace configuration and models. Shared account status is served by // /harnesses/status; only workspace overrides and gateways are probed here. one.get('/harness', async c => { const ws = c.get('ws') const harness = harnessFor(ws) const capabilities = { provider: harness.id, supportsStreaming: harness.capabilities.supportsStreaming, supportsArchiving: Boolean(harness.archiveSession) } if (!existsSync(ws.path)) { return c.json({ ...capabilities, isFolderMissing: true, availability: { status: 'unavailable', reason: 'Workspace folder not found' }, models: [] } satisfies WorkspaceHarness) } const authEnv = harness.id === 'codex' ? /^(OPENAI_|CODEX_)/ : /^(ANTHROPIC_|CLAUDE_|AWS_|GOOGLE_|AZURE_|CLOUD_ML_)/ const hasAuthOverrides = harness.authStatus && Object.entries(await resolveWorkspaceEnv(ws.path)).some( ([key, value]) => value !== process.env[key] && (authEnv.test(key) || /^(HOME|USERPROFILE|XDG_CONFIG_HOME)$/.test(key)) ) const refresh = c.req.query('refresh') === 'true' if (refresh) await loginShellPath({ refresh: true }) // A backend that can't answer (codex CLI missing, gateway down) degrades to // an empty catalog — the picker hides and chat surfaces the real problem via // workspace setup, instead of this endpoint failing on page load. const [availability, models] = await Promise.all([ // Shared account status comes from /harnesses/status. // Gateway-backed harnesses still have workspace-specific readiness. harness.authStatus && !hasAuthOverrides ? Promise.resolve({ status: 'available' as const }) : refresh ? harnessStore.refresh(ws) : harnessStore.getAvailability(ws), harness.listModels(ws).catch(err => { console.error(`[api] listModels failed for ${harness.id}`, err) return [] }) ]) return c.json({ ...capabilities, availability, hasAuthOverrides: Boolean(hasAuthOverrides), models } satisfies WorkspaceHarness) }) // Workspace identity. Uploads use the image route below. one.get('/config', async c => { return c.json(await getWorkspaceConfig(c.get('ws').path)) }) one.put('/config', async c => { const ws = c.get('ws') const parsed: unknown = await c.req.json().catch(() => null) if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return c.text('Expected a workspace config object', 400) } const body = parsed as Record const name = body.name const icon = body.icon if (name !== undefined && name !== null && typeof name !== 'string') { return c.text('Expected { name: string | null }', 400) } if (icon !== undefined && icon !== null && (!isWorkspaceIcon(icon) || icon.type === 'upload')) { return c.text('Invalid icon', 400) } if (name === undefined && icon === undefined) { return c.text('Expected a workspace config field', 400) } await setWorkspaceConfig(ws.path, { name, icon }) publishEvent({ type: 'workspace:updated', origin: eventOrigin(body.origin) }) return c.json(await getWorkspaceConfig(ws.path)) }) // Scratchpad canvas. GET returns the persisted tldraw document snapshot // ({ document } or { document: null } when empty) for hydration; PUT saves a new // snapshot ({ document, origin }) and broadcasts so other open tabs reload. // `origin` is the writing tab's id — echoed in the broadcast so that tab can // ignore its own save. This is the browser's write path; the agent's draws are // written server-side (see server/scratchpad/executor.ts). See docs/moi-scratchpad.md. one.get('/scratchpad', async c => { return c.json(await loadScratchpadDoc(c.get('ws').path)) }) one.put('/scratchpad', async c => { const ws = c.get('ws') const body = await c.req.json().catch(() => null) if (!body || typeof body !== 'object' || !body.document) { return c.text('Expected { document }', 400) } await saveScratchpadDoc(body.document, ws.path) publishEvent({ type: 'scratchpad:updated', workspaceId: ws.id, origin: eventOrigin(body.origin) }) return c.body(null, 204) }) // Scratchpad assets: pasted/dropped image bytes live as content-addressed files // in `.moi/.scratchpad/`, referenced from the snapshot by `asset:` srcs — // never inlined as base64 in the JSON (see server/scratchpad/assets.ts). The // browser's TLAssetStore POSTs the raw file here on paste and resolves `asset:` // srcs back through the GET when rendering. one.post('/scratchpad/assets', async c => { const length = Number(c.req.header('content-length') ?? 0) if (length > MAX_ASSET_BYTES) { return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413) } const bytes = new Uint8Array(await c.req.arrayBuffer()) if (bytes.length === 0) return c.text('Empty body', 400) if (bytes.length > MAX_ASSET_BYTES) { return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413) } const mimeType = c.req.header('content-type') ?? 'application/octet-stream' return c.json(await storeScratchpadAsset(c.get('ws').path, bytes, mimeType)) }) // The file name is content-addressed (sha256 of the bytes), so a hit is // immutable — let the browser cache it indefinitely. one.get('/scratchpad/assets/:file', async c => { const resolved = scratchpadAssetFile(c.get('ws').path, c.req.param('file')) if (!resolved || !(await resolved.file.exists())) return c.text('Not found', 404) return new Response(resolved.file, { headers: { 'Content-Type': resolved.mimeType, 'Cache-Control': 'public, max-age=31536000, immutable', // Assets are only ever consumed via /