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

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 (109) hide show
  1. package/client/app/app-provider.tsx +14 -20
  2. package/client/app/app-router.tsx +5 -8
  3. package/client/app/routes/workspace-route.tsx +28 -11
  4. package/client/app/shell/sidebar-layout.tsx +5 -10
  5. package/client/features/app-settings/api.ts +3 -3
  6. package/client/features/applets/applet-cache.ts +1 -2
  7. package/client/features/applets/use-applet.ts +18 -20
  8. package/client/features/chat/chat-store.ts +1 -1
  9. package/client/features/chat/connection/chat-connection.ts +25 -68
  10. package/client/features/chat/connection/chat-frames.ts +20 -32
  11. package/client/features/chat/sessions/api.ts +2 -2
  12. package/client/features/chat/sessions/use-selected-session.ts +0 -13
  13. package/client/features/collab/presence/client.ts +63 -83
  14. package/client/features/collab/presence/provider.tsx +8 -2
  15. package/client/features/dev/chat-states-page.tsx +1 -1
  16. package/client/features/dev/harness-debug-page.tsx +2 -2
  17. package/client/features/scratchpad/scratchpad.tsx +29 -20
  18. package/client/features/views/api.ts +38 -14
  19. package/client/features/views/use-view-actions.ts +2 -23
  20. package/client/features/workspace/api.ts +6 -11
  21. package/client/features/workspace/harness-transition.ts +3 -5
  22. package/client/features/workspace/remote.ts +9 -0
  23. package/client/features/workspace/settings/use-env-vars.ts +4 -4
  24. package/client/features/workspace/tab-resolution.ts +1 -8
  25. package/client/features/workspace/use-workspace-navigation.ts +5 -4
  26. package/client/features/workspace/use-workspace-socket.ts +51 -0
  27. package/client/features/workspace/workspace-content.tsx +5 -18
  28. package/client/features/workspace/workspace-layout-context.tsx +6 -13
  29. package/client/features/workspace/workspace-preferences.ts +67 -10
  30. package/client/features/workspace/workspace-state.ts +57 -21
  31. package/client/runtime/app-context.ts +2 -2
  32. package/client/runtime/app-events.ts +75 -0
  33. package/client/runtime/reconnecting-socket.ts +115 -0
  34. package/client/runtime/{use-workspace-events.ts → use-client-events.ts} +9 -10
  35. package/client/store/ui.ts +1 -6
  36. package/client/store/workspace-session.ts +30 -0
  37. package/dist/chunk-0t8m1ehd.js +2 -0
  38. package/dist/chunk-851bx8ss.js +72 -0
  39. package/dist/{chunk-n0fawy9x.js → chunk-c8g5x288.js} +1 -1
  40. package/dist/chunk-cty37f3v.js +1 -0
  41. package/dist/chunk-dy6f6h3e.js +5 -0
  42. package/dist/chunk-j6928pwm.js +1 -0
  43. package/dist/{chunk-rmd0ctfx.js → chunk-k32585ne.js} +73 -73
  44. package/dist/chunk-qtkv7hp8.js +2 -0
  45. package/dist/chunk-rh58dc0y.js +2 -0
  46. package/dist/{chunk-ec5ennpv.js → chunk-wjbejzek.js} +1 -1
  47. package/dist/index.html +1 -1
  48. package/lib/events.ts +61 -0
  49. package/lib/ids.ts +2 -8
  50. package/lib/moi-context.ts +19 -5
  51. package/lib/types.ts +16 -20
  52. package/lib/workspace-layout.ts +3 -20
  53. package/package.json +2 -1
  54. package/server/AGENTS.md +4 -4
  55. package/server/README.md +50 -33
  56. package/server/api/index.ts +175 -152
  57. package/server/applets/views.ts +15 -14
  58. package/server/applets/widgets.ts +4 -3
  59. package/server/cli/commands/init.ts +7 -2
  60. package/server/cli/commands/refresh.ts +2 -5
  61. package/server/cli/commands/remote.ts +128 -26
  62. package/server/cli/remote-control.ts +12 -9
  63. package/server/cli/remote-operations.ts +47 -44
  64. package/server/control.ts +33 -34
  65. package/server/events.ts +14 -13
  66. package/server/harness/README.md +7 -7
  67. package/server/harness/acp/session.ts +9 -5
  68. package/server/harness/auth.ts +7 -30
  69. package/server/harness/claude-code/session.ts +8 -4
  70. package/server/harness/codex/NOTES.md +1 -1
  71. package/server/harness/codex/session.ts +18 -10
  72. package/server/harness/hermes/NOTES.md +3 -3
  73. package/server/harness/openclaw/session.ts +9 -5
  74. package/server/onboarding/jobs.ts +8 -8
  75. package/server/operations/commands.ts +1 -1
  76. package/server/remote/broker-client.ts +76 -0
  77. package/server/remote/broker.ts +81 -0
  78. package/server/remote/client.ts +212 -152
  79. package/server/remote/errors.ts +2 -0
  80. package/server/remote/routes.ts +121 -0
  81. package/server/scratchpad/document.ts +3 -2
  82. package/server/scratchpad/executor.ts +2 -2
  83. package/server/scratchpad/relay.ts +3 -3
  84. package/server/sessions/archive.ts +1 -1
  85. package/server/sessions/lifecycle.ts +1 -1
  86. package/server/sessions/pending-views.ts +19 -12
  87. package/server/sessions/send-message.ts +102 -0
  88. package/server/sessions/view-sessions.ts +4 -94
  89. package/server/web.ts +42 -31
  90. package/server/workspace-state/file.ts +2 -0
  91. package/server/workspace-state/index.ts +15 -4
  92. package/server/workspaces/api.ts +4 -8
  93. package/server/workspaces/config.ts +14 -13
  94. package/server/workspaces/env-apply.ts +1 -1
  95. package/server/workspaces/layout.ts +40 -7
  96. package/server/workspaces/shared.ts +1 -1
  97. package/server/workspaces/tabs.ts +1 -2
  98. package/skill/SKILL.md +75 -34
  99. package/skill/references/SCRATCHPAD.md +4 -0
  100. package/skill/references/UI-COMPONENTS.md +1 -1
  101. package/client/features/scratchpad/scratch-executor.ts +0 -20
  102. package/client/runtime/workspace-events.ts +0 -168
  103. package/dist/chunk-44khk4sp.js +0 -2
  104. package/dist/chunk-ba6mz56s.js +0 -72
  105. package/dist/chunk-ectsnw81.js +0 -2
  106. package/dist/chunk-en7w5ypg.js +0 -1
  107. package/dist/chunk-f695wcx5.js +0 -5
  108. package/dist/chunk-pdt9hxfw.js +0 -2
  109. package/dist/chunk-zv22wv0g.js +0 -1
@@ -1,16 +1,15 @@
1
- import {
2
- workspaceAddress,
3
- workspaceApiBase,
4
- parseRemoteWorkspaceTarget
5
- } from '@/lib/workspace-config'
1
+ import { parseRemoteWorkspaceTarget } from '@/lib/workspace-config'
6
2
  import { decodeJwt } from 'jose'
7
3
  import { Mutex } from 'async-mutex'
8
4
  import { lock } from 'proper-lockfile'
9
5
  import { z } from 'zod'
10
- import { chmod, mkdir, rename, rm } from 'node:fs/promises'
11
- import { existsSync } from 'node:fs'
6
+ import { access as fileAccess, chmod, mkdir, rename, rm } from 'node:fs/promises'
7
+ import { accessSync, constants, existsSync } from 'node:fs'
12
8
  import { join } from 'node:path'
13
- import { DATA_DIR } from '../data-dir'
9
+ import { canUseDataDir, DATA_DIR } from '../data-dir'
10
+ import { allowedCloudRequest, cloudRoutes } from './routes'
11
+ import { controlBroker } from './broker-client'
12
+ import { CloudSignInRequired } from './errors'
14
13
  import { PACKAGE_ROOT } from '../version'
15
14
  import {
16
15
  agentCredentialsSchema,
@@ -21,14 +20,25 @@ import {
21
20
  AGENT_CLIENTS
22
21
  } from './agent'
23
22
 
24
- type RemoteRequestOptions = {
23
+ export type RemoteRequestOptions = {
25
24
  method?: string
26
- body?: string | Blob | Uint8Array<ArrayBuffer>
25
+ body?: string | Blob | Uint8Array<ArrayBuffer> | ReadableStream<Uint8Array>
26
+ /** Byte length of a stream body, so the upload keeps a known length. */
27
+ contentLength?: string
27
28
  signal?: AbortSignal
28
29
  contentType?: string
29
30
  }
31
+ export type RemoteLogin = 'human' | 'agent'
32
+ /** A Cloud answer, and which kind of login sent the request. */
33
+ export type RemoteReply = { response: Response; agent: boolean }
34
+ /** A running Moi server that sends listed Cloud requests with its own login.
35
+ * Both calls answer undefined when no such server is running. */
36
+ export type RemoteBroker = {
37
+ info(): Promise<{ url: string; login?: RemoteLogin } | undefined>
38
+ fetch(path: string, options: RemoteRequestOptions): Promise<RemoteReply | undefined>
39
+ }
30
40
 
31
- export class CloudSignInRequired extends Error {}
41
+ export { CloudSignInRequired }
32
42
 
33
43
  const humanCredentialsSchema = z.object({
34
44
  accessToken: z.string().min(1),
@@ -84,7 +94,7 @@ export function resolveRemoteConfig(
84
94
  `For development, configure the Cloud URL to point to your local cloud dev server.\nSet remote.url in ${join(directory, 'config.json')}\nFor example, http://localhost:8787/cloud`
85
95
  )
86
96
  }
87
- const url = new URL(remote.url ?? 'https://run.moi.computer/cloud')
97
+ const url = new URL(remote.url ?? 'https://moi.computer/cloud')
88
98
  if (
89
99
  url.protocol !== 'https:' &&
90
100
  !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
@@ -101,11 +111,35 @@ export function resolveRemoteConfig(
101
111
  }
102
112
  }
103
113
 
104
- /** Each client owns one data directory. Tests use an isolated directory. */
105
- export function createRemoteClient(directory: string) {
114
+ /** Each client owns one data directory. Tests use an isolated directory.
115
+ *
116
+ * A request uses the login saved in that directory. Given a broker, a caller
117
+ * with no readable login of its own asks the running Moi server to send the
118
+ * request instead, so the agent's OS user on a managed machine never holds a
119
+ * credential. With no login and no server, the caller is signed out.
120
+ */
121
+ export function createRemoteClient(directory: string, broker?: RemoteBroker) {
106
122
  const authFile = join(directory, 'remote-auth.json')
107
123
  const mutex = new Mutex()
108
124
  const pendingFile = join(directory, 'remote-agent-pending.json')
125
+ const ownLogin = () =>
126
+ fileAccess(authFile, constants.R_OK).then(
127
+ () => true,
128
+ () => false
129
+ )
130
+ // Sign-in and changes to the account belong to whoever holds the login.
131
+ function ownDirectory() {
132
+ if (!usable()) throw new Error('This is only available to the user that runs Moi')
133
+ }
134
+ // A directory that does not exist yet can still be created and used.
135
+ function usable(): boolean {
136
+ try {
137
+ accessSync(directory, constants.R_OK | constants.W_OK | constants.X_OK)
138
+ return true
139
+ } catch (error) {
140
+ return (error as NodeJS.ErrnoException).code === 'ENOENT'
141
+ }
142
+ }
109
143
 
110
144
  async function json<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
111
145
  // A parser error can quote the response body, which may contain tokens.
@@ -139,7 +173,7 @@ export function createRemoteClient(directory: string) {
139
173
  })
140
174
  }
141
175
 
142
- async function read(config: RemoteConfig): Promise<Credentials> {
176
+ async function readStoredCredentials(): Promise<Credentials> {
143
177
  let value: unknown
144
178
  try {
145
179
  value = await Bun.file(authFile).json()
@@ -150,14 +184,17 @@ export function createRemoteClient(directory: string) {
150
184
  }
151
185
  const parsed = credentialsSchema.safeParse(value)
152
186
  if (!parsed.success) throw new Error('Invalid remote credentials — run moi remote login')
153
- if (parsed.data.url !== config.url || parsed.data.clientId !== config.clientId) {
154
- throw new Error(
155
- 'Saved login belongs to a different cloud — restore the previous Cloud URL or run moi remote login'
156
- )
157
- }
158
187
  return parsed.data
159
188
  }
160
189
 
190
+ async function read(config: RemoteConfig): Promise<Credentials> {
191
+ const credentials = await readStoredCredentials()
192
+ if (credentials.url !== config.url || credentials.clientId !== config.clientId) {
193
+ throw new Error('Your saved login is not valid — sign in again with `moi remote login`')
194
+ }
195
+ return credentials
196
+ }
197
+
161
198
  async function writePrivate(path: string, value: unknown, assertLock: () => void) {
162
199
  const temporary = `${path}.${crypto.randomUUID()}.tmp`
163
200
  try {
@@ -219,7 +256,9 @@ export function createRemoteClient(directory: string) {
219
256
  ): Promise<void> {
220
257
  const config = await remoteConfig()
221
258
  if (config.managed) throw new Error('Cloud manages sign-in on this machine')
222
- if ((await Bun.file(authFile).exists()) && isAgent(await read(config)))
259
+ // A fresh human login can replace credentials for previous Cloud settings.
260
+ // Inspect identity without authorizing those credentials for the new server.
261
+ if ((await Bun.file(authFile).exists()) && isAgent(await readStoredCredentials()))
223
262
  throw new Error('Signed in as an agent — use a separate Moi data directory for human login')
224
263
  if (await Bun.file(pendingFile).exists())
225
264
  throw new Error('An agent join is pending — retry that invitation first')
@@ -248,7 +287,7 @@ export function createRemoteClient(directory: string) {
248
287
  })
249
288
  if (token.ok) {
250
289
  await locked(async assertLock => {
251
- if ((await Bun.file(authFile).exists()) && isAgent(await read(config)))
290
+ if ((await Bun.file(authFile).exists()) && isAgent(await readStoredCredentials()))
252
291
  throw new Error(
253
292
  'An agent signed in while browser login was pending; agent credentials kept'
254
293
  )
@@ -290,7 +329,13 @@ export function createRemoteClient(directory: string) {
290
329
  throw new Error(
291
330
  'Logging out permanently revokes this agent login and deletes its local keys. It cannot be restored. Run moi remote logout --yes to confirm'
292
331
  )
293
- await cloudJson(config, pair, '/agents/logout', {}, z.object({ success: z.boolean() }))
332
+ await answer(
333
+ {
334
+ response: await localSend(config, pair, 'api/agents/logout', jsonRequest({})),
335
+ agent: true
336
+ },
337
+ z.object({ success: z.boolean() })
338
+ )
294
339
  assertLock()
295
340
  await rm(authFile, { force: true })
296
341
  await rm(pendingFile, { force: true })
@@ -332,33 +377,89 @@ export function createRemoteClient(directory: string) {
332
377
  })
333
378
  }
334
379
 
335
- async function cloudJson<T>(
380
+ const jsonRequest = (body: unknown | undefined, method?: string): RemoteRequestOptions => ({
381
+ method: method ?? (body === undefined ? 'GET' : 'POST'),
382
+ body: body === undefined ? undefined : JSON.stringify(body),
383
+ contentType: 'application/json',
384
+ signal: AbortSignal.timeout(30_000)
385
+ })
386
+
387
+ // The one place a credential meets a request. Answers with whatever Cloud
388
+ // returned; callers decide what a failure status means.
389
+ async function localSend(
336
390
  config: RemoteConfig,
337
391
  pair: Credentials,
338
392
  path: string,
339
- body: unknown | undefined,
340
- schema: z.ZodType<T>,
341
- method = body === undefined ? 'GET' : 'POST'
342
- ): Promise<T> {
343
- if (!path.startsWith('/') || path.startsWith('//') || path.includes('..'))
344
- throw new Error('Invalid cloud API path')
345
- const url = `${config.url}/api${path}`,
346
- raw = body === undefined ? '' : JSON.stringify(body)
347
- const authorization = isAgent(pair)
348
- ? await agentAuthorization(pair, url, method, raw)
349
- : `Bearer ${pair.accessToken}`
350
- const response = await fetch(url, {
393
+ options: RemoteRequestOptions
394
+ ): Promise<Response> {
395
+ const url = new URL(path, config.url.replace(/\/+$/, '') + '/').href
396
+ const method = options.method ?? 'GET'
397
+ const limit = 16 * 1024 * 1024
398
+ const tooLarge = () => new Error('Agent uploads are limited to 16 MiB')
399
+ let body = options.body
400
+ let authorization = isAgent(pair) ? '' : `Bearer ${pair.accessToken}`
401
+ if (isAgent(pair)) {
402
+ // Agent Auth signs the exact bytes, so they are read before sending.
403
+ let bytes: string | Uint8Array<ArrayBuffer> = ''
404
+ if (body instanceof ReadableStream) {
405
+ if (Number(options.contentLength) > limit) throw tooLarge()
406
+ const chunks: Uint8Array[] = []
407
+ let size = 0
408
+ for await (const chunk of body) {
409
+ if ((size += chunk.byteLength) > limit) throw tooLarge()
410
+ chunks.push(chunk)
411
+ }
412
+ bytes = new Uint8Array(Buffer.concat(chunks))
413
+ } else if (body instanceof Blob) {
414
+ if (body.size > limit) throw tooLarge()
415
+ bytes = new Uint8Array(await body.arrayBuffer())
416
+ } else if (body !== undefined) bytes = body
417
+ if ((typeof bytes === 'string' ? Buffer.byteLength(bytes) : bytes.byteLength) > limit)
418
+ throw tooLarge()
419
+ if (body !== undefined) body = bytes
420
+ authorization = await agentAuthorization(pair, url, method, bytes)
421
+ }
422
+ return fetch(url, {
351
423
  method,
352
- headers: { authorization, 'content-type': 'application/json' },
353
- body: body === undefined ? undefined : raw,
424
+ body,
354
425
  redirect: 'error',
355
- signal: AbortSignal.timeout(30_000)
426
+ signal: options.signal,
427
+ headers: {
428
+ authorization,
429
+ ...(options.contentType ? { 'content-type': options.contentType } : {}),
430
+ ...(body instanceof ReadableStream && options.contentLength
431
+ ? { 'content-length': options.contentLength }
432
+ : {})
433
+ }
356
434
  })
357
- if (response.status === 401)
435
+ }
436
+
437
+ /** Send a listed Cloud request with this directory's login, or through the
438
+ * running Moi server when the caller has no login of its own. */
439
+ async function send(path: string, options: RemoteRequestOptions = {}): Promise<RemoteReply> {
440
+ const { access: allowed } = allowedCloudRequest(options.method ?? 'GET', path)
441
+ if (allowed === 'own login') ownDirectory()
442
+ else if (broker && !(await ownLogin())) {
443
+ const brokered = await broker.fetch(path, options)
444
+ if (brokered) return brokered
445
+ if (!usable()) throw new Error('Moi is not running, so this user cannot reach Moi Cloud')
446
+ }
447
+ const config = await remoteConfig()
448
+ const pair = await access(config)
449
+ return { response: await localSend(config, pair, path, options), agent: isAgent(pair) }
450
+ }
451
+
452
+ async function answer<T>({ response, agent }: RemoteReply, schema: z.ZodType<T>): Promise<T> {
453
+ if (response.status === 401) {
454
+ await response.body?.cancel()
358
455
  throw new Error(
359
- isAgent(pair) ? 'Agent login is no longer valid' : 'Sign-in expired — run moi remote login'
456
+ agent ? 'Agent login is no longer valid' : 'Sign-in expired — run moi remote login'
360
457
  )
361
- if (!response.ok) throw new Error(`Cloud request failed (${response.status})`)
458
+ }
459
+ if (!response.ok) {
460
+ await response.body?.cancel()
461
+ throw new Error(`Cloud request failed (${response.status})`)
462
+ }
362
463
  return json(response, schema)
363
464
  }
364
465
  async function request<T>(
@@ -367,16 +468,29 @@ export function createRemoteClient(directory: string) {
367
468
  schema: z.ZodType<T>,
368
469
  method?: string
369
470
  ) {
471
+ return answer(await send(path, jsonRequest(body, method)), schema)
472
+ }
473
+
474
+ /** The saved login's kind and Cloud URL, for a server lending it to callers. */
475
+ async function loginInfo(): Promise<{ url: string; login?: RemoteLogin }> {
370
476
  const config = await remoteConfig()
371
- return cloudJson(config, await access(config), path, body, schema, method)
477
+ try {
478
+ return { url: config.url, login: isAgent(await read(config)) ? 'agent' : 'human' }
479
+ } catch (error) {
480
+ if (error instanceof CloudSignInRequired) return { url: config.url }
481
+ throw error
482
+ }
372
483
  }
373
- async function authenticatedGet<T>(
374
- config: RemoteConfig,
375
- pair: Credentials,
376
- path: string,
377
- schema: z.ZodType<T>
378
- ) {
379
- return cloudJson(config, pair, path, undefined, schema)
484
+ // The login requests go out with: this directory's, else the running server's.
485
+ async function activeLogin(): Promise<{ url: string; login?: RemoteLogin }> {
486
+ if (broker && !(await ownLogin())) {
487
+ const info = await broker.info()
488
+ if (info) return info
489
+ }
490
+ return loginInfo()
491
+ }
492
+ async function cloudUrl(): Promise<string> {
493
+ return (await activeLogin()).url
380
494
  }
381
495
  const invitationSchema = z.object({
382
496
  id: z.string(),
@@ -388,13 +502,13 @@ export function createRemoteClient(directory: string) {
388
502
  async function invitations() {
389
503
  return (
390
504
  await request(
391
- '/workspaces/invitations',
505
+ cloudRoutes.invitations.path(),
392
506
  undefined,
393
507
  z.object({ invitations: z.array(invitationSchema) })
394
508
  )
395
509
  ).invitations
396
510
  }
397
- function invitation(value: string, config: RemoteConfig) {
511
+ function invitation(value: string, config: { url: string }) {
398
512
  if (!value.includes('://')) {
399
513
  if (!/^[A-Za-z0-9_-]{1,240}$/.test(value)) throw new Error('Invalid invitation ID')
400
514
  return { id: value, token: undefined, agent: false }
@@ -424,24 +538,33 @@ export function createRemoteClient(directory: string) {
424
538
  .transform(parseRemoteWorkspaceTarget),
425
539
  membershipId: z.string()
426
540
  })
541
+ const acceptPath = (id: string) => cloudRoutes.acceptInvitation.path(id)
427
542
  async function accept(value: string, name?: string, client?: string) {
428
543
  if (client !== undefined && !agentClientSchema.safeParse(client).success)
429
544
  throw new Error(`Invalid client — choose ${AGENT_CLIENTS.join(', ')}`)
545
+ ownDirectory()
430
546
  const config = await remoteConfig(),
431
547
  target = invitation(value, config)
548
+ const acceptWith = async (pair: Credentials) =>
549
+ answer(
550
+ {
551
+ response: await localSend(
552
+ config,
553
+ pair,
554
+ acceptPath(target.id),
555
+ jsonRequest(target.token ? { token: target.token } : {})
556
+ ),
557
+ agent: isAgent(pair)
558
+ },
559
+ accepted
560
+ )
432
561
  if (await Bun.file(authFile).exists()) {
433
562
  const saved = await read(config)
434
563
  if (!isAgent(saved) && (target.agent || name !== undefined || client !== undefined))
435
564
  throw new Error(
436
565
  'Already signed in as a human — use a separate Moi data directory for this agent'
437
566
  )
438
- return cloudJson(
439
- config,
440
- await access(config),
441
- `/invitations/${encodeURIComponent(target.id)}/accept`,
442
- target.token ? { token: target.token } : {},
443
- accepted
444
- )
567
+ return acceptWith(await access(config))
445
568
  }
446
569
  if (!target.agent)
447
570
  throw new CloudSignInRequired(
@@ -455,13 +578,7 @@ export function createRemoteClient(directory: string) {
455
578
  throw new Error(
456
579
  'Already signed in as a human — use a separate Moi data directory for this agent'
457
580
  )
458
- return cloudJson(
459
- config,
460
- pair,
461
- `/invitations/${encodeURIComponent(target.id)}/accept`,
462
- target.token ? { token: target.token } : {},
463
- accepted
464
- )
581
+ return acceptWith(pair)
465
582
  }
466
583
  if (!target.token) throw new Error('First agent acceptance requires an invitation URL')
467
584
  const fingerprint = new Bun.CryptoHasher('sha256').update(target.token).digest('hex')
@@ -491,7 +608,12 @@ export function createRemoteClient(directory: string) {
491
608
  )
492
609
  } else {
493
610
  if (!name?.trim() || name.trim().length > 80 || !client)
494
- throw new Error('First agent acceptance requires --name and --client')
611
+ throw new Error(
612
+ 'Create your agent identity with --name and --client\n' +
613
+ '--name: your display name, shown to workspace members (for example, "Research assistant")\n' +
614
+ `--client: the app you run in (${AGENT_CLIENTS.join(', ')}); use "other" if yours is not listed\n` +
615
+ 'Retry: moi remote accept "<invitation-url>" --name "Research assistant" --client other'
616
+ )
495
617
  pending = {
496
618
  fingerprint,
497
619
  name: name.trim(),
@@ -524,15 +646,13 @@ export function createRemoteClient(directory: string) {
524
646
  })
525
647
  }
526
648
  async function renameAgent(name: string) {
527
- const config = await remoteConfig(),
528
- pair = await access(config)
529
- if (!isAgent(pair)) throw new Error('This command is for agents')
530
- return cloudJson(config, pair, '/me', { name }, agentProfileSchema, 'PATCH')
649
+ ownDirectory()
650
+ if (!isAgent(await access(await remoteConfig()))) throw new Error('This command is for agents')
651
+ return request(cloudRoutes.me.path(), { name }, agentProfileSchema, 'PATCH')
531
652
  }
532
653
  async function leave(ownerId: string, workspaceId: string) {
533
- parseRemoteWorkspaceTarget({ user_id: ownerId, workspace_id: workspaceId })
534
654
  return request(
535
- `/workspaces/${workspaceAddress(workspaceId, ownerId)}/leave`,
655
+ cloudRoutes.leave.path({ user_id: ownerId, workspace_id: workspaceId }),
536
656
  {},
537
657
  z.object({ success: z.literal(true) })
538
658
  )
@@ -542,78 +662,14 @@ export function createRemoteClient(directory: string) {
542
662
  * Refreshes credentials automatically; requires no browser or running Moi server.
543
663
  */
544
664
  async function fetchSharedWorkspaces(): Promise<SharedWorkspace[]> {
545
- const config = await remoteConfig()
546
- const pair = await access(config)
547
- const result = await authenticatedGet(config, pair, '/workspaces/shared', workspacesSchema)
548
- return result.workspaces
549
- }
550
-
551
- /** Byte-preserving operations transport; writes are never automatically replayed. */
552
- async function operation(
553
- ownerId: string,
554
- workspaceId: string,
555
- suffix: string,
556
- options: RemoteRequestOptions = {}
557
- ): Promise<Response> {
558
- parseRemoteWorkspaceTarget({ user_id: ownerId, workspace_id: workspaceId })
559
- if (!/^\/(?:files\/|exec$|commands$)/.test(suffix)) throw new Error('Invalid remote operation')
560
- return authenticatedTransport(
561
- `api/workspaces/${workspaceAddress(workspaceId, ownerId)}/ops${suffix}`,
562
- options
563
- )
665
+ return (await request(cloudRoutes.sharedWorkspaces.path(), undefined, workspacesSchema))
666
+ .workspaces
564
667
  }
565
668
 
566
- async function workspaceRequest(
567
- ownerId: string,
568
- workspaceId: string,
569
- suffix: string,
570
- options: RemoteRequestOptions = {}
571
- ) {
572
- parseRemoteWorkspaceTarget({ user_id: ownerId, workspace_id: workspaceId })
573
- const base = new URL(workspaceApiBase(workspaceId, ownerId), 'http://workspace.local')
574
- const url = new URL(base.href + suffix)
575
- if (
576
- url.origin !== base.origin ||
577
- (url.pathname !== base.pathname && !url.pathname.startsWith(base.pathname + '/'))
578
- )
579
- throw new Error('Invalid workspace path')
580
- return authenticatedTransport(url.pathname + url.search, options)
581
- }
582
-
583
- async function authenticatedTransport(path: string, options: RemoteRequestOptions) {
584
- const config = await remoteConfig()
585
- const pair = await access(config)
586
- const url = new URL(path, config.url.replace(/\/+$/, '') + '/').href
587
- const method = options.method ?? 'GET'
588
- let body = options.body
589
- if (isAgent(pair) && body instanceof Blob) {
590
- if (body.size > 16 * 1024 * 1024) throw new Error('Agent uploads are limited to 16 MiB')
591
- body = new Uint8Array(await body.arrayBuffer())
592
- }
593
- if (
594
- isAgent(pair) &&
595
- body &&
596
- (typeof body === 'string'
597
- ? Buffer.byteLength(body)
598
- : body instanceof Blob
599
- ? body.size
600
- : body.byteLength) >
601
- 16 * 1024 * 1024
602
- )
603
- throw new Error('Agent uploads are limited to 16 MiB')
604
- const authorization = isAgent(pair)
605
- ? await agentAuthorization(pair, url, method, body instanceof Blob ? '' : (body ?? ''))
606
- : `Bearer ${pair.accessToken}`
607
- const response = await fetch(url, {
608
- method,
609
- body,
610
- redirect: 'error',
611
- signal: options.signal,
612
- headers: {
613
- authorization,
614
- ...(options.contentType ? { 'content-type': options.contentType } : {})
615
- }
616
- })
669
+ /** Send a request built from `cloudRoutes` and answer with Cloud's response.
670
+ * Bytes are preserved and writes are never automatically replayed. */
671
+ async function remoteRequest(path: string, options: RemoteRequestOptions = {}) {
672
+ const { response } = await send(path, options)
617
673
  if (!response.ok) {
618
674
  await response.body?.cancel()
619
675
  throw new Error(
@@ -626,23 +682,23 @@ export function createRemoteClient(directory: string) {
626
682
  }
627
683
 
628
684
  async function remoteStatus(): Promise<RemoteStatus> {
629
- const config = await remoteConfig()
630
- const pair = await access(config)
631
685
  const [me, shared] = await Promise.all([
632
- authenticatedGet(config, pair, '/me', profileSchema),
633
- authenticatedGet(config, pair, '/workspaces/shared', workspacesSchema)
686
+ request(cloudRoutes.me.path(), undefined, profileSchema),
687
+ request(cloudRoutes.sharedWorkspaces.path(), undefined, workspacesSchema)
634
688
  ])
635
689
  return { me, workspaces: shared.workspaces }
636
690
  }
637
691
 
638
692
  return {
639
693
  remoteConfig,
694
+ cloudUrl,
695
+ loginInfo,
696
+ send,
640
697
  login,
641
698
  logout,
642
699
  fetchSharedWorkspaces,
643
- workspaceRequest,
700
+ remoteRequest,
644
701
  remoteStatus,
645
- operation,
646
702
  invitations,
647
703
  accept,
648
704
  renameAgent,
@@ -650,16 +706,20 @@ export function createRemoteClient(directory: string) {
650
706
  }
651
707
  }
652
708
 
709
+ // A data directory the caller named and can open is its own: it never borrows
710
+ // the running server's login. Standalone bots and tests rely on this.
711
+ const ownsDataDir = !!process.env.MOI_DATA_DIR && canUseDataDir()
712
+
653
713
  export const {
654
714
  remoteConfig,
715
+ cloudUrl,
655
716
  login,
656
717
  logout,
657
718
  fetchSharedWorkspaces,
658
- workspaceRequest,
719
+ remoteRequest,
659
720
  remoteStatus,
660
- operation,
661
721
  invitations,
662
722
  accept,
663
723
  renameAgent,
664
724
  leave
665
- } = createRemoteClient(DATA_DIR)
725
+ } = createRemoteClient(DATA_DIR, ownsDataDir ? undefined : controlBroker)
@@ -0,0 +1,2 @@
1
+ /** No usable Cloud login: the caller has to sign in before this can work. */
2
+ export class CloudSignInRequired extends Error {}
@@ -0,0 +1,121 @@
1
+ import { parse } from 'regexparam'
2
+ import {
3
+ parseRemoteWorkspaceAddress,
4
+ parseRemoteWorkspaceTarget,
5
+ workspaceAddress,
6
+ type RemoteWorkspaceTarget
7
+ } from '@/lib/workspace-config'
8
+
9
+ // Every Cloud request the CLI may make: its methods, the pattern that allows
10
+ // it, and the function callers use to write its path. The CLI checks a request
11
+ // against this table before sending, and the running server checks it again
12
+ // before lending its login to a caller (broker.ts).
13
+ //
14
+ // `api/…` is sent relative to the Cloud URL; `/api/workspaces/…` goes to the
15
+ // owner's workspace API at its origin. Sign-in itself (login, token refresh,
16
+ // logout, agent join) uses fixed URLs in client.ts and never comes through here.
17
+
18
+ type Access = 'any login' | 'own login'
19
+ type Workspace = RemoteWorkspaceTarget
20
+
21
+ const refused = () => new Error('This Cloud request is not allowed')
22
+
23
+ function route<Args extends unknown[]>(
24
+ methods: string,
25
+ pattern: string,
26
+ path: (...args: Args) => string,
27
+ /** 'own login' requests are never sent with a login lent by the server. */
28
+ access: Access = 'any login'
29
+ ) {
30
+ const [pathname = '', query = ''] = pattern.split('?')
31
+ return { methods: methods.split(' '), ...parse(pathname), pathname, query, path, access }
32
+ }
33
+
34
+ const address = (workspace: Workspace) => {
35
+ const { workspace_id, user_id } = parseRemoteWorkspaceTarget(workspace)
36
+ return workspaceAddress(workspace_id, user_id)
37
+ }
38
+ const cloud = (workspace: Workspace) => `api/workspaces/${address(workspace)}`
39
+ const owner = (workspace: Workspace) => `/api/workspaces/${address(workspace)}`
40
+ // A file path relative to the workspace root, one encoded segment per name.
41
+ function encodePath(file: string) {
42
+ const names = file.split('/')
43
+ if (names.some(name => !name || name === '.' || name === '..' || name.includes('\\')))
44
+ throw new Error('Use a file path relative to the remote workspace')
45
+ return names.map(encodeURIComponent).join('/')
46
+ }
47
+
48
+ const CLOUD = 'api/workspaces/:workspace'
49
+ const OWNER = '/api/workspaces/:workspace'
50
+
51
+ export const cloudRoutes = {
52
+ // Account
53
+ me: route('GET', 'api/me', () => 'api/me'),
54
+ sharedWorkspaces: route('GET', 'api/workspaces/shared', () => 'api/workspaces/shared'),
55
+ invitations: route('GET', 'api/workspaces/invitations', () => 'api/workspaces/invitations'),
56
+ // Changes to the account itself stay with whoever holds the login.
57
+ renameAgent: route('PATCH', 'api/me', () => 'api/me', 'own login'),
58
+ acceptInvitation: route(
59
+ 'POST',
60
+ 'api/invitations/:id/accept',
61
+ (id: string) => `api/invitations/${encodePath(id)}/accept`,
62
+ 'own login'
63
+ ),
64
+ leave: route('POST', `${CLOUD}/leave`, (w: Workspace) => `${cloud(w)}/leave`, 'own login'),
65
+ // Operations on the owner's machine
66
+ exec: route('POST', `${CLOUD}/ops/exec`, (w: Workspace) => `${cloud(w)}/ops/exec`),
67
+ commands: route('POST', `${CLOUD}/ops/commands`, (w: Workspace) => `${cloud(w)}/ops/commands`),
68
+ files: route(
69
+ 'GET PUT PATCH',
70
+ `${CLOUD}/ops/files/*`,
71
+ (w: Workspace, file: string) => `${cloud(w)}/ops/files/${encodePath(file)}`
72
+ ),
73
+ // Owner's workspace API
74
+ views: route(
75
+ 'GET',
76
+ `${OWNER}/views?includePending=true`,
77
+ (w: Workspace) => `${owner(w)}/views?includePending=true`
78
+ ),
79
+ compiledViews: route('GET', `${OWNER}/views`, (w: Workspace) => `${owner(w)}/views`),
80
+ config: route('GET PUT', `${OWNER}/config`, (w: Workspace) => `${owner(w)}/config`),
81
+ icon: route('PUT DELETE', `${OWNER}/icon`, (w: Workspace) => `${owner(w)}/icon`),
82
+ scratchpad: route('GET', `${OWNER}/scratchpad`, (w: Workspace) => `${owner(w)}/scratchpad`),
83
+ scratchpadOps: route(
84
+ 'POST',
85
+ `${OWNER}/scratchpad/ops`,
86
+ (w: Workspace) => `${owner(w)}/scratchpad/ops`
87
+ ),
88
+ scratchpadAsset: route(
89
+ 'GET',
90
+ `${OWNER}/scratchpad/assets/:name`,
91
+ (w: Workspace, name: string) => `${owner(w)}/scratchpad/assets/${encodePath(name)}`
92
+ )
93
+ }
94
+
95
+ // Spellings that make a path resolve somewhere other than where it reads:
96
+ // dot segments, empty segments, backslashes, and their encoded forms. None
97
+ // appears in a path built above.
98
+ const UNSAFE = /(^|\/)\.\.?(\/|\?|$)|\/\/|\\|%2e|%2f|%5c/i
99
+
100
+ export type AllowedCloudRequest = { workspace?: Workspace; access: Access }
101
+
102
+ /** Throws unless the request is listed; names the workspace it addresses, if any. */
103
+ export function allowedCloudRequest(method: string, path: string): AllowedCloudRequest {
104
+ if (UNSAFE.test(path)) throw refused()
105
+ const [pathname = '', query = ''] = path.split('?')
106
+ for (const route of Object.values(cloudRoutes)) {
107
+ if (!route.methods.includes(method.toUpperCase()) || route.query !== query) continue
108
+ // regexparam ignores a leading slash, and here it says where the request goes.
109
+ if (route.pathname.startsWith('/') !== pathname.startsWith('/')) continue
110
+ const found = route.pattern.exec(pathname.replace(/^\/?/, '/'))
111
+ if (!found) continue
112
+ const workspace = found[route.keys.indexOf('workspace') + 1]
113
+ if (!route.keys.includes('workspace')) return { access: route.access }
114
+ try {
115
+ return { access: route.access, workspace: parseRemoteWorkspaceAddress(workspace ?? '') }
116
+ } catch {
117
+ throw refused()
118
+ }
119
+ }
120
+ throw refused()
121
+ }