moi-computer 0.13.1-next.2 → 0.13.1-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/client/features/chat/sessions/use-selected-session.ts +0 -13
  2. package/client/features/views/api.ts +33 -8
  3. package/client/features/views/use-view-actions.ts +2 -23
  4. package/client/features/workspace/tab-resolution.ts +1 -8
  5. package/client/features/workspace/use-workspace-navigation.ts +4 -3
  6. package/client/features/workspace/workspace-content.tsx +2 -11
  7. package/client/features/workspace/workspace-preferences.ts +67 -10
  8. package/client/features/workspace/workspace-state.ts +40 -15
  9. package/client/store/ui.ts +1 -6
  10. package/client/store/workspace-session.ts +30 -0
  11. package/dist/chunk-0h4zypgf.js +1 -0
  12. package/dist/chunk-1tksq43z.js +72 -0
  13. package/dist/chunk-6gxf0xr8.js +5 -0
  14. package/dist/{chunk-ec5ennpv.js → chunk-a865c7x4.js} +1 -1
  15. package/dist/{chunk-pdt9hxfw.js → chunk-f44cs6mw.js} +2 -2
  16. package/dist/{chunk-44khk4sp.js → chunk-h3qag4a6.js} +2 -2
  17. package/dist/{chunk-ectsnw81.js → chunk-q2tpy0h7.js} +2 -2
  18. package/dist/{chunk-rmd0ctfx.js → chunk-r95acex1.js} +74 -74
  19. package/dist/chunk-w5h9grdr.js +1 -0
  20. package/dist/{chunk-n0fawy9x.js → chunk-xj1pjhng.js} +1 -1
  21. package/dist/index.html +1 -1
  22. package/lib/moi-context.ts +19 -5
  23. package/lib/types.ts +4 -5
  24. package/lib/workspace-layout.ts +3 -20
  25. package/package.json +2 -1
  26. package/server/AGENTS.md +1 -1
  27. package/server/README.md +21 -18
  28. package/server/api/index.ts +122 -118
  29. package/server/cli/commands/init.ts +7 -2
  30. package/server/cli/commands/remote.ts +128 -26
  31. package/server/cli/remote-control.ts +12 -9
  32. package/server/cli/remote-operations.ts +47 -44
  33. package/server/control.ts +9 -1
  34. package/server/onboarding/jobs.ts +1 -1
  35. package/server/remote/broker-client.ts +76 -0
  36. package/server/remote/broker.ts +81 -0
  37. package/server/remote/client.ts +212 -152
  38. package/server/remote/errors.ts +2 -0
  39. package/server/remote/routes.ts +121 -0
  40. package/server/scratchpad/document.ts +3 -2
  41. package/server/sessions/pending-views.ts +2 -1
  42. package/server/sessions/send-message.ts +102 -0
  43. package/server/sessions/view-sessions.ts +4 -94
  44. package/server/web.ts +2 -1
  45. package/server/workspace-state/file.ts +2 -0
  46. package/server/workspaces/api.ts +4 -8
  47. package/server/workspaces/tabs.ts +1 -2
  48. package/skill/SKILL.md +75 -34
  49. package/skill/references/SCRATCHPAD.md +4 -0
  50. package/skill/references/UI-COMPONENTS.md +1 -1
  51. package/dist/chunk-ba6mz56s.js +0 -72
  52. package/dist/chunk-en7w5ypg.js +0 -1
  53. package/dist/chunk-f695wcx5.js +0 -5
  54. package/dist/chunk-zv22wv0g.js +0 -1
@@ -6,12 +6,15 @@ import { clearLine, cursorTo } from 'node:readline'
6
6
  import { currentRemoteWorkspace } from '../../remote/workspace'
7
7
  import { parseRemoteWorkspaceAddress } from '@/lib/workspace-config'
8
8
  import pc from '../pc'
9
+ import { columns, keyValue } from '../ui'
10
+ import { resolveWorkspace, staleSkillNotice } from '../../skills/version'
11
+ import { getLayoutPath } from '../../workspaces/layout'
9
12
  import {
10
13
  login as signIn,
11
14
  logout as signOut,
12
15
  CloudSignInRequired,
13
- remoteConfig,
14
16
  remoteStatus,
17
+ fetchSharedWorkspaces,
15
18
  invitations as listInvitations,
16
19
  accept as acceptInvitation,
17
20
  renameAgent,
@@ -22,6 +25,17 @@ import {
22
25
  // oxlint-disable-next-line no-control-regex -- Deliberately remove terminal control characters.
23
26
  const text = (value: string) => Bun.stripANSI(value).replace(/[\u0000-\u001f\u007f-\u009f]/g, '')
24
27
 
28
+ async function warnIfSkillStale() {
29
+ try {
30
+ const { root, harness } = await resolveWorkspace(process.cwd())
31
+ if (!harness && !(await Bun.file(getLayoutPath(root)).exists())) return
32
+ const notice = await staleSkillNotice(root)
33
+ if (notice) console.error('\n' + pc.yellow(notice))
34
+ } catch {
35
+ // A skill check must not prevent displaying remote status.
36
+ }
37
+ }
38
+
25
39
  async function reportErrors(action: () => Promise<void>): Promise<void> {
26
40
  try {
27
41
  await action()
@@ -70,7 +84,7 @@ function waitingForLogin(): () => void {
70
84
  }
71
85
 
72
86
  const login = defineCommand({
73
- meta: { name: 'login', description: 'Sign in to Moi Cloud in your browser' },
87
+ meta: { name: 'login', description: 'Sign in to Moi Cloud in your browser (for humans only)' },
74
88
  args: {
75
89
  browser: {
76
90
  type: 'boolean',
@@ -90,7 +104,9 @@ const login = defineCommand({
90
104
  } finally {
91
105
  stopWaiting()
92
106
  }
93
- console.log(`\n${pc.green('Congratulations!')} You are now signed in.\n`)
107
+ const { me } = await remoteStatus()
108
+ const identity = 'email' in me ? me.email : me.name
109
+ console.log(`${pc.green('✓')} Signed in as ${text(identity)}\n`)
94
110
  })
95
111
  }
96
112
  })
@@ -107,12 +123,11 @@ const logout = defineCommand({
107
123
  })
108
124
 
109
125
  const jsonArg = { type: 'boolean' as const, description: 'Print JSON' }
110
- const pathArg = {
111
- type: 'string' as const,
112
- description: 'Local workspace folder (defaults to current folder)'
113
- }
114
126
  const rename = defineCommand({
115
- meta: { name: 'rename-agent', description: 'Change your agent name across workspaces' },
127
+ meta: {
128
+ name: 'rename-agent',
129
+ description: 'Change your agent name across workspaces (for agents only)'
130
+ },
116
131
  args: { name: { type: 'positional', required: true }, json: jsonArg },
117
132
  async run({ args }) {
118
133
  await reportErrors(async () => {
@@ -137,12 +152,59 @@ const invitations = defineCommand({
137
152
  })
138
153
  }
139
154
  })
155
+ const workspaces = defineCommand({
156
+ meta: { name: 'workspaces', description: 'List shared workspaces and pending invitations' },
157
+ args: { json: jsonArg },
158
+ async run({ args }) {
159
+ await reportErrors(async () => {
160
+ const [available, pending] = await Promise.all([fetchSharedWorkspaces(), listInvitations()])
161
+ if (args.json) {
162
+ console.log(JSON.stringify({ workspaces: available, invitations: pending }, null, 2))
163
+ return
164
+ }
165
+ console.log('\n' + pc.bold('Available shared workspaces') + '\n')
166
+ if (available.length) {
167
+ console.log(
168
+ columns(
169
+ ['Workspace', 'Shared by', 'Remote ID'].map(label => pc.dim(label)),
170
+ available.map(workspace => [
171
+ text(workspace.id),
172
+ text(workspace.owner.email),
173
+ text(`${workspace.owner.id}:${workspace.id}`)
174
+ ])
175
+ )
176
+ )
177
+ console.log(
178
+ '\n' + pc.dim('To link from a new folder: ') + pc.cyan('moi init --remote <remote-id>')
179
+ )
180
+ } else console.log(' No shared workspaces yet')
181
+ console.log('\n' + pc.bold('Pending invitations') + '\n')
182
+ if (pending.length) {
183
+ console.log(
184
+ columns(
185
+ ['Workspace', 'Invited by', 'Invitation ID'].map(label => pc.dim(label)),
186
+ pending.map(invitation => [
187
+ text(invitation.workspaceName),
188
+ text(invitation.inviter.email),
189
+ text(invitation.id)
190
+ ])
191
+ )
192
+ )
193
+ console.log('\n' + pc.dim('To accept: ') + pc.cyan('moi remote accept <invitation-id>'))
194
+ } else console.log(' No pending invitations')
195
+ console.log('\nHelp and full command list: ' + pc.cyan('moi remote workspaces --help') + '\n')
196
+ })
197
+ }
198
+ })
140
199
  const accept = defineCommand({
141
200
  meta: { name: 'accept', description: 'Accept a workspace invitation as a human or agent' },
142
201
  args: {
143
202
  invite: { type: 'positional', required: true },
144
- name: { type: 'string', description: 'Name for a new agent identity' },
145
- client: { type: 'string', description: 'Agent client: ' + AGENT_CLIENTS.join(', ') },
203
+ name: { type: 'string', description: 'Your agent display name, shown to workspace members' },
204
+ client: {
205
+ type: 'string',
206
+ description: 'The app you run in: ' + AGENT_CLIENTS.join(', ') + '; use other if not listed'
207
+ },
146
208
  json: jsonArg
147
209
  },
148
210
  async run({ args }) {
@@ -151,7 +213,7 @@ const accept = defineCommand({
151
213
  console.log(
152
214
  args.json
153
215
  ? JSON.stringify(result)
154
- : `Invitation accepted\n\nmoi init --remote ${result.remote.user_id}:${result.remote.workspace_id}`
216
+ : `Invitation accepted\n\nCreate a local linked folder (choose an unused folder name):\nmoi init ./workspace-folder --remote ${result.remote.user_id}:${result.remote.workspace_id}`
155
217
  )
156
218
  })
157
219
  }
@@ -164,19 +226,18 @@ const leave = defineCommand({
164
226
  required: false,
165
227
  description: 'ownerId:workspaceId (defaults to current folder)'
166
228
  },
167
- path: pathArg,
168
229
  json: jsonArg
169
230
  },
170
231
  async run({ args }) {
171
232
  await reportErrors(async () => {
172
- if (args.workspace !== undefined && args.path)
173
- throw new Error('Use a workspace address or --path, not both')
174
233
  const target =
175
234
  args.workspace !== undefined
176
235
  ? parseRemoteWorkspaceAddress(args.workspace)
177
- : await currentRemoteWorkspace(args.path)
236
+ : await currentRemoteWorkspace()
178
237
  if (!target)
179
- throw new Error('No remote workspace here — provide ownerId:workspaceId or --path')
238
+ throw new Error(
239
+ 'No remote workspace here — run from a linked workspace folder or provide ownerId:workspaceId'
240
+ )
180
241
  const result = await leaveWorkspace(target.user_id, target.workspace_id)
181
242
  console.log(args.json ? JSON.stringify(result) : 'Left the workspace; local files kept')
182
243
  })
@@ -187,15 +248,25 @@ const remoteSubCommands = {
187
248
  login,
188
249
  logout,
189
250
  'rename-agent': rename,
251
+ workspaces,
190
252
  invitations,
191
253
  accept,
192
254
  leave
193
255
  }
194
256
 
195
257
  export const remote = defineCommand({
196
- meta: { name: 'remote', description: 'Show your cloud account and shared workspaces' },
197
- args: { json: jsonArg, path: pathArg },
258
+ meta: { name: 'remote', description: 'Show your identity and linked workspace commands' },
259
+ args: { json: jsonArg },
198
260
  subCommands: remoteSubCommands,
261
+ setup({ rawArgs }) {
262
+ // Citty accepts unknown options. Reject the removed selector before dispatch
263
+ // so an old script cannot silently operate on the current workspace.
264
+ const separator = rawArgs.indexOf('--')
265
+ const options = separator < 0 ? rawArgs : rawArgs.slice(0, separator)
266
+ if (options.some(arg => arg === '--path' || arg.startsWith('--path='))) {
267
+ throw new Error('Unknown option --path — run this command from the workspace folder')
268
+ }
269
+ },
199
270
  async run({ args, rawArgs }) {
200
271
  // citty also runs the parent after a subcommand; only bare `remote` shows status.
201
272
  const sub = rawArgs.find(arg => !arg.startsWith('-'))
@@ -203,26 +274,57 @@ export const remote = defineCommand({
203
274
  await reportErrors(async () => {
204
275
  const status = {
205
276
  ...(await remoteStatus()),
206
- currentWorkspace: await currentRemoteWorkspace(args.path)
277
+ currentWorkspace: await currentRemoteWorkspace()
207
278
  }
208
279
  if (args.json) {
209
280
  console.log(JSON.stringify(status, null, 2))
281
+ await warnIfSkillStale()
210
282
  return
211
283
  }
284
+ const detail = 'email' in status.me ? status.me.email : status.me.client
212
285
  console.log(
213
- `\n${text(status.me.name || ('email' in status.me ? status.me.email : status.me.client))} <${text('email' in status.me ? status.me.email : status.me.client)}>\nAccount: ${text(status.me.id)}\nCloud: ${(await remoteConfig()).url}\n`
286
+ '\nSigned in as ' + pc.bold(text(status.me.name || detail)) + pc.dim(` <${text(detail)}>`)
214
287
  )
215
- if (status.currentWorkspace)
288
+ const linked = status.currentWorkspace
289
+ if (linked) {
290
+ const workspace = status.workspaces.find(
291
+ item => item.id === linked.workspace_id && item.owner.id === linked.user_id
292
+ )
293
+ console.log(
294
+ '\nCurrent workspace is linked to: ' +
295
+ pc.bold(text(linked.workspace_id)) +
296
+ (workspace ? ' by ' + text(workspace.owner.email) : '')
297
+ )
298
+ console.log('Remote ID: ' + text(`${linked.user_id}:${linked.workspace_id}`))
216
299
  console.log(
217
- `Remote workspace: ${text(status.currentWorkspace.user_id)}:${text(status.currentWorkspace.workspace_id)}\n`
300
+ '\n' +
301
+ keyValue([
302
+ [pc.cyan('moi remote read <remote-path>'), 'Read a file'],
303
+ [pc.cyan('moi remote write <remote-path> "content"'), 'Write a file'],
304
+ [pc.cyan('moi remote patch <remote-path>'), 'Apply a diff from stdin'],
305
+ [pc.cyan('moi remote exec "command"'), 'Run a command remotely'],
306
+ [pc.cyan('moi remote file-upload <local-path> <remote-path>'), 'Upload a local file'],
307
+ [
308
+ pc.cyan('moi remote file-download <remote-path> <local-path>'),
309
+ 'Download a remote file'
310
+ ]
311
+ ])
218
312
  )
219
- console.log('Shared workspaces')
220
- if (!status.workspaces.length) console.log(' No shared workspaces')
221
- for (const workspace of status.workspaces)
222
313
  console.log(
223
- ` ${text(workspace.owner.id)}:${text(workspace.id)} — ${text(workspace.owner.name || workspace.owner.email)} <${text(workspace.owner.email)}>`
314
+ '\n' +
315
+ pc.cyan(
316
+ 'moi check|bundle|theme|config|tabs|ui-components|call-server-fn|debug|scratch'
317
+ ) +
318
+ '\n' +
319
+ pc.dim('These regular commands work on the remote workspace')
224
320
  )
321
+ } else {
322
+ console.log('\nThis folder is not linked to a remote workspace')
323
+ }
324
+ console.log('\n' + pc.dim('Help and full command list: ') + pc.cyan('moi remote --help'))
325
+ if (linked) console.log(pc.dim('Command help: ') + pc.cyan('moi remote <command> --help'))
225
326
  console.log()
327
+ await warnIfSkillStale()
226
328
  })
227
329
  }
228
330
  })
@@ -2,10 +2,14 @@ import { basename } from 'node:path'
2
2
  import type { ScratchOp, ViewInfo } from '@/lib/types'
3
3
  import { currentRemoteWorkspace } from '../remote/workspace'
4
4
  import { requestWorkspace } from '../workspaces/api'
5
+ import { cloudRoutes } from '../remote/routes'
5
6
  import { assembleTabRows } from '../workspaces/tabs'
6
7
  import { readScratchpadImage, readScratchpadShapes } from '../scratchpad/document'
7
8
  import type { WorkspaceConfig } from '../workspaces/config'
8
9
 
10
+ const { views, config, icon, scratchpadOps } = cloudRoutes
11
+ const routes = { views, config, icon, scratchpadOps }
12
+
9
13
  type ScratchCliOp = ScratchOp | { kind: 'read' } | { kind: 'read-image'; name: string }
10
14
 
11
15
  // These commands keep parsing, local file IO and output on the caller. Only
@@ -20,26 +24,25 @@ export async function remoteControl(
20
24
  const remote = await currentRemoteWorkspace(path)
21
25
  if (!remote) return
22
26
  const workspace = { remote }
23
- const request = (suffix: string, init?: RequestInit) => requestWorkspace(workspace, suffix, init)
27
+ const request = (route: keyof typeof routes, init?: RequestInit) =>
28
+ requestWorkspace(routes[route].path(remote), init)
24
29
  if (payload.type === 'tabs') {
25
- const { views }: { views: ViewInfo[] } = await (
26
- await request('/views?includePending=true')
27
- ).json()
30
+ const { views }: { views: ViewInfo[] } = await (await request('views')).json()
28
31
  return { tabs: assembleTabRows(views) }
29
32
  }
30
33
  if (payload.type === 'config') {
31
34
  if (typeof payload.iconPath === 'string') {
32
35
  const file = Bun.file(payload.iconPath)
33
36
  if (!(await file.exists())) throw new Error('Local icon file not found')
34
- return { ok: true, ...(await (await request('/icon', { method: 'PUT', body: file })).json()) }
37
+ return { ok: true, ...(await (await request('icon', { method: 'PUT', body: file })).json()) }
35
38
  }
36
39
  if (payload.clearIcon) {
37
- await request('/icon', { method: 'DELETE' })
40
+ await request('icon', { method: 'DELETE' })
38
41
  return { ok: true, clearedIcon: true }
39
42
  }
40
43
  if (payload.name !== undefined || payload.clearName) {
41
44
  const result = await (
42
- await request('/config', {
45
+ await request('config', {
43
46
  method: 'PUT',
44
47
  headers: { 'content-type': 'application/json' },
45
48
  body: JSON.stringify({ name: payload.clearName ? null : payload.name })
@@ -47,7 +50,7 @@ export async function remoteControl(
47
50
  ).json()
48
51
  return { ...result, ok: true, clearedName: payload.clearName === true }
49
52
  }
50
- const config: WorkspaceConfig = await (await request('/config')).json()
53
+ const config: WorkspaceConfig = await (await request('config')).json()
51
54
  return { ...config, hasIcon: !!config.icon }
52
55
  }
53
56
  if (!op) throw new Error('Missing scratch operation')
@@ -65,6 +68,6 @@ export async function remoteControl(
65
68
  } else body.set('op', JSON.stringify(op))
66
69
  return {
67
70
  ok: true,
68
- result: await (await request('/scratchpad/ops', { method: 'POST', body })).json()
71
+ result: await (await request('scratchpadOps', { method: 'POST', body })).json()
69
72
  }
70
73
  }
@@ -1,11 +1,13 @@
1
1
  import { defineCommand } from 'citty'
2
2
  import { mkdir, rename, rm } from 'node:fs/promises'
3
- import { dirname, resolve } from 'node:path'
3
+ import { basename, dirname, resolve } from 'node:path'
4
4
  import { z } from 'zod'
5
- import { operation } from '../remote/client'
5
+ import { remoteRequest } from '../remote/client'
6
+ import { cloudRoutes } from '../remote/routes'
6
7
  import { currentRemoteWorkspace } from '../remote/workspace'
8
+ import { resolveWorkspaceRoot } from '../skills/version'
9
+ import { getLayoutPath, loadWorkspaceFileConfig } from '../workspaces/layout'
7
10
 
8
- const path = { type: 'string' as const, description: 'Local linked workspace folder' }
9
11
  const json = { type: 'boolean' as const, description: 'Print JSON result' }
10
12
  const commandResult = z.object({
11
13
  exitCode: z.number().int(),
@@ -26,7 +28,7 @@ async function printCommandResult(response: Response, json = false) {
26
28
  export async function runLinkedWorkspaceCommand(command: string, args: string[], folder: string) {
27
29
  const linked = await currentRemoteWorkspace(folder)
28
30
  if (!linked) return false
29
- const response = await operation(linked.user_id, linked.workspace_id, '/commands', {
31
+ const response = await remoteRequest(cloudRoutes.commands.path(linked), {
30
32
  method: 'POST',
31
33
  body: JSON.stringify({ command, args }),
32
34
  contentType: 'application/json'
@@ -39,24 +41,28 @@ const execEvent = z.discriminatedUnion('type', [
39
41
  z.object({ type: z.literal('stderr'), data: z.string() }),
40
42
  z.object({ type: z.literal('exit'), code: z.number().int() })
41
43
  ])
42
- const fileSuffix = (value: string) => {
43
- if (
44
- !value ||
45
- value.startsWith('/') ||
46
- value.includes('\\') ||
47
- value.split('/').some(p => p === '.' || p === '..' || !p)
48
- )
49
- throw new Error('Use a file path relative to the remote workspace')
50
- return '/files/' + value.split('/').map(encodeURIComponent).join('/')
51
- }
52
- async function target(folder?: string) {
53
- const current = await currentRemoteWorkspace(folder)
54
- if (!current)
55
- throw new Error(
56
- 'This folder is not a remote workspace — run moi init --remote ownerId:workspaceId first'
57
- )
58
- return (suffix: string, options?: Parameters<typeof operation>[3]) =>
59
- operation(current.user_id, current.workspace_id, suffix, options)
44
+ async function target() {
45
+ const current = await currentRemoteWorkspace()
46
+ if (!current) {
47
+ const root = await resolveWorkspaceRoot(process.cwd())
48
+ const config = await loadWorkspaceFileConfig(root)
49
+ let message = 'This folder is not linked to a remote workspace'
50
+ if (!config.remote && (await Bun.file(getLayoutPath(root)).exists())) {
51
+ const name = Bun.stripANSI(config.name || basename(root)).replace(
52
+ // oxlint-disable-next-line no-control-regex -- Workspace names must not control the terminal.
53
+ /[\u0000-\u001f\u007f-\u009f]/g,
54
+ ''
55
+ )
56
+ message += `\nIt is an existing local workspace: ${name}`
57
+ }
58
+ throw new Error(message)
59
+ }
60
+ type Options = Parameters<typeof remoteRequest>[1]
61
+ return {
62
+ file: (file: string, options?: Options) =>
63
+ remoteRequest(cloudRoutes.files.path(current, file), options),
64
+ exec: (options?: Options) => remoteRequest(cloudRoutes.exec.path(current), options)
65
+ }
60
66
  }
61
67
  async function stdin() {
62
68
  if (process.stdin.isTTY) throw new Error('Supply content or pipe it on stdin')
@@ -66,10 +72,10 @@ async function stdin() {
66
72
  export function remoteOperations(report: (action: () => Promise<void>) => Promise<void>) {
67
73
  const read = defineCommand({
68
74
  meta: { name: 'read', description: 'Read a remote workspace file to stdout' },
69
- args: { file: { type: 'positional', required: true }, path },
75
+ args: { file: { type: 'positional', required: true } },
70
76
  run: ({ args }) =>
71
77
  report(async () => {
72
- const response = await (await target(args.path))(fileSuffix(args.file))
78
+ const response = await (await target()).file(args.file)
73
79
  if (response.body)
74
80
  for await (const chunk of response.body) await Bun.write(Bun.stdout, chunk)
75
81
  })
@@ -79,14 +85,13 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
79
85
  args: {
80
86
  file: { type: 'positional', required: true },
81
87
  content: { type: 'positional', required: false },
82
- path,
83
88
  json
84
89
  },
85
90
  run: ({ args }) =>
86
91
  report(async () => {
87
92
  const response = await (
88
- await target(args.path)
89
- )(fileSuffix(args.file), {
93
+ await target()
94
+ ).file(args.file, {
90
95
  method: 'PUT',
91
96
  body: args.content ?? (await stdin()),
92
97
  contentType: 'application/octet-stream'
@@ -102,7 +107,6 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
102
107
  args: {
103
108
  file: { type: 'positional', required: true },
104
109
  'patch-file': { type: 'string' },
105
- path,
106
110
  json
107
111
  },
108
112
  run: ({ args }) =>
@@ -111,8 +115,8 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
111
115
  ? await Bun.file(resolve(args['patch-file'])).text()
112
116
  : await stdin()
113
117
  const response = await (
114
- await target(args.path)
115
- )(fileSuffix(args.file), {
118
+ await target()
119
+ ).file(args.file, {
116
120
  method: 'PATCH',
117
121
  body: JSON.stringify({ patch: diff }),
118
122
  contentType: 'application/json'
@@ -125,7 +129,6 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
125
129
  args: {
126
130
  source: { type: 'positional', required: true },
127
131
  destination: { type: 'positional', required: true },
128
- path,
129
132
  json
130
133
  },
131
134
  run: ({ args }) =>
@@ -133,8 +136,8 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
133
136
  const file = Bun.file(resolve(args.source))
134
137
  if (!(await file.exists())) throw new Error('Local source file not found')
135
138
  const response = await (
136
- await target(args.path)
137
- )(fileSuffix(args.destination), {
139
+ await target()
140
+ ).file(args.destination, {
138
141
  method: 'PUT',
139
142
  body: file,
140
143
  contentType: 'application/octet-stream'
@@ -152,12 +155,11 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
152
155
  args: {
153
156
  source: { type: 'positional', required: true },
154
157
  destination: { type: 'positional', required: true },
155
- path,
156
158
  json
157
159
  },
158
160
  run: ({ args }) =>
159
161
  report(async () => {
160
- const response = await (await target(args.path))(fileSuffix(args.source))
162
+ const response = await (await target()).file(args.source)
161
163
  const destination = resolve(args.destination),
162
164
  temporary = `${destination}.${crypto.randomUUID()}.tmp`
163
165
  await mkdir(dirname(destination), { recursive: true })
@@ -179,20 +181,21 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
179
181
  name: 'exec',
180
182
  description: 'Run a shell command on the remote host, in this workspace'
181
183
  },
182
- args: { command: { type: 'positional', required: true }, path, json },
184
+ args: { command: { type: 'positional', required: true }, json },
183
185
  run: ({ args }) =>
184
186
  report(async () => {
185
187
  const controller = new AbortController()
186
- const request = await target(args.path)
188
+ const request = await target()
187
189
  const id = crypto.randomUUID()
188
190
  let cancellation: Promise<void> | undefined
189
191
  const interrupt = () => {
190
- cancellation ??= request('/exec', {
191
- method: 'POST',
192
- body: JSON.stringify({ cancel: id }),
193
- contentType: 'application/json',
194
- signal: AbortSignal.timeout(10_000)
195
- })
192
+ cancellation ??= request
193
+ .exec({
194
+ method: 'POST',
195
+ body: JSON.stringify({ cancel: id }),
196
+ contentType: 'application/json',
197
+ signal: AbortSignal.timeout(10_000)
198
+ })
196
199
  .then(async response => {
197
200
  await response.body?.cancel()
198
201
  })
@@ -203,7 +206,7 @@ export function remoteOperations(report: (action: () => Promise<void>) => Promis
203
206
  }
204
207
  process.once('SIGINT', interrupt)
205
208
  try {
206
- const response = await request('/exec', {
209
+ const response = await request.exec({
207
210
  method: 'POST',
208
211
  body: JSON.stringify({ command: args.command, id }),
209
212
  contentType: 'application/json',
package/server/control.ts CHANGED
@@ -39,6 +39,7 @@ import {
39
39
  type WorkspaceConfigPatch
40
40
  } from './workspaces/config'
41
41
  import { VERSION } from './version'
42
+ import { createRemoteBroker } from './remote/broker'
42
43
  import {
43
44
  getWorkspaceEnvView,
44
45
  parseEnvUpdate,
@@ -49,6 +50,8 @@ import {
49
50
 
50
51
  type ControlSocket = { send(data: string): void }
51
52
 
53
+ const remoteBroker = createRemoteBroker()
54
+
52
55
  // Resolve a control request's `path` to the registered workspace that contains
53
56
  // it — the entry itself or its nearest registered ancestor — so every
54
57
  // workspace-scoped command (bundle/theme/config/scratch) works from `.moi/` or
@@ -80,7 +83,12 @@ async function resolveWorkspace(
80
83
  export const control = Bun.serve({
81
84
  port: CONTROL_PORT,
82
85
  hostname: CONTROL_HOST,
83
- fetch(req, server) {
86
+ async fetch(req, server) {
87
+ // Cloud requests from callers with no login of their own (remote/broker.ts).
88
+ // An exec stream can stay quiet for longer than the default idle timeout.
89
+ if (new URL(req.url).pathname.startsWith('/remote/')) server.timeout(req, 0)
90
+ const brokered = await remoteBroker(req)
91
+ if (brokered) return brokered
84
92
  return server.upgrade(req)
85
93
  ? new Response(null, { status: 101 })
86
94
  : new Response('Control WebSocket only', { status: 426 })
@@ -12,7 +12,7 @@ import { saveLayout } from '../workspaces/layout'
12
12
  import { resolveWorkspaceTheme } from '@/lib/themes'
13
13
  import { publishEvent } from '../events'
14
14
  import { harnessFor } from '../harness/registry'
15
- import { sendWorkspaceMessage } from '../sessions/view-sessions'
15
+ import { sendWorkspaceMessage } from '../sessions/send-message'
16
16
  import { resolveRenamedSession, saveSelectedSession } from '../sessions/selected'
17
17
  import { readWorkspaceState } from '../workspace-state'
18
18
  import { ideasSchema, onboardingIdeaSchema, parseIdeas } from './ideas'
@@ -0,0 +1,76 @@
1
+ import { CONTROL_HOST, CONTROL_PORT } from '../constants'
2
+ import type { RemoteBroker, RemoteLogin, RemoteRequestOptions } from './client'
3
+ import { CloudSignInRequired } from './errors'
4
+
5
+ // The caller's side of broker.ts: hand a Cloud request to the Moi server
6
+ // running on this machine, which sends it with its own login. The caller
7
+ // never sees a credential.
8
+
9
+ export const BROKER_ERROR_HEADER = 'x-moi-broker-error'
10
+ export const BROKER_LOGIN_HEADER = 'x-moi-login'
11
+ // A header a web page cannot send across origins without a preflight, which
12
+ // the control server never answers. It keeps browsers out of the broker.
13
+ export const BROKER_CALLER_HEADER = 'x-moi-cli'
14
+
15
+ const notRunning = (error: unknown) =>
16
+ ['ConnectionRefused', 'ECONNREFUSED'].includes(String((error as { code?: unknown })?.code))
17
+
18
+ export function createControlBroker(base: string): RemoteBroker {
19
+ // No server, or one from before the broker existed, answers undefined.
20
+ async function ask(
21
+ route: string,
22
+ options: RemoteRequestOptions = {}
23
+ ): Promise<Response | undefined> {
24
+ let response: Response
25
+ try {
26
+ response = await fetch(base + route, {
27
+ method: options.method ?? 'GET',
28
+ body: options.body,
29
+ signal: options.signal,
30
+ redirect: 'error',
31
+ headers: {
32
+ [BROKER_CALLER_HEADER]: '1',
33
+ ...(options.contentType ? { 'content-type': options.contentType } : {})
34
+ }
35
+ })
36
+ } catch (error) {
37
+ if (notRunning(error)) return undefined
38
+ throw error
39
+ }
40
+ if (response.headers.has(BROKER_ERROR_HEADER)) {
41
+ const failure = (await response.json().catch(() => ({}))) as {
42
+ error?: unknown
43
+ signIn?: unknown
44
+ }
45
+ const message = typeof failure.error === 'string' ? failure.error : 'Moi refused the request'
46
+ throw failure.signIn ? new CloudSignInRequired(message) : new Error(message)
47
+ }
48
+ if (!response.headers.has(BROKER_LOGIN_HEADER)) {
49
+ await response.body?.cancel()
50
+ return undefined
51
+ }
52
+ return response
53
+ }
54
+
55
+ return {
56
+ async info() {
57
+ const response = await ask('/remote/info')
58
+ if (!response) return undefined
59
+ const { url, login } = (await response.json()) as {
60
+ url: string
61
+ login?: RemoteLogin
62
+ }
63
+ return { url, login }
64
+ },
65
+ async fetch(path, options) {
66
+ const response = await ask('/remote/request?path=' + encodeURIComponent(path), options)
67
+ if (!response) return undefined
68
+ return {
69
+ response,
70
+ agent: response.headers.get(BROKER_LOGIN_HEADER) === 'agent'
71
+ }
72
+ }
73
+ }
74
+ }
75
+
76
+ export const controlBroker = createControlBroker(`http://${CONTROL_HOST}:${CONTROL_PORT}`)