moi-computer 0.13.1-next.2 → 0.13.1-next.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/app/app-provider.tsx +14 -20
- package/client/app/app-router.tsx +5 -8
- package/client/app/routes/workspace-route.tsx +28 -11
- package/client/app/shell/sidebar-layout.tsx +5 -10
- package/client/features/app-settings/api.ts +3 -3
- package/client/features/applets/applet-cache.ts +1 -2
- package/client/features/applets/use-applet.ts +18 -20
- package/client/features/chat/chat-store.ts +1 -1
- package/client/features/chat/connection/chat-connection.ts +25 -68
- package/client/features/chat/connection/chat-frames.ts +20 -32
- package/client/features/chat/sessions/api.ts +2 -2
- package/client/features/chat/sessions/use-selected-session.ts +0 -13
- package/client/features/collab/presence/client.ts +63 -83
- package/client/features/collab/presence/provider.tsx +8 -2
- package/client/features/dev/chat-states-page.tsx +1 -1
- package/client/features/dev/harness-debug-page.tsx +2 -2
- package/client/features/scratchpad/scratchpad.tsx +29 -20
- package/client/features/views/api.ts +38 -14
- package/client/features/views/use-view-actions.ts +2 -23
- package/client/features/workspace/api.ts +6 -11
- package/client/features/workspace/harness-transition.ts +3 -5
- package/client/features/workspace/remote.ts +9 -0
- package/client/features/workspace/settings/use-env-vars.ts +4 -4
- package/client/features/workspace/tab-resolution.ts +1 -8
- package/client/features/workspace/use-workspace-navigation.ts +5 -4
- package/client/features/workspace/use-workspace-socket.ts +51 -0
- package/client/features/workspace/workspace-content.tsx +5 -18
- package/client/features/workspace/workspace-layout-context.tsx +6 -13
- package/client/features/workspace/workspace-preferences.ts +67 -10
- package/client/features/workspace/workspace-state.ts +57 -21
- package/client/runtime/app-context.ts +2 -2
- package/client/runtime/app-events.ts +75 -0
- package/client/runtime/reconnecting-socket.ts +115 -0
- package/client/runtime/{use-workspace-events.ts → use-client-events.ts} +9 -10
- package/client/store/ui.ts +1 -6
- package/client/store/workspace-session.ts +30 -0
- package/dist/chunk-0t8m1ehd.js +2 -0
- package/dist/chunk-851bx8ss.js +72 -0
- package/dist/{chunk-n0fawy9x.js → chunk-c8g5x288.js} +1 -1
- package/dist/chunk-cty37f3v.js +1 -0
- package/dist/chunk-dy6f6h3e.js +5 -0
- package/dist/chunk-j6928pwm.js +1 -0
- package/dist/{chunk-rmd0ctfx.js → chunk-k32585ne.js} +73 -73
- package/dist/chunk-qtkv7hp8.js +2 -0
- package/dist/chunk-rh58dc0y.js +2 -0
- package/dist/{chunk-ec5ennpv.js → chunk-wjbejzek.js} +1 -1
- package/dist/index.html +1 -1
- package/lib/events.ts +61 -0
- package/lib/ids.ts +2 -8
- package/lib/moi-context.ts +19 -5
- package/lib/types.ts +16 -20
- package/lib/workspace-layout.ts +3 -20
- package/package.json +2 -1
- package/server/AGENTS.md +4 -4
- package/server/README.md +50 -33
- package/server/api/index.ts +175 -152
- package/server/applets/views.ts +15 -14
- package/server/applets/widgets.ts +4 -3
- package/server/cli/commands/init.ts +7 -2
- package/server/cli/commands/refresh.ts +2 -5
- package/server/cli/commands/remote.ts +128 -26
- package/server/cli/remote-control.ts +12 -9
- package/server/cli/remote-operations.ts +47 -44
- package/server/control.ts +33 -34
- package/server/events.ts +14 -13
- package/server/harness/README.md +7 -7
- package/server/harness/acp/session.ts +9 -5
- package/server/harness/auth.ts +7 -30
- package/server/harness/claude-code/session.ts +8 -4
- package/server/harness/codex/NOTES.md +1 -1
- package/server/harness/codex/session.ts +18 -10
- package/server/harness/hermes/NOTES.md +3 -3
- package/server/harness/openclaw/session.ts +9 -5
- package/server/onboarding/jobs.ts +8 -8
- package/server/operations/commands.ts +1 -1
- package/server/remote/broker-client.ts +76 -0
- package/server/remote/broker.ts +81 -0
- package/server/remote/client.ts +212 -152
- package/server/remote/errors.ts +2 -0
- package/server/remote/routes.ts +121 -0
- package/server/scratchpad/document.ts +3 -2
- package/server/scratchpad/executor.ts +2 -2
- package/server/scratchpad/relay.ts +3 -3
- package/server/sessions/archive.ts +1 -1
- package/server/sessions/lifecycle.ts +1 -1
- package/server/sessions/pending-views.ts +19 -12
- package/server/sessions/send-message.ts +102 -0
- package/server/sessions/view-sessions.ts +4 -94
- package/server/web.ts +42 -31
- package/server/workspace-state/file.ts +2 -0
- package/server/workspace-state/index.ts +15 -4
- package/server/workspaces/api.ts +4 -8
- package/server/workspaces/config.ts +14 -13
- package/server/workspaces/env-apply.ts +1 -1
- package/server/workspaces/layout.ts +40 -7
- package/server/workspaces/shared.ts +1 -1
- package/server/workspaces/tabs.ts +1 -2
- package/skill/SKILL.md +75 -34
- package/skill/references/SCRATCHPAD.md +4 -0
- package/skill/references/UI-COMPONENTS.md +1 -1
- package/client/features/scratchpad/scratch-executor.ts +0 -20
- package/client/runtime/workspace-events.ts +0 -168
- package/dist/chunk-44khk4sp.js +0 -2
- package/dist/chunk-ba6mz56s.js +0 -72
- package/dist/chunk-ectsnw81.js +0 -2
- package/dist/chunk-en7w5ypg.js +0 -1
- package/dist/chunk-f695wcx5.js +0 -5
- package/dist/chunk-pdt9hxfw.js +0 -2
- package/dist/chunk-zv22wv0g.js +0 -1
|
@@ -97,7 +97,7 @@ type SessionRecord = {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
|
|
100
|
-
// `${workspaceId}:${tempId}` -> native thread id after
|
|
100
|
+
// `${workspaceId}:${tempId}` -> native thread id after session:renamed.
|
|
101
101
|
const aliases = new Map<string, string>()
|
|
102
102
|
const resumes = new Map<string, Promise<SessionRecord>>()
|
|
103
103
|
type SendLane = { tail: Promise<void>; generation: number }
|
|
@@ -206,7 +206,7 @@ function publishActivity(rec: SessionRecord) {
|
|
|
206
206
|
if (rec.activity === activity) return
|
|
207
207
|
rec.activity = activity
|
|
208
208
|
broadcast(rec.workspaceId, {
|
|
209
|
-
type: 'status',
|
|
209
|
+
type: 'session:status',
|
|
210
210
|
sessionId: rec.sessionId,
|
|
211
211
|
activity
|
|
212
212
|
})
|
|
@@ -349,7 +349,7 @@ function flushPreviews(rec: SessionRecord) {
|
|
|
349
349
|
const entry = rec.previews.get(itemId)
|
|
350
350
|
if (!entry) continue
|
|
351
351
|
broadcast(rec.workspaceId, {
|
|
352
|
-
type: 'preview',
|
|
352
|
+
type: 'session:preview',
|
|
353
353
|
sessionId: rec.sessionId,
|
|
354
354
|
messageId: itemId,
|
|
355
355
|
parentToolUseId: null,
|
|
@@ -629,7 +629,7 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
|
|
|
629
629
|
setProcessing(rec, false, null)
|
|
630
630
|
if (rec.refreshSessionsOnTurnComplete) {
|
|
631
631
|
rec.refreshSessionsOnTurnComplete = false
|
|
632
|
-
broadcast(rec.workspaceId, { type: '
|
|
632
|
+
broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
|
|
633
633
|
}
|
|
634
634
|
if (turn?.status === 'failed' && turn.error?.message) {
|
|
635
635
|
broadcast(rec.workspaceId, {
|
|
@@ -682,7 +682,7 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
|
|
|
682
682
|
if (status?.type === 'active') setProcessing(rec, true, rec.activeTurnId)
|
|
683
683
|
else if (status?.type === 'notLoaded') {
|
|
684
684
|
releaseSession(rec, 'ChatGPT unloaded this chat')
|
|
685
|
-
broadcast(rec.workspaceId, { type: '
|
|
685
|
+
broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
|
|
686
686
|
} else if (status?.type === 'idle' || status?.type === 'systemError') {
|
|
687
687
|
flushCommandOutput(rec)
|
|
688
688
|
setProcessing(rec, false, null)
|
|
@@ -694,12 +694,12 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
|
|
|
694
694
|
case 'thread/archived':
|
|
695
695
|
case 'thread/deleted': {
|
|
696
696
|
releaseSession(rec, 'ChatGPT closed this chat')
|
|
697
|
-
broadcast(rec.workspaceId, { type: '
|
|
697
|
+
broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
|
|
698
698
|
return
|
|
699
699
|
}
|
|
700
700
|
case 'thread/unarchived':
|
|
701
701
|
case 'thread/name/updated': {
|
|
702
|
-
broadcast(rec.workspaceId, { type: '
|
|
702
|
+
broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
|
|
703
703
|
return
|
|
704
704
|
}
|
|
705
705
|
// Reuse the notice id so completion updates the hook's started row.
|
|
@@ -765,7 +765,7 @@ function startCodexSessionTitleJob(rec: SessionRecord, client: CodexClient) {
|
|
|
765
765
|
isCurrent: () => isCurrentCodexSession(rec, abort)
|
|
766
766
|
})
|
|
767
767
|
if (!renamed || !isCurrentCodexSession(rec, abort)) return
|
|
768
|
-
broadcast(rec.workspaceId, { type: '
|
|
768
|
+
broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
|
|
769
769
|
debug(
|
|
770
770
|
`codex session title ws=${rec.workspaceId} thread=${rec.sessionId} title=${JSON.stringify(title)}`
|
|
771
771
|
)
|
|
@@ -989,7 +989,11 @@ async function sendMessage(
|
|
|
989
989
|
} catch (err) {
|
|
990
990
|
// No session record exists to run setProcessing through — clear the
|
|
991
991
|
// client's optimistic spinner explicitly or it sticks until reconnect.
|
|
992
|
-
broadcast(input.workspaceId, {
|
|
992
|
+
broadcast(input.workspaceId, {
|
|
993
|
+
type: 'session:status',
|
|
994
|
+
sessionId: input.sessionId,
|
|
995
|
+
activity: 'idle'
|
|
996
|
+
})
|
|
993
997
|
broadcast(input.workspaceId, {
|
|
994
998
|
kind: 'error',
|
|
995
999
|
sessionId: input.sessionId,
|
|
@@ -1144,7 +1148,11 @@ export async function interruptCodexRun(input: {
|
|
|
1144
1148
|
broadcast(input.workspaceId, { kind: 'stopped', sessionId: rec?.sessionId ?? input.sessionId })
|
|
1145
1149
|
if (rec) setProcessing(rec, false, null)
|
|
1146
1150
|
else
|
|
1147
|
-
broadcast(input.workspaceId, {
|
|
1151
|
+
broadcast(input.workspaceId, {
|
|
1152
|
+
type: 'session:status',
|
|
1153
|
+
sessionId: input.sessionId,
|
|
1154
|
+
activity: 'idle'
|
|
1155
|
+
})
|
|
1148
1156
|
return
|
|
1149
1157
|
}
|
|
1150
1158
|
try {
|
|
@@ -211,7 +211,7 @@ rediscovered on the next snapshot instead of on every one.
|
|
|
211
211
|
| `agent_thought_chunk` | token deltas | thinking parts |
|
|
212
212
|
| `tool_call` | `toolCallId`, `title`, `kind`, `locations`, `content` | `ToolCall` start |
|
|
213
213
|
| `tool_call_update` | `status: completed\|failed`, `content` | `ToolCall` result |
|
|
214
|
-
| `session_info_update` | generated `title`, `updatedAt` | `
|
|
214
|
+
| `session_info_update` | generated `title`, `updatedAt` | `sessions:changed` |
|
|
215
215
|
| `available_commands_update` | slash commands | init metadata |
|
|
216
216
|
| `usage_update` | context `size` / `used` | context meter |
|
|
217
217
|
| `user_message_chunk` | replayed user turns | history only (§3.6) |
|
|
@@ -807,14 +807,14 @@ returns `{}` but only drops the live session; the chat still lists. There is no
|
|
|
807
807
|
`session/archive` at all.
|
|
808
808
|
|
|
809
809
|
Hermes _does_ have the right primitive internally —
|
|
810
|
-
`hermes_state.SessionDB.
|
|
810
|
+
`hermes_state.SessionDB.set_session:archived(session_id, archived)`, a soft hide
|
|
811
811
|
that keeps every message and walks the whole compression chain (archiving only
|
|
812
812
|
the visible tip lets the still-unarchived root resurrect it). Its `sessions`
|
|
813
813
|
table has an `archived` column, and `list_sessions_rich` takes
|
|
814
814
|
`include_archived: bool = False`, which the ACP adapter never overrides — so an
|
|
815
815
|
archived session would drop out of `session/list` for free.
|
|
816
816
|
|
|
817
|
-
The problem is reach: the only callers of `
|
|
817
|
+
The problem is reach: the only callers of `set_session:archived` are HTTP routes
|
|
818
818
|
on `hermes serve` and the gateway API server, daemons Moi deliberately does not
|
|
819
819
|
run (§6). The `hermes sessions archive` CLI is filter-based (age, source, title,
|
|
820
820
|
cwd — no session id), and `hermes sessions delete <id>` is a real delete.
|
|
@@ -222,7 +222,7 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
|
|
|
222
222
|
else armIdleTimer(rec)
|
|
223
223
|
if (existing?.processing === processing) return
|
|
224
224
|
broadcast(rec.workspaceId, {
|
|
225
|
-
type: 'status',
|
|
225
|
+
type: 'session:status',
|
|
226
226
|
sessionId: rec.sessionId,
|
|
227
227
|
activity: processing ? 'running' : 'idle'
|
|
228
228
|
})
|
|
@@ -286,7 +286,11 @@ export function teardownOpenClawSession(rec: SessionRecord): void {
|
|
|
286
286
|
// If it was mid-run, mirror setProcessing(rec, false, null)'s client-visible
|
|
287
287
|
// effect so no spinner is left hanging.
|
|
288
288
|
if (wasProcessing) {
|
|
289
|
-
broadcast(rec.workspaceId, {
|
|
289
|
+
broadcast(rec.workspaceId, {
|
|
290
|
+
type: 'session:status',
|
|
291
|
+
sessionId: rec.sessionId,
|
|
292
|
+
activity: 'idle'
|
|
293
|
+
})
|
|
290
294
|
}
|
|
291
295
|
}
|
|
292
296
|
|
|
@@ -607,7 +611,7 @@ export function claimPreviewSource(
|
|
|
607
611
|
|
|
608
612
|
function broadcastPreview(rec: SessionRecord, messageId: string, blocks: PreviewBlock[]): void {
|
|
609
613
|
broadcast(rec.workspaceId, {
|
|
610
|
-
type: 'preview',
|
|
614
|
+
type: 'session:preview',
|
|
611
615
|
sessionId: rec.sessionId,
|
|
612
616
|
messageId,
|
|
613
617
|
parentToolUseId: null,
|
|
@@ -906,7 +910,7 @@ function broadcastSessionsChanged(rec: SessionRecord): void {
|
|
|
906
910
|
entry.trailing = setTimeout(
|
|
907
911
|
() => {
|
|
908
912
|
lastListRefresh.set(rec.workspaceId, { at: Date.now() })
|
|
909
|
-
broadcast(rec.workspaceId, { type: '
|
|
913
|
+
broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
|
|
910
914
|
},
|
|
911
915
|
LIST_REFRESH_MIN_MS - (now - entry.at)
|
|
912
916
|
)
|
|
@@ -915,7 +919,7 @@ function broadcastSessionsChanged(rec: SessionRecord): void {
|
|
|
915
919
|
}
|
|
916
920
|
if (entry?.trailing) clearTimeout(entry.trailing)
|
|
917
921
|
lastListRefresh.set(rec.workspaceId, { at: now })
|
|
918
|
-
broadcast(rec.workspaceId, { type: '
|
|
922
|
+
broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
|
|
919
923
|
}
|
|
920
924
|
|
|
921
925
|
// Exported for tests (the live subscription is the only production caller).
|
|
@@ -8,11 +8,11 @@ import { createdWorkspacesRoot } from '../app-config'
|
|
|
8
8
|
import { createWorkspaceDirectory, provisionWorkspace } from '../workspaces/init'
|
|
9
9
|
import { getWorkspace, registerWorkspace } from '../workspaces/registry'
|
|
10
10
|
import { setWorkspaceConfig } from '../workspaces/config'
|
|
11
|
-
import {
|
|
11
|
+
import { updateLayout } from '../workspaces/layout'
|
|
12
12
|
import { resolveWorkspaceTheme } from '@/lib/themes'
|
|
13
13
|
import { publishEvent } from '../events'
|
|
14
14
|
import { harnessFor } from '../harness/registry'
|
|
15
|
-
import { sendWorkspaceMessage } from '../sessions/
|
|
15
|
+
import { sendWorkspaceMessage } from '../sessions/send-message'
|
|
16
16
|
import { resolveRenamedSession, saveSelectedSession } from '../sessions/selected'
|
|
17
17
|
import { readWorkspaceState } from '../workspace-state'
|
|
18
18
|
import { ideasSchema, onboardingIdeaSchema, parseIdeas } from './ideas'
|
|
@@ -197,14 +197,14 @@ export function createOnboardingJobs(overrides: Partial<typeof defaults> = {}) {
|
|
|
197
197
|
const path = job.workspacePath
|
|
198
198
|
await deps.provisionWorkspace(path, progress.harness)
|
|
199
199
|
if (!job.workspaceId) {
|
|
200
|
-
|
|
200
|
+
await deps.setWorkspaceConfig(path, {
|
|
201
201
|
name: idea.name,
|
|
202
202
|
icon: { type: 'glyph', value: idea.icon, background: 'theme' }
|
|
203
203
|
})
|
|
204
|
-
await
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
)
|
|
204
|
+
await updateLayout(path, layout => ({
|
|
205
|
+
...layout,
|
|
206
|
+
theme: resolveWorkspaceTheme({ ...layout.theme, ...idea.theme })
|
|
207
|
+
}))
|
|
208
208
|
}
|
|
209
209
|
const ws = await deps.registerWorkspace(path, {
|
|
210
210
|
id: job.workspaceId ?? basename(path),
|
|
@@ -217,7 +217,7 @@ export function createOnboardingJobs(overrides: Partial<typeof defaults> = {}) {
|
|
|
217
217
|
// Reconciliation must compare against the exact message originally submitted.
|
|
218
218
|
const brief = job.stage ? await Bun.file(briefPath).text() : composeBuildBrief(idea)
|
|
219
219
|
await Bun.write(briefPath, brief)
|
|
220
|
-
deps.publishEvent({ type: 'workspaces-list:
|
|
220
|
+
deps.publishEvent({ type: 'workspaces-list:changed' })
|
|
221
221
|
const harness = deps.harnessFor(ws)
|
|
222
222
|
if (job.stage === 'sending' || job.stage === 'accepted') {
|
|
223
223
|
// The provider may have accepted before a response/save was lost. This
|
|
@@ -40,7 +40,7 @@ export function spawnWorkspaceCommand(root: string, command: string, args: strin
|
|
|
40
40
|
stdout: 'pipe',
|
|
41
41
|
stderr: 'pipe',
|
|
42
42
|
detached: true,
|
|
43
|
-
env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0'
|
|
43
|
+
env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' }
|
|
44
44
|
}
|
|
45
45
|
)
|
|
46
46
|
}
|
|
@@ -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
|
+
}
|