diff --git a/dsh/README.md b/dsh/README.md
index 172b8ac..95ea13a 100644
--- a/dsh/README.md
+++ b/dsh/README.md
@@ -6,14 +6,16 @@ dsh's MCP client sends fixed headers and has no sign-in, so it reaches box with
2. Install the plugin. In dsh Desktop (or dsh web), open **Plugins → Add plugin**, paste this link and turn the plugin on:
```
- https://github.com/simular-ai/box-plugin/releases/download/dsh-v0.2.1/dsh-box.tgz
+ https://github.com/simular-ai/box-plugin/releases/download/dsh-v0.3.0/dsh-box.tgz
```
- From a terminal: `dsh plugin add https://github.com/simular-ai/box-plugin/releases/download/dsh-v0.2.1/dsh-box.tgz`
-3. Open **box** on the Plugins page, paste your key and click **Save**. box connects within a second; changing the key later needs no restart.
+ From a terminal: `dsh plugin add https://github.com/simular-ai/box-plugin/releases/download/dsh-v0.3.0/dsh-box.tgz`
+3. Open **box by Simular** on the Plugins page, paste your key and click **Save**. box connects within a second; changing the key later needs no restart.
box's tools show up as `mcp__box__*`.
+When the agent works on the box's screen (clicks, typing, the browser, screenshots) or calls `box_view`, the box's live screen appears in the chat, view only, as in ChatGPT and Claude, without anyone asking for it. It shows once per turn, stays in the chat while the agent works and after it answers, and **Take control** opens the screen in your browser, where you can type. Shell and file tools, and account tools such as `usage`, don't bring it up.
+
The key is kept in dsh's own credentials store as `BOX_TOKEN`, not in settings. On the command line, an exported `BOX_TOKEN` or a `BOX_TOKEN=cb_...` line in `~/.dsh/.env` works too. To use the staging box, also set `BOX_MCP_URL=https://staging.relay.simular.cloud/mcp` (VPN required).
Always install from a versioned release link like the one above. pnpm caches what a tarball URL resolved to, so new contents behind the same URL (such as `releases/latest`) fail to install.
@@ -23,7 +25,8 @@ Always install from a versioned release link like the one above. pnpm caches wha
- `cordis.patch.yml` inserts two rows: `box-auth` (this package) and `mcp-box` (`@deepseek-ai/dsh-mcp-client`, shipped with dsh). `mcp-box` injects the `boxAuth` service, so it waits quietly until a key exists and restarts with the new header when the key changes.
- `index.js` (Host half) resolves `BOX_TOKEN` from dsh's credentials (store, then launch environment, then `~/.dsh/.env`) and provides `boxAuth`.
- `client.js` (browser half) is the key page in the `plugins.bundle.config` slot. It is hand-written in dsh's lazy-CJS client format, so the package has no build step.
+- Live view: dsh has no MCP Apps host, so `client.js` hosts box's live view page (`ui://box/live`, the MCP App ChatGPT and Claude render) itself. dsh folds a turn's tool calls as soon as the next one starts, so the view is not a tool card: a conversation definition publishes it as its own chat node at the turn's `box_view` call or, without one, its first box tool that works on the screen (the page then gets the box from `box_status`), at the turn level (`groupTree: 'turn'`), which dsh keeps outside the folded process while the agent works and after. The page runs in a sandboxed iframe without same-origin access and talks MCP Apps over `postMessage`; its tool calls go to `POST /api/simular-box/live`, a Host route in `index.js` that adds the key (so the key never reaches the browser) and passes only the six tools the page uses (`box_view`, `box_view_token`, `box_status`, `box_approvals`, `box_approval_token`, `box_approval_answer`).
-Tested on dsh 0.2.1-rc.5 web, which serves the same UI as Desktop.
+Tested on dsh 0.2.1-rc.5 web, which serves the same UI as Desktop. The live view was tested on dsh 0.2.2-rc.1 web.
Contributed by Dora Qian (originally in simular-ai/box-portal#18).
diff --git a/dsh/client.js b/dsh/client.js
index c2db707..a4be072 100644
--- a/dsh/client.js
+++ b/dsh/client.js
@@ -8,7 +8,7 @@ window.__ModuleLoader__.load({
id: '@simular/dsh-box',
factory: (require) => {
const { jsx, jsxs } = require('react/jsx-runtime')
- const { useCallback, useEffect, useState } = require('react')
+ const { useCallback, useEffect, useRef, useState } = require('react')
const { SettingsForm, SettingsSecretField } = require('@deepseek-ai/dsh-client-ui-primitives')
const PKG = '@simular/dsh-box'
@@ -27,6 +27,8 @@ window.__ModuleLoader__.load({
saveFailed: 'Couldn’t save the key. Try again.',
save: 'Save',
saving: 'Saving…',
+ liveTitle: 'box by Simular · live screen',
+ liveFailed: 'Couldn’t show the live screen:',
}
const zh = {
token: 'box 个人 key',
@@ -39,6 +41,8 @@ window.__ModuleLoader__.load({
saveFailed: 'key 没有保存成功,请再试一次。',
save: '保存',
saving: '保存中…',
+ liveTitle: 'box by Simular · 实时画面',
+ liveFailed: '实时画面没能显示:',
}
function BoxTokenPage({ ctx, t }) {
@@ -120,6 +124,306 @@ window.__ModuleLoader__.load({
})
}
+ // --- Live view: box_view's screen in the chat.
+ //
+ // box serves its live view as an MCP App (ui://box/live): ChatGPT and Claude render it inline for
+ // box_view. dsh has no MCP Apps host, so this view is one, just for that page: it loads the page
+ // into a sandboxed iframe (no same-origin, so it cannot reach dsh) and answers the page's
+ // MCP Apps requests. The page's tool calls go to the Host half's relay route, which adds the key.
+
+ const VIEW_TOOL = 'mcp__box__box_view'
+ // Document-relative, like dsh's own routes: Web serves it from the page's origin, Desktop bridges it.
+ const LIVE_ROUTE = 'api/simular-box/live'
+ const APPS_PROTOCOL = '2026-01-26'
+
+ async function relay(body) {
+ const res = await fetch(LIVE_ROUTE, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'same-origin',
+ body: JSON.stringify(body),
+ })
+ const data = await res.json().catch(() => ({}))
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`)
+ return data
+ }
+
+ let pagePromise
+ function livePage() {
+ pagePromise ??= relay({ op: 'page' }).then((data) => data.html).catch((err) => {
+ pagePromise = undefined
+ throw err
+ })
+ return pagePromise
+ }
+
+ function readArgs(block) {
+ const raw = block?.argsRaw ?? block?.call?.argsRaw
+ if (typeof raw !== 'string' || !raw) return {}
+ try {
+ const value = JSON.parse(raw)
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
+ } catch {
+ return {}
+ }
+ }
+
+ // box mirrors box_view's structuredContent ({ box_id, name, state, view_url }) as JSON in its text
+ // block, and dsh keeps the text, so the result for the page is rebuilt from it.
+ function readResult(block) {
+ const text = (block?.content ?? []).filter((c) => c?.type === 'text').map((c) => c.text).join('\n')
+ if (block?.isError) {
+ return { isError: true, content: [{ type: 'text', text: text || block?.error?.reason || 'box_view failed' }] }
+ }
+ let structured
+ try {
+ structured = JSON.parse(text)
+ } catch {}
+ if (!structured?.box_id) return { isError: true, content: [{ type: 'text', text: text || 'box_view sent no box' }] }
+ return { isError: false, content: [{ type: 'text', text }], structuredContent: structured }
+ }
+
+ const isDark = () => {
+ const root = document.documentElement
+ if (root.dataset.theme === 'dark' || root.classList.contains('dark')) return true
+ if (root.dataset.theme === 'light' || root.classList.contains('light')) return false
+ return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false
+ }
+
+ function LiveView(props) {
+ const { phase, block, t } = props
+ const frame = useRef(null)
+ const state = useRef({ ready: false, args: undefined, result: undefined, sentArgs: false, sentResult: false, nextId: 1 })
+ const [html, setHtml] = useState()
+ const [failed, setFailed] = useState('')
+ const [height, setHeight] = useState(380)
+ // The box screen is 16:10 under a 46px bar; the page's own size report can come up a little short.
+ const [minHeight, setMinHeight] = useState(0)
+ useEffect(() => {
+ const el = frame.current
+ if (!el || typeof ResizeObserver === 'undefined') return undefined
+ const ro = new ResizeObserver(() => setMinHeight(Math.round(el.clientWidth * 0.625) + 70))
+ ro.observe(el)
+ return () => ro.disconnect()
+ }, [html])
+
+ useEffect(() => {
+ let live = true
+ livePage().then((page) => live && setHtml(page), (err) => live && setFailed(err?.message ?? String(err)))
+ return () => {
+ live = false
+ }
+ }, [])
+
+ const post = (message) => frame.current?.contentWindow?.postMessage(message, '*')
+ const flush = () => {
+ const s = state.current
+ if (!s.ready) return
+ if (s.args !== undefined && !s.sentArgs) {
+ s.sentArgs = true
+ post({ jsonrpc: '2.0', method: 'ui/notifications/tool-input', params: { arguments: s.args } })
+ }
+ if (s.result !== undefined && !s.sentResult) {
+ s.sentResult = true
+ post({ jsonrpc: '2.0', method: 'ui/notifications/tool-result', params: s.result })
+ }
+ }
+
+ // Arguments exist from the start phase, the result from the result phase.
+ useEffect(() => {
+ if (phase === 'preparing') return
+ state.current.args ??= readArgs(block)
+ if (phase === 'result') state.current.result ??= readResult(block)
+ flush()
+ if (phase !== 'auto' || state.current.statusAsked) return
+ // No box_view result to hand the page: box_status names the box and its view_url instead.
+ state.current.statusAsked = true
+ const ref = typeof state.current.args.box === 'string' ? { box: state.current.args.box } : {}
+ relay({ op: 'tool', name: 'box_status', arguments: ref }).then(({ result }) => {
+ const sc = result?.structuredContent
+ state.current.result = result && !result.isError && sc?.box_id
+ ? { isError: false, content: [{ type: 'text', text: JSON.stringify(sc) }], structuredContent: { box_id: sc.box_id, name: sc.name, state: sc.state, view_url: sc.view_url } }
+ : { isError: true, content: result?.content ?? [{ type: 'text', text: 'Could not find the box.' }] }
+ flush()
+ }, (err) => {
+ state.current.result = { isError: true, content: [{ type: 'text', text: err?.message ?? String(err) }] }
+ flush()
+ })
+ }, [phase, block])
+
+ useEffect(() => {
+ if (!html) return undefined
+ const handle = async (method, params) => {
+ switch (method) {
+ case 'ui/initialize':
+ return {
+ protocolVersion: params?.protocolVersion || APPS_PROTOCOL,
+ hostInfo: { name: 'DeepSeek Harness (box plugin)', version: '0.3.0' },
+ hostCapabilities: { openLinks: {}, serverTools: {} },
+ hostContext: {
+ theme: isDark() ? 'dark' : 'light',
+ displayMode: 'inline',
+ availableDisplayModes: ['inline'],
+ platform: 'desktop',
+ toolInfo: { tool: { name: 'box_view', inputSchema: { type: 'object' } } },
+ },
+ }
+ case 'tools/call': {
+ const data = await relay({ op: 'tool', name: params?.name, arguments: params?.arguments ?? {} })
+ return data.result
+ }
+ case 'ui/open-link': {
+ const url = String(params?.url ?? '')
+ if (!/^https:\/\//.test(url)) throw new Error('only https links open')
+ window.open(url, '_blank', 'noopener,noreferrer')
+ return {}
+ }
+ case 'ui/request-display-mode':
+ return { mode: 'inline' }
+ case 'ui/update-model-context':
+ case 'ping':
+ return {}
+ default: {
+ const err = new Error(`${method} is not supported here`)
+ err.code = -32601
+ throw err
+ }
+ }
+ }
+ const onMessage = (event) => {
+ if (!frame.current || event.source !== frame.current.contentWindow) return
+ const m = event.data
+ if (!m || m.jsonrpc !== '2.0' || typeof m.method !== 'string') return
+ if (m.id === undefined) {
+ if (m.method === 'ui/notifications/initialized') {
+ state.current.ready = true
+ flush()
+ } else if (m.method === 'ui/notifications/size-changed') {
+ const h = Number(m.params?.height)
+ if (Number.isFinite(h) && h > 0) setHeight(Math.min(Math.max(Math.round(h), 220), 900))
+ }
+ return
+ }
+ handle(m.method, m.params).then(
+ (result) => post({ jsonrpc: '2.0', id: m.id, result: result ?? {} }),
+ (err) => post({ jsonrpc: '2.0', id: m.id, error: { code: err?.code ?? -32000, message: err?.message ?? String(err) } }),
+ )
+ }
+ window.addEventListener('message', onMessage)
+ return () => {
+ window.removeEventListener('message', onMessage)
+ post({ jsonrpc: '2.0', id: `teardown-${state.current.nextId++}`, method: 'ui/resource-teardown', params: {} })
+ }
+ }, [html])
+
+ // The page has its own bar (box name, Live, Take control), so this line shows only before it loads or if it fails.
+ const head = jsx('div', { style: { fontSize: 13, opacity: 0.75, margin: '2px 0 6px' }, children: t('liveTitle') })
+ if (failed) {
+ return jsxs('div', { children: [head, jsx('div', { style: { fontSize: 13, opacity: 0.7 }, children: `${t('liveFailed')} ${failed}` }, 'err')] })
+ }
+ if (phase === 'preparing' || !html) return jsxs('div', { children: [head] })
+ return jsxs('div', {
+ children: [
+ jsx('iframe', {
+ ref: frame,
+ title: t('liveTitle'),
+ srcDoc: html,
+ // No allow-same-origin: the page gets an opaque origin and cannot touch dsh.
+ sandbox: 'allow-scripts allow-popups allow-popups-to-escape-sandbox',
+ scrolling: 'no',
+ style: { display: 'block', width: '100%', height: Math.max(height, minHeight), border: 0, borderRadius: 12, background: 'transparent' },
+ }, 'frame'),
+ ],
+ })
+ }
+
+ // --- Where the view sits in the chat.
+ //
+ // dsh folds a turn's tool calls into "Called tools" as soon as the next call starts, so a
+ // tool-call card would hide the screen while the agent works. Instead a conversation definition
+ // publishes the view as its own chat node at the turn level (groupTree 'turn'), which dsh keeps
+ // outside the folded process, running or finished. It sits where box_view was called.
+ // Contexts are keyed by turn: the engine refuses an update before its start, and a tool/result
+ // alone does not say which tool it answers.
+
+ const NODE_KIND = 'simular-box-live'
+
+ // box tools that don't touch the screen: account and box management, and shell and file work
+ // that runs out of sight. Every other box tool (clicks, typing, the browser, screenshots, waking)
+ // is screen work; a tool box adds later counts as screen work too.
+ const OFFSCREEN = new Set([
+ 'box_list', 'box_status', 'box_hibernate', 'box_save', 'box_snapshots', 'box_restore_paths', 'box_upgrade',
+ 'box_delete', 'usage', 'billing', 'box_view_token', 'box_approvals', 'box_approval_token', 'box_approval_answer',
+ 'shell', 'exec', 'read_file', 'write_file', 'edit_file', 'list_dir',
+ ])
+ const BOX_PREFIX = 'mcp__box__'
+ function isScreenTool(name) {
+ return typeof name === 'string' && name.startsWith(BOX_PREFIX) && !OFFSCREEN.has(name.slice(BOX_PREFIX.length))
+ }
+
+ const viewDefinition = {
+ kind: NODE_KIND,
+ target: 'chat',
+ match: (event) => {
+ if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' }
+ if (event.type === 'tool/call') return { id: String(event.data.turn), role: 'update' }
+ if (event.type === 'tool/result' && event.surfaceOp === 'append') return { id: String(event.data.turn), role: 'update' }
+ return null
+ },
+ start: () => ({ call: undefined, result: undefined }),
+ update: (context, match) => {
+ const event = match.event
+ const state = context.state
+ if (event.type === 'tool/call') {
+ const name = event.data.name
+ const call = { callId: String(event.data.callId), argsRaw: event.data.arguments, seq: event.seq, time: event.time }
+ // box_view always gets the view. Any other box tool that works on the screen opens one too,
+ // once per turn, so the person sees the box without the agent being asked to show it.
+ if (name === VIEW_TOOL) return state.call && !state.call.auto ? state : { call, result: undefined }
+ if (!state.call && isScreenTool(name)) return { call: { ...call, auto: true }, result: undefined }
+ return state
+ }
+ if (event.type !== 'tool/result' || !state.call || state.call.auto) return state
+ if (String(event.data.message.source.callId) !== state.call.callId || state.result) return state
+ return {
+ ...state,
+ result: {
+ kind: 'tool-result',
+ seq: event.seq,
+ time: event.time,
+ callId: state.call.callId,
+ name: VIEW_TOOL,
+ call: { name: VIEW_TOOL, argsRaw: state.call.argsRaw },
+ callTime: state.call.time,
+ content: event.data.message.content,
+ isError: event.data.message.isError === true,
+ subCalls: [],
+ },
+ }
+ },
+ buildViewNode: (context) => {
+ const state = context.state
+ if (!state?.call) return null
+ return {
+ key: context.key,
+ kind: NODE_KIND,
+ id: context.id,
+ target: 'chat',
+ anchorSeq: state.call.seq,
+ location: context.start?.location ?? context.matches[0]?.location ?? { kind: 'unresolved' },
+ visibility: state.result?.isError ? 'hidden' : 'visible',
+ groupTree: 'turn',
+ data: { call: state.call, result: state.result },
+ }
+ },
+ }
+
+ function LiveNode({ node, t }) {
+ const { call, result } = node.data
+ const block = result ?? { argsRaw: call.argsRaw }
+ return jsx(LiveView, { phase: call.auto ? 'auto' : result ? 'result' : 'start', block, t }, call.callId)
+ }
+
const inject = ['slots', 'locale', 'remote', 'remote.credentials']
function apply(ctx) {
@@ -129,6 +433,15 @@ window.__ModuleLoader__.load({
key: PKG,
locale: NS,
}, ({ t, view }) => (view === 'summary' ? t('token') : jsx(BoxTokenPage, { ctx, t })))), 'dsh-box: token page')
+ // Optional: a client without the conversation service still gets the key page.
+ ctx.inject(['uiConversation'], (scope) => {
+ scope.effect(() => scope.uiConversation.events.register(viewDefinition), 'dsh-box: live view node')
+ scope.effect(() => scope.slots.inject('conversation.chat.node', () => scope.slots.register({
+ name: 'conversation.chat.node',
+ key: NODE_KIND,
+ locale: NS,
+ }, LiveNode)), 'dsh-box: live view renderer')
+ })
}
return { apply, inject }
diff --git a/dsh/icon.svg b/dsh/icon.svg
index 9949439..803c49b 100644
--- a/dsh/icon.svg
+++ b/dsh/icon.svg
@@ -1 +1,5 @@
-
+
diff --git a/dsh/index.js b/dsh/index.js
index faf2786..2e4af99 100644
--- a/dsh/index.js
+++ b/dsh/index.js
@@ -6,13 +6,34 @@
* falls back to the launch environment and ~/.dsh/.env) and provides it as the `boxAuth` service.
* The `mcp-box` row injects `boxAuth`, so it starts once a key exists and restarts with the new
* header whenever the key changes. The browser half (client.js) is the key page on Plugins.
+ *
+ * It also serves the live view that client.js shows in the chat for box_view: box's MCP App
+ * (ui://box/live), the same page ChatGPT and Claude render inline. The page runs in a sandboxed
+ * iframe and calls a few box tools through its host; this route relays those calls with the key,
+ * which never reaches the browser. Only the tools the page needs pass.
*/
export const name = '@simular/dsh-box'
export const inject = ['credentials']
const REF = 'BOX_TOKEN'
+const MCP_URL = process.env.BOX_MCP_URL || 'https://mcp.box.simular.ai/mcp'
+/** Relative to the shared /api channel; client.js posts to the same path without the leading slash. */
+const LIVE_PATH = '/api/simular-box/live'
+const LIVE_URI = 'ui://box/live'
+/** The tools the live view calls (live.js): screen token, state, waking, approvals. */
+const VIEW_TOOLS = new Set([
+ 'box_view',
+ 'box_view_token',
+ 'box_status',
+ 'box_approvals',
+ 'box_approval_token',
+ 'box_approval_answer',
+])
+const PROTOCOL = '2025-06-18'
+const CALL_TIMEOUT_MS = 180_000
export function apply(ctx) {
+ let token
let unprovide
let generation = 0
const refresh = async () => {
@@ -21,15 +42,159 @@ export function apply(ctx) {
if (mine !== generation) return
unprovide?.()
unprovide = undefined
- const token = hit?.value?.trim()
+ token = hit?.value?.trim() || undefined
+ mcp.reset()
if (token) unprovide = ctx.provide('boxAuth', { authorization: `Bearer ${token}` })
}
// Log why the key couldn't be read (never the key itself); otherwise mcp-box just waits on
// boxAuth with no reason shown.
const refreshLogged = () =>
refresh().catch((err) => ctx.logger?.warn('box: could not read BOX_TOKEN', err?.message))
+
+ const mcp = createMcp(() => token)
+
ctx.on('credentials/reference-updated', (ref) => {
if (ref === REF) void refreshLogged()
})
void refreshLogged()
+
+ // Only owner Peers reach an exact route (Connection answers 403 for anyone else), on Web and Desktop alike.
+ ctx.inject(['connection'], (scope) => {
+ scope.effect(() => scope.connection.fetch.register({
+ path: LIVE_PATH,
+ methods: ['POST'],
+ requestBody: 'buffered',
+ fetch: (request) => serveLive(request, mcp, () => token),
+ }), 'dsh-box: live view route')
+ })
+}
+
+/** One relay request: `{ op: 'page' }` reads the view's page, `{ op: 'tool', name, arguments }` calls a view tool. */
+async function serveLive(request, mcp, currentToken) {
+ let body
+ try {
+ body = await request.json()
+ } catch {
+ return json({ error: 'bad request' }, 400)
+ }
+ if (!currentToken()) return json({ error: 'No box key yet. Add one on the box plugin page under Plugins.' }, 409)
+ try {
+ if (body?.op === 'page') {
+ const read = await mcp.request('resources/read', { uri: LIVE_URI })
+ const page = read?.contents?.find((c) => c?.uri === LIVE_URI)
+ if (typeof page?.text !== 'string') return json({ error: 'box sent no live view page' }, 502)
+ return json({ html: page.text, meta: page._meta ?? null })
+ }
+ if (body?.op === 'tool' && typeof body.name === 'string' && VIEW_TOOLS.has(body.name)) {
+ const args = body.arguments && typeof body.arguments === 'object' ? body.arguments : {}
+ return json({ result: await mcp.request('tools/call', { name: body.name, arguments: args }) })
+ }
+ return json({ error: 'not allowed' }, 403)
+ } catch (err) {
+ return json({ error: err?.message ?? String(err) }, 502)
+ }
+}
+
+function json(value, status = 200) {
+ return new Response(JSON.stringify(value), {
+ status,
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
+ })
+}
+
+/**
+ * A minimal Streamable HTTP MCP client for the relay: one session per key, opened on first use and
+ * again when the server drops it. Answers may come as JSON or as an SSE stream.
+ */
+function createMcp(currentToken) {
+ let session
+ let opening
+ let nextId = 1
+
+ async function post(message, sessionId) {
+ const headers = {
+ authorization: `Bearer ${currentToken()}`,
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ 'mcp-protocol-version': PROTOCOL,
+ }
+ if (sessionId) headers['mcp-session-id'] = sessionId
+ const res = await fetch(MCP_URL, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(message),
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
+ })
+ return res
+ }
+
+ async function answer(res, id) {
+ if (!res.ok) {
+ const err = new Error(res.status === 401 ? 'box refused the key (401). Check it on the box plugin page.' : `box answered ${res.status}`)
+ err.status = res.status
+ throw err
+ }
+ if (id === undefined) return undefined
+ const type = res.headers.get('content-type') ?? ''
+ let message
+ if (type.includes('text/event-stream')) {
+ const text = await res.text()
+ for (const block of text.split(/\r?\n\r?\n/)) {
+ const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trimStart()).join('\n')
+ if (!data) continue
+ const parsed = JSON.parse(data)
+ if (parsed?.id === id) message = parsed
+ }
+ } else {
+ message = await res.json()
+ }
+ if (!message) throw new Error('box sent no answer')
+ if (message.error) throw new Error(message.error.message ?? 'box error')
+ return message.result
+ }
+
+ async function open() {
+ const id = nextId++
+ const res = await post({
+ jsonrpc: '2.0',
+ id,
+ method: 'initialize',
+ params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'dsh-box-live-view', version: '0.3.0' } },
+ })
+ await answer(res, id)
+ const sessionId = res.headers.get('mcp-session-id') ?? ''
+ await answer(await post({ jsonrpc: '2.0', method: 'notifications/initialized' }, sessionId), undefined)
+ return sessionId
+ }
+
+ async function ensure() {
+ if (session !== undefined) return session
+ opening ??= open().finally(() => {
+ opening = undefined
+ })
+ session = await opening
+ return session
+ }
+
+ return {
+ reset() {
+ session = undefined
+ },
+ async request(method, params) {
+ for (let attempt = 0; ; attempt++) {
+ const sessionId = await ensure()
+ const id = nextId++
+ try {
+ return await answer(await post({ jsonrpc: '2.0', id, method, params }, sessionId), id)
+ } catch (err) {
+ // A dropped or expired session answers 404 (or 400): open a new one once.
+ if (attempt === 0 && (err.status === 404 || err.status === 400)) {
+ session = undefined
+ continue
+ }
+ throw err
+ }
+ }
+ },
+ }
}
diff --git a/dsh/locale/en.json b/dsh/locale/en.json
index 53e2b16..e73630b 100644
--- a/dsh/locale/en.json
+++ b/dsh/locale/en.json
@@ -1,6 +1,6 @@
{
"meta": {
- "title": "box",
- "description": "A cloud desktop your agent drives over MCP, by Simular."
+ "title": "box by Simular",
+ "description": "A cloud computer your agent drives over MCP: Chrome, desktop apps and a shell."
}
}
diff --git a/dsh/locale/zh.json b/dsh/locale/zh.json
index 9e4771f..120e8a5 100644
--- a/dsh/locale/zh.json
+++ b/dsh/locale/zh.json
@@ -1,6 +1,6 @@
{
"meta": {
- "title": "box",
- "description": "Simular 的云端电脑,你的 agent 通过 MCP 操作它。"
+ "title": "box by Simular",
+ "description": "给你的 agent 一台云端电脑,有 Chrome、桌面应用和终端,通过 MCP 操作。"
}
}
diff --git a/dsh/package.json b/dsh/package.json
index 3b00fe3..6603044 100644
--- a/dsh/package.json
+++ b/dsh/package.json
@@ -1,6 +1,6 @@
{
"name": "@simular/dsh-box",
- "version": "0.2.1",
+ "version": "0.3.0",
"description": "box by Simular: a cloud desktop your agent drives over MCP",
"license": "MIT",
"type": "module",