moi-computer 0.13.1-next.1 → 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 (205) hide show
  1. package/client/api/app-config.ts +12 -1
  2. package/client/api/http.ts +11 -1
  3. package/client/app/app-router.tsx +3 -2
  4. package/client/app/routes/home-route.tsx +1 -1
  5. package/client/app/routes/workspace-registration.tsx +68 -0
  6. package/client/app/routes/workspace-route.tsx +33 -6
  7. package/client/app/shell/sidebar-layout.tsx +10 -5
  8. package/client/components/shared/workspace-icon.tsx +8 -17
  9. package/client/features/account/account-test-utils.tsx +15 -9
  10. package/client/features/account/api.ts +6 -6
  11. package/client/features/account/profile-actions.ts +5 -7
  12. package/client/features/app-settings/settings-page.tsx +2 -1
  13. package/client/features/applets/api.ts +6 -6
  14. package/client/features/applets/applet-cache.ts +6 -5
  15. package/client/features/applets/applet-log.ts +2 -1
  16. package/client/features/applets/applet-runtime.ts +2 -1
  17. package/client/features/applets/use-applet.ts +73 -18
  18. package/client/features/applets/widget-shell.tsx +4 -2
  19. package/client/features/chat/applet-chat-intents.ts +5 -13
  20. package/client/features/chat/chat-popup.tsx +8 -4
  21. package/client/features/chat/chat-send.ts +2 -2
  22. package/client/features/chat/composer/model-order.ts +4 -4
  23. package/client/features/chat/composer/model-picker.tsx +12 -10
  24. package/client/features/chat/composer/use-workspace-composer-state.tsx +1 -1
  25. package/client/features/chat/sessions/api.ts +11 -28
  26. package/client/features/chat/sessions/use-selected-session.ts +14 -109
  27. package/client/features/chat/use-chat.ts +8 -12
  28. package/client/features/collab/members/api.ts +4 -10
  29. package/client/features/collab/members/hooks.ts +32 -38
  30. package/client/features/collab/members/store.ts +96 -71
  31. package/client/features/collab/members/types.ts +5 -3
  32. package/client/features/collab/presence/client.ts +2 -3
  33. package/client/features/collab/presence/hooks.tsx +1 -1
  34. package/client/features/collab/proxy-user.ts +1 -3
  35. package/client/features/collab/sharing/workspace-members.tsx +0 -8
  36. package/client/features/dev/chat-states-page.tsx +3 -1
  37. package/client/features/dev/harness-debug-page.tsx +7 -7
  38. package/client/features/dev/workspace-setup-mocks.ts +1 -1
  39. package/client/features/dev/workspace-setup-preview.tsx +6 -4
  40. package/client/features/harness/api.ts +13 -10
  41. package/client/features/harness/harness-login-panel.tsx +9 -5
  42. package/client/features/harness/harness-presentation.ts +4 -4
  43. package/client/features/harness/harness-selector.tsx +13 -13
  44. package/client/features/harness/use-harness-login.ts +5 -5
  45. package/client/features/home/api.ts +38 -2
  46. package/client/features/home/home-page.tsx +43 -13
  47. package/client/features/home/shared-workspaces.tsx +70 -0
  48. package/client/features/home/workspace-invitations.tsx +101 -0
  49. package/client/features/identity/host-api.ts +3 -2
  50. package/client/features/identity/store.ts +1 -7
  51. package/client/features/onboarding/agent-setup-step.tsx +8 -8
  52. package/client/features/onboarding/onboarding-page.tsx +3 -2
  53. package/client/features/onboarding/workspace-setup-step.tsx +1 -1
  54. package/client/features/overview/api.ts +3 -5
  55. package/client/features/overview/default/registry.tsx +1 -1
  56. package/client/features/overview/default/views-widget.tsx +2 -2
  57. package/client/features/overview/hidden-panel.tsx +7 -5
  58. package/client/features/overview/overview.tsx +18 -16
  59. package/client/features/overview/workspace-name.tsx +2 -2
  60. package/client/features/scratchpad/scratchpad.tsx +9 -7
  61. package/client/features/scratchpad/use-scratchpad-snapshot.tsx +13 -5
  62. package/client/features/views/api.ts +66 -23
  63. package/client/features/views/use-view-actions.ts +10 -41
  64. package/client/features/views/view-manager.tsx +1 -1
  65. package/client/features/views/view-submission.ts +2 -21
  66. package/client/features/workspace/add/api.ts +5 -4
  67. package/client/features/workspace/add/create-workspace-dialog.tsx +12 -9
  68. package/client/features/workspace/add/import-workspace-dialog.tsx +7 -7
  69. package/client/features/workspace/add/use-workspace-import.ts +10 -10
  70. package/client/features/workspace/add/workspace-agent-options.ts +21 -20
  71. package/client/features/workspace/add/workspace-agent-selector.tsx +11 -11
  72. package/client/features/workspace/api.ts +60 -13
  73. package/client/features/workspace/harness-transition.ts +7 -13
  74. package/client/features/workspace/remote.ts +25 -0
  75. package/client/features/workspace/settings/api.ts +7 -12
  76. package/client/features/workspace/settings/connectors-settings.tsx +3 -3
  77. package/client/features/workspace/settings/general-settings.tsx +8 -8
  78. package/client/features/workspace/setup/workspace-login-state.tsx +4 -4
  79. package/client/features/workspace/setup/workspace-recovery-states.tsx +43 -14
  80. package/client/features/workspace/setup/workspace-setup.tsx +6 -6
  81. package/client/features/workspace/tab-resolution.ts +1 -8
  82. package/client/features/workspace/use-workspace-navigation.ts +11 -7
  83. package/client/features/workspace/workspace-content.tsx +24 -31
  84. package/client/features/workspace/workspace-frame.tsx +13 -26
  85. package/client/features/workspace/workspace-layout-context.tsx +45 -12
  86. package/client/features/workspace/workspace-menu.tsx +2 -2
  87. package/client/features/workspace/workspace-pane.tsx +22 -0
  88. package/client/features/workspace/workspace-pending-screen.tsx +1 -1
  89. package/client/features/workspace/workspace-preferences.ts +91 -0
  90. package/client/features/workspace/workspace-presentation.tsx +12 -16
  91. package/client/features/workspace/workspace-screen.tsx +2 -2
  92. package/client/features/workspace/workspace-state.ts +42 -16
  93. package/client/features/workspace/workspace-tabs.tsx +1 -1
  94. package/client/features/workspace/workspace-test-utils.ts +23 -0
  95. package/client/runtime/use-workspace-events.ts +14 -0
  96. package/client/runtime/workspace-events.ts +9 -9
  97. package/client/store/ui.ts +24 -9
  98. package/client/store/workspace-session.ts +30 -0
  99. package/dist/chunk-0h4zypgf.js +1 -0
  100. package/dist/chunk-1tksq43z.js +72 -0
  101. package/dist/chunk-6gxf0xr8.js +5 -0
  102. package/dist/chunk-a865c7x4.js +1 -0
  103. package/dist/chunk-f44cs6mw.js +2 -0
  104. package/dist/chunk-h3qag4a6.js +2 -0
  105. package/dist/chunk-kffcah9w.css +1 -0
  106. package/dist/chunk-q2tpy0h7.js +2 -0
  107. package/dist/chunk-r95acex1.js +546 -0
  108. package/dist/chunk-w5h9grdr.js +1 -0
  109. package/dist/{chunk-th91xfnp.js → chunk-xj1pjhng.js} +1 -1
  110. package/dist/index.html +1 -1
  111. package/lib/harness-instructions.ts +4 -4
  112. package/lib/harness-types.ts +13 -0
  113. package/lib/moi-context.ts +19 -5
  114. package/lib/types.ts +38 -54
  115. package/lib/workspace-config.ts +48 -0
  116. package/lib/workspace-layout.ts +5 -24
  117. package/package.json +5 -2
  118. package/server/AGENTS.md +1 -1
  119. package/server/README.md +36 -31
  120. package/server/api/harnesses.ts +5 -5
  121. package/server/api/index.ts +268 -162
  122. package/server/applets/index.ts +15 -9
  123. package/server/applets/views.ts +2 -17
  124. package/server/applets/widgets.ts +3 -2
  125. package/server/cli/commands/config.ts +8 -20
  126. package/server/cli/commands/hermes.ts +2 -2
  127. package/server/cli/commands/init.ts +102 -54
  128. package/server/cli/commands/openclaw.ts +2 -2
  129. package/server/cli/commands/refresh.ts +10 -1
  130. package/server/cli/commands/remote.ts +330 -0
  131. package/server/cli/commands/skill.ts +4 -4
  132. package/server/cli/commands/tabs.ts +5 -12
  133. package/server/cli/control.ts +35 -4
  134. package/server/cli/index.ts +10 -6
  135. package/server/cli/remote-command.ts +77 -0
  136. package/server/cli/remote-control.ts +73 -0
  137. package/server/cli/remote-operations.ts +247 -0
  138. package/server/collab/config.ts +3 -3
  139. package/server/collab/skill/index.ts +3 -3
  140. package/server/control.ts +47 -12
  141. package/server/harness/acp/session.ts +4 -4
  142. package/server/harness/auth.ts +26 -31
  143. package/server/harness/claude-code/index.ts +1 -1
  144. package/server/harness/codex/discovery.ts +1 -1
  145. package/server/harness/codex/session.ts +1 -1
  146. package/server/harness/detect.ts +14 -19
  147. package/server/harness/executable.ts +10 -10
  148. package/server/harness/hermes/NOTES.md +2 -2
  149. package/server/harness/hermes/index.ts +1 -1
  150. package/server/harness/install.ts +11 -11
  151. package/server/harness/openclaw/index.ts +1 -1
  152. package/server/harness/registry.ts +7 -6
  153. package/server/harness/types.ts +4 -4
  154. package/server/onboarding/jobs.ts +2 -2
  155. package/server/operations/commands.ts +46 -0
  156. package/server/operations/files.ts +148 -0
  157. package/server/operations/server.ts +206 -0
  158. package/server/remote/agent.ts +103 -0
  159. package/server/remote/broker-client.ts +76 -0
  160. package/server/remote/broker.ts +81 -0
  161. package/server/remote/client.ts +725 -0
  162. package/server/remote/errors.ts +2 -0
  163. package/server/remote/routes.ts +121 -0
  164. package/server/remote/workspace.ts +34 -0
  165. package/server/scratchpad/document.ts +33 -12
  166. package/server/scratchpad/executor.ts +16 -7
  167. package/server/sessions/config.ts +8 -5
  168. package/server/sessions/pending-views.ts +17 -0
  169. package/server/sessions/send-message.ts +102 -0
  170. package/server/sessions/view-sessions.ts +9 -101
  171. package/server/skills/locations.ts +4 -4
  172. package/server/skills/update.ts +11 -11
  173. package/server/skills/version.ts +7 -7
  174. package/server/skills/workspace.ts +13 -11
  175. package/server/web.ts +13 -9
  176. package/server/workspace-state/file.ts +4 -0
  177. package/server/workspace-state/index.ts +0 -4
  178. package/server/workspaces/api.ts +24 -0
  179. package/server/workspaces/change-harness.ts +15 -26
  180. package/server/workspaces/import.ts +4 -4
  181. package/server/workspaces/init.ts +15 -13
  182. package/server/workspaces/layout.ts +60 -66
  183. package/server/workspaces/registry.ts +43 -18
  184. package/server/workspaces/shared.ts +74 -0
  185. package/server/workspaces/tabs.ts +5 -12
  186. package/skill/SKILL.md +80 -19
  187. package/skill/references/SCRATCHPAD.md +4 -0
  188. package/skill/references/UI-COMPONENTS.md +1 -1
  189. package/client/api/app-ui-keys.ts +0 -6
  190. package/client/features/chat/sessions/browser-tab-state.ts +0 -43
  191. package/client/features/collab/members/keys.ts +0 -6
  192. package/client/features/workspace/browser-tab-state.ts +0 -51
  193. package/client/features/workspace/layout-save.ts +0 -13
  194. package/dist/chunk-3smkkcfw.js +0 -546
  195. package/dist/chunk-47h9c2qy.js +0 -2
  196. package/dist/chunk-8qed2gqp.js +0 -75
  197. package/dist/chunk-8zy3vesm.js +0 -1
  198. package/dist/chunk-a47zy276.js +0 -2
  199. package/dist/chunk-g4c1nte9.css +0 -1
  200. package/dist/chunk-kcactdr4.js +0 -2
  201. package/dist/chunk-m8bhx6tw.js +0 -1
  202. package/dist/chunk-pf19zcrn.js +0 -2
  203. package/dist/chunk-ygzxah0e.js +0 -1
  204. package/lib/workspace-types.ts +0 -13
  205. package/server/workspace-state/legacy-migration.ts +0 -79
@@ -0,0 +1,725 @@
1
+ import { parseRemoteWorkspaceTarget } from '@/lib/workspace-config'
2
+ import { decodeJwt } from 'jose'
3
+ import { Mutex } from 'async-mutex'
4
+ import { lock } from 'proper-lockfile'
5
+ import { z } from 'zod'
6
+ import { access as fileAccess, chmod, mkdir, rename, rm } from 'node:fs/promises'
7
+ import { accessSync, constants, existsSync } from 'node:fs'
8
+ import { join } from 'node:path'
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'
13
+ import { PACKAGE_ROOT } from '../version'
14
+ import {
15
+ agentCredentialsSchema,
16
+ agentAuthorization,
17
+ agentJoinBody,
18
+ createAgentKeys,
19
+ agentClientSchema,
20
+ AGENT_CLIENTS
21
+ } from './agent'
22
+
23
+ export type RemoteRequestOptions = {
24
+ method?: string
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
28
+ signal?: AbortSignal
29
+ contentType?: string
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
+ }
40
+
41
+ export { CloudSignInRequired }
42
+
43
+ const humanCredentialsSchema = z.object({
44
+ accessToken: z.string().min(1),
45
+ refreshToken: z.string().min(1),
46
+ url: z.string().min(1),
47
+ clientId: z.string().min(1)
48
+ })
49
+ const credentialsSchema = z.union([agentCredentialsSchema, humanCredentialsSchema])
50
+ type Credentials = z.infer<typeof credentialsSchema>
51
+ const isAgent = (value: Credentials): value is z.infer<typeof agentCredentialsSchema> =>
52
+ 'kind' in value && value.kind === 'agent'
53
+ const tokensSchema = z.object({
54
+ access_token: z.string().min(1),
55
+ refresh_token: z.string().min(1)
56
+ })
57
+ const deviceSchema = z.object({
58
+ device_code: z.string().min(1),
59
+ user_code: z.string().min(1),
60
+ verification_uri_complete: z.url(),
61
+ expires_in: z.number().positive().max(3600),
62
+ interval: z.number().positive().max(60).default(5)
63
+ })
64
+ const humanProfileSchema = z
65
+ .object({ id: z.string(), name: z.string(), email: z.string() })
66
+ .passthrough()
67
+ const agentProfileSchema = z.object({
68
+ id: z.string(),
69
+ type: z.literal('agent'),
70
+ name: z.string(),
71
+ client: agentClientSchema
72
+ })
73
+ const profileSchema = z.union([agentProfileSchema, humanProfileSchema])
74
+ const workspacesSchema = z.object({
75
+ workspaces: z.array(z.object({ id: z.string(), owner: humanProfileSchema }))
76
+ })
77
+ const remoteSchema = z.object({
78
+ url: z.string().min(1).optional(),
79
+ clientId: z.string().min(1).optional(),
80
+ managed: z.boolean().optional()
81
+ })
82
+ const configSchema = z.object({ remote: remoteSchema.optional() })
83
+ type RemoteConfig = { url: string; clientId: string; managed: boolean }
84
+ export type Profile = z.infer<typeof profileSchema>
85
+ export type SharedWorkspace = { id: string; owner: z.infer<typeof humanProfileSchema> }
86
+ export type RemoteStatus = { me: Profile; workspaces: SharedWorkspace[] }
87
+ export function resolveRemoteConfig(
88
+ remote: { url?: string; clientId?: string; managed?: boolean },
89
+ development: boolean,
90
+ directory = DATA_DIR
91
+ ): RemoteConfig {
92
+ if (development && !remote.url) {
93
+ throw new Error(
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`
95
+ )
96
+ }
97
+ const url = new URL(remote.url ?? 'https://moi.computer/cloud')
98
+ if (
99
+ url.protocol !== 'https:' &&
100
+ !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
101
+ ) {
102
+ throw new Error('Remote URL must use HTTPS (HTTP is allowed for localhost)')
103
+ }
104
+ if (url.username || url.password || url.search || url.hash) {
105
+ throw new Error('Cloud URL must not contain credentials, a query, or a fragment')
106
+ }
107
+ return {
108
+ url: url.href.replace(/\/+$/, ''),
109
+ clientId: remote.clientId ?? 'moi-cli',
110
+ managed: remote.managed === true
111
+ }
112
+ }
113
+
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) {
122
+ const authFile = join(directory, 'remote-auth.json')
123
+ const mutex = new Mutex()
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
+ }
143
+
144
+ async function json<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
145
+ // A parser error can quote the response body, which may contain tokens.
146
+ const parsed = schema.safeParse(await response.json().catch(() => undefined))
147
+ if (!parsed.success) throw new Error('Cloud returned an invalid response')
148
+ return parsed.data
149
+ }
150
+
151
+ async function remoteConfig(): Promise<RemoteConfig> {
152
+ let raw: unknown = {}
153
+ try {
154
+ raw = await Bun.file(join(directory, 'config.json')).json()
155
+ } catch (error) {
156
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
157
+ throw new Error('Could not read Moi config.json')
158
+ }
159
+ const parsed = configSchema.safeParse(raw)
160
+ if (!parsed.success) throw new Error('Invalid remote settings in config.json')
161
+ const development =
162
+ process.env.NODE_ENV === 'development' || existsSync(join(PACKAGE_ROOT, '.git'))
163
+ return resolveRemoteConfig(parsed.data.remote ?? {}, development, directory)
164
+ }
165
+
166
+ async function post(config: RemoteConfig, path: string, values: Record<string, string>) {
167
+ return fetch(`${config.url}/api/auth${path}`, {
168
+ method: 'POST',
169
+ redirect: 'error',
170
+ signal: AbortSignal.timeout(30_000),
171
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
172
+ body: new URLSearchParams({ client_id: config.clientId, ...values })
173
+ })
174
+ }
175
+
176
+ async function readStoredCredentials(): Promise<Credentials> {
177
+ let value: unknown
178
+ try {
179
+ value = await Bun.file(authFile).json()
180
+ } catch (error) {
181
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
182
+ throw new CloudSignInRequired('Sign in with moi remote login to see shared workspaces')
183
+ throw new Error('Could not read remote credentials — run moi remote login')
184
+ }
185
+ const parsed = credentialsSchema.safeParse(value)
186
+ if (!parsed.success) throw new Error('Invalid remote credentials — run moi remote login')
187
+ return parsed.data
188
+ }
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
+
198
+ async function writePrivate(path: string, value: unknown, assertLock: () => void) {
199
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`
200
+ try {
201
+ await Bun.write(temporary, JSON.stringify(value) + '\n', { mode: 0o600 })
202
+ await chmod(temporary, 0o600)
203
+ assertLock()
204
+ await rename(temporary, path)
205
+ } finally {
206
+ await rm(temporary, { force: true })
207
+ }
208
+ }
209
+
210
+ async function save(
211
+ response: Response,
212
+ config: RemoteConfig,
213
+ assertLock: () => void
214
+ ): Promise<Credentials> {
215
+ if (!response.ok)
216
+ throw new Error(`Could not refresh login (${response.status}) — run moi remote login`)
217
+ const value = await json(response, tokensSchema)
218
+ const pair = {
219
+ accessToken: value.access_token,
220
+ refreshToken: value.refresh_token,
221
+ url: config.url,
222
+ clientId: config.clientId
223
+ }
224
+ await writePrivate(authFile, pair, assertLock)
225
+ return pair
226
+ }
227
+
228
+ // Only mutations take a cross-process lock. Heartbeats let later commands
229
+ // recover a lock abandoned by a crash; the in-process mutex avoids retry delays.
230
+ async function locked<T>(action: (assertLock: () => void) => Promise<T>): Promise<T> {
231
+ return mutex.runExclusive(async () => {
232
+ await mkdir(directory, { recursive: true, mode: 0o700 })
233
+ let compromised: Error | undefined
234
+ const release = await lock(directory, {
235
+ lockfilePath: `${authFile}.lock`,
236
+ stale: 60_000,
237
+ update: 10_000,
238
+ retries: { retries: 80, factor: 1.5, minTimeout: 50, maxTimeout: 1000 },
239
+ onCompromised: error => {
240
+ compromised = error
241
+ }
242
+ })
243
+ const assertLock = () => {
244
+ if (compromised) throw new Error('Remote credentials lock was lost — retry the command')
245
+ }
246
+ try {
247
+ return await action(assertLock)
248
+ } finally {
249
+ if (!compromised) await release()
250
+ }
251
+ })
252
+ }
253
+
254
+ async function login(
255
+ announce: (url: string, code: string) => void | Promise<void>
256
+ ): Promise<void> {
257
+ const config = await remoteConfig()
258
+ if (config.managed) throw new Error('Cloud manages sign-in on this machine')
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()))
262
+ throw new Error('Signed in as an agent — use a separate Moi data directory for human login')
263
+ if (await Bun.file(pendingFile).exists())
264
+ throw new Error('An agent join is pending — retry that invitation first')
265
+ const response = await post(config, '/device/code', {
266
+ scope: 'profile:read workspaces:read workspaces:access offline_access',
267
+ resource: 'urn:moi:cloud'
268
+ })
269
+ if (!response.ok) throw new Error(`Could not start login (${response.status})`)
270
+ const device = await json(response, deviceSchema)
271
+ const verification = new URL(device.verification_uri_complete)
272
+ if (
273
+ verification.origin !== new URL(config.url).origin ||
274
+ verification.username ||
275
+ verification.password
276
+ )
277
+ throw new Error('Cloud returned a login URL on a different origin')
278
+ await announce(verification.href, device.user_code)
279
+ let interval = device.interval
280
+ const deadline = Date.now() + device.expires_in * 1000
281
+ while (Date.now() < deadline) {
282
+ await Bun.sleep(interval * 1000)
283
+ if (Date.now() >= deadline) break
284
+ const token = await post(config, '/oauth2/token', {
285
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
286
+ device_code: device.device_code
287
+ })
288
+ if (token.ok) {
289
+ await locked(async assertLock => {
290
+ if ((await Bun.file(authFile).exists()) && isAgent(await readStoredCredentials()))
291
+ throw new Error(
292
+ 'An agent signed in while browser login was pending; agent credentials kept'
293
+ )
294
+ if (await Bun.file(pendingFile).exists())
295
+ throw new Error('An agent join is pending; its keys were kept')
296
+ return save(token, config, assertLock)
297
+ })
298
+ return
299
+ }
300
+ if (token.status === 429) {
301
+ interval = Math.min(
302
+ 60,
303
+ Math.max(interval + 5, Number(token.headers.get('retry-after')) || 0)
304
+ )
305
+ continue
306
+ }
307
+ const result = await json(token, z.object({ error: z.string() }))
308
+ if (result.error === 'slow_down') interval = Math.min(60, interval + 5)
309
+ else if (result.error !== 'authorization_pending')
310
+ throw new Error(`Login failed (${token.status}) — run moi remote login again`)
311
+ }
312
+ throw new Error('Login expired — run moi remote login again')
313
+ }
314
+
315
+ async function logout(confirmed = false): Promise<void> {
316
+ const config = await remoteConfig()
317
+ if (config.managed) throw new Error('Cloud manages sign-in on this machine')
318
+ await locked(async assertLock => {
319
+ if (!(await Bun.file(authFile).exists())) {
320
+ if (await Bun.file(pendingFile).exists())
321
+ throw new Error(
322
+ 'An agent join is unfinished — retry the same invitation before logging out'
323
+ )
324
+ return
325
+ }
326
+ const pair = await read(config)
327
+ if (isAgent(pair)) {
328
+ if (!confirmed)
329
+ throw new Error(
330
+ 'Logging out permanently revokes this agent login and deletes its local keys. It cannot be restored. Run moi remote logout --yes to confirm'
331
+ )
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
+ )
339
+ assertLock()
340
+ await rm(authFile, { force: true })
341
+ await rm(pendingFile, { force: true })
342
+ return
343
+ }
344
+ const response = await post(config, '/oauth2/revoke', {
345
+ token_type_hint: 'refresh_token',
346
+ token: pair.refreshToken
347
+ })
348
+ if (!response.ok)
349
+ throw new Error(`Logout failed (${response.status}); credentials kept so you can retry`)
350
+ assertLock()
351
+ await rm(authFile, { force: true })
352
+ })
353
+ }
354
+
355
+ function fresh(pair: z.infer<typeof humanCredentialsSchema>): boolean {
356
+ try {
357
+ return (decodeJwt(pair.accessToken).exp ?? 0) * 1000 > Date.now() + 30_000
358
+ } catch {
359
+ return false
360
+ }
361
+ }
362
+
363
+ async function access(config: RemoteConfig): Promise<Credentials> {
364
+ const pair = await read(config)
365
+ if (isAgent(pair) || fresh(pair)) return pair
366
+ return locked(async assertLock => {
367
+ const current = await read(config)
368
+ if (isAgent(current) || fresh(current)) return current
369
+ return save(
370
+ await post(config, '/oauth2/token', {
371
+ grant_type: 'refresh_token',
372
+ refresh_token: current.refreshToken
373
+ }),
374
+ config,
375
+ assertLock
376
+ )
377
+ })
378
+ }
379
+
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(
390
+ config: RemoteConfig,
391
+ pair: Credentials,
392
+ path: string,
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, {
423
+ method,
424
+ body,
425
+ redirect: 'error',
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
+ }
434
+ })
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()
455
+ throw new Error(
456
+ agent ? 'Agent login is no longer valid' : 'Sign-in expired — run moi remote login'
457
+ )
458
+ }
459
+ if (!response.ok) {
460
+ await response.body?.cancel()
461
+ throw new Error(`Cloud request failed (${response.status})`)
462
+ }
463
+ return json(response, schema)
464
+ }
465
+ async function request<T>(
466
+ path: string,
467
+ body: unknown | undefined,
468
+ schema: z.ZodType<T>,
469
+ method?: string
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 }> {
476
+ const config = await remoteConfig()
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
+ }
483
+ }
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
494
+ }
495
+ const invitationSchema = z.object({
496
+ id: z.string(),
497
+ workspaceId: z.string(),
498
+ workspaceName: z.string(),
499
+ inviter: humanProfileSchema,
500
+ expiresAt: z.string()
501
+ })
502
+ async function invitations() {
503
+ return (
504
+ await request(
505
+ cloudRoutes.invitations.path(),
506
+ undefined,
507
+ z.object({ invitations: z.array(invitationSchema) })
508
+ )
509
+ ).invitations
510
+ }
511
+ function invitation(value: string, config: { url: string }) {
512
+ if (!value.includes('://')) {
513
+ if (!/^[A-Za-z0-9_-]{1,240}$/.test(value)) throw new Error('Invalid invitation ID')
514
+ return { id: value, token: undefined, agent: false }
515
+ }
516
+ const url = new URL(value)
517
+ const root = new URL(config.url)
518
+ const prefix = root.pathname.replace(/\/$/, '')
519
+ const match = new RegExp(
520
+ `^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/(agent-invite|invite)/([A-Za-z0-9_-]{1,240})$`
521
+ ).exec(url.pathname)
522
+ const token = url.searchParams.get('token')
523
+ if (
524
+ url.origin !== root.origin ||
525
+ url.username ||
526
+ url.password ||
527
+ !match ||
528
+ !token ||
529
+ !/^[A-Za-z0-9_-]{43}$/.test(token)
530
+ )
531
+ throw new Error('Use an invitation URL from your configured Cloud URL')
532
+ return { id: match[2]!, token, agent: match[1] === 'agent-invite' }
533
+ }
534
+ const accepted = z.object({
535
+ success: z.literal(true),
536
+ remote: z
537
+ .object({ user_id: z.string(), workspace_id: z.string() })
538
+ .transform(parseRemoteWorkspaceTarget),
539
+ membershipId: z.string()
540
+ })
541
+ const acceptPath = (id: string) => cloudRoutes.acceptInvitation.path(id)
542
+ async function accept(value: string, name?: string, client?: string) {
543
+ if (client !== undefined && !agentClientSchema.safeParse(client).success)
544
+ throw new Error(`Invalid client — choose ${AGENT_CLIENTS.join(', ')}`)
545
+ ownDirectory()
546
+ const config = await remoteConfig(),
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
+ )
561
+ if (await Bun.file(authFile).exists()) {
562
+ const saved = await read(config)
563
+ if (!isAgent(saved) && (target.agent || name !== undefined || client !== undefined))
564
+ throw new Error(
565
+ 'Already signed in as a human — use a separate Moi data directory for this agent'
566
+ )
567
+ return acceptWith(await access(config))
568
+ }
569
+ if (!target.agent)
570
+ throw new CloudSignInRequired(
571
+ 'Sign in with moi remote login before accepting a human invitation'
572
+ )
573
+ if (config.managed) throw new Error('Cloud manages sign-in on this machine')
574
+ return locked(async assertLock => {
575
+ if (await Bun.file(authFile).exists()) {
576
+ const pair = await read(config)
577
+ if (!isAgent(pair))
578
+ throw new Error(
579
+ 'Already signed in as a human — use a separate Moi data directory for this agent'
580
+ )
581
+ return acceptWith(pair)
582
+ }
583
+ if (!target.token) throw new Error('First agent acceptance requires an invitation URL')
584
+ const fingerprint = new Bun.CryptoHasher('sha256').update(target.token).digest('hex')
585
+ const pendingSchema = z.object({
586
+ fingerprint: z.string(),
587
+ name: z.string(),
588
+ client: agentClientSchema,
589
+ keys: agentCredentialsSchema
590
+ })
591
+ let pending: z.infer<typeof pendingSchema>
592
+ if (await Bun.file(pendingFile).exists()) {
593
+ const saved = pendingSchema.safeParse(
594
+ await Bun.file(pendingFile)
595
+ .json()
596
+ .catch(() => undefined)
597
+ )
598
+ if (!saved.success)
599
+ throw new Error('Could not read pending agent keys; credentials were kept')
600
+ pending = saved.data
601
+ if (
602
+ pending.fingerprint !== fingerprint ||
603
+ pending.keys.url !== config.url ||
604
+ pending.keys.clientId !== config.clientId
605
+ )
606
+ throw new Error(
607
+ 'Retry the original pending agent invitation before switching accounts or clouds'
608
+ )
609
+ } else {
610
+ if (!name?.trim() || name.trim().length > 80 || !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
+ )
617
+ pending = {
618
+ fingerprint,
619
+ name: name.trim(),
620
+ client: agentClientSchema.parse(client),
621
+ keys: await createAgentKeys(config)
622
+ }
623
+ await writePrivate(pendingFile, pending, assertLock)
624
+ }
625
+ const body = await agentJoinBody(pending.keys, target.token, pending.name, pending.client)
626
+ const response = await fetch(`${config.url}/api/agents/join`, {
627
+ method: 'POST',
628
+ headers: { 'content-type': 'application/json' },
629
+ body: JSON.stringify(body),
630
+ redirect: 'error',
631
+ signal: AbortSignal.timeout(30_000)
632
+ })
633
+ if (!response.ok)
634
+ throw new Error(
635
+ `Agent acceptance failed (${response.status}); keys kept so you can retry the same invitation`
636
+ )
637
+ const joined = await json(
638
+ response,
639
+ accepted.extend({ agentId: z.string(), hostId: z.string() })
640
+ )
641
+ if (joined.agentId !== pending.keys.agentId || joined.hostId !== pending.keys.hostId)
642
+ throw new Error('Cloud returned an unexpected agent identity')
643
+ await writePrivate(authFile, pending.keys, assertLock)
644
+ await rm(pendingFile, { force: true })
645
+ return joined
646
+ })
647
+ }
648
+ async function renameAgent(name: string) {
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')
652
+ }
653
+ async function leave(ownerId: string, workspaceId: string) {
654
+ return request(
655
+ cloudRoutes.leave.path({ user_id: ownerId, workspace_id: workspaceId }),
656
+ {},
657
+ z.object({ success: z.literal(true) })
658
+ )
659
+ }
660
+
661
+ /** Read accepted shared workspaces using this machine's configured cloud login.
662
+ * Refreshes credentials automatically; requires no browser or running Moi server.
663
+ */
664
+ async function fetchSharedWorkspaces(): Promise<SharedWorkspace[]> {
665
+ return (await request(cloudRoutes.sharedWorkspaces.path(), undefined, workspacesSchema))
666
+ .workspaces
667
+ }
668
+
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)
673
+ if (!response.ok) {
674
+ await response.body?.cancel()
675
+ throw new Error(
676
+ response.status === 401
677
+ ? 'Cloud login expired or revoked — run moi remote login'
678
+ : `Remote operation failed (${response.status})`
679
+ )
680
+ }
681
+ return response
682
+ }
683
+
684
+ async function remoteStatus(): Promise<RemoteStatus> {
685
+ const [me, shared] = await Promise.all([
686
+ request(cloudRoutes.me.path(), undefined, profileSchema),
687
+ request(cloudRoutes.sharedWorkspaces.path(), undefined, workspacesSchema)
688
+ ])
689
+ return { me, workspaces: shared.workspaces }
690
+ }
691
+
692
+ return {
693
+ remoteConfig,
694
+ cloudUrl,
695
+ loginInfo,
696
+ send,
697
+ login,
698
+ logout,
699
+ fetchSharedWorkspaces,
700
+ remoteRequest,
701
+ remoteStatus,
702
+ invitations,
703
+ accept,
704
+ renameAgent,
705
+ leave
706
+ }
707
+ }
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
+
713
+ export const {
714
+ remoteConfig,
715
+ cloudUrl,
716
+ login,
717
+ logout,
718
+ fetchSharedWorkspaces,
719
+ remoteRequest,
720
+ remoteStatus,
721
+ invitations,
722
+ accept,
723
+ renameAgent,
724
+ leave
725
+ } = createRemoteClient(DATA_DIR, ownsDataDir ? undefined : controlBroker)