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
@@ -0,0 +1,81 @@
1
+ import type { WorkspaceEntry } from '@/lib/types'
2
+ import { DATA_DIR } from '../data-dir'
3
+ import { listWorkspaces } from '../workspaces/registry'
4
+ import { allowedCloudRequest } from './routes'
5
+ import { BROKER_CALLER_HEADER, BROKER_ERROR_HEADER, BROKER_LOGIN_HEADER } from './broker-client'
6
+ import { createRemoteClient } from './client'
7
+ import { CloudSignInRequired } from './errors'
8
+
9
+ // The running server lends its Cloud login to callers on this machine that
10
+ // have none of their own, such as the agent's OS user on a managed machine
11
+ // (docs/config.md). It sends the request itself and passes the answer back,
12
+ // so the credential never leaves this process. Three checks bound what a
13
+ // caller can do with it:
14
+ //
15
+ // - the request must be listed in routes.ts, and not as one that needs the
16
+ // caller's own login
17
+ // - a request that names a workspace must name one linked on this machine
18
+ // - the caller must be a program, not a web page (see BROKER_CALLER_HEADER)
19
+
20
+ type BrokerClient = Pick<ReturnType<typeof createRemoteClient>, 'send' | 'loginInfo'>
21
+
22
+ const failure = (error: unknown, status: number) =>
23
+ Response.json(
24
+ {
25
+ error: error instanceof Error ? error.message : 'Cloud request failed',
26
+ signIn: error instanceof CloudSignInRequired
27
+ },
28
+ { status, headers: { [BROKER_ERROR_HEADER]: '1' } }
29
+ )
30
+
31
+ export function createRemoteBroker(
32
+ // This server's own login only: it never asks another server.
33
+ client: BrokerClient = createRemoteClient(DATA_DIR),
34
+ workspaces: () => Promise<WorkspaceEntry[]> = listWorkspaces
35
+ ) {
36
+ /** Answers undefined for a request that is not addressed to the broker. */
37
+ return async function handle(request: Request): Promise<Response | undefined> {
38
+ const url = new URL(request.url)
39
+ if (url.pathname !== '/remote/info' && url.pathname !== '/remote/request') return undefined
40
+ if (request.headers.get(BROKER_CALLER_HEADER) !== '1' || request.headers.has('origin'))
41
+ return failure(new Error('Only the moi CLI can use this'), 403)
42
+ try {
43
+ if (url.pathname === '/remote/info') {
44
+ const info = await client.loginInfo()
45
+ return Response.json(info, {
46
+ headers: { [BROKER_LOGIN_HEADER]: info.login ?? 'none' }
47
+ })
48
+ }
49
+ const path = url.searchParams.get('path') ?? ''
50
+ const { workspace, access } = allowedCloudRequest(request.method, path)
51
+ if (access === 'own login') throw new Error('This request needs your own Cloud login')
52
+ if (
53
+ workspace &&
54
+ !(await workspaces()).some(
55
+ entry =>
56
+ entry.remote?.user_id === workspace.user_id &&
57
+ entry.remote.workspace_id === workspace.workspace_id
58
+ )
59
+ )
60
+ throw new Error('This workspace is not linked on this machine')
61
+ const { response, agent } = await client.send(path, {
62
+ method: request.method,
63
+ // Passed on as it arrives, so a large upload is never held in memory.
64
+ body: request.body ?? undefined,
65
+ contentLength: request.headers.get('content-length') ?? undefined,
66
+ contentType: request.headers.get('content-type') ?? undefined,
67
+ signal: request.signal
68
+ })
69
+ const contentType = response.headers.get('content-type')
70
+ return new Response(response.body, {
71
+ status: response.status,
72
+ headers: {
73
+ [BROKER_LOGIN_HEADER]: agent ? 'agent' : 'human',
74
+ ...(contentType ? { 'content-type': contentType } : {})
75
+ }
76
+ })
77
+ } catch (error) {
78
+ return failure(error, 502)
79
+ }
80
+ }
81
+ }
@@ -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 {}