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.
- package/client/api/app-config.ts +12 -1
- package/client/api/http.ts +11 -1
- package/client/app/app-router.tsx +3 -2
- package/client/app/routes/home-route.tsx +1 -1
- package/client/app/routes/workspace-registration.tsx +68 -0
- package/client/app/routes/workspace-route.tsx +33 -6
- package/client/app/shell/sidebar-layout.tsx +10 -5
- package/client/components/shared/workspace-icon.tsx +8 -17
- package/client/features/account/account-test-utils.tsx +15 -9
- package/client/features/account/api.ts +6 -6
- package/client/features/account/profile-actions.ts +5 -7
- package/client/features/app-settings/settings-page.tsx +2 -1
- package/client/features/applets/api.ts +6 -6
- package/client/features/applets/applet-cache.ts +6 -5
- package/client/features/applets/applet-log.ts +2 -1
- package/client/features/applets/applet-runtime.ts +2 -1
- package/client/features/applets/use-applet.ts +73 -18
- package/client/features/applets/widget-shell.tsx +4 -2
- package/client/features/chat/applet-chat-intents.ts +5 -13
- package/client/features/chat/chat-popup.tsx +8 -4
- package/client/features/chat/chat-send.ts +2 -2
- package/client/features/chat/composer/model-order.ts +4 -4
- package/client/features/chat/composer/model-picker.tsx +12 -10
- package/client/features/chat/composer/use-workspace-composer-state.tsx +1 -1
- package/client/features/chat/sessions/api.ts +11 -28
- package/client/features/chat/sessions/use-selected-session.ts +14 -109
- package/client/features/chat/use-chat.ts +8 -12
- package/client/features/collab/members/api.ts +4 -10
- package/client/features/collab/members/hooks.ts +32 -38
- package/client/features/collab/members/store.ts +96 -71
- package/client/features/collab/members/types.ts +5 -3
- package/client/features/collab/presence/client.ts +2 -3
- package/client/features/collab/presence/hooks.tsx +1 -1
- package/client/features/collab/proxy-user.ts +1 -3
- package/client/features/collab/sharing/workspace-members.tsx +0 -8
- package/client/features/dev/chat-states-page.tsx +3 -1
- package/client/features/dev/harness-debug-page.tsx +7 -7
- package/client/features/dev/workspace-setup-mocks.ts +1 -1
- package/client/features/dev/workspace-setup-preview.tsx +6 -4
- package/client/features/harness/api.ts +13 -10
- package/client/features/harness/harness-login-panel.tsx +9 -5
- package/client/features/harness/harness-presentation.ts +4 -4
- package/client/features/harness/harness-selector.tsx +13 -13
- package/client/features/harness/use-harness-login.ts +5 -5
- package/client/features/home/api.ts +38 -2
- package/client/features/home/home-page.tsx +43 -13
- package/client/features/home/shared-workspaces.tsx +70 -0
- package/client/features/home/workspace-invitations.tsx +101 -0
- package/client/features/identity/host-api.ts +3 -2
- package/client/features/identity/store.ts +1 -7
- package/client/features/onboarding/agent-setup-step.tsx +8 -8
- package/client/features/onboarding/onboarding-page.tsx +3 -2
- package/client/features/onboarding/workspace-setup-step.tsx +1 -1
- package/client/features/overview/api.ts +3 -5
- package/client/features/overview/default/registry.tsx +1 -1
- package/client/features/overview/default/views-widget.tsx +2 -2
- package/client/features/overview/hidden-panel.tsx +7 -5
- package/client/features/overview/overview.tsx +18 -16
- package/client/features/overview/workspace-name.tsx +2 -2
- package/client/features/scratchpad/scratchpad.tsx +9 -7
- package/client/features/scratchpad/use-scratchpad-snapshot.tsx +13 -5
- package/client/features/views/api.ts +66 -23
- package/client/features/views/use-view-actions.ts +10 -41
- package/client/features/views/view-manager.tsx +1 -1
- package/client/features/views/view-submission.ts +2 -21
- package/client/features/workspace/add/api.ts +5 -4
- package/client/features/workspace/add/create-workspace-dialog.tsx +12 -9
- package/client/features/workspace/add/import-workspace-dialog.tsx +7 -7
- package/client/features/workspace/add/use-workspace-import.ts +10 -10
- package/client/features/workspace/add/workspace-agent-options.ts +21 -20
- package/client/features/workspace/add/workspace-agent-selector.tsx +11 -11
- package/client/features/workspace/api.ts +60 -13
- package/client/features/workspace/harness-transition.ts +7 -13
- package/client/features/workspace/remote.ts +25 -0
- package/client/features/workspace/settings/api.ts +7 -12
- package/client/features/workspace/settings/connectors-settings.tsx +3 -3
- package/client/features/workspace/settings/general-settings.tsx +8 -8
- package/client/features/workspace/setup/workspace-login-state.tsx +4 -4
- package/client/features/workspace/setup/workspace-recovery-states.tsx +43 -14
- package/client/features/workspace/setup/workspace-setup.tsx +6 -6
- package/client/features/workspace/tab-resolution.ts +1 -8
- package/client/features/workspace/use-workspace-navigation.ts +11 -7
- package/client/features/workspace/workspace-content.tsx +24 -31
- package/client/features/workspace/workspace-frame.tsx +13 -26
- package/client/features/workspace/workspace-layout-context.tsx +45 -12
- package/client/features/workspace/workspace-menu.tsx +2 -2
- package/client/features/workspace/workspace-pane.tsx +22 -0
- package/client/features/workspace/workspace-pending-screen.tsx +1 -1
- package/client/features/workspace/workspace-preferences.ts +91 -0
- package/client/features/workspace/workspace-presentation.tsx +12 -16
- package/client/features/workspace/workspace-screen.tsx +2 -2
- package/client/features/workspace/workspace-state.ts +42 -16
- package/client/features/workspace/workspace-tabs.tsx +1 -1
- package/client/features/workspace/workspace-test-utils.ts +23 -0
- package/client/runtime/use-workspace-events.ts +14 -0
- package/client/runtime/workspace-events.ts +9 -9
- package/client/store/ui.ts +24 -9
- package/client/store/workspace-session.ts +30 -0
- package/dist/chunk-0h4zypgf.js +1 -0
- package/dist/chunk-1tksq43z.js +72 -0
- package/dist/chunk-6gxf0xr8.js +5 -0
- package/dist/chunk-a865c7x4.js +1 -0
- package/dist/chunk-f44cs6mw.js +2 -0
- package/dist/chunk-h3qag4a6.js +2 -0
- package/dist/chunk-kffcah9w.css +1 -0
- package/dist/chunk-q2tpy0h7.js +2 -0
- package/dist/chunk-r95acex1.js +546 -0
- package/dist/chunk-w5h9grdr.js +1 -0
- package/dist/{chunk-th91xfnp.js → chunk-xj1pjhng.js} +1 -1
- package/dist/index.html +1 -1
- package/lib/harness-instructions.ts +4 -4
- package/lib/harness-types.ts +13 -0
- package/lib/moi-context.ts +19 -5
- package/lib/types.ts +38 -54
- package/lib/workspace-config.ts +48 -0
- package/lib/workspace-layout.ts +5 -24
- package/package.json +5 -2
- package/server/AGENTS.md +1 -1
- package/server/README.md +36 -31
- package/server/api/harnesses.ts +5 -5
- package/server/api/index.ts +268 -162
- package/server/applets/index.ts +15 -9
- package/server/applets/views.ts +2 -17
- package/server/applets/widgets.ts +3 -2
- package/server/cli/commands/config.ts +8 -20
- package/server/cli/commands/hermes.ts +2 -2
- package/server/cli/commands/init.ts +102 -54
- package/server/cli/commands/openclaw.ts +2 -2
- package/server/cli/commands/refresh.ts +10 -1
- package/server/cli/commands/remote.ts +330 -0
- package/server/cli/commands/skill.ts +4 -4
- package/server/cli/commands/tabs.ts +5 -12
- package/server/cli/control.ts +35 -4
- package/server/cli/index.ts +10 -6
- package/server/cli/remote-command.ts +77 -0
- package/server/cli/remote-control.ts +73 -0
- package/server/cli/remote-operations.ts +247 -0
- package/server/collab/config.ts +3 -3
- package/server/collab/skill/index.ts +3 -3
- package/server/control.ts +47 -12
- package/server/harness/acp/session.ts +4 -4
- package/server/harness/auth.ts +26 -31
- package/server/harness/claude-code/index.ts +1 -1
- package/server/harness/codex/discovery.ts +1 -1
- package/server/harness/codex/session.ts +1 -1
- package/server/harness/detect.ts +14 -19
- package/server/harness/executable.ts +10 -10
- package/server/harness/hermes/NOTES.md +2 -2
- package/server/harness/hermes/index.ts +1 -1
- package/server/harness/install.ts +11 -11
- package/server/harness/openclaw/index.ts +1 -1
- package/server/harness/registry.ts +7 -6
- package/server/harness/types.ts +4 -4
- package/server/onboarding/jobs.ts +2 -2
- package/server/operations/commands.ts +46 -0
- package/server/operations/files.ts +148 -0
- package/server/operations/server.ts +206 -0
- package/server/remote/agent.ts +103 -0
- package/server/remote/broker-client.ts +76 -0
- package/server/remote/broker.ts +81 -0
- package/server/remote/client.ts +725 -0
- package/server/remote/errors.ts +2 -0
- package/server/remote/routes.ts +121 -0
- package/server/remote/workspace.ts +34 -0
- package/server/scratchpad/document.ts +33 -12
- package/server/scratchpad/executor.ts +16 -7
- package/server/sessions/config.ts +8 -5
- package/server/sessions/pending-views.ts +17 -0
- package/server/sessions/send-message.ts +102 -0
- package/server/sessions/view-sessions.ts +9 -101
- package/server/skills/locations.ts +4 -4
- package/server/skills/update.ts +11 -11
- package/server/skills/version.ts +7 -7
- package/server/skills/workspace.ts +13 -11
- package/server/web.ts +13 -9
- package/server/workspace-state/file.ts +4 -0
- package/server/workspace-state/index.ts +0 -4
- package/server/workspaces/api.ts +24 -0
- package/server/workspaces/change-harness.ts +15 -26
- package/server/workspaces/import.ts +4 -4
- package/server/workspaces/init.ts +15 -13
- package/server/workspaces/layout.ts +60 -66
- package/server/workspaces/registry.ts +43 -18
- package/server/workspaces/shared.ts +74 -0
- package/server/workspaces/tabs.ts +5 -12
- package/skill/SKILL.md +80 -19
- package/skill/references/SCRATCHPAD.md +4 -0
- package/skill/references/UI-COMPONENTS.md +1 -1
- package/client/api/app-ui-keys.ts +0 -6
- package/client/features/chat/sessions/browser-tab-state.ts +0 -43
- package/client/features/collab/members/keys.ts +0 -6
- package/client/features/workspace/browser-tab-state.ts +0 -51
- package/client/features/workspace/layout-save.ts +0 -13
- package/dist/chunk-3smkkcfw.js +0 -546
- package/dist/chunk-47h9c2qy.js +0 -2
- package/dist/chunk-8qed2gqp.js +0 -75
- package/dist/chunk-8zy3vesm.js +0 -1
- package/dist/chunk-a47zy276.js +0 -2
- package/dist/chunk-g4c1nte9.css +0 -1
- package/dist/chunk-kcactdr4.js +0 -2
- package/dist/chunk-m8bhx6tw.js +0 -1
- package/dist/chunk-pf19zcrn.js +0 -2
- package/dist/chunk-ygzxah0e.js +0 -1
- package/lib/workspace-types.ts +0 -13
- package/server/workspace-state/legacy-migration.ts +0 -79
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { chmod, rm } from 'node:fs/promises'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { getWorkspace } from '../workspaces/registry'
|
|
4
|
+
import { applyUnifiedPatch, OperationError, workspaceFile, writeWorkspaceFile } from './files'
|
|
5
|
+
import { spawnWorkspaceCommand } from './commands'
|
|
6
|
+
|
|
7
|
+
const executionId = z.string().uuid()
|
|
8
|
+
const execSchema = z.union([
|
|
9
|
+
z.object({ command: z.string().min(1).max(100_000), id: executionId.optional() }).strict(),
|
|
10
|
+
z.object({ cancel: executionId }).strict()
|
|
11
|
+
])
|
|
12
|
+
const commandSchema = z
|
|
13
|
+
.object({ command: z.string(), args: z.array(z.string().max(100_000)).max(500).default([]) })
|
|
14
|
+
.strict()
|
|
15
|
+
const patchSchema = z
|
|
16
|
+
.object({
|
|
17
|
+
patch: z
|
|
18
|
+
.string()
|
|
19
|
+
.min(1)
|
|
20
|
+
.max(4 * 1024 * 1024)
|
|
21
|
+
})
|
|
22
|
+
.strict()
|
|
23
|
+
const processes = new Set<Bun.Subprocess>()
|
|
24
|
+
function stopChild(child: Bun.Subprocess) {
|
|
25
|
+
try {
|
|
26
|
+
process.kill(-child.pid, 'SIGKILL')
|
|
27
|
+
} catch {
|
|
28
|
+
child.kill('SIGKILL')
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async function readOutput(source: ReadableStream<Uint8Array>, child: Bun.Subprocess) {
|
|
32
|
+
const chunks: Uint8Array[] = []
|
|
33
|
+
let size = 0
|
|
34
|
+
for await (const chunk of source) {
|
|
35
|
+
size += chunk.byteLength
|
|
36
|
+
if (size > 8 * 1024 * 1024) {
|
|
37
|
+
stopChild(child)
|
|
38
|
+
throw new OperationError('Command output exceeded 8 MiB; use exec for streaming', 413)
|
|
39
|
+
}
|
|
40
|
+
chunks.push(chunk)
|
|
41
|
+
}
|
|
42
|
+
return new TextDecoder().decode(Buffer.concat(chunks))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function track(child: Bun.Subprocess, signal: AbortSignal) {
|
|
46
|
+
processes.add(child)
|
|
47
|
+
const stop = () => stopChild(child)
|
|
48
|
+
signal.addEventListener('abort', stop, { once: true })
|
|
49
|
+
if (signal.aborted) stop()
|
|
50
|
+
void child.exited.finally(() => {
|
|
51
|
+
processes.delete(child)
|
|
52
|
+
signal.removeEventListener('abort', stop)
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
export function stopOperations() {
|
|
56
|
+
for (const child of processes) stopChild(child)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Distinct listener: these handlers are never mounted on the browser API.
|
|
60
|
+
export function createOperationsHandler(resolveWorkspace = getWorkspace) {
|
|
61
|
+
const executions = new Map<string, Bun.Subprocess>()
|
|
62
|
+
const cancelled = new Map<string, number>()
|
|
63
|
+
return async (request: Request): Promise<Response> => {
|
|
64
|
+
try {
|
|
65
|
+
const url = new URL(request.url)
|
|
66
|
+
const match = /^\/workspaces\/([A-Za-z0-9_-]+)\/(files\/(.+)|exec|commands)$/.exec(
|
|
67
|
+
url.pathname
|
|
68
|
+
)
|
|
69
|
+
if (!match) return Response.json({ error: 'Not found' }, { status: 404 })
|
|
70
|
+
const workspace = await resolveWorkspace(match[1]!)
|
|
71
|
+
if (!workspace || workspace.remote)
|
|
72
|
+
return Response.json({ error: 'Workspace unavailable' }, { status: 404 })
|
|
73
|
+
const root = workspace.path
|
|
74
|
+
if (match[3]) {
|
|
75
|
+
const path = decodeURIComponent(match[3])
|
|
76
|
+
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
77
|
+
const file = Bun.file(await workspaceFile(root, path))
|
|
78
|
+
return new Response(request.method === 'HEAD' ? null : file, {
|
|
79
|
+
headers: {
|
|
80
|
+
'content-type': file.type,
|
|
81
|
+
'content-length': String(file.size),
|
|
82
|
+
'cache-control': 'no-store'
|
|
83
|
+
}
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
if (request.method === 'PUT') {
|
|
87
|
+
return Response.json(
|
|
88
|
+
await writeWorkspaceFile(root, path, request.body ?? new Blob([]).stream())
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
if (request.method === 'PATCH') {
|
|
92
|
+
const { patch } = patchSchema.parse(await request.json())
|
|
93
|
+
return Response.json(
|
|
94
|
+
await writeWorkspaceFile(root, path, new ReadableStream(), source =>
|
|
95
|
+
applyUnifiedPatch(source, patch)
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (request.method !== 'POST')
|
|
101
|
+
return Response.json({ error: 'Method not allowed' }, { status: 405 })
|
|
102
|
+
if (match[2] === 'commands') {
|
|
103
|
+
const { command, args } = commandSchema.parse(await request.json())
|
|
104
|
+
const child = spawnWorkspaceCommand(root, command, args)
|
|
105
|
+
track(child, request.signal)
|
|
106
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
107
|
+
readOutput(child.stdout, child),
|
|
108
|
+
readOutput(child.stderr, child),
|
|
109
|
+
child.exited
|
|
110
|
+
])
|
|
111
|
+
return Response.json({ exitCode, stdout, stderr })
|
|
112
|
+
}
|
|
113
|
+
if (match[2] === 'exec') {
|
|
114
|
+
const input = execSchema.parse(await request.json())
|
|
115
|
+
const key = JSON.stringify([
|
|
116
|
+
workspace.id,
|
|
117
|
+
request.headers.get('x-moi-user-id'),
|
|
118
|
+
'cancel' in input ? input.cancel : input.id
|
|
119
|
+
])
|
|
120
|
+
for (const [id, expires] of cancelled) if (expires < Date.now()) cancelled.delete(id)
|
|
121
|
+
if ('cancel' in input) {
|
|
122
|
+
// Retain a short cancellation marker in case it overtakes startup.
|
|
123
|
+
cancelled.set(key, Date.now() + 60_000)
|
|
124
|
+
const running = executions.get(key)
|
|
125
|
+
if (running) stopChild(running)
|
|
126
|
+
return Response.json({ cancelled: true })
|
|
127
|
+
}
|
|
128
|
+
if (cancelled.has(key)) throw new OperationError('Execution was cancelled', 409)
|
|
129
|
+
if (input.id && executions.has(key))
|
|
130
|
+
throw new OperationError('Execution already exists', 409)
|
|
131
|
+
const { command } = input
|
|
132
|
+
const child = Bun.spawn(['/bin/sh', '-c', command], {
|
|
133
|
+
cwd: root,
|
|
134
|
+
stdin: 'ignore',
|
|
135
|
+
stdout: 'pipe',
|
|
136
|
+
stderr: 'pipe',
|
|
137
|
+
detached: true
|
|
138
|
+
})
|
|
139
|
+
track(child, request.signal)
|
|
140
|
+
if (input.id) {
|
|
141
|
+
executions.set(key, child)
|
|
142
|
+
void child.exited.finally(() => executions.delete(key))
|
|
143
|
+
}
|
|
144
|
+
const encoder = new TextEncoder()
|
|
145
|
+
const stream = new TransformStream<Uint8Array, Uint8Array>()
|
|
146
|
+
const writer = stream.writable.getWriter()
|
|
147
|
+
const send = (event: unknown) => writer.write(encoder.encode(JSON.stringify(event) + '\n'))
|
|
148
|
+
const read = async (type: string, source: ReadableStream<Uint8Array>) => {
|
|
149
|
+
const decoder = new TextDecoder()
|
|
150
|
+
for await (const bytes of source)
|
|
151
|
+
await send({ type, data: decoder.decode(bytes, { stream: true }) })
|
|
152
|
+
const tail = decoder.decode()
|
|
153
|
+
if (tail) await send({ type, data: tail })
|
|
154
|
+
}
|
|
155
|
+
void writer.closed.catch(() => stopChild(child))
|
|
156
|
+
void Promise.all([read('stdout', child.stdout), read('stderr', child.stderr), child.exited])
|
|
157
|
+
.then(async ([, , code]) => {
|
|
158
|
+
await send({ type: 'exit', code })
|
|
159
|
+
await writer.close()
|
|
160
|
+
})
|
|
161
|
+
.catch(async error => {
|
|
162
|
+
stopChild(child)
|
|
163
|
+
await writer.abort(error).catch(() => {})
|
|
164
|
+
})
|
|
165
|
+
return new Response(stream.readable, {
|
|
166
|
+
headers: {
|
|
167
|
+
'content-type': 'application/x-ndjson',
|
|
168
|
+
'cache-control': 'no-store, no-transform',
|
|
169
|
+
'content-encoding': 'identity',
|
|
170
|
+
'x-content-type-options': 'nosniff'
|
|
171
|
+
}
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
return Response.json({ error: 'Method not allowed' }, { status: 405 })
|
|
175
|
+
} catch (error) {
|
|
176
|
+
const status =
|
|
177
|
+
error instanceof OperationError
|
|
178
|
+
? error.status
|
|
179
|
+
: error instanceof z.ZodError || error instanceof SyntaxError || error instanceof URIError
|
|
180
|
+
? 400
|
|
181
|
+
: 500
|
|
182
|
+
if (status === 500) console.error('[operations]', error)
|
|
183
|
+
return Response.json(
|
|
184
|
+
{
|
|
185
|
+
error:
|
|
186
|
+
error instanceof OperationError
|
|
187
|
+
? error.message
|
|
188
|
+
: status === 400
|
|
189
|
+
? 'Invalid operation request'
|
|
190
|
+
: 'Operation failed'
|
|
191
|
+
},
|
|
192
|
+
{ status }
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
export async function startOperations(socket: string) {
|
|
198
|
+
await rm(socket, { force: true })
|
|
199
|
+
const server = Bun.serve({
|
|
200
|
+
...({ unix: socket } as unknown as { port: number }),
|
|
201
|
+
idleTimeout: 0,
|
|
202
|
+
fetch: createOperationsHandler()
|
|
203
|
+
})
|
|
204
|
+
await chmod(socket, 0o660)
|
|
205
|
+
return server
|
|
206
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { calculateJwkThumbprint, exportJWK, generateKeyPair, importJWK, SignJWT } from 'jose'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
export const AGENT_CLIENTS = ['grok-bot', 'instinct', 'muse', 'dot', 'duet', 'other'] as const
|
|
5
|
+
export const agentClientSchema = z.enum(AGENT_CLIENTS)
|
|
6
|
+
export type AgentClient = z.infer<typeof agentClientSchema>
|
|
7
|
+
|
|
8
|
+
const privateKey = z.object({
|
|
9
|
+
kty: z.literal('OKP'),
|
|
10
|
+
crv: z.literal('Ed25519'),
|
|
11
|
+
x: z.string().regex(/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/),
|
|
12
|
+
d: z.string().regex(/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/)
|
|
13
|
+
})
|
|
14
|
+
export const agentCredentialsSchema = z.object({
|
|
15
|
+
kind: z.literal('agent'),
|
|
16
|
+
url: z.string(),
|
|
17
|
+
clientId: z.string(),
|
|
18
|
+
agentId: z.string(),
|
|
19
|
+
hostId: z.string(),
|
|
20
|
+
agentKey: privateKey,
|
|
21
|
+
hostKey: privateKey
|
|
22
|
+
})
|
|
23
|
+
export type AgentCredentials = z.infer<typeof agentCredentialsSchema>
|
|
24
|
+
|
|
25
|
+
function canonical(value: unknown): string {
|
|
26
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
|
|
27
|
+
if (value !== null && typeof value === 'object')
|
|
28
|
+
return `{${Object.entries(value)
|
|
29
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
30
|
+
.map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`)
|
|
31
|
+
.join(',')}}`
|
|
32
|
+
return JSON.stringify(value)
|
|
33
|
+
}
|
|
34
|
+
const hash = (value: string | Uint8Array<ArrayBuffer>) =>
|
|
35
|
+
new Bun.CryptoHasher('sha256').update(value).digest('base64url')
|
|
36
|
+
export async function createAgentKeys(config: {
|
|
37
|
+
url: string
|
|
38
|
+
clientId: string
|
|
39
|
+
}): Promise<AgentCredentials> {
|
|
40
|
+
const host = await generateKeyPair('EdDSA', { extractable: true }),
|
|
41
|
+
agent = await generateKeyPair('EdDSA', { extractable: true })
|
|
42
|
+
const hostKey = privateKey.parse(await exportJWK(host.privateKey))
|
|
43
|
+
const agentKey = privateKey.parse(await exportJWK(agent.privateKey))
|
|
44
|
+
return {
|
|
45
|
+
kind: 'agent',
|
|
46
|
+
...config,
|
|
47
|
+
hostKey,
|
|
48
|
+
agentKey,
|
|
49
|
+
hostId: `h_${await calculateJwkThumbprint(hostKey)}`,
|
|
50
|
+
agentId: `a_${await calculateJwkThumbprint(agentKey)}`
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function publicKey(key: AgentCredentials['agentKey']) {
|
|
54
|
+
return { kty: key.kty, crv: key.crv, x: key.x }
|
|
55
|
+
}
|
|
56
|
+
async function sign(
|
|
57
|
+
keys: AgentCredentials,
|
|
58
|
+
key: AgentCredentials['agentKey'],
|
|
59
|
+
typ: string,
|
|
60
|
+
url: string,
|
|
61
|
+
method: string,
|
|
62
|
+
body: string | Uint8Array<ArrayBuffer>
|
|
63
|
+
) {
|
|
64
|
+
const requestHash = hash(`${method.toUpperCase()}\n${url}\n${hash(body)}`)
|
|
65
|
+
return new SignJWT({ sub: keys.agentId, iss: keys.hostId, requestHash })
|
|
66
|
+
.setProtectedHeader({ alg: 'EdDSA', typ })
|
|
67
|
+
.setAudience(`${keys.url}/api/auth`)
|
|
68
|
+
.setIssuedAt()
|
|
69
|
+
.setExpirationTime('60s')
|
|
70
|
+
.setJti(crypto.randomUUID())
|
|
71
|
+
.sign(await importJWK(key, 'EdDSA'))
|
|
72
|
+
}
|
|
73
|
+
export async function agentAuthorization(
|
|
74
|
+
keys: AgentCredentials,
|
|
75
|
+
url: string,
|
|
76
|
+
method: string,
|
|
77
|
+
body: string | Uint8Array<ArrayBuffer>
|
|
78
|
+
) {
|
|
79
|
+
return `Bearer ${await sign(keys, keys.agentKey, 'agent+jwt', url, method, body)}`
|
|
80
|
+
}
|
|
81
|
+
export async function agentJoinBody(
|
|
82
|
+
keys: AgentCredentials,
|
|
83
|
+
token: string,
|
|
84
|
+
name: string,
|
|
85
|
+
client: AgentClient
|
|
86
|
+
) {
|
|
87
|
+
const unsigned = {
|
|
88
|
+
token,
|
|
89
|
+
name,
|
|
90
|
+
client,
|
|
91
|
+
hostPublicKey: publicKey(keys.hostKey),
|
|
92
|
+
agentPublicKey: publicKey(keys.agentKey)
|
|
93
|
+
}
|
|
94
|
+
const body = canonical(unsigned),
|
|
95
|
+
url = `${keys.url}/api/agents/join`
|
|
96
|
+
return {
|
|
97
|
+
...unsigned,
|
|
98
|
+
proof: {
|
|
99
|
+
host: await sign(keys, keys.hostKey, 'host+jwt', url, 'POST', body),
|
|
100
|
+
agent: await sign(keys, keys.agentKey, 'agent+jwt', url, 'POST', body)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { CONTROL_HOST, CONTROL_PORT } from '../constants'
|
|
2
|
+
import type { RemoteBroker, RemoteLogin, RemoteRequestOptions } from './client'
|
|
3
|
+
import { CloudSignInRequired } from './errors'
|
|
4
|
+
|
|
5
|
+
// The caller's side of broker.ts: hand a Cloud request to the Moi server
|
|
6
|
+
// running on this machine, which sends it with its own login. The caller
|
|
7
|
+
// never sees a credential.
|
|
8
|
+
|
|
9
|
+
export const BROKER_ERROR_HEADER = 'x-moi-broker-error'
|
|
10
|
+
export const BROKER_LOGIN_HEADER = 'x-moi-login'
|
|
11
|
+
// A header a web page cannot send across origins without a preflight, which
|
|
12
|
+
// the control server never answers. It keeps browsers out of the broker.
|
|
13
|
+
export const BROKER_CALLER_HEADER = 'x-moi-cli'
|
|
14
|
+
|
|
15
|
+
const notRunning = (error: unknown) =>
|
|
16
|
+
['ConnectionRefused', 'ECONNREFUSED'].includes(String((error as { code?: unknown })?.code))
|
|
17
|
+
|
|
18
|
+
export function createControlBroker(base: string): RemoteBroker {
|
|
19
|
+
// No server, or one from before the broker existed, answers undefined.
|
|
20
|
+
async function ask(
|
|
21
|
+
route: string,
|
|
22
|
+
options: RemoteRequestOptions = {}
|
|
23
|
+
): Promise<Response | undefined> {
|
|
24
|
+
let response: Response
|
|
25
|
+
try {
|
|
26
|
+
response = await fetch(base + route, {
|
|
27
|
+
method: options.method ?? 'GET',
|
|
28
|
+
body: options.body,
|
|
29
|
+
signal: options.signal,
|
|
30
|
+
redirect: 'error',
|
|
31
|
+
headers: {
|
|
32
|
+
[BROKER_CALLER_HEADER]: '1',
|
|
33
|
+
...(options.contentType ? { 'content-type': options.contentType } : {})
|
|
34
|
+
}
|
|
35
|
+
})
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (notRunning(error)) return undefined
|
|
38
|
+
throw error
|
|
39
|
+
}
|
|
40
|
+
if (response.headers.has(BROKER_ERROR_HEADER)) {
|
|
41
|
+
const failure = (await response.json().catch(() => ({}))) as {
|
|
42
|
+
error?: unknown
|
|
43
|
+
signIn?: unknown
|
|
44
|
+
}
|
|
45
|
+
const message = typeof failure.error === 'string' ? failure.error : 'Moi refused the request'
|
|
46
|
+
throw failure.signIn ? new CloudSignInRequired(message) : new Error(message)
|
|
47
|
+
}
|
|
48
|
+
if (!response.headers.has(BROKER_LOGIN_HEADER)) {
|
|
49
|
+
await response.body?.cancel()
|
|
50
|
+
return undefined
|
|
51
|
+
}
|
|
52
|
+
return response
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
async info() {
|
|
57
|
+
const response = await ask('/remote/info')
|
|
58
|
+
if (!response) return undefined
|
|
59
|
+
const { url, login } = (await response.json()) as {
|
|
60
|
+
url: string
|
|
61
|
+
login?: RemoteLogin
|
|
62
|
+
}
|
|
63
|
+
return { url, login }
|
|
64
|
+
},
|
|
65
|
+
async fetch(path, options) {
|
|
66
|
+
const response = await ask('/remote/request?path=' + encodeURIComponent(path), options)
|
|
67
|
+
if (!response) return undefined
|
|
68
|
+
return {
|
|
69
|
+
response,
|
|
70
|
+
agent: response.headers.get(BROKER_LOGIN_HEADER) === 'agent'
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const controlBroker = createControlBroker(`http://${CONTROL_HOST}:${CONTROL_PORT}`)
|
|
@@ -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
|
+
}
|