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

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 (230) hide show
  1. package/client/api/app-config.ts +12 -2
  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 +37 -13
  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 +18 -4
  10. package/client/features/account/api.ts +10 -8
  11. package/client/features/account/profile-actions.ts +5 -7
  12. package/client/features/app-settings/avatar-upload.tsx +62 -0
  13. package/client/features/app-settings/profile-settings.tsx +10 -0
  14. package/client/features/app-settings/settings-page.tsx +2 -1
  15. package/client/features/applets/api.ts +6 -6
  16. package/client/features/applets/applet-cache.ts +6 -5
  17. package/client/features/applets/applet-log.ts +2 -1
  18. package/client/features/applets/applet-runtime.ts +2 -1
  19. package/client/features/applets/use-applet.ts +73 -18
  20. package/client/features/applets/widget-shell.tsx +4 -2
  21. package/client/features/chat/applet-chat-intents.ts +5 -13
  22. package/client/features/chat/chat-popup.tsx +8 -4
  23. package/client/features/chat/chat-send.ts +2 -2
  24. package/client/features/chat/composer/model-order.ts +4 -4
  25. package/client/features/chat/composer/model-picker.tsx +12 -10
  26. package/client/features/chat/composer/use-workspace-composer-state.tsx +1 -1
  27. package/client/features/chat/sessions/api.ts +11 -28
  28. package/client/features/chat/sessions/use-selected-session.ts +18 -100
  29. package/client/features/chat/use-chat.ts +8 -12
  30. package/client/features/collab/applet-api.ts +1 -1
  31. package/client/features/collab/components/cursors.tsx +6 -1
  32. package/client/features/collab/components/presence-avatars.tsx +1 -1
  33. package/client/features/collab/components/presence-frame.tsx +1 -1
  34. package/client/features/collab/components/presence-group.tsx +1 -1
  35. package/client/features/collab/components/presence-helpers.ts +2 -2
  36. package/client/features/collab/components/user-avatar-group.tsx +1 -1
  37. package/client/features/collab/components/user-avatar.tsx +1 -1
  38. package/client/features/collab/components/user.tsx +1 -1
  39. package/client/features/collab/index.ts +3 -3
  40. package/client/features/collab/members/api.ts +17 -0
  41. package/client/features/collab/members/hooks.ts +97 -0
  42. package/client/features/collab/members/store.ts +148 -0
  43. package/client/features/{workspace-members → collab/members}/types.ts +7 -5
  44. package/client/features/collab/{client.ts → presence/client.ts} +4 -5
  45. package/client/features/collab/{hooks.tsx → presence/hooks.tsx} +1 -1
  46. package/client/features/collab/{provider.tsx → presence/provider.tsx} +1 -12
  47. package/client/features/collab/{users.ts → presence/users.ts} +19 -21
  48. package/client/features/collab/proxy-user.ts +1 -3
  49. package/client/features/collab/sharing/agent-invite.tsx +30 -0
  50. package/client/features/collab/sharing/workspace-members.tsx +269 -0
  51. package/client/features/collab/sharing/workspace-sharing-menu.tsx +179 -0
  52. package/client/features/collab/testing/component-fixtures.tsx +3 -3
  53. package/client/features/collab/testing/fake-engine.ts +2 -2
  54. package/client/features/dev/chat-states-page.tsx +3 -1
  55. package/client/features/dev/collab/collab-playground.tsx +2 -2
  56. package/client/features/dev/dev-index-page.tsx +0 -6
  57. package/client/features/dev/dev-routes.tsx +0 -2
  58. package/client/features/dev/harness-debug-page.tsx +7 -7
  59. package/client/features/dev/workspace-setup-mocks.ts +1 -2
  60. package/client/features/dev/workspace-setup-preview.tsx +6 -4
  61. package/client/features/harness/api.ts +13 -10
  62. package/client/features/harness/harness-login-panel.tsx +9 -5
  63. package/client/features/harness/harness-presentation.ts +4 -4
  64. package/client/features/harness/harness-selector.tsx +13 -13
  65. package/client/features/harness/use-harness-login.ts +5 -5
  66. package/client/features/home/api.ts +38 -2
  67. package/client/features/home/home-page.tsx +43 -13
  68. package/client/features/home/shared-workspaces.tsx +70 -0
  69. package/client/features/home/workspace-invitations.tsx +101 -0
  70. package/client/features/identity/host-api.ts +5 -4
  71. package/client/features/identity/store.ts +1 -7
  72. package/client/features/onboarding/agent-setup-step.tsx +8 -8
  73. package/client/features/onboarding/onboarding-page.tsx +3 -2
  74. package/client/features/onboarding/workspace-setup-step.tsx +1 -1
  75. package/client/features/overview/api.ts +3 -5
  76. package/client/features/overview/default/registry.tsx +1 -1
  77. package/client/features/overview/default/views-widget.tsx +2 -2
  78. package/client/features/overview/hidden-panel.tsx +7 -5
  79. package/client/features/overview/overview.tsx +18 -16
  80. package/client/features/overview/workspace-name.tsx +2 -2
  81. package/client/features/scratchpad/scratchpad.tsx +9 -7
  82. package/client/features/scratchpad/use-scratchpad-snapshot.tsx +13 -5
  83. package/client/features/views/api.ts +34 -16
  84. package/client/features/views/use-view-actions.ts +10 -20
  85. package/client/features/views/view-manager.tsx +1 -1
  86. package/client/features/views/view-submission.ts +2 -21
  87. package/client/features/workspace/add/api.ts +5 -4
  88. package/client/features/workspace/add/create-workspace-dialog.tsx +12 -9
  89. package/client/features/workspace/add/import-workspace-dialog.tsx +7 -7
  90. package/client/features/workspace/add/use-workspace-import.ts +10 -10
  91. package/client/features/workspace/add/workspace-agent-options.ts +21 -20
  92. package/client/features/workspace/add/workspace-agent-selector.tsx +11 -11
  93. package/client/features/workspace/api.ts +60 -13
  94. package/client/features/workspace/harness-transition.ts +7 -13
  95. package/client/features/workspace/remote.ts +25 -0
  96. package/client/features/workspace/settings/api.ts +7 -12
  97. package/client/features/workspace/settings/connectors-settings.tsx +3 -3
  98. package/client/features/workspace/settings/general-settings.tsx +8 -8
  99. package/client/features/workspace/setup/workspace-login-state.tsx +4 -4
  100. package/client/features/workspace/setup/workspace-recovery-states.tsx +43 -14
  101. package/client/features/workspace/setup/workspace-setup.tsx +6 -6
  102. package/client/features/workspace/tab-resolution.ts +2 -2
  103. package/client/features/workspace/use-workspace-navigation.ts +7 -4
  104. package/client/features/workspace/workspace-content.tsx +32 -26
  105. package/client/features/workspace/workspace-frame.tsx +13 -26
  106. package/client/features/workspace/workspace-layout-context.tsx +45 -12
  107. package/client/features/workspace/workspace-menu.tsx +2 -2
  108. package/client/features/workspace/workspace-pane.tsx +22 -0
  109. package/client/features/workspace/workspace-pending-screen.tsx +1 -1
  110. package/client/features/workspace/workspace-preferences.ts +34 -0
  111. package/client/features/workspace/workspace-presentation.tsx +12 -16
  112. package/client/features/workspace/workspace-screen.tsx +2 -2
  113. package/client/features/workspace/workspace-state.ts +2 -1
  114. package/client/features/workspace/workspace-tabs.tsx +1 -1
  115. package/client/features/workspace/workspace-test-utils.ts +23 -0
  116. package/client/runtime/use-workspace-events.ts +14 -0
  117. package/client/runtime/workspace-events.ts +9 -9
  118. package/client/store/ui.ts +29 -9
  119. package/dist/chunk-44khk4sp.js +2 -0
  120. package/dist/chunk-ba6mz56s.js +72 -0
  121. package/dist/chunk-ec5ennpv.js +1 -0
  122. package/dist/chunk-ectsnw81.js +2 -0
  123. package/dist/chunk-en7w5ypg.js +1 -0
  124. package/dist/chunk-f695wcx5.js +5 -0
  125. package/dist/chunk-kffcah9w.css +1 -0
  126. package/dist/{chunk-kdgk4dac.js → chunk-n0fawy9x.js} +1 -1
  127. package/dist/chunk-pdt9hxfw.js +2 -0
  128. package/dist/chunk-rmd0ctfx.js +546 -0
  129. package/dist/chunk-zv22wv0g.js +1 -0
  130. package/dist/index.html +1 -1
  131. package/lib/harness-instructions.ts +4 -4
  132. package/lib/harness-types.ts +13 -0
  133. package/lib/types.ts +34 -50
  134. package/lib/workspace-config.ts +48 -0
  135. package/lib/workspace-layout.ts +2 -4
  136. package/package.json +4 -2
  137. package/server/README.md +29 -27
  138. package/server/api/harnesses.ts +5 -5
  139. package/server/api/index.ts +170 -68
  140. package/server/app-config.ts +2 -7
  141. package/server/applets/declarations.ts +6 -7
  142. package/server/applets/index.ts +15 -9
  143. package/server/applets/views.ts +2 -17
  144. package/server/applets/widgets.ts +3 -2
  145. package/server/cli/commands/config.ts +8 -20
  146. package/server/cli/commands/hermes.ts +2 -2
  147. package/server/cli/commands/init.ts +96 -64
  148. package/server/cli/commands/openclaw.ts +2 -2
  149. package/server/cli/commands/refresh.ts +10 -1
  150. package/server/cli/commands/remote.ts +228 -0
  151. package/server/cli/commands/skill.ts +4 -4
  152. package/server/cli/commands/tabs.ts +5 -12
  153. package/server/cli/control.ts +35 -4
  154. package/server/cli/index.ts +10 -6
  155. package/server/cli/remote-command.ts +77 -0
  156. package/server/cli/remote-control.ts +70 -0
  157. package/server/cli/remote-operations.ts +244 -0
  158. package/server/collab/config.ts +4 -8
  159. package/server/collab/manager.ts +5 -2
  160. package/server/collab/skill/index.ts +4 -50
  161. package/server/control.ts +38 -11
  162. package/server/harness/acp/session.ts +4 -4
  163. package/server/harness/auth.ts +26 -31
  164. package/server/harness/claude-code/index.ts +1 -1
  165. package/server/harness/codex/discovery.ts +1 -1
  166. package/server/harness/codex/session.ts +1 -1
  167. package/server/harness/detect.ts +14 -19
  168. package/server/harness/executable.ts +10 -10
  169. package/server/harness/hermes/NOTES.md +2 -2
  170. package/server/harness/hermes/index.ts +1 -1
  171. package/server/harness/install.ts +11 -11
  172. package/server/harness/openclaw/index.ts +1 -1
  173. package/server/harness/registry.ts +7 -6
  174. package/server/harness/types.ts +4 -4
  175. package/server/onboarding/jobs.ts +1 -1
  176. package/server/operations/commands.ts +46 -0
  177. package/server/operations/files.ts +148 -0
  178. package/server/operations/server.ts +206 -0
  179. package/server/remote/agent.ts +103 -0
  180. package/server/remote/client.ts +665 -0
  181. package/server/remote/workspace.ts +34 -0
  182. package/server/scratchpad/document.ts +32 -12
  183. package/server/scratchpad/executor.ts +16 -7
  184. package/server/sessions/config.ts +8 -5
  185. package/server/sessions/pending-views.ts +16 -0
  186. package/server/sessions/view-sessions.ts +10 -12
  187. package/server/skills/locations.ts +4 -4
  188. package/server/skills/template.ts +3 -2
  189. package/server/skills/update.ts +12 -12
  190. package/server/skills/version.ts +7 -7
  191. package/server/skills/workspace.ts +13 -13
  192. package/server/web.ts +12 -10
  193. package/server/workspace-state/file.ts +2 -0
  194. package/server/workspace-state/index.ts +0 -4
  195. package/server/workspaces/api.ts +28 -0
  196. package/server/workspaces/change-harness.ts +15 -26
  197. package/server/workspaces/import.ts +4 -4
  198. package/server/workspaces/init.ts +15 -13
  199. package/server/workspaces/layout.ts +60 -66
  200. package/server/workspaces/registry.ts +43 -18
  201. package/server/workspaces/scaffold.ts +1 -0
  202. package/server/workspaces/shared.ts +74 -0
  203. package/server/workspaces/tabs.ts +6 -12
  204. package/skill/SKILL.md +24 -4
  205. package/client/api/app-ui-keys.ts +0 -6
  206. package/client/features/chat/sessions/browser-tab-state.ts +0 -43
  207. package/client/features/collab/workspace-users-menu.tsx +0 -190
  208. package/client/features/dev/cloud-avatar-upload.tsx +0 -58
  209. package/client/features/dev/cloud-page.tsx +0 -363
  210. package/client/features/workspace/browser-tab-state.ts +0 -51
  211. package/client/features/workspace/layout-save.ts +0 -13
  212. package/client/features/workspace-members/api.ts +0 -20
  213. package/client/features/workspace-members/hooks.ts +0 -127
  214. package/client/features/workspace-members/keys.ts +0 -6
  215. package/client/features/workspace-members/store.ts +0 -123
  216. package/dist/chunk-00s35r33.js +0 -546
  217. package/dist/chunk-7rz6g7g7.js +0 -1
  218. package/dist/chunk-af2jyddf.js +0 -2
  219. package/dist/chunk-cekekc3f.css +0 -1
  220. package/dist/chunk-ep5vh16c.js +0 -75
  221. package/dist/chunk-s5s1vzdw.js +0 -2
  222. package/dist/chunk-svxhxfeq.js +0 -2
  223. package/dist/chunk-t0r0bds1.js +0 -1
  224. package/dist/chunk-vp2qzc0d.js +0 -1
  225. package/dist/chunk-wz5qv1bn.js +0 -2
  226. package/lib/workspace-types.ts +0 -13
  227. package/server/workspace-state/legacy-migration.ts +0 -79
  228. /package/client/features/collab/{presence-publisher.ts → presence/presence-publisher.ts} +0 -0
  229. /package/client/features/collab/{presence-target.ts → presence/presence-target.ts} +0 -0
  230. /package/client/features/collab/{store.ts → presence/store.ts} +0 -0
@@ -0,0 +1,665 @@
1
+ import {
2
+ workspaceAddress,
3
+ workspaceApiBase,
4
+ parseRemoteWorkspaceTarget
5
+ } from '@/lib/workspace-config'
6
+ import { decodeJwt } from 'jose'
7
+ import { Mutex } from 'async-mutex'
8
+ import { lock } from 'proper-lockfile'
9
+ import { z } from 'zod'
10
+ import { chmod, mkdir, rename, rm } from 'node:fs/promises'
11
+ import { existsSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { DATA_DIR } from '../data-dir'
14
+ import { PACKAGE_ROOT } from '../version'
15
+ import {
16
+ agentCredentialsSchema,
17
+ agentAuthorization,
18
+ agentJoinBody,
19
+ createAgentKeys,
20
+ agentClientSchema,
21
+ AGENT_CLIENTS
22
+ } from './agent'
23
+
24
+ type RemoteRequestOptions = {
25
+ method?: string
26
+ body?: string | Blob | Uint8Array<ArrayBuffer>
27
+ signal?: AbortSignal
28
+ contentType?: string
29
+ }
30
+
31
+ export class CloudSignInRequired extends Error {}
32
+
33
+ const humanCredentialsSchema = z.object({
34
+ accessToken: z.string().min(1),
35
+ refreshToken: z.string().min(1),
36
+ url: z.string().min(1),
37
+ clientId: z.string().min(1)
38
+ })
39
+ const credentialsSchema = z.union([agentCredentialsSchema, humanCredentialsSchema])
40
+ type Credentials = z.infer<typeof credentialsSchema>
41
+ const isAgent = (value: Credentials): value is z.infer<typeof agentCredentialsSchema> =>
42
+ 'kind' in value && value.kind === 'agent'
43
+ const tokensSchema = z.object({
44
+ access_token: z.string().min(1),
45
+ refresh_token: z.string().min(1)
46
+ })
47
+ const deviceSchema = z.object({
48
+ device_code: z.string().min(1),
49
+ user_code: z.string().min(1),
50
+ verification_uri_complete: z.url(),
51
+ expires_in: z.number().positive().max(3600),
52
+ interval: z.number().positive().max(60).default(5)
53
+ })
54
+ const humanProfileSchema = z
55
+ .object({ id: z.string(), name: z.string(), email: z.string() })
56
+ .passthrough()
57
+ const agentProfileSchema = z.object({
58
+ id: z.string(),
59
+ type: z.literal('agent'),
60
+ name: z.string(),
61
+ client: agentClientSchema
62
+ })
63
+ const profileSchema = z.union([agentProfileSchema, humanProfileSchema])
64
+ const workspacesSchema = z.object({
65
+ workspaces: z.array(z.object({ id: z.string(), owner: humanProfileSchema }))
66
+ })
67
+ const remoteSchema = z.object({
68
+ url: z.string().min(1).optional(),
69
+ clientId: z.string().min(1).optional(),
70
+ managed: z.boolean().optional()
71
+ })
72
+ const configSchema = z.object({ remote: remoteSchema.optional() })
73
+ type RemoteConfig = { url: string; clientId: string; managed: boolean }
74
+ export type Profile = z.infer<typeof profileSchema>
75
+ export type SharedWorkspace = { id: string; owner: z.infer<typeof humanProfileSchema> }
76
+ export type RemoteStatus = { me: Profile; workspaces: SharedWorkspace[] }
77
+ export function resolveRemoteConfig(
78
+ remote: { url?: string; clientId?: string; managed?: boolean },
79
+ development: boolean,
80
+ directory = DATA_DIR
81
+ ): RemoteConfig {
82
+ if (development && !remote.url) {
83
+ throw new Error(
84
+ `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
+ )
86
+ }
87
+ const url = new URL(remote.url ?? 'https://run.moi.computer/cloud')
88
+ if (
89
+ url.protocol !== 'https:' &&
90
+ !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
91
+ ) {
92
+ throw new Error('Remote URL must use HTTPS (HTTP is allowed for localhost)')
93
+ }
94
+ if (url.username || url.password || url.search || url.hash) {
95
+ throw new Error('Cloud URL must not contain credentials, a query, or a fragment')
96
+ }
97
+ return {
98
+ url: url.href.replace(/\/+$/, ''),
99
+ clientId: remote.clientId ?? 'moi-cli',
100
+ managed: remote.managed === true
101
+ }
102
+ }
103
+
104
+ /** Each client owns one data directory. Tests use an isolated directory. */
105
+ export function createRemoteClient(directory: string) {
106
+ const authFile = join(directory, 'remote-auth.json')
107
+ const mutex = new Mutex()
108
+ const pendingFile = join(directory, 'remote-agent-pending.json')
109
+
110
+ async function json<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
111
+ // A parser error can quote the response body, which may contain tokens.
112
+ const parsed = schema.safeParse(await response.json().catch(() => undefined))
113
+ if (!parsed.success) throw new Error('Cloud returned an invalid response')
114
+ return parsed.data
115
+ }
116
+
117
+ async function remoteConfig(): Promise<RemoteConfig> {
118
+ let raw: unknown = {}
119
+ try {
120
+ raw = await Bun.file(join(directory, 'config.json')).json()
121
+ } catch (error) {
122
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
123
+ throw new Error('Could not read Moi config.json')
124
+ }
125
+ const parsed = configSchema.safeParse(raw)
126
+ if (!parsed.success) throw new Error('Invalid remote settings in config.json')
127
+ const development =
128
+ process.env.NODE_ENV === 'development' || existsSync(join(PACKAGE_ROOT, '.git'))
129
+ return resolveRemoteConfig(parsed.data.remote ?? {}, development, directory)
130
+ }
131
+
132
+ async function post(config: RemoteConfig, path: string, values: Record<string, string>) {
133
+ return fetch(`${config.url}/api/auth${path}`, {
134
+ method: 'POST',
135
+ redirect: 'error',
136
+ signal: AbortSignal.timeout(30_000),
137
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
138
+ body: new URLSearchParams({ client_id: config.clientId, ...values })
139
+ })
140
+ }
141
+
142
+ async function read(config: RemoteConfig): Promise<Credentials> {
143
+ let value: unknown
144
+ try {
145
+ value = await Bun.file(authFile).json()
146
+ } catch (error) {
147
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
148
+ throw new CloudSignInRequired('Sign in with moi remote login to see shared workspaces')
149
+ throw new Error('Could not read remote credentials — run moi remote login')
150
+ }
151
+ const parsed = credentialsSchema.safeParse(value)
152
+ 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
+ return parsed.data
159
+ }
160
+
161
+ async function writePrivate(path: string, value: unknown, assertLock: () => void) {
162
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`
163
+ try {
164
+ await Bun.write(temporary, JSON.stringify(value) + '\n', { mode: 0o600 })
165
+ await chmod(temporary, 0o600)
166
+ assertLock()
167
+ await rename(temporary, path)
168
+ } finally {
169
+ await rm(temporary, { force: true })
170
+ }
171
+ }
172
+
173
+ async function save(
174
+ response: Response,
175
+ config: RemoteConfig,
176
+ assertLock: () => void
177
+ ): Promise<Credentials> {
178
+ if (!response.ok)
179
+ throw new Error(`Could not refresh login (${response.status}) — run moi remote login`)
180
+ const value = await json(response, tokensSchema)
181
+ const pair = {
182
+ accessToken: value.access_token,
183
+ refreshToken: value.refresh_token,
184
+ url: config.url,
185
+ clientId: config.clientId
186
+ }
187
+ await writePrivate(authFile, pair, assertLock)
188
+ return pair
189
+ }
190
+
191
+ // Only mutations take a cross-process lock. Heartbeats let later commands
192
+ // recover a lock abandoned by a crash; the in-process mutex avoids retry delays.
193
+ async function locked<T>(action: (assertLock: () => void) => Promise<T>): Promise<T> {
194
+ return mutex.runExclusive(async () => {
195
+ await mkdir(directory, { recursive: true, mode: 0o700 })
196
+ let compromised: Error | undefined
197
+ const release = await lock(directory, {
198
+ lockfilePath: `${authFile}.lock`,
199
+ stale: 60_000,
200
+ update: 10_000,
201
+ retries: { retries: 80, factor: 1.5, minTimeout: 50, maxTimeout: 1000 },
202
+ onCompromised: error => {
203
+ compromised = error
204
+ }
205
+ })
206
+ const assertLock = () => {
207
+ if (compromised) throw new Error('Remote credentials lock was lost — retry the command')
208
+ }
209
+ try {
210
+ return await action(assertLock)
211
+ } finally {
212
+ if (!compromised) await release()
213
+ }
214
+ })
215
+ }
216
+
217
+ async function login(
218
+ announce: (url: string, code: string) => void | Promise<void>
219
+ ): Promise<void> {
220
+ const config = await remoteConfig()
221
+ if (config.managed) throw new Error('Cloud manages sign-in on this machine')
222
+ if ((await Bun.file(authFile).exists()) && isAgent(await read(config)))
223
+ throw new Error('Signed in as an agent — use a separate Moi data directory for human login')
224
+ if (await Bun.file(pendingFile).exists())
225
+ throw new Error('An agent join is pending — retry that invitation first')
226
+ const response = await post(config, '/device/code', {
227
+ scope: 'profile:read workspaces:read workspaces:access offline_access',
228
+ resource: 'urn:moi:cloud'
229
+ })
230
+ if (!response.ok) throw new Error(`Could not start login (${response.status})`)
231
+ const device = await json(response, deviceSchema)
232
+ const verification = new URL(device.verification_uri_complete)
233
+ if (
234
+ verification.origin !== new URL(config.url).origin ||
235
+ verification.username ||
236
+ verification.password
237
+ )
238
+ throw new Error('Cloud returned a login URL on a different origin')
239
+ await announce(verification.href, device.user_code)
240
+ let interval = device.interval
241
+ const deadline = Date.now() + device.expires_in * 1000
242
+ while (Date.now() < deadline) {
243
+ await Bun.sleep(interval * 1000)
244
+ if (Date.now() >= deadline) break
245
+ const token = await post(config, '/oauth2/token', {
246
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
247
+ device_code: device.device_code
248
+ })
249
+ if (token.ok) {
250
+ await locked(async assertLock => {
251
+ if ((await Bun.file(authFile).exists()) && isAgent(await read(config)))
252
+ throw new Error(
253
+ 'An agent signed in while browser login was pending; agent credentials kept'
254
+ )
255
+ if (await Bun.file(pendingFile).exists())
256
+ throw new Error('An agent join is pending; its keys were kept')
257
+ return save(token, config, assertLock)
258
+ })
259
+ return
260
+ }
261
+ if (token.status === 429) {
262
+ interval = Math.min(
263
+ 60,
264
+ Math.max(interval + 5, Number(token.headers.get('retry-after')) || 0)
265
+ )
266
+ continue
267
+ }
268
+ const result = await json(token, z.object({ error: z.string() }))
269
+ if (result.error === 'slow_down') interval = Math.min(60, interval + 5)
270
+ else if (result.error !== 'authorization_pending')
271
+ throw new Error(`Login failed (${token.status}) — run moi remote login again`)
272
+ }
273
+ throw new Error('Login expired — run moi remote login again')
274
+ }
275
+
276
+ async function logout(confirmed = false): Promise<void> {
277
+ const config = await remoteConfig()
278
+ if (config.managed) throw new Error('Cloud manages sign-in on this machine')
279
+ await locked(async assertLock => {
280
+ if (!(await Bun.file(authFile).exists())) {
281
+ if (await Bun.file(pendingFile).exists())
282
+ throw new Error(
283
+ 'An agent join is unfinished — retry the same invitation before logging out'
284
+ )
285
+ return
286
+ }
287
+ const pair = await read(config)
288
+ if (isAgent(pair)) {
289
+ if (!confirmed)
290
+ throw new Error(
291
+ 'Logging out permanently revokes this agent login and deletes its local keys. It cannot be restored. Run moi remote logout --yes to confirm'
292
+ )
293
+ await cloudJson(config, pair, '/agents/logout', {}, z.object({ success: z.boolean() }))
294
+ assertLock()
295
+ await rm(authFile, { force: true })
296
+ await rm(pendingFile, { force: true })
297
+ return
298
+ }
299
+ const response = await post(config, '/oauth2/revoke', {
300
+ token_type_hint: 'refresh_token',
301
+ token: pair.refreshToken
302
+ })
303
+ if (!response.ok)
304
+ throw new Error(`Logout failed (${response.status}); credentials kept so you can retry`)
305
+ assertLock()
306
+ await rm(authFile, { force: true })
307
+ })
308
+ }
309
+
310
+ function fresh(pair: z.infer<typeof humanCredentialsSchema>): boolean {
311
+ try {
312
+ return (decodeJwt(pair.accessToken).exp ?? 0) * 1000 > Date.now() + 30_000
313
+ } catch {
314
+ return false
315
+ }
316
+ }
317
+
318
+ async function access(config: RemoteConfig): Promise<Credentials> {
319
+ const pair = await read(config)
320
+ if (isAgent(pair) || fresh(pair)) return pair
321
+ return locked(async assertLock => {
322
+ const current = await read(config)
323
+ if (isAgent(current) || fresh(current)) return current
324
+ return save(
325
+ await post(config, '/oauth2/token', {
326
+ grant_type: 'refresh_token',
327
+ refresh_token: current.refreshToken
328
+ }),
329
+ config,
330
+ assertLock
331
+ )
332
+ })
333
+ }
334
+
335
+ async function cloudJson<T>(
336
+ config: RemoteConfig,
337
+ pair: Credentials,
338
+ 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, {
351
+ method,
352
+ headers: { authorization, 'content-type': 'application/json' },
353
+ body: body === undefined ? undefined : raw,
354
+ redirect: 'error',
355
+ signal: AbortSignal.timeout(30_000)
356
+ })
357
+ if (response.status === 401)
358
+ throw new Error(
359
+ isAgent(pair) ? 'Agent login is no longer valid' : 'Sign-in expired — run moi remote login'
360
+ )
361
+ if (!response.ok) throw new Error(`Cloud request failed (${response.status})`)
362
+ return json(response, schema)
363
+ }
364
+ async function request<T>(
365
+ path: string,
366
+ body: unknown | undefined,
367
+ schema: z.ZodType<T>,
368
+ method?: string
369
+ ) {
370
+ const config = await remoteConfig()
371
+ return cloudJson(config, await access(config), path, body, schema, method)
372
+ }
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)
380
+ }
381
+ const invitationSchema = z.object({
382
+ id: z.string(),
383
+ workspaceId: z.string(),
384
+ workspaceName: z.string(),
385
+ inviter: humanProfileSchema,
386
+ expiresAt: z.string()
387
+ })
388
+ async function invitations() {
389
+ return (
390
+ await request(
391
+ '/workspaces/invitations',
392
+ undefined,
393
+ z.object({ invitations: z.array(invitationSchema) })
394
+ )
395
+ ).invitations
396
+ }
397
+ function invitation(value: string, config: RemoteConfig) {
398
+ if (!value.includes('://')) {
399
+ if (!/^[A-Za-z0-9_-]{1,240}$/.test(value)) throw new Error('Invalid invitation ID')
400
+ return { id: value, token: undefined, agent: false }
401
+ }
402
+ const url = new URL(value)
403
+ const root = new URL(config.url)
404
+ const prefix = root.pathname.replace(/\/$/, '')
405
+ const match = new RegExp(
406
+ `^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/(agent-invite|invite)/([A-Za-z0-9_-]{1,240})$`
407
+ ).exec(url.pathname)
408
+ const token = url.searchParams.get('token')
409
+ if (
410
+ url.origin !== root.origin ||
411
+ url.username ||
412
+ url.password ||
413
+ !match ||
414
+ !token ||
415
+ !/^[A-Za-z0-9_-]{43}$/.test(token)
416
+ )
417
+ throw new Error('Use an invitation URL from your configured Cloud URL')
418
+ return { id: match[2]!, token, agent: match[1] === 'agent-invite' }
419
+ }
420
+ const accepted = z.object({
421
+ success: z.literal(true),
422
+ remote: z
423
+ .object({ user_id: z.string(), workspace_id: z.string() })
424
+ .transform(parseRemoteWorkspaceTarget),
425
+ membershipId: z.string()
426
+ })
427
+ async function accept(value: string, name?: string, client?: string) {
428
+ if (client !== undefined && !agentClientSchema.safeParse(client).success)
429
+ throw new Error(`Invalid client — choose ${AGENT_CLIENTS.join(', ')}`)
430
+ const config = await remoteConfig(),
431
+ target = invitation(value, config)
432
+ if (await Bun.file(authFile).exists()) {
433
+ const saved = await read(config)
434
+ if (!isAgent(saved) && (target.agent || name !== undefined || client !== undefined))
435
+ throw new Error(
436
+ 'Already signed in as a human — use a separate Moi data directory for this agent'
437
+ )
438
+ return cloudJson(
439
+ config,
440
+ await access(config),
441
+ `/invitations/${encodeURIComponent(target.id)}/accept`,
442
+ target.token ? { token: target.token } : {},
443
+ accepted
444
+ )
445
+ }
446
+ if (!target.agent)
447
+ throw new CloudSignInRequired(
448
+ 'Sign in with moi remote login before accepting a human invitation'
449
+ )
450
+ if (config.managed) throw new Error('Cloud manages sign-in on this machine')
451
+ return locked(async assertLock => {
452
+ if (await Bun.file(authFile).exists()) {
453
+ const pair = await read(config)
454
+ if (!isAgent(pair))
455
+ throw new Error(
456
+ 'Already signed in as a human — use a separate Moi data directory for this agent'
457
+ )
458
+ return cloudJson(
459
+ config,
460
+ pair,
461
+ `/invitations/${encodeURIComponent(target.id)}/accept`,
462
+ target.token ? { token: target.token } : {},
463
+ accepted
464
+ )
465
+ }
466
+ if (!target.token) throw new Error('First agent acceptance requires an invitation URL')
467
+ const fingerprint = new Bun.CryptoHasher('sha256').update(target.token).digest('hex')
468
+ const pendingSchema = z.object({
469
+ fingerprint: z.string(),
470
+ name: z.string(),
471
+ client: agentClientSchema,
472
+ keys: agentCredentialsSchema
473
+ })
474
+ let pending: z.infer<typeof pendingSchema>
475
+ if (await Bun.file(pendingFile).exists()) {
476
+ const saved = pendingSchema.safeParse(
477
+ await Bun.file(pendingFile)
478
+ .json()
479
+ .catch(() => undefined)
480
+ )
481
+ if (!saved.success)
482
+ throw new Error('Could not read pending agent keys; credentials were kept')
483
+ pending = saved.data
484
+ if (
485
+ pending.fingerprint !== fingerprint ||
486
+ pending.keys.url !== config.url ||
487
+ pending.keys.clientId !== config.clientId
488
+ )
489
+ throw new Error(
490
+ 'Retry the original pending agent invitation before switching accounts or clouds'
491
+ )
492
+ } else {
493
+ if (!name?.trim() || name.trim().length > 80 || !client)
494
+ throw new Error('First agent acceptance requires --name and --client')
495
+ pending = {
496
+ fingerprint,
497
+ name: name.trim(),
498
+ client: agentClientSchema.parse(client),
499
+ keys: await createAgentKeys(config)
500
+ }
501
+ await writePrivate(pendingFile, pending, assertLock)
502
+ }
503
+ const body = await agentJoinBody(pending.keys, target.token, pending.name, pending.client)
504
+ const response = await fetch(`${config.url}/api/agents/join`, {
505
+ method: 'POST',
506
+ headers: { 'content-type': 'application/json' },
507
+ body: JSON.stringify(body),
508
+ redirect: 'error',
509
+ signal: AbortSignal.timeout(30_000)
510
+ })
511
+ if (!response.ok)
512
+ throw new Error(
513
+ `Agent acceptance failed (${response.status}); keys kept so you can retry the same invitation`
514
+ )
515
+ const joined = await json(
516
+ response,
517
+ accepted.extend({ agentId: z.string(), hostId: z.string() })
518
+ )
519
+ if (joined.agentId !== pending.keys.agentId || joined.hostId !== pending.keys.hostId)
520
+ throw new Error('Cloud returned an unexpected agent identity')
521
+ await writePrivate(authFile, pending.keys, assertLock)
522
+ await rm(pendingFile, { force: true })
523
+ return joined
524
+ })
525
+ }
526
+ 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')
531
+ }
532
+ async function leave(ownerId: string, workspaceId: string) {
533
+ parseRemoteWorkspaceTarget({ user_id: ownerId, workspace_id: workspaceId })
534
+ return request(
535
+ `/workspaces/${workspaceAddress(workspaceId, ownerId)}/leave`,
536
+ {},
537
+ z.object({ success: z.literal(true) })
538
+ )
539
+ }
540
+
541
+ /** Read accepted shared workspaces using this machine's configured cloud login.
542
+ * Refreshes credentials automatically; requires no browser or running Moi server.
543
+ */
544
+ 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
+ )
564
+ }
565
+
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
+ })
617
+ if (!response.ok) {
618
+ await response.body?.cancel()
619
+ throw new Error(
620
+ response.status === 401
621
+ ? 'Cloud login expired or revoked — run moi remote login'
622
+ : `Remote operation failed (${response.status})`
623
+ )
624
+ }
625
+ return response
626
+ }
627
+
628
+ async function remoteStatus(): Promise<RemoteStatus> {
629
+ const config = await remoteConfig()
630
+ const pair = await access(config)
631
+ const [me, shared] = await Promise.all([
632
+ authenticatedGet(config, pair, '/me', profileSchema),
633
+ authenticatedGet(config, pair, '/workspaces/shared', workspacesSchema)
634
+ ])
635
+ return { me, workspaces: shared.workspaces }
636
+ }
637
+
638
+ return {
639
+ remoteConfig,
640
+ login,
641
+ logout,
642
+ fetchSharedWorkspaces,
643
+ workspaceRequest,
644
+ remoteStatus,
645
+ operation,
646
+ invitations,
647
+ accept,
648
+ renameAgent,
649
+ leave
650
+ }
651
+ }
652
+
653
+ export const {
654
+ remoteConfig,
655
+ login,
656
+ logout,
657
+ fetchSharedWorkspaces,
658
+ workspaceRequest,
659
+ remoteStatus,
660
+ operation,
661
+ invitations,
662
+ accept,
663
+ renameAgent,
664
+ leave
665
+ } = createRemoteClient(DATA_DIR)
@@ -0,0 +1,34 @@
1
+ import { resolve } from 'node:path'
2
+ import { fetchSharedWorkspaces } from './client'
3
+ import { parseRemoteWorkspaceTarget, type RemoteWorkspaceTarget } from '@/lib/workspace-config'
4
+ import { loadWorkspaceFileConfig } from '../workspaces/layout'
5
+ import { registerRemoteWorkspaceReference } from '../workspaces/shared'
6
+ import { listWorkspaces } from '../workspaces/registry'
7
+ import { resolveWorkspaceRoot } from '../skills/version'
8
+
9
+ export async function currentRemoteWorkspace(path = process.cwd()) {
10
+ const root = await resolveWorkspaceRoot(resolve(path))
11
+ const config = await loadWorkspaceFileConfig(root)
12
+ return config.remote ? { path: root, ...config.remote } : undefined
13
+ }
14
+ export async function initializeRemoteWorkspace(path: string, target: RemoteWorkspaceTarget) {
15
+ target = parseRemoteWorkspaceTarget(target)
16
+ const shares = await fetchSharedWorkspaces()
17
+ if (!shares.some(w => w.id === target.workspace_id && w.owner.id === target.user_id))
18
+ throw new Error('This workspace is not shared with this account')
19
+ // Initialization creates a workspace at the requested folder. An ancestor's
20
+ // registration must not redirect this write into a different directory.
21
+ const root = resolve(path)
22
+ const existing = (await listWorkspaces()).find(
23
+ workspace =>
24
+ workspace.remote?.user_id === target.user_id &&
25
+ workspace.remote.workspace_id === target.workspace_id &&
26
+ resolve(workspace.path) !== root
27
+ )
28
+ if (existing)
29
+ throw new Error(
30
+ `This workspace is already initialized at ${existing.path} — remove that registration in Moi first`
31
+ )
32
+ const entry = await registerRemoteWorkspaceReference(root, target)
33
+ return { path: root, id: entry.id, ...target }
34
+ }