moi-computer 0.13.1-next.1 → 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 (195) hide show
  1. package/client/api/app-config.ts +12 -1
  2. package/client/api/http.ts +11 -1
  3. package/client/app/app-router.tsx +3 -2
  4. package/client/app/routes/home-route.tsx +1 -1
  5. package/client/app/routes/workspace-registration.tsx +68 -0
  6. package/client/app/routes/workspace-route.tsx +33 -6
  7. package/client/app/shell/sidebar-layout.tsx +10 -5
  8. package/client/components/shared/workspace-icon.tsx +8 -17
  9. package/client/features/account/account-test-utils.tsx +15 -9
  10. package/client/features/account/api.ts +6 -6
  11. package/client/features/account/profile-actions.ts +5 -7
  12. package/client/features/app-settings/settings-page.tsx +2 -1
  13. package/client/features/applets/api.ts +6 -6
  14. package/client/features/applets/applet-cache.ts +6 -5
  15. package/client/features/applets/applet-log.ts +2 -1
  16. package/client/features/applets/applet-runtime.ts +2 -1
  17. package/client/features/applets/use-applet.ts +73 -18
  18. package/client/features/applets/widget-shell.tsx +4 -2
  19. package/client/features/chat/applet-chat-intents.ts +5 -13
  20. package/client/features/chat/chat-popup.tsx +8 -4
  21. package/client/features/chat/chat-send.ts +2 -2
  22. package/client/features/chat/composer/model-order.ts +4 -4
  23. package/client/features/chat/composer/model-picker.tsx +12 -10
  24. package/client/features/chat/composer/use-workspace-composer-state.tsx +1 -1
  25. package/client/features/chat/sessions/api.ts +11 -28
  26. package/client/features/chat/sessions/use-selected-session.ts +18 -100
  27. package/client/features/chat/use-chat.ts +8 -12
  28. package/client/features/collab/members/api.ts +4 -10
  29. package/client/features/collab/members/hooks.ts +32 -38
  30. package/client/features/collab/members/store.ts +96 -71
  31. package/client/features/collab/members/types.ts +5 -3
  32. package/client/features/collab/presence/client.ts +2 -3
  33. package/client/features/collab/presence/hooks.tsx +1 -1
  34. package/client/features/collab/proxy-user.ts +1 -3
  35. package/client/features/collab/sharing/workspace-members.tsx +0 -8
  36. package/client/features/dev/chat-states-page.tsx +3 -1
  37. package/client/features/dev/harness-debug-page.tsx +7 -7
  38. package/client/features/dev/workspace-setup-mocks.ts +1 -1
  39. package/client/features/dev/workspace-setup-preview.tsx +6 -4
  40. package/client/features/harness/api.ts +13 -10
  41. package/client/features/harness/harness-login-panel.tsx +9 -5
  42. package/client/features/harness/harness-presentation.ts +4 -4
  43. package/client/features/harness/harness-selector.tsx +13 -13
  44. package/client/features/harness/use-harness-login.ts +5 -5
  45. package/client/features/home/api.ts +38 -2
  46. package/client/features/home/home-page.tsx +43 -13
  47. package/client/features/home/shared-workspaces.tsx +70 -0
  48. package/client/features/home/workspace-invitations.tsx +101 -0
  49. package/client/features/identity/host-api.ts +3 -2
  50. package/client/features/identity/store.ts +1 -7
  51. package/client/features/onboarding/agent-setup-step.tsx +8 -8
  52. package/client/features/onboarding/onboarding-page.tsx +3 -2
  53. package/client/features/onboarding/workspace-setup-step.tsx +1 -1
  54. package/client/features/overview/api.ts +3 -5
  55. package/client/features/overview/default/registry.tsx +1 -1
  56. package/client/features/overview/default/views-widget.tsx +2 -2
  57. package/client/features/overview/hidden-panel.tsx +7 -5
  58. package/client/features/overview/overview.tsx +18 -16
  59. package/client/features/overview/workspace-name.tsx +2 -2
  60. package/client/features/scratchpad/scratchpad.tsx +9 -7
  61. package/client/features/scratchpad/use-scratchpad-snapshot.tsx +13 -5
  62. package/client/features/views/api.ts +34 -16
  63. package/client/features/views/use-view-actions.ts +10 -20
  64. package/client/features/views/view-manager.tsx +1 -1
  65. package/client/features/views/view-submission.ts +2 -21
  66. package/client/features/workspace/add/api.ts +5 -4
  67. package/client/features/workspace/add/create-workspace-dialog.tsx +12 -9
  68. package/client/features/workspace/add/import-workspace-dialog.tsx +7 -7
  69. package/client/features/workspace/add/use-workspace-import.ts +10 -10
  70. package/client/features/workspace/add/workspace-agent-options.ts +21 -20
  71. package/client/features/workspace/add/workspace-agent-selector.tsx +11 -11
  72. package/client/features/workspace/api.ts +60 -13
  73. package/client/features/workspace/harness-transition.ts +7 -13
  74. package/client/features/workspace/remote.ts +25 -0
  75. package/client/features/workspace/settings/api.ts +7 -12
  76. package/client/features/workspace/settings/connectors-settings.tsx +3 -3
  77. package/client/features/workspace/settings/general-settings.tsx +8 -8
  78. package/client/features/workspace/setup/workspace-login-state.tsx +4 -4
  79. package/client/features/workspace/setup/workspace-recovery-states.tsx +43 -14
  80. package/client/features/workspace/setup/workspace-setup.tsx +6 -6
  81. package/client/features/workspace/tab-resolution.ts +2 -2
  82. package/client/features/workspace/use-workspace-navigation.ts +7 -4
  83. package/client/features/workspace/workspace-content.tsx +22 -20
  84. package/client/features/workspace/workspace-frame.tsx +13 -26
  85. package/client/features/workspace/workspace-layout-context.tsx +45 -12
  86. package/client/features/workspace/workspace-menu.tsx +2 -2
  87. package/client/features/workspace/workspace-pane.tsx +22 -0
  88. package/client/features/workspace/workspace-pending-screen.tsx +1 -1
  89. package/client/features/workspace/workspace-preferences.ts +34 -0
  90. package/client/features/workspace/workspace-presentation.tsx +12 -16
  91. package/client/features/workspace/workspace-screen.tsx +2 -2
  92. package/client/features/workspace/workspace-state.ts +2 -1
  93. package/client/features/workspace/workspace-tabs.tsx +1 -1
  94. package/client/features/workspace/workspace-test-utils.ts +23 -0
  95. package/client/runtime/use-workspace-events.ts +14 -0
  96. package/client/runtime/workspace-events.ts +9 -9
  97. package/client/store/ui.ts +29 -9
  98. package/dist/chunk-44khk4sp.js +2 -0
  99. package/dist/chunk-ba6mz56s.js +72 -0
  100. package/dist/chunk-ec5ennpv.js +1 -0
  101. package/dist/chunk-ectsnw81.js +2 -0
  102. package/dist/chunk-en7w5ypg.js +1 -0
  103. package/dist/chunk-f695wcx5.js +5 -0
  104. package/dist/chunk-kffcah9w.css +1 -0
  105. package/dist/{chunk-th91xfnp.js → chunk-n0fawy9x.js} +1 -1
  106. package/dist/chunk-pdt9hxfw.js +2 -0
  107. package/dist/chunk-rmd0ctfx.js +546 -0
  108. package/dist/chunk-zv22wv0g.js +1 -0
  109. package/dist/index.html +1 -1
  110. package/lib/harness-instructions.ts +4 -4
  111. package/lib/harness-types.ts +13 -0
  112. package/lib/types.ts +34 -49
  113. package/lib/workspace-config.ts +48 -0
  114. package/lib/workspace-layout.ts +2 -4
  115. package/package.json +4 -2
  116. package/server/README.md +29 -27
  117. package/server/api/harnesses.ts +5 -5
  118. package/server/api/index.ts +170 -68
  119. package/server/applets/index.ts +15 -9
  120. package/server/applets/views.ts +2 -17
  121. package/server/applets/widgets.ts +3 -2
  122. package/server/cli/commands/config.ts +8 -20
  123. package/server/cli/commands/hermes.ts +2 -2
  124. package/server/cli/commands/init.ts +96 -53
  125. package/server/cli/commands/openclaw.ts +2 -2
  126. package/server/cli/commands/refresh.ts +10 -1
  127. package/server/cli/commands/remote.ts +228 -0
  128. package/server/cli/commands/skill.ts +4 -4
  129. package/server/cli/commands/tabs.ts +5 -12
  130. package/server/cli/control.ts +35 -4
  131. package/server/cli/index.ts +10 -6
  132. package/server/cli/remote-command.ts +77 -0
  133. package/server/cli/remote-control.ts +70 -0
  134. package/server/cli/remote-operations.ts +244 -0
  135. package/server/collab/config.ts +3 -3
  136. package/server/collab/skill/index.ts +3 -3
  137. package/server/control.ts +38 -11
  138. package/server/harness/acp/session.ts +4 -4
  139. package/server/harness/auth.ts +26 -31
  140. package/server/harness/claude-code/index.ts +1 -1
  141. package/server/harness/codex/discovery.ts +1 -1
  142. package/server/harness/codex/session.ts +1 -1
  143. package/server/harness/detect.ts +14 -19
  144. package/server/harness/executable.ts +10 -10
  145. package/server/harness/hermes/NOTES.md +2 -2
  146. package/server/harness/hermes/index.ts +1 -1
  147. package/server/harness/install.ts +11 -11
  148. package/server/harness/openclaw/index.ts +1 -1
  149. package/server/harness/registry.ts +7 -6
  150. package/server/harness/types.ts +4 -4
  151. package/server/onboarding/jobs.ts +1 -1
  152. package/server/operations/commands.ts +46 -0
  153. package/server/operations/files.ts +148 -0
  154. package/server/operations/server.ts +206 -0
  155. package/server/remote/agent.ts +103 -0
  156. package/server/remote/client.ts +665 -0
  157. package/server/remote/workspace.ts +34 -0
  158. package/server/scratchpad/document.ts +32 -12
  159. package/server/scratchpad/executor.ts +16 -7
  160. package/server/sessions/config.ts +8 -5
  161. package/server/sessions/pending-views.ts +16 -0
  162. package/server/sessions/view-sessions.ts +10 -12
  163. package/server/skills/locations.ts +4 -4
  164. package/server/skills/update.ts +11 -11
  165. package/server/skills/version.ts +7 -7
  166. package/server/skills/workspace.ts +13 -11
  167. package/server/web.ts +11 -8
  168. package/server/workspace-state/file.ts +2 -0
  169. package/server/workspace-state/index.ts +0 -4
  170. package/server/workspaces/api.ts +28 -0
  171. package/server/workspaces/change-harness.ts +15 -26
  172. package/server/workspaces/import.ts +4 -4
  173. package/server/workspaces/init.ts +15 -13
  174. package/server/workspaces/layout.ts +60 -66
  175. package/server/workspaces/registry.ts +43 -18
  176. package/server/workspaces/shared.ts +74 -0
  177. package/server/workspaces/tabs.ts +6 -12
  178. package/skill/SKILL.md +24 -4
  179. package/client/api/app-ui-keys.ts +0 -6
  180. package/client/features/chat/sessions/browser-tab-state.ts +0 -43
  181. package/client/features/collab/members/keys.ts +0 -6
  182. package/client/features/workspace/browser-tab-state.ts +0 -51
  183. package/client/features/workspace/layout-save.ts +0 -13
  184. package/dist/chunk-3smkkcfw.js +0 -546
  185. package/dist/chunk-47h9c2qy.js +0 -2
  186. package/dist/chunk-8qed2gqp.js +0 -75
  187. package/dist/chunk-8zy3vesm.js +0 -1
  188. package/dist/chunk-a47zy276.js +0 -2
  189. package/dist/chunk-g4c1nte9.css +0 -1
  190. package/dist/chunk-kcactdr4.js +0 -2
  191. package/dist/chunk-m8bhx6tw.js +0 -1
  192. package/dist/chunk-pf19zcrn.js +0 -2
  193. package/dist/chunk-ygzxah0e.js +0 -1
  194. package/lib/workspace-types.ts +0 -13
  195. package/server/workspace-state/legacy-migration.ts +0 -79
@@ -0,0 +1,148 @@
1
+ import { constants } from 'node:fs'
2
+ import { lstat, mkdir, open, realpath, rename, rm } from 'node:fs/promises'
3
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
4
+ import { Mutex } from 'async-mutex'
5
+
6
+ export class OperationError extends Error {
7
+ constructor(
8
+ message: string,
9
+ readonly status = 400
10
+ ) {
11
+ super(message)
12
+ }
13
+ }
14
+
15
+ // All file operations share this queue. Keep validation and replacement together
16
+ // so two requests through this listener cannot swap an ancestor during a write.
17
+ const writes = new Mutex()
18
+ function inside(root: string, path: string) {
19
+ const rel = relative(root, path)
20
+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
21
+ }
22
+ export async function workspaceFile(root: string, path: string, create = false): Promise<string> {
23
+ if (
24
+ !path ||
25
+ isAbsolute(path) ||
26
+ path.includes('\\') ||
27
+ path.includes('\0') ||
28
+ path.split('/').some(p => p === '..' || p === '.')
29
+ )
30
+ throw new OperationError('Use a file path relative to the workspace')
31
+ root = await realpath(root)
32
+ const target = resolve(root, path)
33
+ if (!inside(root, target)) throw new OperationError('File is outside the workspace')
34
+ let current = root
35
+ const parts = relative(root, target).split(sep)
36
+ for (const [i, part] of parts.entries()) {
37
+ current = resolve(current, part)
38
+ try {
39
+ const info = await lstat(current)
40
+ // Reject symlinks even if currently pointing inside: no check/use redirect.
41
+ if (info.isSymbolicLink()) throw new OperationError('Symbolic links are not supported')
42
+ if (i < parts.length - 1 && !info.isDirectory())
43
+ throw new OperationError('Parent is not a directory')
44
+ if (i === parts.length - 1 && !info.isFile()) throw new OperationError('Path is not a file')
45
+ } catch (error) {
46
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
47
+ if (!create) throw new OperationError('File not found', 404)
48
+ if (i < parts.length - 1) await mkdir(current)
49
+ }
50
+ }
51
+ return target
52
+ }
53
+
54
+ export async function writeWorkspaceFile(
55
+ root: string,
56
+ path: string,
57
+ body: ReadableStream<Uint8Array>,
58
+ patch?: (source: string) => string
59
+ ) {
60
+ return writes.runExclusive(async () => {
61
+ const target = await workspaceFile(root, path, !patch)
62
+ const temporary = resolve(dirname(target), `.moi-write-${crypto.randomUUID()}`)
63
+ let mode = 0o664
64
+ try {
65
+ mode = (await lstat(target)).mode & 0o777
66
+ } catch {}
67
+ const file = await open(
68
+ temporary,
69
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
70
+ mode
71
+ )
72
+ try {
73
+ if (patch) {
74
+ const source = new TextDecoder('utf-8', { fatal: true }).decode(
75
+ await Bun.file(target).arrayBuffer()
76
+ )
77
+ await file.writeFile(patch(source))
78
+ } else {
79
+ for await (const chunk of body) await file.writeFile(chunk)
80
+ }
81
+ await file.close()
82
+ // Recheck after streaming an upload; an external shell can change paths.
83
+ if ((await workspaceFile(root, path, true)) !== target)
84
+ throw new OperationError('File changed during upload', 409)
85
+ await rename(temporary, target)
86
+ } finally {
87
+ await file.close().catch(() => {})
88
+ await rm(temporary, { force: true })
89
+ }
90
+ return { ok: true, bytes: (await lstat(target)).size }
91
+ })
92
+ }
93
+
94
+ /** Apply an exact unified diff to this file. No fuzzy matching or shell execution. */
95
+ export function applyUnifiedPatch(source: string, patch: string): string {
96
+ const original = source ? source.split('\n') : []
97
+ if (source.endsWith('\n')) original.pop()
98
+ const output: string[] = []
99
+ const lines = patch.split('\n')
100
+ let cursor = 0,
101
+ hunks = 0,
102
+ newline = source.endsWith('\n')
103
+ for (let i = 0; i < lines.length; i++) {
104
+ const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(lines[i]!)
105
+ if (!header) {
106
+ if (lines[i] === '' || lines[i]?.startsWith('--- ') || lines[i]?.startsWith('+++ ')) continue
107
+ throw new OperationError('Expected a unified diff', 422)
108
+ }
109
+ hunks++
110
+ const oldCount = Number(header[2] ?? 1),
111
+ newCount = Number(header[4] ?? 1)
112
+ const start = Number(header[1]) - (oldCount ? 1 : 0)
113
+ if (start < cursor || start > original.length)
114
+ throw new OperationError('Patch does not match the file', 409)
115
+ output.push(...original.slice(cursor, start))
116
+ cursor = start
117
+ if (Number(header[3]) - (newCount ? 1 : 0) !== output.length)
118
+ throw new OperationError('Invalid patch position', 422)
119
+ let removed = 0,
120
+ added = 0
121
+ while (removed < oldCount || added < newCount) {
122
+ const line = lines[++i]
123
+ if (line === undefined) throw new OperationError('Incomplete patch', 422)
124
+ const prefix = line[0],
125
+ value = line.slice(1)
126
+ if (prefix === ' ' || prefix === '-') {
127
+ if (original[cursor++] !== value)
128
+ throw new OperationError('Patch does not match the file', 409)
129
+ removed++
130
+ }
131
+ if (prefix === ' ' || prefix === '+') {
132
+ output.push(value)
133
+ added++
134
+ newline = true
135
+ }
136
+ if (![' ', '+', '-'].includes(prefix ?? '') || removed > oldCount || added > newCount)
137
+ throw new OperationError('Invalid patch hunk', 422)
138
+ if (lines[i + 1] === '\') {
139
+ if (prefix !== '-') newline = false
140
+ i++
141
+ }
142
+ }
143
+ }
144
+ if (!hunks) throw new OperationError('Patch has no hunks', 422)
145
+ if (cursor < original.length) newline = source.endsWith('\n')
146
+ output.push(...original.slice(cursor))
147
+ return output.join('\n') + (output.length && newline ? '\n' : '')
148
+ }
@@ -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
+ }