moi-computer 0.11.1-next.4 → 0.12.0

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 (131) hide show
  1. package/client/api/app-config.ts +7 -4
  2. package/client/app/AppRouter.tsx +2 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +27 -19
  4. package/client/features/applets/{AppletMount.tsx → AppletContainer.tsx} +7 -5
  5. package/client/features/applets/WidgetShell.tsx +3 -3
  6. package/client/features/applets/applet-cache.ts +3 -5
  7. package/client/features/applets/applet-runtime.ts +27 -12
  8. package/client/features/applets/applet-thumbnail.ts +2 -1
  9. package/client/features/chat/applet-chat-intents.ts +14 -6
  10. package/client/features/chat/composer/attachments/draft-attachments.ts +21 -4
  11. package/client/features/chat/messages/MarkdownContent.tsx +5 -2
  12. package/client/features/chat/sessions/browser-tab-state.ts +18 -0
  13. package/client/features/chat/sessions/useSelectedSession.ts +55 -21
  14. package/client/features/chat/useChat.ts +4 -0
  15. package/client/features/collab/applet-api.ts +34 -0
  16. package/client/features/collab/client.ts +239 -0
  17. package/client/features/collab/components/cursors.tsx +199 -0
  18. package/client/features/collab/components/presence-avatars.tsx +61 -0
  19. package/client/features/collab/components/presence-frame.tsx +126 -0
  20. package/client/features/collab/components/presence-group.tsx +23 -0
  21. package/client/features/collab/components/presence-helpers.ts +50 -0
  22. package/client/features/collab/components/user-avatar-group.tsx +22 -0
  23. package/client/features/collab/components/user-avatar.tsx +40 -0
  24. package/client/features/collab/components/user.tsx +50 -0
  25. package/client/features/collab/hooks.tsx +164 -0
  26. package/client/features/collab/host-state.ts +254 -0
  27. package/client/features/collab/index.ts +5 -0
  28. package/client/features/collab/local-user.ts +46 -0
  29. package/client/features/collab/presence-publisher.ts +30 -0
  30. package/client/features/collab/presence-target.ts +8 -0
  31. package/client/features/collab/provider.tsx +79 -0
  32. package/client/features/collab/proxy-user.ts +35 -0
  33. package/client/features/collab/store.ts +156 -0
  34. package/client/features/collab/testing/component-fixtures.tsx +54 -0
  35. package/client/features/collab/testing/fake-engine.ts +129 -0
  36. package/client/features/collab/users.ts +106 -0
  37. package/client/features/collab/workspace-users-menu.tsx +194 -0
  38. package/client/features/connectors/mcp-icons.ts +0 -2
  39. package/client/features/dev/DevIndexPage.tsx +5 -0
  40. package/client/features/dev/DevRoutes.tsx +16 -4
  41. package/client/features/dev/collab/collab-page.tsx +24 -0
  42. package/client/features/dev/collab/collab-playground.tsx +614 -0
  43. package/client/features/dev/collab/local-user-settings.tsx +166 -0
  44. package/client/features/dev/collab/playground-room.ts +33 -0
  45. package/client/features/dev/{UiComponentsPage.tsx → ui-components/ui-components-page.tsx} +1 -1
  46. package/client/features/overview/WidgetCanvas.tsx +3 -1
  47. package/client/features/views/ViewManager.tsx +12 -7
  48. package/client/features/views/api.ts +2 -2
  49. package/client/features/views/useViewBuilderActions.ts +3 -0
  50. package/client/features/workspace/WorkspaceContext.tsx +1 -1
  51. package/client/features/workspace/WorkspaceLayoutContext.tsx +8 -2
  52. package/client/features/workspace/WorkspaceScreen.tsx +19 -11
  53. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  54. package/client/features/workspace/api.ts +2 -1
  55. package/client/features/workspace/browser-tab-state.ts +44 -0
  56. package/client/features/workspace/layout-save.ts +13 -0
  57. package/client/features/workspace/moi-context.ts +2 -1
  58. package/client/features/workspace/useWorkspaceNavigation.ts +20 -8
  59. package/client/index.css +45 -0
  60. package/client/index.tsx +9 -4
  61. package/client/main.tsx +1 -11
  62. package/client/theme.css +4 -1
  63. package/dist/chunk-2jncyq65.js +1 -0
  64. package/dist/{chunk-brr0zbeh.js → chunk-3a48fyf7.js} +2 -2
  65. package/dist/{chunk-tzz101ea.js → chunk-97eg9mjn.js} +1 -1
  66. package/dist/chunk-e2q5ken7.js +68 -0
  67. package/dist/{chunk-zs4mte79.js → chunk-efdyz6xp.js} +1 -1
  68. package/dist/chunk-h2kj1ysj.js +1 -0
  69. package/dist/chunk-jf6czgrz.js +2 -0
  70. package/dist/chunk-nez8sdta.js +1 -0
  71. package/dist/chunk-nzwgm8vc.css +1 -0
  72. package/dist/chunk-ph0h6h86.js +1 -0
  73. package/dist/chunk-ryg9z3kn.js +10 -0
  74. package/dist/chunk-tpn177bt.js +2 -0
  75. package/dist/chunk-vfpsc75k.js +2 -0
  76. package/dist/{chunk-m1fvqssh.js → chunk-z3byfve5.js} +2 -2
  77. package/dist/index.html +1 -1
  78. package/lib/collab/colors.ts +30 -0
  79. package/lib/collab/protocol.ts +84 -0
  80. package/lib/collab/types.ts +52 -0
  81. package/lib/experimental.ts +14 -0
  82. package/lib/moi-context.ts +11 -3
  83. package/lib/navigation.ts +25 -5
  84. package/lib/types.ts +20 -33
  85. package/package.json +2 -2
  86. package/server/AGENTS.md +1 -1
  87. package/server/api.ts +28 -5
  88. package/server/app-config.ts +127 -34
  89. package/server/applet-typecheck.ts +8 -3
  90. package/server/applets/applet-css.ts +1 -1
  91. package/server/applets/build-applet.ts +9 -3
  92. package/server/applets/declarations/base.d.ts +75 -0
  93. package/server/applets/declarations/collab.d.ts +88 -0
  94. package/server/applets/declarations.ts +46 -0
  95. package/server/applets/index.ts +8 -8
  96. package/server/applets/runtime/collab.ts +94 -0
  97. package/server/applets/runtime/moi.ts +12 -19
  98. package/server/applets/runtime/rpc.ts +2 -4
  99. package/server/chat-selection.ts +22 -0
  100. package/server/cli.ts +86 -21
  101. package/server/collab/cloudflare-access.ts +78 -0
  102. package/server/collab/config.ts +18 -0
  103. package/server/collab/manager.ts +407 -0
  104. package/server/collab/service.ts +136 -0
  105. package/server/collab/skill/index.ts +53 -0
  106. package/server/collab/worker-messages.ts +10 -0
  107. package/server/collab/worker.ts +52 -0
  108. package/server/layout.ts +10 -3
  109. package/server/moi-scaffold.ts +55 -84
  110. package/server/preview.ts +1 -1
  111. package/server/skill-update.ts +7 -9
  112. package/server/skills-template.ts +14 -2
  113. package/server/web.ts +65 -17
  114. package/server/workspace-init.ts +6 -3
  115. package/ui-components/avatar.tsx +24 -11
  116. package/ui-components/button.tsx +9 -9
  117. package/ui-components/docs/avatar.md +11 -30
  118. package/workspace/.claude/skills/moi-workspace/SKILL.md +14 -11
  119. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +262 -0
  120. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +10 -7
  121. package/client/assets/mcp/agentation.png +0 -0
  122. package/dist/agentation-4s0nn45p.png +0 -0
  123. package/dist/chunk-2gs8jjx4.css +0 -1
  124. package/dist/chunk-7vvg5fyz.js +0 -68
  125. package/dist/chunk-94m3q9ce.js +0 -1
  126. package/dist/chunk-by2wqgak.js +0 -1
  127. package/dist/chunk-p34hvqt3.js +0 -1
  128. package/dist/chunk-p83f0jnj.js +0 -2
  129. package/dist/chunk-xg01f6pn.js +0 -10
  130. /package/client/features/dev/{UiComponentPreviews.tsx → ui-components/ui-component-previews.tsx} +0 -0
  131. /package/server/applets/{runtime/base.ts → api-base.ts} +0 -0
@@ -1,13 +1,8 @@
1
- import type { AppletBridge, AttachmentInput } from '../../../lib/types'
1
+ import type { AttachmentInput, ChatMessageInput } from 'moi'
2
+ import type { AppletBridge } from '../../../lib/types'
3
+ import { resolveUrl as resolveWorkspaceUrl } from '../../../lib/navigation'
2
4
 
3
- import { APPLET_API_BASE_SENTINEL } from './base'
4
-
5
- type AppletChatInput = {
6
- message: string
7
- attachments?: AttachmentInput[]
8
- }
9
-
10
- const BASE = APPLET_API_BASE_SENTINEL
5
+ import { APPLET_API_BASE_SENTINEL } from '../api-base'
11
6
 
12
7
  let bridge: Partial<AppletBridge> | null = null
13
8
 
@@ -19,17 +14,15 @@ export function __getBridge(): Partial<AppletBridge> | null {
19
14
  return bridge
20
15
  }
21
16
 
22
- export function fileUrl(path: string): string {
23
- const clean = String(path).replace(/^\/+/, '')
24
- return BASE + '/fs/' + clean.split('/').map(encodeURIComponent).join('/')
25
- }
26
-
27
- export function navigate(href: string): void {
28
- bridge?.navigate?.(href)
17
+ export function resolveUrl(url: string): string {
18
+ // File URLs also work during module evaluation, before the host attaches.
19
+ if (url.startsWith('moi:/files/'))
20
+ return resolveWorkspaceUrl(url, { apiBase: APPLET_API_BASE_SENTINEL })
21
+ return bridge?.resolveUrl?.(url) ?? ''
29
22
  }
30
23
 
31
- export function resolveHref(href: string): string {
32
- return bridge?.resolveHref?.(href) ?? ''
24
+ export function navigate(url: string): void {
25
+ bridge?.navigate?.(url)
33
26
  }
34
27
 
35
28
  export function addChatAttachment(input: AttachmentInput): void {
@@ -37,6 +30,6 @@ export function addChatAttachment(input: AttachmentInput): void {
37
30
  }
38
31
 
39
32
  // Keep positional calls working for previously built applets.
40
- export function sendChatMessage(input: AppletChatInput | string, legacyContext?: unknown): void {
33
+ export function sendChatMessage(input: ChatMessageInput | string, legacyContext?: unknown): void {
41
34
  bridge?.sendChatMessage?.(input, legacyContext)
42
35
  }
@@ -1,12 +1,10 @@
1
1
  import { parse, stringify } from 'devalue'
2
2
 
3
- import { APPLET_API_BASE_SENTINEL } from './base'
4
-
5
- const BASE = APPLET_API_BASE_SENTINEL
3
+ import { APPLET_API_BASE_SENTINEL } from '../api-base'
6
4
 
7
5
  export function rpc(module: string, name: string) {
8
6
  return async (...args: unknown[]): Promise<unknown> => {
9
- const res = await fetch(BASE + '/rpc/' + module + '/' + name, {
7
+ const res = await fetch(APPLET_API_BASE_SENTINEL + '/rpc/' + module + '/' + name, {
10
8
  method: 'POST',
11
9
  headers: { 'Content-Type': 'application/json' },
12
10
  body: stringify(args)
@@ -0,0 +1,22 @@
1
+ import type { SelectedSessionScope, WorkspaceEntry } from '@/lib/types'
2
+
3
+ import { publishEvent } from './events'
4
+ import { saveSelectedSession } from './selected-session'
5
+
6
+ // A new chat updates the shared selection only when this tab uses that scope.
7
+ export async function selectChatSession(
8
+ workspace: Pick<WorkspaceEntry, 'id' | 'path'>,
9
+ sessionId: string,
10
+ selectedSessionScope: SelectedSessionScope = 'shared',
11
+ previousSessionId?: string | null
12
+ ): Promise<void> {
13
+ if (selectedSessionScope === 'browser-tab') return
14
+ const selection = await saveSelectedSession(workspace.path, sessionId, previousSessionId)
15
+ if (selection.changed) {
16
+ publishEvent({
17
+ type: 'selected-session:updated',
18
+ workspaceId: workspace.id,
19
+ sessionId: selection.sessionId
20
+ })
21
+ }
22
+ }
package/server/cli.ts CHANGED
@@ -9,7 +9,7 @@ import { dirname, join, resolve } from 'path'
9
9
  import pc from './cli-pc'
10
10
 
11
11
  import { isAgentCaller } from './agent-caller'
12
- import { getAppConfig } from './app-config'
12
+ import { getAppConfig, initializeAppConfig } from './app-config'
13
13
 
14
14
  import { appletSelectorMatches, parseAppletSelector } from '@/lib/applet-selector'
15
15
  import type { AppletSelector } from '@/lib/applet-selector'
@@ -23,6 +23,8 @@ import {
23
23
  } from '@/lib/themes'
24
24
  import type { AgentTheme, ColorTheme, FontTheme, RadiusTheme } from '@/lib/themes'
25
25
  import { parseMoiHref } from '@/lib/navigation'
26
+ import { EXPERIMENTAL_FEATURES, experimentalFlagName } from '@/lib/experimental'
27
+ import type { ExperimentalFeatures } from '@/lib/experimental'
26
28
  import type {
27
29
  AppletLogEntry,
28
30
  ScratchArrowEnd,
@@ -45,6 +47,7 @@ import {
45
47
  resolveCwdWorkspace
46
48
  } from './cli-env'
47
49
  import { columns, keyValue } from './cli-ui'
50
+ import { installCollabSkill } from './collab/skill'
48
51
  import { CONTROL_HOST, CONTROL_PORT, CONTROL_URL, PORT } from './constants'
49
52
  import { type ControlProbe, controlFailureMessage, probeControlServer } from './control-client'
50
53
  import {
@@ -157,14 +160,19 @@ async function openBrowser(url: string) {
157
160
  // (see runDevSupervisor).
158
161
  function spawnServer(
159
162
  cwd: string,
160
- env: Record<string, string | undefined> = process.env
163
+ env: Record<string, string | undefined> = process.env,
164
+ experimentalFlags: string[] = []
161
165
  ): ReturnType<typeof Bun.spawn> {
162
- return Bun.spawn(['bun', import.meta.filename, 'start'], {
166
+ const argv = ['bun', import.meta.filename, 'start', ...experimentalFlags]
167
+ return Bun.spawn(argv, {
163
168
  stdin: 'inherit',
164
169
  stdout: 'inherit',
165
170
  stderr: 'inherit',
166
171
  cwd,
167
- env: { ...env, MOI_SERVER: '1' }
172
+ env: {
173
+ ...env,
174
+ MOI_SERVER: '1'
175
+ }
168
176
  })
169
177
  }
170
178
 
@@ -175,11 +183,12 @@ function spawnServer(
175
183
  // (closing servers + killing function workers), so restarts leak nothing.
176
184
  async function runDevSupervisor(
177
185
  projectRoot: string,
178
- env: Record<string, string | undefined>
186
+ env: Record<string, string | undefined>,
187
+ experimentalFlags: string[]
179
188
  ): Promise<void> {
180
189
  const { watch } = await import('node:fs')
181
190
 
182
- let child = spawnServer(projectRoot, env)
191
+ let child = spawnServer(projectRoot, env, experimentalFlags)
183
192
  let restarting = false
184
193
  let debounce: ReturnType<typeof setTimeout> | undefined
185
194
 
@@ -198,7 +207,7 @@ async function runDevSupervisor(
198
207
  await child.exited
199
208
  clearTimeout(sigkill)
200
209
  restarting = false
201
- child = spawnServer(projectRoot, env)
210
+ child = spawnServer(projectRoot, env, experimentalFlags)
202
211
  }
203
212
 
204
213
  for (const dir of ['server', 'lib']) {
@@ -334,6 +343,11 @@ const init = defineCommand({
334
343
  default: false,
335
344
  description: 'Start the web server if not already running'
336
345
  },
346
+ 'experimental-collab': {
347
+ type: 'boolean',
348
+ default: false,
349
+ description: 'Include the optional collaboration guide and applet types'
350
+ },
337
351
  id: {
338
352
  type: 'string',
339
353
  description:
@@ -395,14 +409,23 @@ const init = defineCommand({
395
409
  // Provision: bundled skills + the `.moi/` bootstrap (widgets dir +
396
410
  // package.json + bun install). An existing `.moi/` is left untouched.
397
411
  console.log()
398
- const { scaffold, skillsDir } = await provisionWorkspace(target, type)
412
+ const { scaffold, skillsDir, installLogPath } = await provisionWorkspace(target, type)
413
+ if (args['experimental-collab']) {
414
+ const { referencePath } = await installCollabSkill(target, type)
415
+ console.log(pc.dim(' Collaboration guide installed to ' + referencePath))
416
+ console.log(pc.dim(' Live presence requires moi start --experimental-collab'))
417
+ }
399
418
  if (scaffold !== 'exists') {
400
419
  if (scaffold === 'installing') {
401
420
  console.log(pc.dim(' Widget dependencies still installing in .moi/ (background)'))
421
+ console.log(pc.dim(' Install log: ' + installLogPath))
402
422
  } else if (scaffold === 0) {
403
423
  console.log(pc.dim(' Installed widget dependencies in .moi/'))
404
424
  } else {
405
- console.warn(pc.yellow(' bun install failed — run it manually in .moi/'))
425
+ console.warn(
426
+ pc.yellow(` bun install failed (exit ${scaffold}) — run it manually in .moi/`)
427
+ )
428
+ console.warn(pc.dim(' Install log: ' + installLogPath))
406
429
  }
407
430
  }
408
431
 
@@ -468,15 +491,38 @@ const init = defineCommand({
468
491
  }
469
492
  })
470
493
 
494
+ const experimentalArgs = Object.fromEntries(
495
+ EXPERIMENTAL_FEATURES.map(feature => {
496
+ const name = experimentalFlagName(feature)
497
+ const label = name.slice('experimental-'.length).replaceAll('-', ' ')
498
+ return [name, { type: 'boolean' as const, description: `Enable experimental ${label}` }]
499
+ })
500
+ )
501
+
471
502
  const start = defineCommand({
472
503
  meta: { name: 'start', description: 'Start the moi web server' },
473
504
  args: {
474
505
  port: {
475
506
  type: 'string',
476
507
  description: 'HTTP port to listen on (default: 13337)'
477
- }
508
+ },
509
+ ...experimentalArgs
478
510
  },
479
- async run({ args }) {
511
+ async run({ args, rawArgs }) {
512
+ const knownFlags = new Set(EXPERIMENTAL_FEATURES.map(experimentalFlagName))
513
+ for (const arg of rawArgs) {
514
+ if (arg.startsWith('--experimental-') && !knownFlags.has(arg.slice(2))) {
515
+ throw new Error(`Unknown experimental feature: ${arg.slice('--experimental-'.length)}`)
516
+ }
517
+ }
518
+ const experimental: Partial<ExperimentalFeatures> = {}
519
+ const experimentalFlags: string[] = []
520
+ for (const feature of EXPERIMENTAL_FEATURES) {
521
+ const flag = experimentalFlagName(feature)
522
+ if (args[flag] !== true) continue
523
+ experimental[feature] = true
524
+ experimentalFlags.push(`--${flag}`)
525
+ }
480
526
  const projectRoot = join(import.meta.dir, '..')
481
527
  // Undocumented: --dev runs the watch-and-full-restart dev supervisor.
482
528
  const dev = process.argv.includes('--dev')
@@ -529,17 +575,20 @@ const start = defineCommand({
529
575
  ...(debug ? { MOI_DEBUG: '1' } : {})
530
576
  }
531
577
  if (dev) {
532
- await runDevSupervisor(projectRoot, env)
578
+ await runDevSupervisor(projectRoot, env, experimentalFlags)
533
579
  return
534
580
  }
535
581
  const cwd = serverCwd(projectRoot, dev)
536
- const proc = spawnServer(cwd, env)
537
- process.exit(await superviseServerUpdates(proc, () => spawnServer(cwd, env)))
582
+ const proc = spawnServer(cwd, env, experimentalFlags)
583
+ process.exit(
584
+ await superviseServerUpdates(proc, () => spawnServer(cwd, env, experimentalFlags))
585
+ )
538
586
  }
539
587
 
540
588
  // This IS the server process (MOI_SERVER=1). cwd is the package root when the
541
589
  // dev bundler runs (bunfig loaded at Bun startup) or a neutral dir for a
542
590
  // prebuilt install — see serverCwd().
591
+ initializeAppConfig(experimental)
543
592
  try {
544
593
  await import('./web')
545
594
  } catch (err) {
@@ -1358,14 +1407,22 @@ const openclawInit = defineCommand({
1358
1407
  // with the highest precedence, so these win over any same-named bundled or
1359
1408
  // per-user skill), plus the `.moi/` bootstrap — the widgets skill assumes
1360
1409
  // the folder and its dependencies exist. Existing `.moi/` stays untouched.
1361
- const { scaffold, skillsDir: skillsRoot } = await provisionWorkspace(target.path, 'openclaw')
1410
+ const {
1411
+ scaffold,
1412
+ skillsDir: skillsRoot,
1413
+ installLogPath
1414
+ } = await provisionWorkspace(target.path, 'openclaw')
1362
1415
  if (scaffold !== 'exists') {
1363
1416
  if (scaffold === 'installing') {
1364
1417
  console.log('\n' + pc.dim(' Widget dependencies still installing in .moi/ (background)'))
1418
+ console.log(pc.dim(' Install log: ' + installLogPath))
1365
1419
  } else if (scaffold === 0) {
1366
1420
  console.log('\n' + pc.dim(' Installed widget dependencies in .moi/'))
1367
1421
  } else {
1368
- console.warn('\n' + pc.yellow(' bun install failed — run it manually in .moi/'))
1422
+ console.warn(
1423
+ '\n' + pc.yellow(` bun install failed (exit ${scaffold}) — run it manually in .moi/`)
1424
+ )
1425
+ console.warn(pc.dim(' Install log: ' + installLogPath))
1369
1426
  }
1370
1427
  }
1371
1428
 
@@ -1496,14 +1553,22 @@ const hermesInit = defineCommand({
1496
1553
  // dir with the highest precedence, so these win over bundled ones), plus
1497
1554
  // the `.moi/` bootstrap. The default profile has no workspace directory
1498
1555
  // until now — provisionWorkspace creates it.
1499
- const { scaffold, skillsDir: skillsRoot } = await provisionWorkspace(target.path, 'hermes')
1556
+ const {
1557
+ scaffold,
1558
+ skillsDir: skillsRoot,
1559
+ installLogPath
1560
+ } = await provisionWorkspace(target.path, 'hermes')
1500
1561
  if (scaffold !== 'exists') {
1501
1562
  if (scaffold === 'installing') {
1502
1563
  console.log('\n' + pc.dim(' Widget dependencies still installing in .moi/ (background)'))
1564
+ console.log(pc.dim(' Install log: ' + installLogPath))
1503
1565
  } else if (scaffold === 0) {
1504
1566
  console.log('\n' + pc.dim(' Installed widget dependencies in .moi/'))
1505
1567
  } else {
1506
- console.warn('\n' + pc.yellow(' bun install failed — run it manually in .moi/'))
1568
+ console.warn(
1569
+ '\n' + pc.yellow(` bun install failed (exit ${scaffold}) — run it manually in .moi/`)
1570
+ )
1571
+ console.warn(pc.dim(' Install log: ' + installLogPath))
1507
1572
  }
1508
1573
  }
1509
1574
 
@@ -2435,7 +2500,7 @@ async function runSkillUpdate(cwd: string): Promise<void> {
2435
2500
  // Type-aware: an OpenClaw workspace keeps its skills in `skills/`, so the
2436
2501
  // update must target the same dir the agent actually loads from.
2437
2502
  const { root, type } = await resolveWorkspace(cwd)
2438
- const { before, status, changedSkills, appletTypesWritten } = await updateWorkspaceSkills(
2503
+ const { before, status, changedSkills, updatedAppletTypes } = await updateWorkspaceSkills(
2439
2504
  root,
2440
2505
  type ?? 'claude-code'
2441
2506
  )
@@ -2444,8 +2509,8 @@ async function runSkillUpdate(cwd: string): Promise<void> {
2444
2509
 
2445
2510
  console.log('\n' + pc.green('✓') + ' ' + heading + pc.bold(root) + '\n')
2446
2511
  printSkillUpdateTable(before, after, changedSkills)
2447
- if (appletTypesWritten) {
2448
- console.log(pc.dim(' Ambient applet types regenerated: ') + pc.bold('.moi/applet-env.d.ts\n'))
2512
+ for (const file of updatedAppletTypes) {
2513
+ console.log(pc.dim(' Applet types regenerated: ') + pc.bold(`.moi/${file}\n`))
2449
2514
  }
2450
2515
  }
2451
2516
 
@@ -0,0 +1,78 @@
1
+ import { createRemoteJWKSet, customFetch, errors, jwtVerify } from 'jose'
2
+ import type { FetchImplementation } from 'jose'
3
+
4
+ import { colorForId } from '@/lib/collab/colors'
5
+ import { isUserProfile } from '@/lib/collab/protocol'
6
+ import type { ProxyUserState, UserProfile } from '@/lib/collab/types'
7
+
8
+ import { type CloudflareAccessConfig, getAppConfig } from '../app-config'
9
+
10
+ // Cloudflare Access adds a signed application token (an RS256 JWT) to every
11
+ // request it lets through. Only the verified signature, issuer, and audience
12
+ // make the claimed user trustworthy: anyone who reaches the origin some other way
13
+ // can send the header too.
14
+ // https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/validating-json/
15
+ export const ACCESS_TOKEN_HEADER = 'cf-access-jwt-assertion'
16
+ // Browsers hold the same application token in this cookie on the app's domain.
17
+ export const ACCESS_TOKEN_COOKIE = 'CF_Authorization'
18
+
19
+ // Failing to load the team's keys is a setup problem worth logging; a bad
20
+ // token is expected noise.
21
+ const KEY_ERRORS = new Set(['ERR_JOSE_GENERIC', 'ERR_JWKS_INVALID', 'ERR_JWKS_TIMEOUT'])
22
+
23
+ export type AccessUser = { id: string; email: string }
24
+ export type AccessVerifier = (token: string) => Promise<AccessUser | null>
25
+
26
+ // jose caches the team's signing keys for ten minutes and refetches them for
27
+ // an unknown key id at most every 30 seconds, which covers key rotation.
28
+ export function accessVerifier(
29
+ config: CloudflareAccessConfig,
30
+ fetch?: FetchImplementation
31
+ ): AccessVerifier {
32
+ const url = new URL('/cdn-cgi/access/certs', config.teamDomain)
33
+ const keys = createRemoteJWKSet(url, fetch ? { [customFetch]: fetch } : {})
34
+ return async token => {
35
+ try {
36
+ const { payload } = await jwtVerify(token, keys, {
37
+ issuer: config.teamDomain,
38
+ audience: [...config.audience],
39
+ algorithms: ['RS256'],
40
+ requiredClaims: ['exp'],
41
+ clockTolerance: 60
42
+ })
43
+ // Service tokens have an empty `sub` and no email: there is no person.
44
+ const { sub, email } = payload
45
+ return sub && typeof email === 'string' && email ? { id: sub, email } : null
46
+ } catch (error) {
47
+ if (!(error instanceof errors.JOSEError) || KEY_ERRORS.has(error.code)) {
48
+ console.error(`[moi] Cloudflare Access: could not load signing keys from ${url}: ${error}`)
49
+ }
50
+ return null
51
+ }
52
+ }
53
+ }
54
+
55
+ // Access tokens carry an id and an email but no display name, so the profile
56
+ // has none and labels fall back to the email. The color is a stable pick from the id.
57
+ export function accessProfile({ id, email }: AccessUser): UserProfile | null {
58
+ const profile: UserProfile = { id, color: colorForId(id), email }
59
+ return isUserProfile(profile) ? profile : null
60
+ }
61
+
62
+ // The verifier and its key cache live as long as the resolved config object.
63
+ let current: { config: CloudflareAccessConfig; verify: AccessVerifier } | null = null
64
+
65
+ // Who the configured proxy says sent this request. Without Cloudflare Access
66
+ // configured, moi trusts no proxy and every request resolves to no provider.
67
+ export async function proxyUserState(req: Request): Promise<ProxyUserState> {
68
+ const config = getAppConfig().cloudflareAccess
69
+ if (!config) return {}
70
+ if (current?.config !== config) current = { config, verify: accessVerifier(config) }
71
+ // The header Access adds wins; the cookie covers proxies that drop it.
72
+ const token =
73
+ req.headers.get(ACCESS_TOKEN_HEADER) ??
74
+ new Bun.CookieMap(req.headers.get('cookie') ?? '').get(ACCESS_TOKEN_COOKIE)
75
+ const user = token ? await current.verify(token) : null
76
+ const profile = user ? accessProfile(user) : null
77
+ return profile ? { provider: 'cloudflare-access', profile } : { provider: 'cloudflare-access' }
78
+ }
@@ -0,0 +1,18 @@
1
+ import type { WorkspaceType } from '@/lib/types'
2
+
3
+ import { getAppConfig } from '../app-config'
4
+ import { collabSkillReferencePath } from './skill'
5
+
6
+ // Only an explicit startup CLI flag enables this process setting.
7
+ export function isCollabEnabled(): boolean {
8
+ return getAppConfig().experimental.collab
9
+ }
10
+
11
+ export async function getCollabReferencePath(
12
+ workspacePath: string,
13
+ type?: WorkspaceType
14
+ ): Promise<string | undefined> {
15
+ if (!isCollabEnabled()) return undefined
16
+ const referencePath = collabSkillReferencePath(workspacePath, type)
17
+ return (await Bun.file(referencePath).exists()) ? referencePath : undefined
18
+ }