From 86aafd99c617ebfecc105f0d14f6ee9e49500dcc Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 00:05:33 -0800 Subject: [PATCH 01/46] feat(cloud): read a sleeping workspace from an E2EE snapshot (desktop + phone clients) --- mobile/src/cloud/CloudReadSnapshotSection.tsx | 286 +++++++++++++++ .../src/cloud/CloudReadSnapshotSessions.tsx | 152 ++++++++ mobile/src/cloud/CloudWorkspaceScreen.tsx | 19 +- .../src/cloud/cloud-control-plane-client.ts | 8 +- .../src/cloud/cloud-control-plane-request.ts | 2 +- mobile/src/cloud/cloud-device-identity.ts | 3 + .../src/cloud/cloud-read-snapshot-styles.ts | 96 +++++ mobile/src/cloud/cloud-read-snapshot.test.ts | 297 +++++++++++++++ mobile/src/cloud/cloud-read-snapshot.ts | 165 +++++++++ mobile/src/cloud/cloud-reader-key.test.ts | 80 +++++ mobile/src/cloud/cloud-reader-key.ts | 104 ++++++ mobile/src/cloud/cloud-sealed-grant.ts | 6 +- mobile/src/cloud/use-cloud-read-snapshot.ts | 38 ++ mobile/src/cloud/use-cloud-workspaces.ts | 3 + mobile/src/home/MobileHomeCloudSection.tsx | 14 +- mobile/src/i18n/locales/en.json | 48 ++- .../cloud-read-snapshot-reader.test.ts | 234 ++++++++++++ .../cloud-read-snapshot-reader.ts | 164 +++++++++ .../cloud-reader-key-store.test.ts | 101 ++++++ .../cloud-reader-key-store.ts | 166 +++++++++ .../cloud-workspaces-client.test.ts | 115 ++++++ .../cloud-workspaces-client.ts | 47 ++- .../cloud-workspaces-service.ts | 24 +- .../read-snapshot-sealer.test-fixture.ts | 78 ++++ .../cloud-offline-cloud-read.test.ts | 36 ++ .../cloud-offline-cloud-read.ts | 82 +++++ .../hosted-sandbox/cloud-offline-service.ts | 20 +- .../cloud-offline-snapshot-merge.test.ts | 113 ++++++ .../cloud-offline-snapshot-merge.ts | 62 ++++ .../hosted-sandbox/cloud-offline-snapshot.ts | 3 +- .../hosted-sandbox/hosted-sandbox-install.ts | 6 + src/main/ipc/cloud-workspaces.ts | 42 ++- .../orca-profiles/profile-cloud-service.ts | 3 + src/preload/api/cloud-workspaces-api.ts | 3 + src/preload/api/cloud-workspaces-bridge.ts | 1 + .../CloudReadSnapshotSheet.tsx | 58 +++ .../CloudWorkspaceRow.fixture.tsx | 1 + .../cloud-workspaces/CloudWorkspaceRow.tsx | 13 +- .../CloudWorkspaceRowMenu.tsx | 29 +- .../CloudWorkspacesHome.fixture.tsx | 99 +++++ .../cloud-workspaces/CloudWorkspacesHome.tsx | 18 +- .../use-cloud-read-snapshot.ts | 79 ++++ .../components/orca-cloud/CloudGitChanges.tsx | 26 +- .../orca-cloud/CloudWorkspaceHeader.tsx | 7 +- .../offline/CloudOfflineChatPanel.tsx | 3 +- .../CloudWorkspaceOfflineView.fixture.tsx | 41 +++ .../offline/CloudWorkspaceOfflineView.tsx | 217 +++++------ .../read-snapshot/CloudReadPrLink.tsx | 56 +++ .../read-snapshot/CloudReadSessions.tsx | 135 +++++++ .../CloudReadSnapshotView.fixture.tsx | 179 +++++++++ .../read-snapshot/CloudReadSnapshotView.tsx | 200 +++++++++++ .../cloud-read-snapshot-format.ts | 85 +++++ .../src/i18n/en-runtime-required.json | 6 + src/renderer/src/i18n/locales/en.json | 43 ++- .../preload-api/web-cloud-workspaces-api.ts | 1 + .../cloud-workspaces/cloud-workspaces-wire.ts | 33 +- .../cloud-workspaces/read-snapshot-state.ts | 18 + src/shared/cloud-workspaces/read-snapshot.ts | 340 ++++++++++++++++++ .../cloud-workspace-offline-api.ts | 32 +- 59 files changed, 4198 insertions(+), 142 deletions(-) create mode 100644 mobile/src/cloud/CloudReadSnapshotSection.tsx create mode 100644 mobile/src/cloud/CloudReadSnapshotSessions.tsx create mode 100644 mobile/src/cloud/cloud-read-snapshot-styles.ts create mode 100644 mobile/src/cloud/cloud-read-snapshot.test.ts create mode 100644 mobile/src/cloud/cloud-read-snapshot.ts create mode 100644 mobile/src/cloud/cloud-reader-key.test.ts create mode 100644 mobile/src/cloud/cloud-reader-key.ts create mode 100644 mobile/src/cloud/use-cloud-read-snapshot.ts create mode 100644 src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts create mode 100644 src/main/cloud-workspaces/cloud-read-snapshot-reader.ts create mode 100644 src/main/cloud-workspaces/cloud-reader-key-store.test.ts create mode 100644 src/main/cloud-workspaces/cloud-reader-key-store.ts create mode 100644 src/main/cloud-workspaces/cloud-workspaces-client.test.ts create mode 100644 src/main/cloud-workspaces/read-snapshot-sealer.test-fixture.ts create mode 100644 src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts create mode 100644 src/main/hosted-sandbox/cloud-offline-cloud-read.ts create mode 100644 src/main/hosted-sandbox/cloud-offline-snapshot-merge.test.ts create mode 100644 src/main/hosted-sandbox/cloud-offline-snapshot-merge.ts create mode 100644 src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx create mode 100644 src/renderer/src/components/cloud-workspaces/use-cloud-read-snapshot.ts create mode 100644 src/renderer/src/components/orca-cloud/read-snapshot/CloudReadPrLink.tsx create mode 100644 src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx create mode 100644 src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx create mode 100644 src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx create mode 100644 src/renderer/src/components/orca-cloud/read-snapshot/cloud-read-snapshot-format.ts create mode 100644 src/shared/cloud-workspaces/read-snapshot-state.ts create mode 100644 src/shared/cloud-workspaces/read-snapshot.ts diff --git a/mobile/src/cloud/CloudReadSnapshotSection.tsx b/mobile/src/cloud/CloudReadSnapshotSection.tsx new file mode 100644 index 00000000000..9f8ec991ad4 --- /dev/null +++ b/mobile/src/cloud/CloudReadSnapshotSection.tsx @@ -0,0 +1,286 @@ +import { ExternalLink } from 'lucide-react-native' +import { useEffect, useRef, useState } from 'react' +import { Animated, Easing, Linking, Pressable, Text, View } from 'react-native' +import type { + ReadSnapshot, + ReadSnapshotGit, + ReadSnapshotPr +} from '../../../src/shared/cloud-workspaces/read-snapshot' +import type { Translate } from '../i18n/mobile-i18n' +import { getUiIntlLocale } from '../i18n/ui-intl-locale' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { useReducedMotionEnabled } from '../platform/use-reduced-motion' +import { colors } from '../theme/mobile-theme' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { formatTimeAgo } from '../worktree/agent-row-display' +import { CloudErrorBanner } from './CloudErrorBanner' +import { CloudReadSnapshotSessions } from './CloudReadSnapshotSessions' +import type { CloudReadSnapshotResult } from './cloud-read-snapshot' +import { readSnapshotStyles as styles } from './cloud-read-snapshot-styles' +import { cloudWorkspaceScreenStyles as screen } from './cloud-workspace-screen-styles' + +const GIT_PATHS_SHOWN = 5 + +export function formatReadSnapshotAbsolute(at: number): string { + try { + return new Intl.DateTimeFormat(getUiIntlLocale(), { + dateStyle: 'medium', + timeStyle: 'short' + }).format(at) + } catch { + return new Date(at).toLocaleString() + } +} + +/** "As of 5m ago" (relative); the absolute time is the long-press / screen-reader form. */ +export function formatReadSnapshotAsOf(at: number, now: number, t: Translate): string { + return now - at < 60_000 + ? t('cloud.snapshot.asOfJustNow', 'As of just now') + : t('cloud.snapshot.asOf', 'As of {{ago}} ago', { ago: formatTimeAgo(at, now) }) +} + +/** + * The asleep workspace's read-only "Latest from this workspace": what its PR, agents and git looked + * like when it went to sleep, opened on this phone. Never wakes the sandbox. + */ +export function CloudReadSnapshotSection(props: { + result: CloudReadSnapshotResult | undefined + /** When the result was fetched: the clock "As of" counts from (no impure clock read in render). */ + fetchedAt: number + loading: boolean + onRetry: () => void +}) { + useMobileColorScheme() + const t = useMobileTranslation() + const { result } = props + // Gone or not openable: the screen itself says so; this area has nothing to add. + if (!props.loading && result?.state === 'not_found') { + return null + } + return ( + + + {t('cloud.snapshot.heading', 'Latest from this workspace')} + + {props.loading || !result ? ( + + ) : result.state === 'ready' ? ( + + ) : result.state === 'no_snapshot' ? ( + + ) : result.state === 'not_sealed_for_key' ? ( + + ) : ( + + )} + + ) +} + +function Notice({ text }: { text: string }) { + return ( + + {text} + + ) +} + +function SnapshotSkeleton() { + const t = useMobileTranslation() + const reducedMotion = useReducedMotionEnabled() !== false + const pulse = useRef(new Animated.Value(1)).current + useEffect(() => { + if (reducedMotion) { + pulse.setValue(1) + return + } + const loop = Animated.loop( + Animated.sequence([ + Animated.timing(pulse, { + toValue: 0.45, + duration: 800, + easing: Easing.inOut(Easing.quad), + useNativeDriver: true + }), + Animated.timing(pulse, { + toValue: 1, + duration: 800, + easing: Easing.inOut(Easing.quad), + useNativeDriver: true + }) + ]) + ) + loop.start() + return () => loop.stop() + }, [reducedMotion, pulse]) + return ( + + + + + + ) +} + +function SnapshotBody({ snapshot, now }: { snapshot: ReadSnapshot; now: number }) { + const t = useMobileTranslation() + const [absolute, setAbsolute] = useState(false) + const exact = formatReadSnapshotAbsolute(snapshot.capturedAt) + const empty = !snapshot.pr && !snapshot.git && snapshot.sessions.length === 0 + return ( + + setAbsolute((value) => !value)} + style={styles.asOfButton} + > + + {absolute + ? t('cloud.snapshot.asOfExact', 'As of {{time}}', { time: exact }) + : formatReadSnapshotAsOf(snapshot.capturedAt, Math.max(now, snapshot.capturedAt), t)} + + + + {snapshot.pr ? : null} + + {snapshot.git ? : null} + {empty ? ( + + ) : null} + + + ) +} + +function prStateLabel(pr: ReadSnapshotPr, t: Translate): string { + switch (pr.state.toLowerCase()) { + case 'merged': + return t('cloud.snapshot.pr.merged', 'Merged') + case 'closed': + return t('cloud.snapshot.pr.closed', 'Closed') + case 'draft': + return t('cloud.snapshot.pr.draft', 'Draft') + default: + return t('cloud.snapshot.pr.open', 'Open') + } +} + +function prChecksLabel(pr: ReadSnapshotPr, t: Translate): string | null { + switch (pr.checksStatus?.toLowerCase()) { + case 'success': + case 'passed': + case 'passing': + return t('cloud.snapshot.checks.passing', 'Checks passing') + case 'failure': + case 'failed': + case 'failing': + return t('cloud.snapshot.checks.failing', 'Checks failing') + case 'pending': + case 'running': + return t('cloud.snapshot.checks.pending', 'Checks running') + default: + return pr.checksSummary + } +} + +function PrCard({ pr }: { pr: ReadSnapshotPr }) { + const t = useMobileTranslation() + const failing = /fail/i.test(pr.checksStatus ?? '') + const meta = [prStateLabel(pr, t), prChecksLabel(pr, t)].filter(Boolean).join(' · ') + const title = t('cloud.snapshot.pr.title', '#{{number}} {{title}}', { + number: pr.number, + title: pr.title + }) + return ( + + void Linking.openURL(pr.url).catch(() => undefined)} + style={({ pressed }) => [styles.row, pressed && screen.pressed]} + > + + + {title} + + + {meta} + + + + + + ) +} + +function GitCard({ git }: { git: ReadSnapshotGit }) { + const t = useMobileTranslation() + const count = git.changeCount + const files = + count === 1 + ? t('cloud.snapshot.git.files_one', '{{count}} changed file', { count }) + : t('cloud.snapshot.git.files_other', '{{count}} changed files', { count }) + const more = count - Math.min(git.changes.length, GIT_PATHS_SHOWN) + return ( + + + {git.branch ? ( + + {git.branch} + + ) : null} + + + {count === 0 ? t('cloud.snapshot.git.clean', 'No uncommitted changes') : files} + + {git.added !== null ? ( + +{git.added} + ) : null} + {git.removed !== null ? ( + −{git.removed} + ) : null} + + {git.changes.slice(0, GIT_PATHS_SHOWN).map((change) => ( + + {change.path} + + ))} + {more > 0 ? ( + + {more === 1 + ? t('cloud.snapshot.git.more_one', 'and {{count}} more', { count: more }) + : t('cloud.snapshot.git.more_other', 'and {{count}} more', { count: more })} + + ) : null} + + + ) +} diff --git a/mobile/src/cloud/CloudReadSnapshotSessions.tsx b/mobile/src/cloud/CloudReadSnapshotSessions.tsx new file mode 100644 index 00000000000..064ffcdbfda --- /dev/null +++ b/mobile/src/cloud/CloudReadSnapshotSessions.tsx @@ -0,0 +1,152 @@ +import { ChevronDown, ChevronRight } from 'lucide-react-native' +import { useState } from 'react' +import { Pressable, Text, View } from 'react-native' +import type { + ReadSnapshotMessage, + ReadSnapshotSession +} from '../../../src/shared/cloud-workspaces/read-snapshot' +import type { Translate } from '../i18n/mobile-i18n' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { MobileNativeChatMarkdown } from '../session/native-chat/MobileNativeChatMarkdown' +import { colors } from '../theme/mobile-theme' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { readSnapshotStyles as styles } from './cloud-read-snapshot-styles' +import { cloudWorkspaceScreenStyles as screen } from './cloud-workspace-screen-styles' + +export function readSnapshotSessionStatus( + session: Pick, + t: Translate +): string | null { + switch (session.status) { + case 'working': + return t('cloud.snapshot.status.working', 'Working') + case 'attention': + return t('cloud.snapshot.status.attention', 'Needs you') + case 'idle': + return session.turnOutcome + ? t('cloud.snapshot.status.done', 'Done') + : t('cloud.snapshot.status.idle', 'Idle') + case 'unknown': + return null + } +} + +function agentName(agent: string | null, t: Translate): string { + const trimmed = agent?.trim() + return trimmed + ? trimmed.charAt(0).toUpperCase() + trimmed.slice(1) + : t('cloud.snapshot.agentFallback', 'Agent') +} + +/** Agents as they were when the workspace went to sleep; each opens to the tail of its chat. */ +export function CloudReadSnapshotSessions({ sessions }: { sessions: ReadSnapshotSession[] }) { + useMobileColorScheme() + const t = useMobileTranslation() + const [open, setOpen] = useState>(new Set()) + if (sessions.length === 0) { + return null + } + const toggle = (id: string) => + setOpen((current) => { + const next = new Set(current) + if (!next.delete(id)) { + next.add(id) + } + return next + }) + return ( + + {sessions.map((session, index) => { + const expanded = open.has(session.sessionId) + const name = agentName(session.agent, t) + const status = readSnapshotSessionStatus(session, t) + const title = session.title?.trim() || name + const meta = [title === name ? null : name, status].filter(Boolean).join(' · ') + const Chevron = expanded ? ChevronDown : ChevronRight + return ( + 0 ? styles.rowDivider : undefined}> + toggle(session.sessionId)} + style={({ pressed }) => [styles.row, pressed && screen.pressed]} + > + + + {title} + + {meta ? ( + + {meta} + + ) : null} + + + + {expanded ? : null} + + ) + })} + + ) +} + +function Transcript({ session, agent }: { session: ReadSnapshotSession; agent: string }) { + const t = useMobileTranslation() + return ( + + {session.truncated ? ( + + {t('cloud.snapshot.truncated', 'Earlier messages aren’t in this copy.')} + + ) : null} + {session.messages.length === 0 ? ( + + {t('cloud.snapshot.noMessages', 'No messages in this chat yet.')} + + ) : ( + session.messages.map((message) => ( + + )) + )} + + ) +} + +function Bubble({ message, agent }: { message: ReadSnapshotMessage; agent: string }) { + const t = useMobileTranslation() + if (message.role === 'user') { + return ( + + {t('cloud.snapshot.role.you', 'You')} + + {message.text} + + + ) + } + if (message.role === 'system') { + return ( + + {t('cloud.snapshot.role.system', 'System')} + + {message.text} + + + ) + } + return ( + + {agent} + + + ) +} diff --git a/mobile/src/cloud/CloudWorkspaceScreen.tsx b/mobile/src/cloud/CloudWorkspaceScreen.tsx index d040de7a1f2..2d6c1b2b0e6 100644 --- a/mobile/src/cloud/CloudWorkspaceScreen.tsx +++ b/mobile/src/cloud/CloudWorkspaceScreen.tsx @@ -20,6 +20,7 @@ import { CloudAgentStartedCard } from './CloudAgentStartedCard' import { CloudErrorBanner } from './CloudErrorBanner' import { CloudPromptComposer } from './CloudPromptComposer' import { CloudPromptQueueSection } from './CloudPromptQueueSection' +import { CloudReadSnapshotSection } from './CloudReadSnapshotSection' import { CloudStatusCard } from './CloudStatusCard' import { CloudWorkspaceActions } from './CloudWorkspaceActions' import { archiveCloudWorkspace, sleepCloudWorkspace } from './cloud-control-plane-client' @@ -41,6 +42,7 @@ import { cloudScrollBottomPadding, cloudWorkspaceScreenStyles as styles } from './cloud-workspace-screen-styles' +import { useCloudReadSnapshot } from './use-cloud-read-snapshot' import { useCloudWorkspaceRun } from './use-cloud-workspace-run' import { useCloudEnrollment, @@ -64,6 +66,9 @@ export function CloudWorkspaceScreen({ const enrollment = useCloudEnrollment() const { workspace, isPending, isFetching, refetch } = useCloudWorkspace(enrollment, sandboxId) const live = useCloudWorkspaceLiveStatus(sandboxId, workspace?.status === 'running') + // Asleep: read its last sealed snapshot instead of waking it. Nothing here ever wakes it. + const asleep = workspace?.status === 'sleeping' + const snapshot = useCloudReadSnapshot(sandboxId, asleep, workspace?.readSnapshotAt ?? null) const invalidate = useInvalidateCloudWorkspaces() const { run, active, start, fail, clearError, openSession } = useCloudWorkspaceRun( sandboxId, @@ -196,7 +201,9 @@ export function CloudWorkspaceScreen({ ? t('cloud.status.archived', 'Archived') : awake ? t('cloud.action.open', 'Open workspace') - : t('cloud.action.wakeOpen', 'Wake and open workspace') + : asleep + ? t('cloud.action.wakeToContinue', 'Wake to continue') + : t('cloud.action.wakeOpen', 'Wake and open workspace') const primaryDisabled = active || unavailable return ( @@ -233,6 +240,16 @@ export function CloudWorkspaceScreen({ onRetry={run.retry ? () => void start(run.retry ?? 'open') : null} /> ) : null} + {asleep ? ( + void snapshot.refetch()} + /> + ) : null} diff --git a/mobile/src/cloud/cloud-control-plane-client.ts b/mobile/src/cloud/cloud-control-plane-client.ts index f04d1e612a2..07efea2c30d 100644 --- a/mobile/src/cloud/cloud-control-plane-client.ts +++ b/mobile/src/cloud/cloud-control-plane-client.ts @@ -41,6 +41,8 @@ export type CloudWorkspace = { /** Compute spend so far, when the registry reports it. */ cost: { usd: number; usdPerHour: number | null } | null createdByUserId: string | null + /** When the last sleeping read snapshot was stored (ms); null when none or unknown. */ + readSnapshotAt: number | null } const SANDBOX_STATUS: Record = { creating: 'creating', @@ -95,7 +97,8 @@ function fromRegistry(row: TeamWorkspace): CloudWorkspace { usd: row.cost.totalUsdMicros / 1_000_000, usdPerHour: row.cost.rateUsdMicrosPerHour ? row.cost.rateUsdMicrosPerHour / 1_000_000 : null }, - createdByUserId: row.createdBy + createdByUserId: row.createdBy, + readSnapshotAt: row.readSnapshotAt ?? null } } @@ -110,7 +113,8 @@ function fromSandbox(row: z.infer): CloudWorkspace { createdAt: row.createdAt, lastActivityAt: null, cost: null, - createdByUserId: null + createdByUserId: null, + readSnapshotAt: null } } // Lists archived rows as `archived` rather than folding them into `suspended` (W2 lifecycle). diff --git a/mobile/src/cloud/cloud-control-plane-request.ts b/mobile/src/cloud/cloud-control-plane-request.ts index b8f552dc4d1..e7c8ec34351 100644 --- a/mobile/src/cloud/cloud-control-plane-request.ts +++ b/mobile/src/cloud/cloud-control-plane-request.ts @@ -23,7 +23,7 @@ const ErrorBodySchema = z.object({ error: z.string(), reason: z.string().optiona export async function cloudRequest( plane: CloudControlPlane, - method: 'GET' | 'POST' | 'PATCH' | 'DELETE', + method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', path: string, schema: z.ZodType, init: { diff --git a/mobile/src/cloud/cloud-device-identity.ts b/mobile/src/cloud/cloud-device-identity.ts index 820d32fe430..239d50d67f2 100644 --- a/mobile/src/cloud/cloud-device-identity.ts +++ b/mobile/src/cloud/cloud-device-identity.ts @@ -3,6 +3,7 @@ import nacl from 'tweetnacl' import { z } from 'zod' import { randomBytes } from '../transport/encryption/e2ee' import { decodeBase64Bytes, encodeBase64Bytes } from '../transport/encryption/base64-byte-codec' +import { clearCloudReaderKey } from './cloud-reader-key' // This phone's own Orca Cloud key and enrollment. Kept off iCloud Keychain and backups, like pairing // credentials, so a restored phone has to be enrolled again rather than inheriting access. @@ -91,6 +92,8 @@ export async function saveCloudEnrollment(enrollment: CloudEnrollment): Promise< export async function clearCloudEnrollment(): Promise { const seed = randomBytes(32) await write(seed, null) + // The reader key goes with the session: snapshots sealed to it stay unreadable here. + await clearCloudReaderKey().catch(() => undefined) cached = Promise.resolve(fromSeed(seed, null)) listeners.forEach((listener) => listener()) } diff --git a/mobile/src/cloud/cloud-read-snapshot-styles.ts b/mobile/src/cloud/cloud-read-snapshot-styles.ts new file mode 100644 index 00000000000..3eb5e7c3505 --- /dev/null +++ b/mobile/src/cloud/cloud-read-snapshot-styles.ts @@ -0,0 +1,96 @@ +import { StyleSheet } from 'react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' + +// The asleep workspace's read-only "Latest from this workspace" area; scheme-aware like every cloud card. +export const readSnapshotStyles = themedStyleSheet(() => ({ + asOf: { + fontSize: 13, + lineHeight: 18, + color: colors.textMuted, + marginBottom: spacing.sm, + paddingHorizontal: spacing.xs + }, + asOfButton: { alignSelf: 'flex-start', minHeight: 32, justifyContent: 'center' }, + stack: { gap: spacing.sm }, + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md, + minHeight: 52 + }, + rowDivider: { + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle + }, + rowText: { flex: 1, gap: 2 }, + rowTitle: { fontSize: 15, lineHeight: 20, color: colors.textPrimary }, + rowMeta: { fontSize: 13, lineHeight: 18, color: colors.textSecondary }, + rowMetaAttention: { color: colors.statusAmber }, + mono: { + fontFamily: typography.monoFamily, + fontSize: 12, + lineHeight: 17, + color: colors.textSecondary + }, + added: { color: colors.gitDecorationAdded }, + removed: { color: colors.gitDecorationDeleted }, + gitBody: { paddingHorizontal: spacing.lg, paddingVertical: spacing.md, gap: 6 }, + gitHeadline: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm, flexWrap: 'wrap' }, + transcript: { + paddingHorizontal: spacing.md, + paddingBottom: spacing.md, + gap: spacing.sm + }, + truncatedNote: { + fontSize: 12, + color: colors.textMuted, + textAlign: 'center', + paddingVertical: spacing.xs + }, + roleLabel: { fontSize: 11, fontWeight: '600', color: colors.textMuted, marginBottom: 2 }, + bubbleUser: { + alignSelf: 'flex-end', + maxWidth: '88%', + backgroundColor: colors.chatUserSurface, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.chatUserBorder, + borderRadius: radii.surface, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm + }, + bubbleAssistant: { + alignSelf: 'stretch', + paddingHorizontal: spacing.xs, + paddingVertical: 2 + }, + bubbleSystem: { + alignSelf: 'stretch', + paddingHorizontal: spacing.sm, + paddingVertical: spacing.xs, + borderRadius: radii.control, + backgroundColor: colors.bgRaised + }, + userText: { fontSize: 15, lineHeight: 21, color: colors.textPrimary }, + systemText: { fontSize: 13, lineHeight: 18, color: colors.textSecondary }, + notice: { + backgroundColor: colors.bgPanel, + borderRadius: radii.surface, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md + }, + noticeText: { fontSize: typography.bodySize, lineHeight: 20, color: colors.textSecondary }, + skeletonCard: { + backgroundColor: colors.bgPanel, + borderRadius: radii.surface, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle, + padding: spacing.lg, + gap: spacing.md + }, + skeletonBar: { height: 10, borderRadius: 5, backgroundColor: colors.bgRaised } +})) diff --git a/mobile/src/cloud/cloud-read-snapshot.test.ts b/mobile/src/cloud/cloud-read-snapshot.test.ts new file mode 100644 index 00000000000..9987029479c --- /dev/null +++ b/mobile/src/cloud/cloud-read-snapshot.test.ts @@ -0,0 +1,297 @@ +import { + createCipheriv, + createPublicKey, + diffieHellman, + generateKeyPairSync, + hkdfSync, + randomBytes +} from 'node:crypto' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { store } = vi.hoisted(() => ({ store: new Map() })) +vi.mock('expo-secure-store', () => ({ + WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY', + getItemAsync: async (key: string) => store.get(key) ?? null, + setItemAsync: async (key: string, value: string) => void store.set(key, value), + deleteItemAsync: async (key: string) => void store.delete(key) +})) +vi.mock('./cloud-device-identity', () => ({ + loadCloudDeviceIdentity: async () => ({ + publicKeyB64: 'x', + secretKey: new Uint8Array(64), + enrollment: { + controlPlaneUrl: 'https://cloud.test', + deviceSessionId: 'ds_1', + label: 'Neil’s iPhone', + enrolledAt: 1 + } + }) +})) + +import type { SealedReadSnapshot } from '../../../src/shared/cloud-workspaces/read-snapshot' +import type { CloudControlPlane } from './cloud-control-plane-request' +import { + CLOUD_READER_KEY_REFRESH_MS, + ensureCloudReaderKey, + readCloudWorkspaceSnapshot +} from './cloud-read-snapshot' +import { loadCloudReaderKey } from './cloud-reader-key' + +// Seals exactly as the header of src/shared/cloud-workspaces/read-snapshot.ts says the VM does. +function sealLikeVm(args: { + readerPublicKeyB64: string + keyId: string + workspaceId: string + snapshotId: string + payload: unknown +}): SealedReadSnapshot { + const dek = randomBytes(32) + const nonce = randomBytes(12) + const body = createCipheriv('aes-256-gcm', dek, nonce) + body.setAAD(Buffer.from(`orca-cloud-read-v1:${args.workspaceId}:${args.snapshotId}`)) + const ciphertext = Buffer.concat([ + body.update(JSON.stringify(args.payload), 'utf8'), + body.final(), + body.getAuthTag() + ]) + const readerPublic = Buffer.from(args.readerPublicKeyB64, 'base64') + const eph = generateKeyPairSync('x25519') + const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x!, 'base64url') + const shared = diffieHellman({ + privateKey: eph.privateKey, + publicKey: createPublicKey({ + key: { kty: 'OKP', crv: 'X25519', x: readerPublic.toString('base64url') }, + format: 'jwk' + }) + }) + const kek = Buffer.from( + hkdfSync('sha256', shared, Buffer.concat([ephRaw, readerPublic]), 'orca-cloud-read-wrap-v1', 32) + ) + const wrapNonce = randomBytes(12) + const wrap = createCipheriv('aes-256-gcm', kek, wrapNonce) + wrap.setAAD( + Buffer.from(`orca-cloud-read-wrap-v1:${args.workspaceId}:${args.snapshotId}:${args.keyId}`) + ) + const wrapped = Buffer.concat([wrap.update(dek), wrap.final(), wrap.getAuthTag()]) + return { + v: 1, + snapshotId: args.snapshotId, + workspaceId: args.workspaceId, + storedAt: 2, + nonceB64: nonce.toString('base64'), + ciphertextB64: ciphertext.toString('base64'), + recipient: { + keyId: args.keyId, + ephemeralPublicKeyB64: ephRaw.toString('base64'), + nonceB64: wrapNonce.toString('base64'), + wrappedKeyB64: wrapped.toString('base64') + } + } +} + +const PAYLOAD = { + v: 1, + workspaceId: 'sbx_1', + snapshotId: 'snap_1', + capturedAt: 1_700_000_000_000, + reason: 'sleep', + pr: { + number: 42, + title: 'Fix login', + state: 'open', + url: 'https://github.com/o/r/pull/42', + checksStatus: 'success', + checksSummary: null + }, + git: { branch: 'fix-login', changes: [{ path: 'a.ts', added: 3, removed: 1 }], changeCount: 1 }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'Login bug', + status: 'idle', + turnOutcome: 'completed', + messages: [ + { itemId: 'm1', role: 'user', text: 'fix it', at: 1 }, + { itemId: 'm2', role: 'assistant', text: '**Done**', at: 2 } + ] + } + ] +} + +type Call = { method: string; url: string; body: unknown } + +function fakePlane(handle: (call: Call) => { status: number; body: unknown }): { + plane: CloudControlPlane + calls: Call[] +} { + const calls: Call[] = [] + const plane: CloudControlPlane = { + baseUrl: 'https://cloud.test', + token: () => 'tok', + fetch: (async (url: string, init: RequestInit) => { + const call = { + method: init.method ?? 'GET', + url, + body: init.body ? JSON.parse(String(init.body)) : undefined + } + calls.push(call) + const reply = handle(call) + return new Response(JSON.stringify(reply.body), { status: reply.status }) + }) as typeof fetch + } + return { plane, calls } +} + +const registered = (id = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa') => ({ + status: 200, + body: { + readerKey: { id, deviceKind: 'mobile', deviceLabel: 'x', createdAt: 1, lastSeenAt: 1 } + } +}) + +beforeEach(() => store.clear()) + +describe('ensureCloudReaderKey', () => { + it('registers once as a mobile key, then only again after 6 h or when forced', async () => { + let clock = 1_000 + const now = () => clock + const { plane, calls } = fakePlane(() => registered()) + const first = await ensureCloudReaderKey(plane, { now }) + const key = await loadCloudReaderKey('ds_1') + expect(first?.keyId).toBe('rk_aaaaaaaaaaaaaaaaaaaaaaaa') + expect(calls).toHaveLength(1) + expect(calls[0]).toMatchObject({ + method: 'PUT', + url: 'https://cloud.test/v1/reader-keys', + body: { publicKeyB64: key.publicKeyB64, deviceLabel: 'Neil’s iPhone', deviceKind: 'mobile' } + }) + await ensureCloudReaderKey(plane, { now }) + expect(calls).toHaveLength(1) + clock += CLOUD_READER_KEY_REFRESH_MS + await ensureCloudReaderKey(plane, { now }) + expect(calls).toHaveLength(2) + await ensureCloudReaderKey(plane, { now, force: true }) + expect(calls).toHaveLength(3) + }) +}) + +describe('readCloudWorkspaceSnapshot', () => { + it('opens a snapshot the VM sealed to this phone (node:crypto seal, Hermes primitives open)', async () => { + const key = await loadCloudReaderKey('ds_1') + const keyId = 'rk_bbbbbbbbbbbbbbbbbbbbbbbb' + const sealed = sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId, + workspaceId: 'sbx_1', + snapshotId: 'snap_1', + payload: PAYLOAD + }) + const { plane, calls } = fakePlane((call) => + call.method === 'PUT' ? registered(keyId) : { status: 200, body: { snapshot: sealed } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(calls[1]?.url).toBe( + `https://cloud.test/v1/team/workspaces/sbx_1/read-snapshot?keyId=${keyId}` + ) + expect(calls.some((call) => /wake/.test(call.url))).toBe(false) + expect(result.state).toBe('ready') + if (result.state !== 'ready') { + return + } + expect(result.snapshot.capturedAt).toBe(PAYLOAD.capturedAt) + expect(result.snapshot.pr?.number).toBe(42) + expect(result.snapshot.git?.branch).toBe('fix-login') + expect(result.snapshot.sessions[0]?.messages.map((m) => m.role)).toEqual(['user', 'assistant']) + }) + + it('refuses a snapshot sealed for another workspace', async () => { + const key = await loadCloudReaderKey('ds_1') + const sealed = sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId: 'rk_111111111111111111111111', + workspaceId: 'sbx_other', + snapshotId: 'snap_1', + payload: { ...PAYLOAD, workspaceId: 'sbx_other' } + }) + const { plane } = fakePlane((call) => + call.method === 'PUT' + ? registered('rk_111111111111111111111111') + : { status: 200, body: { snapshot: sealed } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(result.state).toBe('error') + }) + + it('fails closed when the wrapped key is for another key id', async () => { + const key = await loadCloudReaderKey('ds_1') + const sealed = sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId: 'rk_111111111111111111111111', + workspaceId: 'sbx_1', + snapshotId: 'snap_1', + payload: PAYLOAD + }) + sealed.recipient.keyId = 'rk_222222222222222222222222' + const { plane } = fakePlane((call) => + call.method === 'PUT' + ? registered('rk_222222222222222222222222') + : { status: 200, body: { snapshot: sealed } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(result).toMatchObject({ state: 'error', error: { code: 'decrypt_failed' } }) + }) + + it.each(['no_snapshot', 'not_sealed_for_key', 'not_found'] as const)( + 'maps 404 %s to its state', + async (code) => { + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 404, body: { error: code } } + ) + await expect(readCloudWorkspaceSnapshot(plane, 'sbx_1')).resolves.toEqual({ state: code }) + } + ) + + it('renews the key after not_sealed_for_key so the next sleep seals to it', async () => { + const { plane, calls } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 404, body: { error: 'not_sealed_for_key' } } + ) + await readCloudWorkspaceSnapshot(plane, 'sbx_1') + await vi.waitFor(() => expect(calls.filter((c) => c.method === 'PUT')).toHaveLength(2)) + }) + + it('re-registers once on invalid_request and asks again', async () => { + let gets = 0 + const { plane, calls } = fakePlane((call) => { + if (call.method === 'PUT') { + return registered( + gets === 0 ? 'rk_000000000000000000000000' : 'rk_ffffffffffffffffffffffff' + ) + } + gets += 1 + return gets === 1 + ? { status: 400, body: { error: 'invalid_request' } } + : { status: 404, body: { error: 'no_snapshot' } } + }) + await expect(readCloudWorkspaceSnapshot(plane, 'sbx_1')).resolves.toEqual({ + state: 'no_snapshot' + }) + expect(calls.map((c) => c.method)).toEqual(['PUT', 'GET', 'PUT', 'GET']) + expect(calls[3]?.url).toContain('keyId=rk_ffffffffffffffffffffffff') + }) + + it('returns a 401 as an error carrying the status, for the caller to forget the session', async () => { + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 401, body: { error: 'unauthorized' } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(result).toMatchObject({ state: 'error', error: { status: 401 } }) + }) + + it('returns a malformed reply as an error', async () => { + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 200, body: { snapshot: { v: 2 } } } + ) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_1')).state).toBe('error') + }) +}) diff --git a/mobile/src/cloud/cloud-read-snapshot.ts b/mobile/src/cloud/cloud-read-snapshot.ts new file mode 100644 index 00000000000..e7c34490f4a --- /dev/null +++ b/mobile/src/cloud/cloud-read-snapshot.ts @@ -0,0 +1,165 @@ +import { + CloudReadSnapshotResponseSchema, + CloudReaderKeyResponseSchema +} from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire' +import { + openReadSnapshot, + type ReadSnapshot, + type SealedReadSnapshot +} from '../../../src/shared/cloud-workspaces/read-snapshot' +import { + CloudRequestError, + cloudRequest, + type CloudControlPlane +} from './cloud-control-plane-request' +import { loadCloudDeviceIdentity } from './cloud-device-identity' +import { loadCloudReaderKey, saveCloudReaderKeyRegistration } from './cloud-reader-key' +import { CLOUD_SEALED_PRIMITIVES } from './cloud-sealed-grant' + +// Reads a sleeping workspace's sealed snapshot without waking it. The control plane relays only +// ciphertext plus this phone's own wrapped key; the reader key's secret opens it on the phone. + +/** Re-register at most this often; the control plane bumps lastSeenAt on each. */ +export const CLOUD_READER_KEY_REFRESH_MS = 6 * 60 * 60 * 1000 + +export type CloudReadSnapshotResult = + | { state: 'ready'; snapshot: ReadSnapshot } + /** Nothing captured yet: it is captured each time the workspace goes to sleep. */ + | { state: 'no_snapshot' } + /** A snapshot exists, but this phone's key was added (or renewed) after it last slept. */ + | { state: 'not_sealed_for_key' } + /** Gone, or this phone may no longer open it. */ + | { state: 'not_found' } + /** Anything else; a 401 here means the session was revoked (see forgetRevokedCloudSession). */ + | { state: 'error'; error: unknown } + +const inflight = new Map>() + +/** + * This phone's reader key, registered with the control plane (PUT /v1/reader-keys) when it never + * was, when the last registration is over 6 h old, or when `force` is set. Null before enrollment. + */ +export async function ensureCloudReaderKey( + plane: CloudControlPlane, + options: { force?: boolean; now?: () => number } = {} +): Promise<{ keyId: string; secretKey: Uint8Array } | null> { + const enrollment = (await loadCloudDeviceIdentity()).enrollment + if (!enrollment) { + return null + } + const now = options.now ?? Date.now + const sessionId = enrollment.deviceSessionId + const running = inflight.get(sessionId) + if (running) { + return running + } + const task = (async () => { + const key = await loadCloudReaderKey(sessionId) + const registered = key.registration + if ( + !options.force && + registered && + now() - registered.registeredAt < CLOUD_READER_KEY_REFRESH_MS + ) { + return { keyId: registered.keyId, secretKey: key.secretKey } + } + const reply = await cloudRequest( + plane, + 'PUT', + '/v1/reader-keys', + CloudReaderKeyResponseSchema, + { + body: { + publicKeyB64: key.publicKeyB64, + deviceLabel: enrollment.label.trim().slice(0, 80) || 'Orca mobile', + deviceKind: 'mobile' + }, + timeoutMs: 15_000 + } + ) + const keyId = reply.readerKey.id + await saveCloudReaderKeyRegistration(key, { keyId, registeredAt: now() }) + return { keyId, secretKey: key.secretKey } + })() + inflight.set(sessionId, task) + try { + return await task + } finally { + inflight.delete(sessionId) + } +} + +async function fetchSealed( + plane: CloudControlPlane, + sandboxId: string, + keyId: string, + signal?: AbortSignal +): Promise { + const reply = await cloudRequest( + plane, + 'GET', + `/v1/team/workspaces/${encodeURIComponent(sandboxId)}/read-snapshot?keyId=${encodeURIComponent(keyId)}`, + CloudReadSnapshotResponseSchema, + { signal, timeoutMs: 20_000 } + ) + return reply.snapshot +} + +const NOT_FOUND_STATES = new Set(['no_snapshot', 'not_sealed_for_key', 'not_found']) +type MissingState = 'no_snapshot' | 'not_sealed_for_key' | 'not_found' + +function missingState(error: unknown): MissingState | null { + return error instanceof CloudRequestError && + error.status === 404 && + NOT_FOUND_STATES.has(error.code) + ? (error.code as MissingState) + : null +} + +/** The sleeping workspace's last snapshot, opened on this phone; never wakes the sandbox. */ +export async function readCloudWorkspaceSnapshot( + plane: CloudControlPlane, + sandboxId: string, + options: { signal?: AbortSignal; now?: () => number } = {} +): Promise { + const { signal, now } = options + try { + let reader = await ensureCloudReaderKey(plane, { now }) + if (!reader) { + return { state: 'error', error: new CloudRequestError('not_enrolled', 0) } + } + let sealed: SealedReadSnapshot + try { + sealed = await fetchSealed(plane, sandboxId, reader.keyId, signal) + } catch (error) { + if ( + !(error instanceof CloudRequestError) || + error.status !== 400 || + error.code !== 'invalid_request' + ) { + throw error + } + // A key id the control plane no longer takes: register again and ask once more. + reader = await ensureCloudReaderKey(plane, { force: true, now }) + if (!reader) { + throw error + } + sealed = await fetchSealed(plane, sandboxId, reader.keyId, signal) + } + // The AAD binds exactly the sandbox row id this phone asked for. + const snapshot = await openReadSnapshot( + sealed, + sandboxId, + reader.secretKey, + CLOUD_SEALED_PRIMITIVES + ) + return { state: 'ready', snapshot } + } catch (error) { + const missing = missingState(error) + if (missing === 'not_sealed_for_key') { + // The key may have been revoked or pruned: renewing it now gets it into the next sleep. + void ensureCloudReaderKey(plane, { force: true, now }).catch(() => undefined) + } + return missing ? { state: missing } : { state: 'error', error } + } +} diff --git a/mobile/src/cloud/cloud-reader-key.test.ts b/mobile/src/cloud/cloud-reader-key.test.ts new file mode 100644 index 00000000000..311b3c69c04 --- /dev/null +++ b/mobile/src/cloud/cloud-reader-key.test.ts @@ -0,0 +1,80 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { store, options } = vi.hoisted(() => ({ + store: new Map(), + options: [] as unknown[] +})) +vi.mock('expo-secure-store', () => ({ + WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY', + getItemAsync: vi.fn(async (key: string, opts: unknown) => { + options.push(opts) + return store.get(key) ?? null + }), + setItemAsync: vi.fn(async (key: string, value: string, opts: unknown) => { + options.push(opts) + store.set(key, value) + }), + deleteItemAsync: vi.fn(async (key: string) => { + store.delete(key) + }) +})) + +import nacl from 'tweetnacl' +import { + clearCloudReaderKey, + loadCloudReaderKey, + saveCloudReaderKeyRegistration +} from './cloud-reader-key' + +const STORE_KEY = 'orca.cloud-reader.v1' + +beforeEach(() => { + store.clear() + options.length = 0 +}) + +describe('cloud reader key store', () => { + it('generates one X25519 key lazily, this device only, and keeps it', async () => { + const [a, b] = await Promise.all([loadCloudReaderKey('ds_1'), loadCloudReaderKey('ds_1')]) + expect(a.publicKeyB64).toBe(b.publicKeyB64) + expect(a.secretKey).toHaveLength(32) + expect(a.registration).toBeNull() + expect(Buffer.from(nacl.scalarMult.base(a.secretKey)).toString('base64')).toBe(a.publicKeyB64) + expect(options).toContainEqual({ keychainAccessible: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY' }) + expect(options.every((o) => JSON.stringify(o).includes('WHEN_UNLOCKED_THIS_DEVICE_ONLY'))).toBe( + true + ) + expect((await loadCloudReaderKey('ds_1')).publicKeyB64).toBe(a.publicKeyB64) + }) + + it('records the registration for the same key only', async () => { + const key = await loadCloudReaderKey('ds_1') + await saveCloudReaderKeyRegistration(key, { keyId: 'rk_1', registeredAt: 5 }) + expect((await loadCloudReaderKey('ds_1')).registration).toEqual({ + keyId: 'rk_1', + registeredAt: 5 + }) + await saveCloudReaderKeyRegistration( + { deviceSessionId: 'ds_1', publicKeyB64: 'other' }, + { keyId: 'rk_2', registeredAt: 6 } + ) + expect((await loadCloudReaderKey('ds_1')).registration?.keyId).toBe('rk_1') + }) + + it('mints a new key for a new device session', async () => { + const first = await loadCloudReaderKey('ds_1') + await saveCloudReaderKeyRegistration(first, { keyId: 'rk_1', registeredAt: 5 }) + const second = await loadCloudReaderKey('ds_2') + expect(second.publicKeyB64).not.toBe(first.publicKeyB64) + expect(second.registration).toBeNull() + }) + + it('replaces an unreadable item and drops the key on clear', async () => { + store.set(STORE_KEY, '{not json') + const key = await loadCloudReaderKey('ds_1') + expect(key.secretKey).toHaveLength(32) + await clearCloudReaderKey() + expect(store.has(STORE_KEY)).toBe(false) + expect((await loadCloudReaderKey('ds_1')).publicKeyB64).not.toBe(key.publicKeyB64) + }) +}) diff --git a/mobile/src/cloud/cloud-reader-key.ts b/mobile/src/cloud/cloud-reader-key.ts new file mode 100644 index 00000000000..4e951001dff --- /dev/null +++ b/mobile/src/cloud/cloud-reader-key.ts @@ -0,0 +1,104 @@ +import * as SecureStore from 'expo-secure-store' +import nacl from 'tweetnacl' +import { z } from 'zod' +import { decodeBase64Bytes, encodeBase64Bytes } from '../transport/encryption/base64-byte-codec' + +// This phone's long-lived X25519 "reader key": sleeping workspaces seal their read-only snapshot to +// its public half. The secret never leaves this keychain item (off iCloud Keychain and backups), and +// it is bound to one device session, so a new enrollment never inherits an old session's key. +const STORE_KEY = 'orca.cloud-reader.v1' +const OPTIONS: SecureStore.SecureStoreOptions = { + keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY +} + +const RegistrationSchema = z.object({ keyId: z.string().min(1), registeredAt: z.number() }) +const StoredSchema = z.object({ + deviceSessionId: z.string().min(1), + secretKeyB64: z.string(), + registration: RegistrationSchema.nullable() +}) + +export type CloudReaderKeyRegistration = z.infer + +export type CloudReaderKey = { + deviceSessionId: string + publicKeyB64: string + secretKey: Uint8Array + /** The control plane's id for this key (`rk_…`), once registered. */ + registration: CloudReaderKeyRegistration | null +} + +type Stored = z.infer + +// Every read-modify-write runs in order, so two callers never mint two keys. +let queue: Promise = Promise.resolve() +function serial(task: () => Promise): Promise { + const next = queue.then(task, task) + queue = next.catch(() => undefined) + return next +} + +async function readStored(): Promise { + const raw = await SecureStore.getItemAsync(STORE_KEY, OPTIONS) + if (!raw) { + return null + } + try { + const parsed = StoredSchema.safeParse(JSON.parse(raw)) + return parsed.success && decodeBase64Bytes(parsed.data.secretKeyB64).length === 32 + ? parsed.data + : null + } catch { + return null + } +} + +function toKey(stored: Stored): CloudReaderKey { + const secretKey = decodeBase64Bytes(stored.secretKeyB64) + return { + deviceSessionId: stored.deviceSessionId, + publicKeyB64: encodeBase64Bytes(nacl.scalarMult.base(new Uint8Array(secretKey))), + secretKey, + registration: stored.registration + } +} + +/** This session's reader key, generated on first use (only once the phone is enrolled). */ +export function loadCloudReaderKey(deviceSessionId: string): Promise { + return serial(async () => { + const stored = await readStored() + if (stored && stored.deviceSessionId === deviceSessionId) { + return toKey(stored) + } + const pair = nacl.box.keyPair() + const fresh: Stored = { + deviceSessionId, + secretKeyB64: encodeBase64Bytes(new Uint8Array(pair.secretKey)), + registration: null + } + await SecureStore.setItemAsync(STORE_KEY, JSON.stringify(fresh), OPTIONS) + return toKey(fresh) + }) +} + +/** Records the control plane's id, unless the key was replaced or dropped meanwhile. */ +export function saveCloudReaderKeyRegistration( + key: Pick, + registration: CloudReaderKeyRegistration | null +): Promise { + return serial(async () => { + const stored = await readStored() + if (!stored || stored.deviceSessionId !== key.deviceSessionId) { + return + } + if (toKey(stored).publicKeyB64 !== key.publicKeyB64) { + return + } + await SecureStore.setItemAsync(STORE_KEY, JSON.stringify({ ...stored, registration }), OPTIONS) + }) +} + +/** Drops the key with the cloud session: nothing this phone could read outlives its access. */ +export function clearCloudReaderKey(): Promise { + return serial(() => SecureStore.deleteItemAsync(STORE_KEY, OPTIONS)) +} diff --git a/mobile/src/cloud/cloud-sealed-grant.ts b/mobile/src/cloud/cloud-sealed-grant.ts index 6cbf032cbce..eba15132cb7 100644 --- a/mobile/src/cloud/cloud-sealed-grant.ts +++ b/mobile/src/cloud/cloud-sealed-grant.ts @@ -9,8 +9,8 @@ import { type SealedGrantPrimitives } from '../../../src/shared/cloud-workspaces/sealed-grant' -// Hermes has no WebCrypto, so the shared opener runs on pure-JS primitives here. -const PRIMITIVES: SealedGrantPrimitives = { +// Hermes has no WebCrypto, so the shared openers (grants, read snapshots) run on pure-JS primitives. +export const CLOUD_SEALED_PRIMITIVES: SealedGrantPrimitives = { x25519: (secretKey, publicKey) => nacl.scalarMult(new Uint8Array(secretKey), new Uint8Array(publicKey)), x25519PublicKey: (secretKey) => nacl.scalarMult.base(new Uint8Array(secretKey)), @@ -29,5 +29,5 @@ export function openCloudSealedGrant( grantId: string, recipientSecretKey: Uint8Array ): Promise { - return openSealedGrant(sealed, grantId, recipientSecretKey, PRIMITIVES, 'mobile') + return openSealedGrant(sealed, grantId, recipientSecretKey, CLOUD_SEALED_PRIMITIVES, 'mobile') } diff --git a/mobile/src/cloud/use-cloud-read-snapshot.ts b/mobile/src/cloud/use-cloud-read-snapshot.ts new file mode 100644 index 00000000000..11c74d23cf1 --- /dev/null +++ b/mobile/src/cloud/use-cloud-read-snapshot.ts @@ -0,0 +1,38 @@ +import { useQuery } from '@tanstack/react-query' +import { readCloudWorkspaceSnapshot, type CloudReadSnapshotResult } from './cloud-read-snapshot' +import { + forgetRevokedCloudSession, + loadCloudControlPlane, + useCloudHostRemoval +} from './cloud-session' + +/** + * The sleeping workspace's read-only snapshot, fetched only while it is asleep and never waking it. + * Keyed by `readSnapshotAt`, so a newer sleep refetches; kept in memory only (never persisted). + */ +export function useCloudReadSnapshot( + sandboxId: string, + asleep: boolean, + readSnapshotAt: number | null +) { + const removal = useCloudHostRemoval() + return useQuery({ + queryKey: ['orca-cloud', 'read-snapshot', sandboxId, readSnapshotAt], + enabled: asleep, + queryFn: async ({ signal }) => { + const plane = await loadCloudControlPlane() + if (!plane) { + return { state: 'error', error: new Error('not_enrolled') } + } + const result = await readCloudWorkspaceSnapshot(plane, sandboxId, { signal }) + if (result.state === 'error') { + await forgetRevokedCloudSession(result.error, removal) + } + return result + }, + // A snapshot only changes when the workspace sleeps again, which changes the key above. + staleTime: 5 * 60_000, + gcTime: 60_000, + retry: false + }) +} diff --git a/mobile/src/cloud/use-cloud-workspaces.ts b/mobile/src/cloud/use-cloud-workspaces.ts index 3ef74125e1f..d918f99b568 100644 --- a/mobile/src/cloud/use-cloud-workspaces.ts +++ b/mobile/src/cloud/use-cloud-workspaces.ts @@ -13,6 +13,7 @@ import { type CloudEnrollment } from './cloud-device-identity' import { pruneCloudHostsMissingFrom } from './cloud-host-pruning' +import { ensureCloudReaderKey } from './cloud-read-snapshot' import { cloudHostRemover, forgetRevokedCloudSession, @@ -75,6 +76,8 @@ export function useCloudWorkspaces(enrollment: CloudEnrollment | null | undefine try { const startedAt = Date.now() const list = await listCloudWorkspaces(plane, signal) + // Keeps this phone's reader key registered (at most every 6 h) so the next sleep seals to it. + void ensureCloudReaderKey(plane).catch(() => undefined) if (list.complete) { // A linked workspace the list lacks is checked by id; one the registry says is gone // (destroyed, or no longer shared) stops being retried. diff --git a/mobile/src/home/MobileHomeCloudSection.tsx b/mobile/src/home/MobileHomeCloudSection.tsx index 025049effbb..ff4aa8d6679 100644 --- a/mobile/src/home/MobileHomeCloudSection.tsx +++ b/mobile/src/home/MobileHomeCloudSection.tsx @@ -2,6 +2,7 @@ import { ChevronRight, Cloud, Plus, RotateCw } from 'lucide-react-native' import { Fragment, useState } from 'react' import { ActivityIndicator, Pressable, Text, View } from 'react-native' import { CloudStatusDot } from '../cloud/CloudStatusDot' +import { formatReadSnapshotAsOf } from '../cloud/CloudReadSnapshotSection' import type { CloudWorkspace } from '../cloud/cloud-control-plane-client' import { CloudEnrollmentError, enrollCloudDevice } from '../cloud/cloud-device-enrollment' import type { CloudEnrollment } from '../cloud/cloud-device-identity' @@ -154,10 +155,17 @@ function CloudWorkspaceRow({ ago: formatTimeAgo(workspace.createdAt, reference) }) // "Created just now · just now" says one thing twice: the activity time adds nothing yet. + // Asleep with a saved read-only copy: say how fresh that copy is; it opens without waking. const when = - createdLine && lastActive - workspace.createdAt < 60_000 - ? null - : formatTimeAgo(lastActive, reference) + workspace.status === 'sleeping' && workspace.readSnapshotAt + ? formatReadSnapshotAsOf( + workspace.readSnapshotAt, + Math.max(reference, workspace.readSnapshotAt), + t + ) + : createdLine && lastActive - workspace.createdAt < 60_000 + ? null + : formatTimeAgo(lastActive, reference) const line = [status, detail, when].filter(Boolean).join(' · ') return ( identity, + load: () => + options.keychain === false + ? { ok: false, reason: 'keychain_unavailable', message: 'no keychain' } + : { ok: true, key } + } + let now = 10_000 + const ids = [KEY_A] + const registerReaderKey = vi.fn(async () => ({ + id: ids[0]!, + deviceKind: 'desktop' as const, + deviceLabel: 'test', + createdAt: 1, + lastSeenAt: 1 + })) + const getReadSnapshot = vi.fn(async (_id: string, keyId: string): Promise => ({ + kind: 'sealed', + sealed: sealReadSnapshotForTest({ + payload, + workspaceId: SBX, + snapshotId: 'snap_1', + readerPublicKeyB64: key.publicKeyB64, + keyId, + storedAt: 5 + }) + })) + const reader = createReadSnapshotReader({ + client: { registerReaderKey, getReadSnapshot }, + readerKey, + deviceLabel: () => 'test-mac', + now: () => now + }) + return { + reader, + key, + ids, + registerReaderKey, + getReadSnapshot, + tick: (ms: number) => { + now += ms + }, + setIdentity: (next: string | null) => { + identity = next + } + } +} + +describe('createReadSnapshotReader', () => { + it('registers the key, then opens a snapshot sealed to it (independent sealer roundtrip)', async () => { + const t = setup() + const result = await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledWith({ + publicKeyB64: t.key.publicKeyB64, + deviceLabel: 'test-mac', + deviceKind: 'desktop' + }) + expect(t.getReadSnapshot).toHaveBeenCalledWith(SBX, KEY_A) + expect(result.state).toBe('ready') + if (result.state !== 'ready') { + return + } + expect(result.storedAt).toBe(5) + expect(result.snapshot.capturedAt).toBe(payload.capturedAt) + expect(result.snapshot.pr?.number).toBe(42) + expect(result.snapshot.git?.changes[0]).toMatchObject({ path: 'src/a.ts', added: 3 }) + expect(result.snapshot.sessions[0]).toMatchObject({ agent: 'claude', status: 'idle' }) + }) + + it('reuses the registration for 6 h, then refreshes it', async () => { + const t = setup() + await t.reader.register() + await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + t.tick(READER_KEY_REFRESH_MS) + await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledTimes(2) + }) + + it('shares one registration between concurrent callers', async () => { + const t = setup() + await Promise.all([t.reader.register(), t.reader.read(SBX), t.reader.read(SBX)]) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + }) + + it('registers again after an account switch', async () => { + const t = setup() + await t.reader.read(SBX) + t.setIdentity('someone-else') + await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledTimes(2) + }) + + it.each(['no_snapshot', 'not_found'] as const)('reports %s as a state', async (kind) => { + const t = setup() + t.getReadSnapshot.mockResolvedValueOnce({ kind }) + expect(await t.reader.read(SBX)).toEqual({ state: kind }) + }) + + it('reports not_sealed_for_key when the snapshot predates a freshly registered key', async () => { + const t = setup() + t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' }) + expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' }) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + }) + + it('re-registers a remembered key the server dropped and retries with the new id', async () => { + const t = setup() + await t.reader.register() + t.ids[0] = KEY_B + t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' }) + const result = await t.reader.read(SBX) + expect(result.state).toBe('ready') + expect(t.getReadSnapshot).toHaveBeenLastCalledWith(SBX, KEY_B) + }) + + it('keeps not_sealed_for_key when re-registering returns the same id', async () => { + const t = setup() + await t.reader.register() + t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' }) + expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' }) + expect(t.getReadSnapshot).toHaveBeenCalledTimes(1) + }) + + it('re-registers on invalid_request for a remembered key id', async () => { + const t = setup() + await t.reader.register() + t.ids[0] = KEY_B + t.getReadSnapshot.mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request')) + expect((await t.reader.read(SBX)).state).toBe('ready') + expect(t.getReadSnapshot).toHaveBeenLastCalledWith(SBX, KEY_B) + }) + + it('is off with a clear reason without an OS keychain', async () => { + const t = setup({ keychain: false }) + expect(await t.reader.read(SBX)).toEqual({ + state: 'unavailable', + reason: 'keychain_unavailable', + message: 'no keychain' + }) + expect(t.registerReaderKey).not.toHaveBeenCalled() + }) + + it('refuses when signed out', async () => { + const t = setup({ identity: null }) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ code: 'unauthorized' }) + }) + + it('turns a snapshot sealed to another key into snapshot_unreadable', async () => { + const t = setup() + const other = generateGrantRecipientKey() + t.getReadSnapshot.mockResolvedValueOnce({ + kind: 'sealed', + sealed: sealReadSnapshotForTest({ + payload, + workspaceId: SBX, + snapshotId: 'snap_1', + readerPublicKeyB64: other.publicKeyB64, + keyId: KEY_A + }) + }) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ + code: 'snapshot_unreadable', + reason: 'decrypt_failed' + }) + }) + + it('refuses a snapshot of another workspace', async () => { + const t = setup() + const sealed = sealReadSnapshotForTest({ + payload: { ...payload, workspaceId: 'sbx_ffffffffffffffffffffffff' }, + workspaceId: 'sbx_ffffffffffffffffffffffff', + snapshotId: 'snap_1', + readerPublicKeyB64: t.key.publicKeyB64, + keyId: KEY_A + }) + t.getReadSnapshot.mockResolvedValueOnce({ kind: 'sealed', sealed }) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ reason: 'wrong_workspace' }) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts new file mode 100644 index 00000000000..dae0d872054 --- /dev/null +++ b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts @@ -0,0 +1,164 @@ +// Reads a sleeping Orca Cloud workspace from the sealed snapshot it left on the control plane, +// without waking the VM. This device's reader key is registered with the control plane (on start, +// after a sign-in or account switch, and at most every 6 h after); the VM seals each snapshot to +// the reader keys registered when it went to sleep. +import { hostname } from 'node:os' +import { openReadSnapshot, ReadSnapshotError } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' +import { CloudWorkspacesError, type CloudWorkspacesClient } from './cloud-workspaces-client' +import type { CloudReaderKey, ReaderKeyLoad } from './cloud-reader-key-store' +import { nodeSealedGrantPrimitives } from './sealed-grant-node' + +export const READER_KEY_REFRESH_MS = 6 * 60 * 60_000 + +export type ReaderKeyAccess = { + /** Who is asking (profile, user, account); null when signed out. Registrations are per identity. */ + identity: () => string | null + /** This profile's key (created on first use), or why there can be none. */ + load: () => ReaderKeyLoad +} + +type Registration = { identity: string; publicKeyB64: string; keyId: string; at: number } +type Ready = { key: CloudReaderKey; keyId: string; fresh: boolean } +type Unavailable = { unavailable: Extract } + +export function createReadSnapshotReader(deps: { + client: Pick + readerKey: ReaderKeyAccess + deviceLabel?: () => string + now?: () => number +}) { + const now = deps.now ?? Date.now + let registration: Registration | null = null + let inflight: { tag: string; promise: Promise } | null = null + + async function ensure(force = false): Promise { + const identity = deps.readerKey.identity() + if (!identity) { + throw new CloudWorkspacesError(401, 'unauthorized') + } + const loaded = deps.readerKey.load() + if (!loaded.ok) { + return { unavailable: loaded } + } + const { key } = loaded + const known = registration + if ( + !force && + known && + known.identity === identity && + known.publicKeyB64 === key.publicKeyB64 && + now() - known.at < READER_KEY_REFRESH_MS + ) { + return { key, keyId: known.keyId, fresh: false } + } + // Concurrent reads (and the start-up registration) share one PUT per identity and key. + const tag = `${identity}\0${key.publicKeyB64}` + let shared = !force && inflight?.tag === tag ? inflight : null + if (!shared) { + const promise = deps.client + .registerReaderKey({ + publicKeyB64: key.publicKeyB64, + deviceLabel: (deps.deviceLabel?.() ?? hostname()).slice(0, 80) || 'Desktop', + deviceKind: 'desktop' + }) + .then((readerKey) => { + const next = { + identity, + publicKeyB64: key.publicKeyB64, + keyId: readerKey.id, + at: now() + } + // A sign-out or account switch while this was in flight must not adopt the old id. + if (deps.readerKey.identity() === identity) { + registration = next + } + return next + }) + const entry = { tag, promise } + shared = entry + inflight = entry + void promise + .catch(() => undefined) + .finally(() => { + if (inflight === entry) { + inflight = null + } + }) + } + const done = await shared.promise + return { key, keyId: done.keyId, fresh: true } + } + + async function fetchWith(sandboxId: string, ready: Ready) { + try { + return await deps.client.getReadSnapshot(sandboxId, ready.keyId) + } catch (error) { + // A remembered id the server no longer accepts: register again (a revoked key gets a new id). + if ( + !ready.fresh && + error instanceof CloudWorkspacesError && + error.status === 400 && + error.code === 'invalid_request' + ) { + const again = await ensure(true) + if ('unavailable' in again) { + throw error + } + return { ready: again, fetched: await deps.client.getReadSnapshot(sandboxId, again.keyId) } + } + throw error + } + } + + return { + /** Best effort: make sure the control plane knows this device's key before workspaces sleep. */ + async register(): Promise { + await ensure().catch(() => undefined) + }, + + async read(sandboxId: string): Promise { + const first = await ensure() + if ('unavailable' in first) { + return { + state: 'unavailable', + reason: first.unavailable.reason, + message: first.unavailable.message + } + } + let ready = first + const answer = await fetchWith(sandboxId, ready) + let fetched = 'ready' in answer ? answer.fetched : answer + if ('ready' in answer) { + ready = answer.ready + } + // The id we remembered may have been revoked server-side; re-registering hands out a new one. + if (fetched.kind === 'not_sealed_for_key' && !ready.fresh) { + const again = await ensure(true) + if (!('unavailable' in again) && again.keyId !== ready.keyId) { + ready = again + fetched = await deps.client.getReadSnapshot(sandboxId, again.keyId) + } + } + if (fetched.kind !== 'sealed') { + return { state: fetched.kind } + } + try { + const snapshot = await openReadSnapshot( + fetched.sealed, + sandboxId, + ready.key.secretKey, + nodeSealedGrantPrimitives + ) + return { state: 'ready', snapshot, storedAt: fetched.sealed.storedAt } + } catch (error) { + if (error instanceof ReadSnapshotError) { + throw new CloudWorkspacesError(0, 'snapshot_unreadable', error.code) + } + throw error + } + } + } +} + +export type ReadSnapshotReader = ReturnType diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.test.ts b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts new file mode 100644 index 00000000000..6f2d41c7f9e --- /dev/null +++ b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts @@ -0,0 +1,101 @@ +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { getPath: () => tmpdir() }, + safeStorage: { + isEncryptionAvailable: () => false, + encryptString: () => Buffer.alloc(0), + decryptString: () => '' + } +})) + +import { createCloudReaderKeyStore, type ReaderKeyCodec } from './cloud-reader-key-store' +import { nodeSealedGrantPrimitives } from './sealed-grant-node' +import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant' + +// Reversible stand-in for the OS keychain: the file must never hold the raw secret. +const codec: ReaderKeyCodec = { + encrypt: (plain) => Buffer.from(`sealed:${Buffer.from(plain).toString('hex')}`), + decrypt: (sealed) => { + const text = sealed.toString() + if (!text.startsWith('sealed:')) { + throw new Error('bad seal') + } + return Buffer.from(text.slice(7), 'hex').toString() + } +} + +let dir: string +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'reader-key-')) +}) +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +const storeWith = (next: () => ReaderKeyCodec | null = () => codec) => + createCloudReaderKeyStore({ + pathFor: (profileId) => join(dir, profileId, 'key.enc'), + codec: next + }) + +describe('createCloudReaderKeyStore', () => { + it('creates one key per profile lazily and keeps it sealed on disk', () => { + const store = storeWith() + const first = store.load('p1') + expect(first.ok).toBe(true) + if (!first.ok) { + return + } + expect(first.key.secretKey).toHaveLength(32) + const derived = nodeSealedGrantPrimitives.x25519PublicKey(first.key.secretKey) as Uint8Array + expect(first.key.publicKeyB64).toBe(bytesToBase64(derived)) + const file = readFileSync(join(dir, 'p1', 'key.enc'), 'utf8') + expect(file).not.toContain(bytesToBase64(first.key.secretKey)) + expect(JSON.parse(file)).toMatchObject({ version: 1, format: 'electron-safe-storage-v1' }) + + const second = store.load('p2') + expect(second.ok && second.key.publicKeyB64).not.toBe(first.key.publicKeyB64) + }) + + it('reads the same key back after a restart', () => { + const first = storeWith().load('p1') + const again = storeWith().load('p1') + expect(first.ok && again.ok).toBe(true) + if (first.ok && again.ok) { + expect(again.key.publicKeyB64).toBe(first.key.publicKeyB64) + expect(base64ToBytes(bytesToBase64(again.key.secretKey))).toEqual(first.key.secretKey) + } + }) + + it('is off with a reason when the OS keychain is missing, and writes nothing', () => { + const store = storeWith(() => null) + expect(store.load('p1')).toMatchObject({ ok: false, reason: 'keychain_unavailable' }) + expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) + }) + + it('replaces a key the keychain can no longer open', () => { + const first = storeWith().load('p1') + writeFileSync( + join(dir, 'p1', 'key.enc'), + JSON.stringify({ version: 1, format: 'electron-safe-storage-v1', ciphertext: 'AAAA' }) + ) + const replaced = storeWith().load('p1') + expect(replaced.ok).toBe(true) + expect(first.ok && replaced.ok && replaced.key.publicKeyB64 !== first.key.publicKeyB64).toBe( + true + ) + }) + + it('clear drops the key from memory and disk (sign-out)', () => { + const store = storeWith() + const first = store.load('p1') + store.clear('p1') + expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) + const next = store.load('p1') + expect(first.ok && next.ok && next.key.publicKeyB64 !== first.key.publicKeyB64).toBe(true) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.ts b/src/main/cloud-workspaces/cloud-reader-key-store.ts new file mode 100644 index 00000000000..72b1672ae1a --- /dev/null +++ b/src/main/cloud-workspaces/cloud-reader-key-store.ts @@ -0,0 +1,166 @@ +// This device's long-lived X25519 "reader key", one per Orca profile. A sleeping Orca Cloud +// workspace seals its read snapshot to every registered reader key allowed to open it; the secret +// half never leaves this machine. It is sealed by the OS keychain (safeStorage at level 'os'); with +// no real keychain the feature is off rather than keeping a long-lived secret in the clear. +import { existsSync, readFileSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { assessSecretProtection } from '../host/electron-secret-store' +import { guardedSafeStorage } from '../host/safe-storage-availability' +import { writeSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant' +import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths' +import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from './sealed-grant-node' + +export const READER_KEY_FILE_NAME = 'cloud-reader-key.json.enc' + +export type ReaderKeyCodec = { + encrypt: (plain: string) => Buffer + decrypt: (sealed: Buffer) => string +} + +export type CloudReaderKey = { + /** 32-byte X25519 secret. Callers must not keep or zero it; the store owns the buffer. */ + secretKey: Uint8Array + publicKeyB64: string +} + +export type ReaderKeyLoad = + | { ok: true; key: CloudReaderKey } + | { ok: false; reason: 'keychain_unavailable' | 'storage_failed'; message: string } + +type PersistedReaderKey = { + version: 1 + format: 'electron-safe-storage-v1' + createdAt: number + ciphertext: string +} + +const KEYCHAIN_MESSAGE = + 'Reading sleeping workspaces needs the OS keychain to protect this device’s key.' + +/** The OS keychain, or null when it is missing or only obfuscates (Linux basic_text). */ +export function osReaderKeyCodec(): ReaderKeyCodec | null { + try { + if (!guardedSafeStorage.isEncryptionAvailable() || assessSecretProtection().level !== 'os') { + return null + } + } catch { + return null + } + return { + encrypt: (plain) => guardedSafeStorage.encryptString(plain), + decrypt: (sealed) => guardedSafeStorage.decryptString(sealed) + } +} + +export function getCloudReaderKeyPath(profileId: string, userDataPath: string): string { + return join(getOrcaProfileDirectory(profileId, userDataPath), READER_KEY_FILE_NAME) +} + +export function createCloudReaderKeyStore(deps: { + pathFor: (profileId: string) => string + codec: () => ReaderKeyCodec | null + now?: () => number +}) { + const cache = new Map() + + function decode(path: string, codec: ReaderKeyCodec): CloudReaderKey | null { + try { + const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial + if ( + parsed.version !== 1 || + parsed.format !== 'electron-safe-storage-v1' || + typeof parsed.ciphertext !== 'string' + ) { + return null + } + const secretKey = base64ToBytes(codec.decrypt(Buffer.from(parsed.ciphertext, 'base64'))) + if (secretKey.length !== 32) { + return null + } + return { + secretKey, + publicKeyB64: bytesToBase64( + nodeSealedGrantPrimitives.x25519PublicKey(secretKey) as Uint8Array + ) + } + } catch { + return null + } + } + + return { + /** The profile's key, created on first use. A key the keychain can no longer open is replaced. */ + load(profileId: string): ReaderKeyLoad { + const codec = deps.codec() + if (!codec) { + return { ok: false, reason: 'keychain_unavailable', message: KEYCHAIN_MESSAGE } + } + const path = deps.pathFor(profileId) + const cached = cache.get(path) + if (cached) { + return { ok: true, key: cached } + } + const existing = existsSync(path) ? decode(path, codec) : null + if (existing) { + cache.set(path, existing) + return { ok: true, key: existing } + } + // A new key only means snapshots taken before it are not readable here until the next sleep. + const fresh = generateGrantRecipientKey() + try { + const persisted: PersistedReaderKey = { + version: 1, + format: 'electron-safe-storage-v1', + createdAt: (deps.now ?? Date.now)(), + ciphertext: codec.encrypt(bytesToBase64(fresh.secretKey)).toString('base64') + } + writeSecureJsonFile(path, persisted) + } catch (error) { + fresh.secretKey.fill(0) + return { + ok: false, + reason: 'storage_failed', + message: `Could not save this device’s reader key: ${String(error).slice(0, 120)}` + } + } + const key = { secretKey: fresh.secretKey, publicKeyB64: fresh.publicKeyB64 } + cache.set(path, key) + return { ok: true, key } + }, + /** Sign-out: the next account on this profile gets a new key (never one an old account knew). */ + clear(profileId: string): void { + const path = deps.pathFor(profileId) + cache.get(path)?.secretKey.fill(0) + cache.delete(path) + rmSync(path, { force: true }) + } + } +} + +export type CloudReaderKeyStore = ReturnType + +let defaultStore: { userDataPath: string; store: CloudReaderKeyStore } | null = null + +/** The process-wide store for this user data directory (the OS keychain codec). */ +export function getCloudReaderKeyStore(userDataPath: string): CloudReaderKeyStore { + if (defaultStore?.userDataPath !== userDataPath) { + defaultStore = { + userDataPath, + store: createCloudReaderKeyStore({ + pathFor: (profileId) => getCloudReaderKeyPath(profileId, userDataPath), + codec: osReaderKeyCodec + }) + } + } + return defaultStore.store +} + +/** Sign-out / profile reset hook: drop the profile's reader key (memory and disk). */ +export function clearCloudReaderKey(profileId: string, userDataPath: string): void { + try { + getCloudReaderKeyStore(userDataPath).clear(profileId) + } catch (error) { + console.error(`[orca-cloud] clearing the reader key failed: ${String(error)}`) + } +} diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts new file mode 100644 index 00000000000..d1c9b8c5645 --- /dev/null +++ b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it, vi } from 'vitest' +import { CloudWorkspaceSchema } from '../../shared/cloud-workspaces/cloud-workspaces-wire' +import { createCloudWorkspacesClient } from './cloud-workspaces-client' + +const SBX = 'sbx_0123456789abcdef01234567' +const KEY = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa' + +function clientAnswering(status: number, body: unknown) { + const fetch = vi.fn( + async (_url: URL | RequestInfo, _init?: RequestInit) => + new Response(JSON.stringify(body), { status }) + ) + const client = createCloudWorkspacesClient({ + baseUrl: 'https://cp.example.test', + getAccessToken: async () => 'tok', + fetch: fetch as unknown as typeof globalThis.fetch + }) + return { client, fetch } +} + +const sealed = { + v: 1, + snapshotId: 'snap_1', + workspaceId: SBX, + storedAt: 5, + nonceB64: 'AAAAAAAAAAAAAAAA', + ciphertextB64: 'AAAA', + recipient: { + keyId: KEY, + ephemeralPublicKeyB64: 'AAAA', + nonceB64: 'AAAA', + wrappedKeyB64: 'AAAA' + } +} + +describe('cloud workspaces client: read snapshots', () => { + it('PUTs the reader key and returns its id', async () => { + const { client, fetch } = clientAnswering(200, { + readerKey: { id: KEY, deviceKind: 'desktop', deviceLabel: 'mac', createdAt: 1, lastSeenAt: 2 } + }) + const key = await client.registerReaderKey({ + publicKeyB64: 'pub', + deviceLabel: 'mac', + deviceKind: 'desktop' + }) + expect(key.id).toBe(KEY) + const [url, init] = fetch.mock.calls[0]! + expect(String(url)).toBe('https://cp.example.test/v1/reader-keys') + expect(init?.method).toBe('PUT') + expect(JSON.parse(String(init?.body))).toEqual({ + publicKeyB64: 'pub', + deviceLabel: 'mac', + deviceKind: 'desktop' + }) + }) + + it('GETs the sealed snapshot for this key', async () => { + const { client, fetch } = clientAnswering(200, { snapshot: sealed }) + expect(await client.getReadSnapshot(SBX, KEY)).toEqual({ kind: 'sealed', sealed }) + expect(String(fetch.mock.calls[0]![0])).toBe( + `https://cp.example.test/v1/team/workspaces/${SBX}/read-snapshot?keyId=${KEY}` + ) + }) + + it.each(['not_found', 'no_snapshot', 'not_sealed_for_key'] as const)( + 'maps 404 %s to a typed result', + async (code) => { + const { client } = clientAnswering(404, { error: code }) + expect(await client.getReadSnapshot(SBX, KEY)).toEqual({ kind: code }) + } + ) + + it('keeps other failures as errors', async () => { + await expect( + clientAnswering(404, { error: 'something_else' }).client.getReadSnapshot(SBX, KEY) + ).rejects.toMatchObject({ status: 404, code: 'something_else' }) + await expect( + clientAnswering(400, { error: 'invalid_request' }).client.getReadSnapshot(SBX, KEY) + ).rejects.toMatchObject({ status: 400, code: 'invalid_request' }) + }) +}) + +describe('CloudWorkspaceSchema.readSnapshotAt', () => { + const base = { + id: SBX, + workspaceId: 'w', + status: 'suspended', + machineSize: 'standard', + region: 'iad1', + createdAt: 1, + title: null, + repo: null, + visibility: 'team', + section: null, + archivedAt: null, + createdBy: 'u', + ownerUserId: 'u', + lastActivityAt: 1, + lastActivityBy: null, + cost: { + computeMs: 0, + rateUsdMicrosPerHour: 0, + computeUsdMicros: 0, + tokenUsdMicros: null, + totalUsdMicros: 0 + }, + access: 'can_open', + presence: [] + } + it('is optional for older control planes and nullable', () => { + expect(CloudWorkspaceSchema.parse(base).readSnapshotAt).toBeUndefined() + expect(CloudWorkspaceSchema.parse({ ...base, readSnapshotAt: null }).readSnapshotAt).toBeNull() + expect(CloudWorkspaceSchema.parse({ ...base, readSnapshotAt: 9 }).readSnapshotAt).toBe(9) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.ts b/src/main/cloud-workspaces/cloud-workspaces-client.ts index 71453f65bd5..5d536db6f7a 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.ts @@ -2,7 +2,10 @@ // hosted sandbox driver: a short-lived Orca token (aud=orca-sandbox), never a provider credential. import { z } from 'zod' import { errorMessage } from '../../shared/error-message' +import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' import { + CloudReadSnapshotResponseSchema, + CloudReaderKeyResponseSchema, CloudWorkspaceGrantIssuedSchema, CloudWorkspaceGrantListSchema, CloudWorkspaceLinkResponseSchema, @@ -38,6 +41,15 @@ const CONTROL_TIMEOUT_MS = 20_000 // Opening a sleeping teammate workspace includes a VM boot. const GRANT_TIMEOUT_MS = 120_000 const MAX_RESPONSE_BYTES = 512 * 1024 +// A read snapshot carries chat tails (bounded by READ_SNAPSHOT_LIMITS), base64 over AES-GCM. +const MAX_READ_SNAPSHOT_BYTES = 16 * 1024 * 1024 + +/** The read-snapshot 404s are states, not failures: each has its own copy. */ +const READ_SNAPSHOT_MISSES = ['not_found', 'no_snapshot', 'not_sealed_for_key'] as const +export type ReadSnapshotMiss = (typeof READ_SNAPSHOT_MISSES)[number] +export type ReadSnapshotFetch = + | { kind: 'sealed'; sealed: SealedReadSnapshot } + | { kind: ReadSnapshotMiss } export function createCloudWorkspacesClient(options: CloudWorkspacesClientOptions) { const doFetch = options.fetch ?? fetch @@ -48,7 +60,8 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption path: string, schema: z.ZodType, body?: unknown, - timeoutMs = CONTROL_TIMEOUT_MS + timeoutMs = CONTROL_TIMEOUT_MS, + maxBytes = MAX_RESPONSE_BYTES ): Promise { const signal = AbortSignal.timeout(timeoutMs) let token: string @@ -80,7 +93,7 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption ) } const text = await response.text() - if (text.length > MAX_RESPONSE_BYTES) { + if (text.length > maxBytes) { throw new CloudWorkspacesError(response.status, 'invalid_response') } let payload: unknown = null @@ -177,6 +190,36 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption } return call('GET', `/v1/team/links/resolve?${params}`, CloudWorkspaceLinkResponseSchema) }, + /** Idempotent per (user, account, public key): the same id comes back, lastSeenAt bumped. */ + async registerReaderKey(body: { + publicKeyB64: string + deviceLabel: string + deviceKind: 'desktop' | 'mobile' + }) { + return (await call('PUT', '/v1/reader-keys', CloudReaderKeyResponseSchema, body)).readerKey + }, + async getReadSnapshot(id: string, keyId: string): Promise { + try { + const { snapshot } = await call( + 'GET', + `${ws(id)}/read-snapshot?${new URLSearchParams({ keyId })}`, + CloudReadSnapshotResponseSchema, + undefined, + CONTROL_TIMEOUT_MS, + MAX_READ_SNAPSHOT_BYTES + ) + return { kind: 'sealed', sealed: snapshot } + } catch (error) { + const miss = + error instanceof CloudWorkspacesError && error.status === 404 + ? READ_SNAPSHOT_MISSES.find((code) => code === error.code) + : undefined + if (miss) { + return { kind: miss } + } + throw error + } + }, getOrgPrompts(): Promise { return call('GET', '/v1/team/prompts', OrgPromptsSchema) }, diff --git a/src/main/cloud-workspaces/cloud-workspaces-service.ts b/src/main/cloud-workspaces/cloud-workspaces-service.ts index 6a3340a1c22..495fec84340 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-service.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-service.ts @@ -18,6 +18,7 @@ import { type CloudWorkspacesClient } from './cloud-workspaces-client' import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from './sealed-grant-node' +import { createReadSnapshotReader, type ReaderKeyAccess } from './cloud-read-snapshot-reader' const PRESENCE_BEAT_MS = 20_000 /** Renew a teammate-opened workspace's lease well before the control plane's 30 min lease lapses. */ @@ -52,6 +53,8 @@ export function createCloudWorkspacesService(deps: { config: HostedSandboxConfig clientId: string fetch?: typeof fetch + /** This profile's reader key (sleeping-workspace snapshots); absent: reading them is off. */ + readerKey?: ReaderKeyAccess }) { const client: CloudWorkspacesClient = createCloudWorkspacesClient({ baseUrl: deps.config.controlPlaneUrl, @@ -69,6 +72,11 @@ export function createCloudWorkspacesService(deps: { let heartbeat: ReturnType | null = null let leaseSandboxId: string | null = null let leaseRenewedAt = 0 + const reader = deps.readerKey + ? createReadSnapshotReader({ client, readerKey: deps.readerKey }) + : null + // Register the key up front: a workspace seals its snapshot to the keys known when it sleeps. + void reader?.register() function localWorkspaces(): LocalCloudWorkspace[] { const out: LocalCloudWorkspace[] = [] @@ -126,7 +134,21 @@ export function createCloudWorkspacesService(deps: { return { available: true as const, - list: (query: CloudWorkspaceListQuery) => wrap(() => client.list(query)), + list: (query: CloudWorkspaceListQuery) => + wrap(async () => { + const workspaces = await client.list(query) + // Cheap when already registered; catches a sign-in or account switch since the last list. + void reader?.register() + return workspaces + }), + /** A sleeping workspace's sealed snapshot, opened on this device; never wakes it. */ + readSnapshot: (id: string) => + wrap(async () => { + if (!reader) { + throw new CloudWorkspacesError(0, 'not_configured') + } + return reader.read(id) + }), get: (id: string) => wrap(() => client.get(id)), patch: (id: string, patch: CloudWorkspacePatch) => wrap(async () => (await client.patch(id, patch)).workspace), diff --git a/src/main/cloud-workspaces/read-snapshot-sealer.test-fixture.ts b/src/main/cloud-workspaces/read-snapshot-sealer.test-fixture.ts new file mode 100644 index 00000000000..ed147061bcc --- /dev/null +++ b/src/main/cloud-workspaces/read-snapshot-sealer.test-fixture.ts @@ -0,0 +1,78 @@ +// Test-only sealer: the VM's construction (see read-snapshot.ts header) with node:crypto, so the +// desktop opener is checked against an independent implementation rather than itself. +import { + createCipheriv, + createPublicKey, + diffieHellman, + generateKeyPairSync, + hkdfSync, + randomBytes +} from 'node:crypto' +import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' + +const b64 = (bytes: Uint8Array): string => Buffer.from(bytes).toString('base64') + +function gcm(key: Uint8Array, nonce: Uint8Array, plain: Uint8Array, aad: string): Buffer { + const cipher = createCipheriv('aes-256-gcm', key, nonce) + cipher.setAAD(Buffer.from(aad, 'utf8')) + return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()]) +} + +export function sealReadSnapshotForTest(args: { + payload: unknown + workspaceId: string + snapshotId: string + readerPublicKeyB64: string + keyId: string + storedAt?: number +}): SealedReadSnapshot { + const { workspaceId, snapshotId, keyId } = args + const dek = randomBytes(32) + const nonce = randomBytes(12) + const body = gcm( + dek, + nonce, + Buffer.from(JSON.stringify(args.payload), 'utf8'), + `orca-cloud-read-v1:${workspaceId}:${snapshotId}` + ) + const readerPublic = Buffer.from(args.readerPublicKeyB64, 'base64') + const ephemeral = generateKeyPairSync('x25519') + const ephemeralPublic = Buffer.from(ephemeral.publicKey.export({ format: 'jwk' }).x!, 'base64url') + const shared = diffieHellman({ + privateKey: ephemeral.privateKey, + publicKey: createPublicKey({ + key: { kty: 'OKP', crv: 'X25519', x: readerPublic.toString('base64url') }, + format: 'jwk' + }) + }) + const kek = Buffer.from( + hkdfSync( + 'sha256', + shared, + Buffer.concat([ephemeralPublic, readerPublic]), + Buffer.from('orca-cloud-read-wrap-v1', 'utf8'), + 32 + ) + ) + const wrapNonce = randomBytes(12) + const wrapped = gcm( + kek, + wrapNonce, + dek, + `orca-cloud-read-wrap-v1:${workspaceId}:${snapshotId}:${keyId}` + ) + return { + v: 1, + snapshotId, + workspaceId, + storedAt: args.storedAt ?? 1_000, + nonceB64: b64(nonce), + ciphertextB64: b64(body), + recipient: { + keyId, + ephemeralPublicKeyB64: b64(ephemeralPublic), + nonceB64: b64(wrapNonce), + wrappedKeyB64: b64(wrapped) + } + } +} diff --git a/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts b/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts new file mode 100644 index 00000000000..8a6b03d142a --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it, vi } from 'vitest' +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import { createCloudReadMemo } from './cloud-offline-cloud-read' + +const snap = { v: 1, capturedAt: 1 } as ReadSnapshot + +describe('createCloudReadMemo', () => { + it('reads once per workspace while fresh, again after forget', async () => { + const read = vi.fn(async () => snap) + const memo = createCloudReadMemo(read) + expect(await memo.get('w')).toBe(snap) + expect(await memo.get('w')).toBe(snap) + expect(read).toHaveBeenCalledTimes(1) + memo.forget('w') + await memo.get('w') + expect(read).toHaveBeenCalledTimes(2) + }) + + it('never throws and never waits past its budget; a late answer serves the next call', async () => { + let resolve: (value: ReadSnapshot) => void = () => {} + const read = vi.fn(() => new Promise((r) => (resolve = r))) + const memo = createCloudReadMemo(read, { waitMs: 10 }) + expect(await memo.get('w')).toBeNull() + resolve(snap) + expect(await memo.get('w')).toBe(snap) + expect(read).toHaveBeenCalledTimes(1) + const failing = createCloudReadMemo(async () => { + throw new Error('offline') + }) + expect(await failing.get('w')).toBeNull() + }) + + it('is a no-op without a reader', async () => { + expect(await createCloudReadMemo(undefined).get('w')).toBeNull() + }) +}) diff --git a/src/main/hosted-sandbox/cloud-offline-cloud-read.ts b/src/main/hosted-sandbox/cloud-offline-cloud-read.ts new file mode 100644 index 00000000000..317090592c3 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-cloud-read.ts @@ -0,0 +1,82 @@ +// The asleep view's reads of a workspace's sealed sleep snapshot (Orca Cloud), memoized: the +// snapshot only changes when the workspace wakes and sleeps again, and the view polls. +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' +import type { CloudOfflineCache } from './cloud-offline-cache' +import { buildOfflineSnapshot } from './cloud-offline-snapshot' +import { mergeCloudReadSnapshot } from './cloud-offline-snapshot-merge' + +/** The workspace's sealed sleep snapshot opened on this device, or null (none, unreadable). */ +export type CloudSnapshotReader = (workspaceId: string) => Promise + +const TTL_MS = 2 * 60_000 +const FAILED_TTL_MS = 30_000 +/** The asleep view never waits long on the network; a slow read lands on the next poll. */ +const WAIT_MS = 3_000 + +type Entry = { at: number; ttl: number; promise: Promise } + +export function createCloudReadMemo( + read: CloudSnapshotReader | undefined, + options: { waitMs?: number; now?: () => number } = {} +) { + const now = options.now ?? Date.now + const entries = new Map() + const memo = { + /** Resolves null (never throws) when there is none, it failed, or it is not back in time. */ + async get(workspaceId: string): Promise { + if (!read) { + return null + } + let entry = entries.get(workspaceId) + if (!entry || now() - entry.at >= entry.ttl) { + const fresh: Entry = { + at: now(), + ttl: TTL_MS, + promise: read(workspaceId).catch(() => null) + } + void fresh.promise.then((value) => { + if (value === null) { + fresh.ttl = FAILED_TTL_MS + } + }) + entries.set(workspaceId, fresh) + entry = fresh + } + let timer: ReturnType | undefined + const late = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), options.waitMs ?? WAIT_MS) + }) + try { + return await Promise.race([entry.promise, late]) + } finally { + clearTimeout(timer) + } + }, + /** Awake again: the next sleep leaves a new snapshot. */ + forget(workspaceId: string): void { + entries.delete(workspaceId) + }, + clear(): void { + entries.clear() + }, + /** + * The asleep view: this computer's cached copy, with newer sections from the workspace's own + * sleep snapshot while it is asleep. Any cloud failure leaves the cached copy as it was. + */ + async snapshot( + cache: CloudOfflineCache, + info: { environmentId: string; asleep: boolean }, + workspaceId: string + ): Promise { + const local = await buildOfflineSnapshot(cache, info.environmentId, workspaceId, info.asleep) + if (!info.asleep) { + memo.forget(workspaceId) + return local + } + const remote = await memo.get(workspaceId) + return remote ? mergeCloudReadSnapshot(local, remote) : local + } + } + return memo +} diff --git a/src/main/hosted-sandbox/cloud-offline-service.ts b/src/main/hosted-sandbox/cloud-offline-service.ts index 89ee90f9d63..0323ff36a6b 100644 --- a/src/main/hosted-sandbox/cloud-offline-service.ts +++ b/src/main/hosted-sandbox/cloud-offline-service.ts @@ -29,12 +29,8 @@ import { import { createOwedWorkBeat } from './cloud-offline-beat' import { setCloudOfflineReset } from './cloud-offline-reset' import { safeStorageCodec, setCloudOfflineObserver } from './cloud-offline-seam' -import { - archiveCheckoutsFromCache, - buildOfflineSnapshot, - stringParam, - terminalHandlesOf -} from './cloud-offline-snapshot' +import { archiveCheckoutsFromCache, stringParam, terminalHandlesOf } from './cloud-offline-snapshot' +import { createCloudReadMemo, type CloudSnapshotReader } from './cloud-offline-cloud-read' import { getHostedWorkspaceService, setArchiveCheckoutsProvider } from './hosted-workspace-service' type CloudRuntimeInfo = { @@ -71,6 +67,11 @@ export function installCloudOfflineService(deps: { windows: () => readonly BrowserWindow[] /** The control plane says the workspace is archived (nothing wakes or sends to it). */ isArchived: (workspaceId: string) => Promise + /** + * The workspace's own sealed sleep snapshot, opened on this device (never wakes it). Null when + * there is none or it cannot be read; the view then shows this computer's copy alone. + */ + readCloudSnapshot?: CloudSnapshotReader codec?: OfflineCacheCodec | null log?: (line: string) => void }): CloudOfflineService { @@ -122,6 +123,8 @@ export function installCloudOfflineService(deps: { memo = null } + const cloudReads = createCloudReadMemo(deps.readCloudSnapshot) + const broadcast = (channel: string, payload: unknown): void => { for (const window of deps.windows()) { if (!window.isDestroyed()) { @@ -252,6 +255,7 @@ export function installCloudOfflineService(deps: { } }) setCloudOfflineReset(() => { + cloudReads.clear() void cache.clear() queue.clear() }) @@ -274,9 +278,7 @@ export function installCloudOfflineService(deps: { async (_event, args: { workspaceId: string }): Promise => { invalidate() const info = runtimes().byWorkspace.get(args.workspaceId) - return info - ? await buildOfflineSnapshot(cache, info.environmentId, args.workspaceId, info.asleep) - : null + return info ? await cloudReads.snapshot(cache, info, args.workspaceId) : null } ) ipcMain.handle( diff --git a/src/main/hosted-sandbox/cloud-offline-snapshot-merge.test.ts b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.test.ts new file mode 100644 index 00000000000..2ff941b247e --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest' +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' +import { mergeCloudReadSnapshot } from './cloud-offline-snapshot-merge' + +const local: CloudOfflineSnapshot = { + workspaceId: 'w', + asleep: true, + capturedAt: 1_000, + git: { + branch: 'old', + head: 'aaa', + changes: [{ path: 'a.ts', status: 'modified', area: 'unstaged' }], + changeCount: 1, + commits: [], + at: 1_000 + }, + terminals: [{ handle: 'h', title: null, lines: ['x'], at: 1_000 }], + chats: [ + { sessionId: 's1', at: 1_000, messages: [{ itemId: 'a', role: 'user', text: 'hi', at: 1 }] }, + { sessionId: 's9', at: 900, messages: [{ itemId: 'z', role: 'user', text: 'kept', at: 1 }] } + ], + source: 'device' +} + +function remote(capturedAt: number): ReadSnapshot { + return { + v: 1, + workspaceId: 'sbx', + snapshotId: 'snap', + capturedAt, + reason: 'sleep', + git: { + branch: 'new', + head: 'bbb', + changes: [{ path: 'b.ts', status: 'added', area: 'untracked', added: 5, removed: 0 }], + changeCount: 1, + added: 5, + removed: 0, + commits: [] + }, + pr: { + number: 7, + title: 'PR', + state: 'open', + url: 'https://github.com/a/b/pull/7', + checksStatus: 'success', + checksSummary: null + }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'T', + status: 'idle', + turnOutcome: 'done', + updatedAt: null, + messages: [{ itemId: 'b', role: 'assistant', text: 'newer', at: 2 }], + truncated: false + }, + { + sessionId: 's2', + agent: 'codex', + title: null, + status: 'working', + turnOutcome: null, + updatedAt: null, + messages: [{ itemId: 'c', role: 'user', text: 'only in cloud', at: 2 }], + truncated: false + } + ] + } +} + +describe('mergeCloudReadSnapshot', () => { + it('takes newer cloud sections, keeps terminals and chats the snapshot lacks', () => { + const merged = mergeCloudReadSnapshot(local, remote(2_000)) + expect(merged.git).toMatchObject({ branch: 'new', at: 2_000, added: 5 }) + expect(merged.git?.changes[0]).toMatchObject({ path: 'b.ts', added: 5 }) + expect(merged.terminals).toEqual(local.terminals) + expect(merged.chats.map((chat) => chat.sessionId)).toEqual(['s1', 's2', 's9']) + expect(merged.chats[0]).toMatchObject({ agent: 'claude', title: 'T' }) + expect(merged.chats[0]!.messages[0]!.text).toBe('newer') + expect(merged.pr?.number).toBe(7) + expect(merged.capturedAt).toBe(2_000) + expect(merged.source).toBe('mixed') + }) + + it('keeps the local copy where it is newer, but adds what only the cloud has', () => { + const merged = mergeCloudReadSnapshot(local, remote(500)) + expect(merged.git?.branch).toBe('old') + expect(merged.chats.find((chat) => chat.sessionId === 's1')!.messages[0]!.text).toBe('hi') + expect(merged.chats.some((chat) => chat.sessionId === 's2')).toBe(true) + expect(merged.pr?.number).toBe(7) + expect(merged.capturedAt).toBe(1_000) + }) + + it('fills an empty local cache entirely from the cloud', () => { + const empty: CloudOfflineSnapshot = { + workspaceId: 'w', + asleep: true, + capturedAt: null, + git: null, + terminals: [], + chats: [] + } + const merged = mergeCloudReadSnapshot(empty, remote(2_000)) + expect(merged.capturedAt).toBe(2_000) + expect(merged.source).toBe('cloud') + expect(merged.git?.branch).toBe('new') + expect(merged.chats).toHaveLength(2) + }) +}) diff --git a/src/main/hosted-sandbox/cloud-offline-snapshot-merge.ts b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.ts new file mode 100644 index 00000000000..88979adebe4 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.ts @@ -0,0 +1,62 @@ +// Folds a sleeping workspace's sealed read snapshot (Orca Cloud) into this computer's cached copy. +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' + +const MAX_CHANGES = 300 + +/** + * Folds the workspace's own sealed sleep snapshot into this computer's cached copy: each section + * (git, each chat) comes from whichever is newer, so the view is never older than either. The cache + * keeps terminals (the snapshot has none); the PR only exists in the snapshot. + */ +export function mergeCloudReadSnapshot( + local: CloudOfflineSnapshot, + remote: ReadSnapshot +): CloudOfflineSnapshot { + const at = remote.capturedAt + let fromCloud = false + let git = local.git + if (remote.git && (!local.git || at > local.git.at)) { + fromCloud = true + git = { + branch: remote.git.branch, + head: remote.git.head, + changes: remote.git.changes.slice(0, MAX_CHANGES).map((change) => ({ ...change })), + changeCount: remote.git.changeCount, + commits: remote.git.commits.map((commit) => ({ ...commit })), + at, + added: remote.git.added, + removed: remote.git.removed + } + } + const chats = new Map(local.chats.map((chat) => [chat.sessionId, chat])) + for (const session of remote.sessions) { + const known = chats.get(session.sessionId) + // A session the snapshot saw with no messages adds nothing a cached transcript lacks. + if (session.messages.length === 0 && known) { + continue + } + if (!known || at > known.at) { + fromCloud = true + chats.set(session.sessionId, { + sessionId: session.sessionId, + at, + messages: session.messages.map((message) => ({ ...message })), + agent: session.agent, + title: session.title + }) + } + } + const pr = remote.pr ? { ...remote.pr } : (local.pr ?? null) + fromCloud ||= pr !== null && local.pr == null + const hadLocal = local.capturedAt !== null + const times = [local.capturedAt ?? 0, fromCloud ? at : 0].filter((time) => time > 0) + return { + ...local, + capturedAt: times.length > 0 ? Math.max(...times) : null, + git, + chats: [...chats.values()].sort((a, b) => b.at - a.at), + pr, + source: !fromCloud ? (local.source ?? 'device') : hadLocal ? 'mixed' : 'cloud' + } +} diff --git a/src/main/hosted-sandbox/cloud-offline-snapshot.ts b/src/main/hosted-sandbox/cloud-offline-snapshot.ts index 27233aa83a8..2965d500959 100644 --- a/src/main/hosted-sandbox/cloud-offline-snapshot.ts +++ b/src/main/hosted-sandbox/cloud-offline-snapshot.ts @@ -227,7 +227,8 @@ export async function buildOfflineSnapshot( capturedAt: times.length > 0 ? Math.max(...times) : null, git, terminals, - chats + chats, + source: 'device' } } diff --git a/src/main/hosted-sandbox/hosted-sandbox-install.ts b/src/main/hosted-sandbox/hosted-sandbox-install.ts index 923ca2a52c2..70cb592cd3d 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-install.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-install.ts @@ -21,6 +21,7 @@ import { createHostedSandboxDeviceEnroller } from './hosted-sandbox-device-enrol import { registerOrcaCloudDeviceEnroller } from '../runtime/rpc/methods/orca-cloud/orca-cloud-device-enrollment' import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' import { registerCloudRemoteDesktopHandlers } from '../ipc/cloud-remote-desktop' +import { readCloudWorkspaceSnapshot } from '../ipc/cloud-workspaces' import { ORCA_CLOUD_RECIPE, createHostedSandboxRecipeClient, @@ -157,6 +158,11 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo return found ? (await client.workspaceStatus(found.sandboxId)).status.state === 'archived' : false + }, + readCloudSnapshot: async (workspaceId) => { + const found = findCloudRuntime(userDataPath, workspaceId) + const read = found ? await readCloudWorkspaceSnapshot(found.sandboxId) : null + return read?.state === 'ready' ? read.snapshot : null } }) setCloudOfflineService(offline) diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index 01df642c556..9a9c44831b1 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -11,6 +11,10 @@ import { createCloudWorkspacesService, type CloudWorkspacesService } from '../cloud-workspaces/cloud-workspaces-service' +import { getCloudReaderKeyStore } from '../cloud-workspaces/cloud-reader-key-store' +import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader' +import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' +import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/) const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/) @@ -60,7 +64,8 @@ function getService(): Promise { service = createCloudWorkspacesService({ userDataPath, config, - clientId: await clientIdFor(userDataPath) + clientId: await clientIdFor(userDataPath), + readerKey: profileReaderKey(userDataPath) }) return service })() @@ -74,6 +79,36 @@ function getService(): Promise { return starting } +/** The active Orca profile's reader key; registrations follow its signed-in user and account. */ +function profileReaderKey(userDataPath: string): ReaderKeyAccess { + return { + identity: () => { + const active = ensureActiveOrcaProfile(userDataPath) + const cloud = active.profile.cloud + return cloud + ? JSON.stringify([active.profile.id, cloud.userId ?? null, cloud.activeOrgId ?? null]) + : null + }, + load: () => + getCloudReaderKeyStore(userDataPath).load(ensureActiveOrcaProfile(userDataPath).profile.id) + } +} + +/** + * The owner's asleep view merges this in (main process). Null when it cannot be read (no control + * plane, keychain, network); the view then keeps showing this computer's own copy. + */ +export async function readCloudWorkspaceSnapshot( + sandboxId: string +): Promise { + if (!Id.safeParse(sandboxId).success) { + return null + } + const s = await getService().catch(() => null) + const result = await s?.readSnapshot(sandboxId) + return result?.ok ? result.value : null +} + /** Stable per-install id for presence rows (one row per device, not per window). */ async function clientIdFor(userDataPath: string): Promise { const file = join(userDataPath, 'cloud-workspaces-client-id') @@ -187,6 +222,11 @@ export function registerCloudWorkspacesHandlers(): void { const s = await getService() return !s ? NOT_CONFIGURED : parsed.success ? s.openGrant(parsed.data.id) : INVALID }) + handle('cloudWorkspaces:readSnapshot', async (args) => { + const parsed = z.object({ id: Id }).safeParse(args) + const s = await getService() + return !s ? NOT_CONFIGURED : parsed.success ? s.readSnapshot(parsed.data.id) : INVALID + }) handle('cloudWorkspaces:listGrants', async (args) => { const parsed = z.object({ id: Id }).safeParse(args) const s = await getService() diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index bc4cd0295b8..f39e47f7337 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -1,4 +1,5 @@ import { resetCloudOfflineData } from '../hosted-sandbox/cloud-offline-reset' +import { clearCloudReaderKey } from '../cloud-workspaces/cloud-reader-key-store' import type { ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileArgs, @@ -175,6 +176,8 @@ export async function signOutCurrentOrcaProfile( const list = unlinkOrcaProfileFromCloud(active.profile.id, userDataPath) // Cached Orca Cloud transcripts and queued prompts belong to the signed-out account. resetCloudOfflineData() + // The next account signed in on this profile gets its own reader key. + clearCloudReaderKey(active.profile.id, userDataPath) try { clearRelayRegionPreferenceCache(userDataPath) } catch { diff --git a/src/preload/api/cloud-workspaces-api.ts b/src/preload/api/cloud-workspaces-api.ts index 0e37a68192e..0e419815469 100644 --- a/src/preload/api/cloud-workspaces-api.ts +++ b/src/preload/api/cloud-workspaces-api.ts @@ -5,6 +5,7 @@ import type { CloudWorkspacePatch, OrgPrompts } from '../../shared/cloud-workspaces/cloud-workspaces-wire' +import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' export type CloudWorkspacesResult = | { ok: true; value: T } @@ -33,6 +34,8 @@ export type CloudWorkspacesApi = { openGrant: ( id: string ) => Promise> + /** A sleeping workspace's sealed read snapshot, opened in main with this device's reader key. Never wakes it. */ + readSnapshot: (id: string) => Promise> listGrants: (id: string) => Promise> revokeGrant: (id: string, grantId: string) => Promise> localWorkspaces: () => Promise diff --git a/src/preload/api/cloud-workspaces-bridge.ts b/src/preload/api/cloud-workspaces-bridge.ts index c35320aa55f..a8ea180d427 100644 --- a/src/preload/api/cloud-workspaces-bridge.ts +++ b/src/preload/api/cloud-workspaces-bridge.ts @@ -9,6 +9,7 @@ export const cloudWorkspacesApi = { resolveLink: (workspaceId, chatId) => ipcRenderer.invoke('cloudWorkspaces:resolveLink', { workspaceId, chatId }), openGrant: (id) => ipcRenderer.invoke('cloudWorkspaces:openGrant', { id }), + readSnapshot: (id) => ipcRenderer.invoke('cloudWorkspaces:readSnapshot', { id }), listGrants: (id) => ipcRenderer.invoke('cloudWorkspaces:listGrants', { id }), revokeGrant: (id, grantId) => ipcRenderer.invoke('cloudWorkspaces:revokeGrant', { id, grantId }), localWorkspaces: () => ipcRenderer.invoke('cloudWorkspaces:localWorkspaces'), diff --git a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx new file mode 100644 index 00000000000..688f0153c35 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx @@ -0,0 +1,58 @@ +// The team list's read-only view of an Asleep workspace: what it looked like when it went to +// sleep, read from the copy it sealed to this computer's key. Opening it never wakes the sandbox; +// "Wake to continue" runs the normal open flow. +import React, { useEffect, useState } from 'react' +import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { CloudReadSnapshotView } from '../orca-cloud/read-snapshot/CloudReadSnapshotView' +import { cloudWorkspaceTitle } from './open-cloud-workspace' +import { useCloudReadSnapshot } from './use-cloud-read-snapshot' + +export function CloudReadSnapshotSheet({ + workspace, + waking, + onWake, + onClose +}: { + /** Null keeps the sheet closed. */ + workspace: CloudWorkspace | null + waking: boolean + onWake: (w: CloudWorkspace) => void + onClose: () => void +}): React.JSX.Element { + const { state, retry, retrying } = useCloudReadSnapshot(workspace?.id ?? null) + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + if (!workspace) { + return + } + setNow(Date.now()) + return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 30_000 }) + }, [workspace]) + const title = workspace ? cloudWorkspaceTitle(workspace) : '' + return ( + !open && onClose()}> + + {/* The view's own heading is the visible title; Radix needs one for the dialog name. */} + {title} + {workspace ? ( +
+ onWake(workspace)} + onRetry={retry} + retrying={retrying} + /> +
+ ) : null} +
+
+ ) +} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx index b85b1402eb1..c65d1b09e81 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx @@ -13,6 +13,7 @@ import { const WIDTH = 760 const ACTIONS: RowActions = { open: () => {}, + read: () => {}, copyLink: () => {}, copyWorkspaceLink: () => {}, goToChat: () => {}, diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx index d0a2ba297a9..6c1dfdab1e7 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx @@ -11,7 +11,7 @@ import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-w import { CloudStateDot } from '../orca-cloud/CloudStateDot' import type { CloudDotState } from '@/lib/orca-cloud/orca-cloud-workspace-state' import { MemberAvatar, PresenceStack } from './CloudMemberAvatars' -import { CloudWorkspaceRowMenu, type RowActions } from './CloudWorkspaceRowMenu' +import { CloudWorkspaceRowMenu, isReadableAsleep, type RowActions } from './CloudWorkspaceRowMenu' import { formatSandboxHours, formatRelative, @@ -112,6 +112,9 @@ export function CloudWorkspaceRow({ } }, [highlighted]) const canOpen = w.access !== 'none' + // Asleep: Enter / click reads the saved copy; waking is its own explicit action. + const readable = isReadableAsleep(w) + const primary = readable ? actions.read : actions.open const cost = formatUsdMicros(w.cost.totalUsdMicros, intlLocale) const lastActive = formatRelative(w.lastActivityAt, now, t, intlLocale) const presence = presenceSummary( @@ -179,7 +182,7 @@ export function CloudWorkspaceRow({ )} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx index d1b15467fd8..e94a44b661a 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx @@ -3,11 +3,13 @@ import { Archive, ArchiveRestore, ArrowUpRight, + BookOpen, FolderInput, FolderPlus, Link2, Lock, MoreHorizontal, + Play, UserRoundCog, Users } from 'lucide-react' @@ -37,7 +39,10 @@ import { MemberAvatar } from './CloudMemberAvatars' import { memberName, presentMembers, type MemberDirectory } from './cloud-workspace-format' export type RowActions = { + /** Opens it, waking it first when it is asleep. */ open: (w: CloudWorkspace) => void + /** Asleep: the read-only copy it saved when it went to sleep (never wakes it). */ + read: (w: CloudWorkspace) => void /** The link to the chat you have in front when this workspace is in front, else the workspace. */ copyLink: (w: CloudWorkspace) => void copyWorkspaceLink: (w: CloudWorkspace) => void @@ -53,6 +58,15 @@ const NO_SECTION = '\u0000none' // Keeps submenus off the window edge when the row sits near the bottom of Home. const SUBMENU_COLLISION_PADDING = 8 +/** An Asleep workspace this account can open: its row reads the saved copy instead of waking. */ +export function isReadableAsleep(w: CloudWorkspace): boolean { + return ( + w.archivedAt === null && + w.access !== 'none' && + (w.status === 'suspended' || w.status === 'suspending') + ) +} + export function CloudWorkspaceRowMenu({ workspace: w, title, @@ -116,7 +130,20 @@ export function CloudWorkspaceRowMenu({ } }} > - {canOpen && ( + {canOpen && isReadableAsleep(w) && ( + <> + actions.read(w)}> + + {t('auto.components.cloudWorkspaces.viewAsleep', 'View read-only copy')} + ↵ + + actions.open(w)}> + + {t('components.orcaCloud.read.wakeToContinue', 'Wake to continue')} + + + )} + {canOpen && !isReadableAsleep(w) && ( actions.open(w)}> {t('auto.components.cloudWorkspaces.open', 'Open')} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx index 06bffc8fc40..662685960cb 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx @@ -6,6 +6,7 @@ import { teamWorkspaces, workspace } from './cloud-workspaces.test-fixture' +import type { CloudReadSnapshotState } from '../../../../shared/cloud-workspaces/read-snapshot-state' const WIDTH = 760 @@ -66,3 +67,101 @@ export const emptyTeam = defineFixture({ render: () => , interact: () => waitFor(() => document.querySelector('section p') !== null) }) + +const ASLEEP_ID = 'sbx_00000000000000000000a51e' + +function stubAsleep(answer: () => Promise): void { + const rows = [ + workspace({ + id: ASLEEP_ID, + title: 'Checkout retries', + status: 'suspended', + ownerUserId: 'user_grace', + createdBy: 'user_grace', + access: 'can_open' + }) + ] + stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows })) + Object.assign(window.api.cloudWorkspaces, { + readSnapshot: async () => ({ ok: true as const, value: await answer() }) + }) +} + +async function openAsleepRow(): Promise { + await waitFor(() => document.querySelector('[data-cloud-workspace-row] button') !== null) + document.querySelector('[data-cloud-workspace-row] button')?.click() + await waitFor( + () => + document.querySelector('[data-cloud-read-view]:not([data-cloud-read-view="loading"])') !== + null + ) +} + +/** Clicking a teammate's Asleep row opens its read-only copy in a sheet (no wake). */ +export const asleepReadView = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => + stubAsleep(async () => ({ + state: 'ready', + storedAt: Date.now() - 20 * 60_000, + snapshot: { + v: 1, + workspaceId: ASLEEP_ID, + snapshotId: 'snap_1', + capturedAt: Date.now() - 20 * 60_000, + reason: 'sleep', + pr: { + number: 412, + title: 'Retry checkout webhooks with backoff', + state: 'open', + url: 'https://github.com/acme/web/pull/412', + checksStatus: 'success', + checksSummary: '9/9 passed' + }, + git: { + branch: 'checkout-retries', + head: '3f95655', + changeCount: 1, + added: 88, + removed: 19, + changes: [ + { + path: 'src/payments/webhooks.ts', + status: 'modified', + area: 'unstaged', + added: 88, + removed: 19 + } + ], + commits: [] + }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'Retry failed checkout webhooks', + status: 'idle', + turnOutcome: 'done', + updatedAt: null, + truncated: false, + messages: [ + { itemId: 'm1', role: 'user', text: 'Retry failed webhooks with backoff.', at: 0 }, + { itemId: 'm2', role: 'assistant', text: 'Done. Tests pass.', at: 0 } + ] + } + ] + } + })), + render: () => , + interact: openAsleepRow +}) + +/** The snapshot predates this computer's reader key. */ +export const asleepNotSealedForKey = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => stubAsleep(async () => ({ state: 'not_sealed_for_key' })), + render: () => , + interact: openAsleepRow +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index ba5dab24ac0..49ff2e5a1da 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -17,6 +17,7 @@ import { NEW_SECTION } from './CloudWorkspaceRowMenu' import { ANY, CloudWorkspacesToolbar, type CloudWorkspacesFilters } from './CloudWorkspacesToolbar' import { EmptyState, ErrorState, NewSectionDialog, SkeletonRows } from './CloudWorkspacesStates' import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog' +import { CloudReadSnapshotSheet } from './CloudReadSnapshotSheet' import { formatUsdMicros, type MemberDirectory } from './cloud-workspace-format' import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender' import { describeError } from './cloud-workspace-errors' @@ -85,6 +86,8 @@ export function CloudWorkspacesHome({ const [now, setNow] = useState(() => Date.now()) const [sectionFor, setSectionFor] = useState(null) const [confirm, setConfirm] = useState(null) + // The Asleep workspace whose read-only copy is open (never wakes it). + const [readingId, setReadingId] = useState(null) const signIn = useAppStore((s) => s.connectCurrentOrcaProfile) const scope = orgId ? filters.scope : 'mine' const { state, stale, reading, refresh, replace } = useCloudWorkspaces( @@ -171,7 +174,11 @@ export function CloudWorkspacesHome({ const outcome = await openCloudWorkspace(w) if (!outcome.ok) { toast.error(outcome.message) - } else if (chatId) { + return + } + // Woken from its read-only copy: the live workspace replaces it. + setReadingId((current) => (current === w.id ? null : current)) + if (chatId) { await focusCloudChat(outcome.worktreeId, chatId) } } finally { @@ -232,6 +239,7 @@ export function CloudWorkspacesHome({ const actions = useMemo( () => ({ open: (w: CloudWorkspace) => void open(w), + read: (w: CloudWorkspace) => setReadingId(w.id), copyLink: (w: CloudWorkspace) => { const front = frontCloudChat() void copyCloudWorkspaceLink(w.id, front?.sandboxId === w.id ? front.chatId : null) @@ -357,6 +365,14 @@ export function CloudWorkspacesHome({ : null} + w.id === readingId) ?? null) : null} + waking={opening !== null && opening === readingId} + onWake={(w) => void open(w)} + onClose={() => setReadingId(null)} + /> + {confirm && ( void + retrying: boolean +} { + const t = useTranslate() + const [state, setState] = useState({ kind: 'loading' }) + const [attempt, setAttempt] = useState(0) + const [retrying, setRetrying] = useState(false) + const asked = useRef(id) + asked.current = id + + useEffect(() => { + if (!id) { + return + } + let live = true + void window.api.cloudWorkspaces + .readSnapshot(id) + .catch((): { ok: false; error: string; reason?: string } => ({ + ok: false, + error: 'unavailable' + })) + .then((result) => { + if (!live || asked.current !== id) { + return + } + setRetrying(false) + if (!result.ok) { + setState({ + kind: 'error', + message: + result.error === 'snapshot_unreadable' + ? t( + 'components.orcaCloud.read.unreadable', + "Couldn't open the saved copy on this computer. Your files are safe." + ) + : describeError(result.error, result.reason, t) + }) + return + } + const value = result.value + setState( + value.state === 'ready' + ? { kind: 'ready', snapshot: value.snapshot } + : value.state === 'unavailable' + ? { kind: 'unavailable', message: value.message } + : { kind: value.state } + ) + }) + return () => { + live = false + } + }, [id, attempt, t]) + + // A different workspace starts from the skeleton, never the previous one's copy. + const [shownFor, setShownFor] = useState(id) + if (shownFor !== id) { + setShownFor(id) + setState({ kind: 'loading' }) + setRetrying(false) + } + + const retry = useCallback(() => { + setRetrying(true) + setAttempt((value) => value + 1) + }, []) + + return { state, retry, retrying } +} diff --git a/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx b/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx index 5acf9a3f0e8..0bb70063c05 100644 --- a/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx +++ b/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx @@ -17,7 +17,15 @@ export type CloudGitChangesData = { behind?: number | null /** A `--shortstat` line, if captured. */ diffStat?: string | null - changes: readonly { status: string; path: string }[] + /** Line totals when known directly (the sleep snapshot); wins over `diffStat`. */ + lineTotals?: { added: number; removed: number } | null + /** Per-file line counts are optional: only the sleep snapshot has them. */ + changes: readonly { + status: string + path: string + added?: number | null + removed?: number | null + }[] /** Total uncommitted changes when `changes` was capped. */ changeCount?: number commits: readonly { sha: string; subject: string; at: number | null }[] @@ -68,8 +76,10 @@ export function CloudGitChanges({ now: number }): React.JSX.Element { const t = useTranslate() - const stat = parseDiffStat(data.diffStat) const totalChanges = Math.max(data.changeCount ?? 0, data.changes.length) + const stat = data.lineTotals + ? { files: totalChanges, insertions: data.lineTotals.added, deletions: data.lineTotals.removed } + : parseDiffStat(data.diffStat) return (
{kindLabel(kind, t)}: - {change.path} + {change.path} + {typeof change.added === 'number' || typeof change.removed === 'number' ? ( + + + +{change.added ?? 0} + {' '} + + −{change.removed ?? 0} + + + ) : null} ) })} diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceHeader.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceHeader.tsx index b33f3547dd4..d74a4ee4cc7 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceHeader.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceHeader.tsx @@ -12,6 +12,7 @@ export function CloudWorkspaceHeader({ title, state, stateLine, + stateTitle, note, action, headingRef @@ -20,6 +21,8 @@ export function CloudWorkspaceHeader({ title: string state: CloudDotState stateLine: string + /** Hover text for the state line (e.g. the absolute time behind "As of 5 minutes ago"). */ + stateTitle?: string /** One quieter sentence under the state line. */ note?: string action?: React.ReactNode @@ -40,7 +43,9 @@ export function CloudWorkspaceHeader({

- {stateLine} + + {stateLine} +

{note ?

{note}

: null}
diff --git a/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx b/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx index c81f83f95bb..e4ac3c77f54 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx @@ -200,7 +200,8 @@ export function ChatPanel({ aria-pressed={candidate.sessionId === chat.sessionId} onClick={() => setSelected(candidate.sessionId)} > - {candidate.messages.find((m) => m.role === 'user')?.text.slice(0, 40) ?? + {candidate.title?.slice(0, 40) ?? + candidate.messages.find((m) => m.role === 'user')?.text.slice(0, 40) ?? t('components.orcaCloud.offline.chatN', 'Chat {{n}}', { n: index + 1 })} ))} diff --git a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx index be4b164e2dd..ceeecc4ad1a 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx @@ -209,3 +209,44 @@ export const deliveryFailed = defineFixture({ /> ) }) + +/** Merged with the copy the workspace saved when it went to sleep: PR, line counts, "As of". */ +export const withCloudSnapshot = defineFixture({ + width: 900, + render: () => + frame( + ({ + ...change, + added: [120, 54, 8][index] ?? 0, + removed: [0, 37, 4][index] ?? 0 + })) + } + }} + queued={[]} + workspaceName="fix-auth-redirect" + now={NOW} + onWake={noop} + onQueue={yes} + onCancel={noop} + onEdit={yes} + /> + ) +}) diff --git a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx index bac1b590076..989bd4b54f7 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx @@ -7,9 +7,10 @@ import type { import { Button } from '@/components/ui/button' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { useTranslate } from '@/i18n/use-translate' -import { formatRelative } from '@/lib/orca-cloud/orca-cloud-workspace-state' import { CloudGitChanges } from '../CloudGitChanges' import { CloudWorkspaceHeader } from '../CloudWorkspaceHeader' +import { asOfParts } from '../read-snapshot/cloud-read-snapshot-format' +import { CloudReadPrLink } from '../read-snapshot/CloudReadPrLink' import { ChatPanel } from './CloudOfflineChatPanel' export type CloudOfflineViewProps = { @@ -43,11 +44,12 @@ export function CloudWorkspaceOfflineView(props: CloudOfflineViewProps): React.J const defaultTab = snapshot.chats.length > 0 ? 'chat' : snapshot.terminals.length > 0 ? 'terminals' : 'changes' const empty = snapshot.capturedAt === null - const stateLine = empty - ? t('orcaCloudWorkspace.asleep.noCopy', 'Asleep · nothing cached yet') - : t('orcaCloudWorkspace.asleep.copyFrom', 'Asleep · copy from {{when}}', { - when: formatRelative(snapshot.capturedAt!, now) - }) + const asOf = snapshot.capturedAt === null ? null : asOfParts(snapshot.capturedAt, now) + const stateLine = asOf + ? t('components.orcaCloud.read.asOf', 'Asleep · As of {{when}}', { when: asOf.relative }) + : t('orcaCloudWorkspace.asleep.noCopy', 'Asleep · nothing cached yet') + // Sections may come from the copy the workspace saved when it went to sleep (Orca Cloud). + const fromCloud = snapshot.source === 'cloud' || snapshot.source === 'mixed' return (
) : ( - - - - {t('components.orcaCloud.offline.tabChat', 'Chat')} - {snapshot.chats.length > 0 ? ( - {snapshot.chats.length} - ) : null} - - - {t('components.orcaCloud.offline.tabTerminals', 'Terminals')} - {snapshot.terminals.length > 0 ? ( - {snapshot.terminals.length} - ) : null} - - - {t('components.orcaCloud.offline.tabChanges', 'Changes')} - {changeCount > 0 ? ( - {changeCount} - ) : null} - - - - - - -
- {snapshot.terminals.length === 0 ? ( -

- {t('components.orcaCloud.offline.noTerminals', 'No terminal output was saved.')} -

- ) : ( -
- {snapshot.terminals.map((terminal) => { - const title = terminal.title ?? terminal.handle - return ( -
-
-
-
+          {snapshot.pr ?  : null}
+          
+            
+              
+                {t('components.orcaCloud.offline.tabChat', 'Chat')}
+                {snapshot.chats.length > 0 ? (
+                  {snapshot.chats.length}
+                ) : null}
+              
+              
+                {t('components.orcaCloud.offline.tabTerminals', 'Terminals')}
+                {snapshot.terminals.length > 0 ? (
+                  {snapshot.terminals.length}
+                ) : null}
+              
+              
+                {t('components.orcaCloud.offline.tabChanges', 'Changes')}
+                {changeCount > 0 ? (
+                  {changeCount}
+                ) : null}
+              
+            
+            
+              
+            
+            
+              
+ {snapshot.terminals.length === 0 ? ( +

+ {t('components.orcaCloud.offline.noTerminals', 'No terminal output was saved.')} +

+ ) : ( +
+ {snapshot.terminals.map((terminal) => { + const title = terminal.title ?? terminal.handle + return ( +
- {terminal.lines.join('\n')} -
-
- ) - })} -
- )} -
-
- -
- {snapshot.git ? ( - ({ - sha: commit.id, - subject: commit.subject, - at: commit.at - })) - }} - /> - ) : ( -

- {t('components.orcaCloud.offline.noGit', 'No source control state was saved.')} -

- )} -
-
-
+
+
+
+                            {terminal.lines.join('\n')}
+                          
+ + ) + })} + + )} + + + +
+ {snapshot.git ? ( + ({ + sha: commit.id, + subject: commit.subject, + at: commit.at + })) + }} + /> + ) : ( +

+ {t('components.orcaCloud.offline.noGit', 'No source control state was saved.')} +

+ )} +
+
+ + )}
) diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadPrLink.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadPrLink.tsx new file mode 100644 index 00000000000..553abc5d749 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadPrLink.tsx @@ -0,0 +1,56 @@ +import React from 'react' +import { CircleCheck, CircleDashed, CircleX, GitPullRequest, Minus } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { CloudOfflinePr } from '../../../../../shared/hosted-sandbox/cloud-workspace-offline-api' +import { + checksLabel, + checksTone, + prStateLabel, + type ChecksTone +} from './cloud-read-snapshot-format' + +const TONE: Record = { + success: { icon: CircleCheck, className: 'text-status-success' }, + failure: { icon: CircleX, className: 'text-destructive' }, + pending: { icon: CircleDashed, className: 'text-status-warning-text' }, + neutral: { icon: Minus, className: 'text-muted-foreground' } +} + +/** The workspace's pull request as of its last sleep: a link out plus its checks. */ +export function CloudReadPrLink({ pr }: { pr: CloudOfflinePr }): React.JSX.Element { + const t = useTranslate() + const tone = checksTone(pr.checksStatus) + const Icon = TONE[tone].icon + const checks = checksLabel(tone, t) + return ( + + ) +} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx new file mode 100644 index 00000000000..6d2f2e6bc9b --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx @@ -0,0 +1,135 @@ +import React, { useId, useState } from 'react' +import { Bot, ChevronDown } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { + ReadSnapshotAgentStatus, + ReadSnapshotSession +} from '../../../../../shared/cloud-workspaces/read-snapshot' +import { agentStatusLabel } from './cloud-read-snapshot-format' + +/** Messages shown before "Show more": enough to see where the agent left off. */ +const COLLAPSED_MESSAGES = 2 + +const STATUS_TONE: Record = { + working: 'text-foreground', + attention: 'text-status-warning-text', + idle: 'text-muted-foreground', + unknown: 'text-muted-foreground' +} + +function SessionCard({ session }: { session: ReadSnapshotSession }): React.JSX.Element { + const t = useTranslate() + const [expanded, setExpanded] = useState(false) + const listId = useId() + const hidden = Math.max(0, session.messages.length - COLLAPSED_MESSAGES) + const shown = expanded ? session.messages : session.messages.slice(-COLLAPSED_MESSAGES) + const title = + session.title ?? + session.messages.find((message) => message.role === 'user')?.text.slice(0, 80) ?? + t('components.orcaCloud.read.untitledChat', 'Untitled chat') + return ( +
  • +
    + + {title} + {session.agent ? ( + + {session.agent} + + ) : null} + + {agentStatusLabel(session.status, session.turnOutcome, t)} + +
    + {session.messages.length === 0 ? ( +

    + {t('components.orcaCloud.read.noMessages', 'No messages were saved for this chat.')} +

    + ) : ( +
      + {shown.map((message) => ( +
    1. + + {message.role === 'user' + ? t('components.orcaCloud.read.roleUser', 'Person:') + : t('components.orcaCloud.read.roleAgent', 'Agent:')}{' '} + + {message.text} +
    2. + ))} +
    + )} + {hidden > 0 || session.truncated ? ( +
    + {hidden > 0 ? ( + + ) : null} + {session.truncated && (expanded || hidden === 0) ? ( + + {t( + 'components.orcaCloud.read.truncated', + 'Older messages are in the workspace. Wake it to read them.' + )} + + ) : null} +
    + ) : null} +
  • + ) +} + +/** Each agent chat as it was when the workspace went to sleep: agent, status and the tail. */ +export function CloudReadSessions({ + sessions +}: { + sessions: readonly ReadSnapshotSession[] +}): React.JSX.Element { + const t = useTranslate() + if (sessions.length === 0) { + return ( +

    + {t('components.orcaCloud.read.noSessions', 'No agent chats were open.')} +

    + ) + } + return ( +
      + {sessions.map((session) => ( + + ))} +
    + ) +} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx new file mode 100644 index 00000000000..c4070685ea2 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx @@ -0,0 +1,179 @@ +import { defineFixture } from '../../../component-fixtures/component-fixture' +import type { ReadSnapshot } from '../../../../../shared/cloud-workspaces/read-snapshot' +import { CloudReadSnapshotView, type CloudReadViewState } from './CloudReadSnapshotView' + +const NOW = 1_794_230_000_000 +const MIN = 60_000 + +const snapshot: ReadSnapshot = { + v: 1, + workspaceId: 'sbx_00000000000000000000beef', + snapshotId: 'snap_1', + capturedAt: NOW - 42 * MIN, + reason: 'sleep', + pr: { + number: 412, + title: 'Retry checkout webhooks with backoff', + state: 'open', + url: 'https://github.com/acme/web/pull/412', + checksStatus: 'failure', + checksSummary: '1 of 9 failed' + }, + git: { + branch: 'checkout-retries', + head: '3f95655684912ab', + changeCount: 3, + added: 131, + removed: 22, + changes: [ + { + path: 'src/payments/webhooks.ts', + status: 'modified', + area: 'unstaged', + added: 88, + removed: 19 + }, + { + path: 'src/payments/backoff.ts', + status: 'added', + area: 'untracked', + added: 41, + removed: 0 + }, + { path: 'README.md', status: 'modified', area: 'staged', added: 2, removed: 3 } + ], + commits: [ + { + id: '3f956556849', + subject: 'Back off webhook retries', + author: 'Grace', + at: NOW - 70 * MIN + }, + { + id: '41b60ea4b10', + subject: 'Log webhook failures', + author: 'Grace', + at: NOW - 3 * 60 * MIN + } + ] + }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'Retry failed checkout webhooks', + status: 'attention', + turnOutcome: null, + updatedAt: NOW - 43 * MIN, + truncated: true, + messages: [ + { + itemId: 'm1', + role: 'user', + text: 'Retry failed checkout webhooks with exponential backoff.', + at: NOW - 80 * MIN + }, + { + itemId: 'm2', + role: 'assistant', + text: 'Added a backoff helper and wired it into the webhook handler.', + at: NOW - 60 * MIN + }, + { itemId: 'm3', role: 'user', text: 'Cap it at 5 attempts.', at: NOW - 50 * MIN }, + { + itemId: 'm4', + role: 'assistant', + text: 'Capped at 5 attempts. One e2e check fails on a timeout unrelated to this change. Should I re-run it or skip it for now?', + at: NOW - 43 * MIN + } + ] + }, + { + sessionId: 's2', + agent: 'codex', + title: 'Write tests for backoff', + status: 'idle', + turnOutcome: 'done', + updatedAt: NOW - 45 * MIN, + truncated: false, + messages: [ + { + itemId: 'n1', + role: 'user', + text: 'Write unit tests for the backoff helper.', + at: NOW - 55 * MIN + }, + { itemId: 'n2', role: 'assistant', text: 'Added 6 tests. All pass.', at: NOW - 45 * MIN } + ] + } + ] +} + +const noop = (): void => {} + +function view(state: CloudReadViewState, extra: { waking?: boolean; retrying?: boolean } = {}) { + return ( +
    + +
    + ) +} + +const WIDTH = 620 + +/** Two agents (one needs input, one done), PR with failing checks, changes with +/−. */ +export const ready = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'ready', snapshot }) +}) + +/** "Show earlier messages" opened on the first chat. */ +export const readyExpanded = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'ready', snapshot }), + interact: (frame) => { + frame.querySelector('[aria-expanded="false"]')?.click() + } +}) + +/** A saved copy with no PR, agents or source control state. */ +export const readyBare = defineFixture({ + width: WIDTH, + render: () => + view({ kind: 'ready', snapshot: { ...snapshot, pr: null, git: null, sessions: [] } }) +}) + +export const loading = defineFixture({ width: WIDTH, render: () => view({ kind: 'loading' }) }) + +export const empty = defineFixture({ width: WIDTH, render: () => view({ kind: 'no_snapshot' }) }) + +export const notSealedForKey = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'not_sealed_for_key' }) +}) + +export const notFound = defineFixture({ width: WIDTH, render: () => view({ kind: 'not_found' }) }) + +export const keychainUnavailable = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'unavailable', message: 'no keychain' }) +}) + +export const error = defineFixture({ + width: WIDTH, + render: () => + view({ kind: 'error', message: "Couldn't reach Orca Cloud. Your files are safe. Try again." }) +}) + +export const waking = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'ready', snapshot }, { waking: true }) +}) diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx new file mode 100644 index 00000000000..f1b3447ff65 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx @@ -0,0 +1,200 @@ +import React from 'react' +import { Loader2, Moon, Play } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' +import { Skeleton } from '@/components/ui/skeleton' +import { useTranslate } from '@/i18n/use-translate' +import type { ReadSnapshot } from '../../../../../shared/cloud-workspaces/read-snapshot' +import { CloudGitChanges } from '../CloudGitChanges' +import { CloudWorkspaceHeader } from '../CloudWorkspaceHeader' +import { asOfParts } from './cloud-read-snapshot-format' +import { CloudReadPrLink } from './CloudReadPrLink' +import { CloudReadSessions } from './CloudReadSessions' + +export type CloudReadViewState = + | { kind: 'loading' } + | { kind: 'ready'; snapshot: ReadSnapshot } + | { kind: 'no_snapshot' } + | { kind: 'not_sealed_for_key' } + | { kind: 'not_found' } + /** This computer cannot hold a reader key (no OS keychain). */ + | { kind: 'unavailable'; message: string } + | { kind: 'error'; message: string } + +export type CloudReadSnapshotViewProps = { + title: string + state: CloudReadViewState + now: number + /** Wakes, then the normal open. */ + onWake: () => void + waking: boolean + onRetry: () => void + retrying: boolean + headingRef?: React.Ref +} + +function LoadingBody(): React.JSX.Element { + const t = useTranslate() + return ( +
    + + {t('components.orcaCloud.read.loading', 'Loading the saved copy')} + + + {[0, 1].map((i) => ( +
    + + + +
    + ))} + +
    + ) +} + +function SectionHeading({ id, children }: { id: string; children: React.ReactNode }) { + return ( +

    + {children} +

    + ) +} + +function ReadyBody({ snapshot, now }: { snapshot: ReadSnapshot; now: number }) { + const t = useTranslate() + const git = snapshot.git + return ( +
    + {snapshot.pr ? : null} +
    + + {t('components.orcaCloud.read.agents', 'Agents')} + + +
    +
    + + {t('components.orcaCloud.read.changes', 'Changes')} + + {git ? ( + ({ + sha: commit.id, + subject: commit.subject, + at: commit.at + })) + }} + /> + ) : ( +

    + {t('components.orcaCloud.offline.noGit', 'No source control state was saved.')} +

    + )} +
    +
    + ) +} + +/** + * A sleeping workspace, read from the copy it saved when it went to sleep (sealed to this + * computer's reader key). Read-only; the only way forward is the explicit "Wake to continue". + */ +export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React.JSX.Element { + const t = useTranslate() + const { state, now } = props + const asOf = state.kind === 'ready' ? asOfParts(state.snapshot.capturedAt, now) : null + return ( +
    + + {props.waking ? : } + {t('components.orcaCloud.read.wakeToContinue', 'Wake to continue')} + + } + /> + {state.kind === 'loading' ? : null} + {state.kind === 'ready' ? : null} + {state.kind === 'no_snapshot' ? ( + + ) : null} + {state.kind === 'not_sealed_for_key' ? ( + + ) : null} + {state.kind === 'not_found' ? ( + + ) : null} + {state.kind === 'unavailable' ? ( + + ) : null} + {state.kind === 'error' ? ( + + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/cloud-read-snapshot-format.ts b/src/renderer/src/components/orca-cloud/read-snapshot/cloud-read-snapshot-format.ts new file mode 100644 index 00000000000..47553294d27 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/cloud-read-snapshot-format.ts @@ -0,0 +1,85 @@ +// Display helpers for a sleeping workspace's read-only copy (owner asleep view and team read view). +import { uiDateTimeFormat } from '@/i18n/ui-intl-formatters' +import type { Translate } from '@/i18n/use-translate' +import { formatRelative } from '@/lib/orca-cloud/orca-cloud-workspace-state' +import type { ReadSnapshotAgentStatus } from '../../../../../shared/cloud-workspaces/read-snapshot' + +// Intl formatter caches key on option identity, so this must be a module constant. +const ABSOLUTE: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'short' } + +/** "As of" parts: relative for the label, absolute (glossary dateStyle medium) for hover. */ +export function asOfParts(at: number, now: number): { relative: string; absolute: string } { + return { relative: formatRelative(at, now), absolute: uiDateTimeFormat(ABSOLUTE).format(at) } +} + +export type ChecksTone = 'success' | 'failure' | 'pending' | 'neutral' + +/** Check states arrive as free text from the sandbox; anything unknown reads as neutral. */ +export function checksTone(status: string | null): ChecksTone { + switch ((status ?? '').toLowerCase()) { + case 'success': + case 'passed': + case 'passing': + return 'success' + case 'failure': + case 'failed': + case 'failing': + case 'error': + return 'failure' + case 'pending': + case 'running': + case 'in_progress': + case 'queued': + return 'pending' + default: + return 'neutral' + } +} + +export function checksLabel(tone: ChecksTone, t: Translate): string { + switch (tone) { + case 'success': + return t('components.orcaCloud.read.checksPassed', 'Checks passed') + case 'failure': + return t('components.orcaCloud.read.checksFailed', 'Checks failed') + case 'pending': + return t('components.orcaCloud.read.checksPending', 'Checks running') + case 'neutral': + return t('components.orcaCloud.read.checksNone', 'No checks') + } +} + +/** Where the agent was when the workspace went to sleep. */ +export function agentStatusLabel( + status: ReadSnapshotAgentStatus, + turnOutcome: string | null, + t: Translate +): string { + switch (status) { + case 'working': + return t('components.orcaCloud.read.agentWorking', 'Was working') + case 'attention': + return t('components.orcaCloud.read.agentAttention', 'Needs input') + case 'idle': + return turnOutcome + ? t('components.orcaCloud.read.agentDone', 'Done') + : t('components.orcaCloud.read.agentIdle', 'Idle') + case 'unknown': + return t('components.orcaCloud.read.agentUnknown', 'Status unknown') + } +} + +export function prStateLabel(state: string, t: Translate): string { + switch (state.toLowerCase()) { + case 'open': + return t('components.orcaCloud.read.prOpen', 'Open') + case 'draft': + return t('components.orcaCloud.read.prDraft', 'Draft') + case 'merged': + return t('components.orcaCloud.read.prMerged', 'Merged') + case 'closed': + return t('components.orcaCloud.read.prClosed', 'Closed') + default: + return state + } +} diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 923e688ad7a..57bae3d07d8 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2052,6 +2052,12 @@ } } }, + "orcaCloud": { + "read": { + "showMore_one": "Show {{count}} earlier message", + "showMore_other": "Show {{count}} earlier messages" + } + }, "orchestrationCrew": { "needsYou_one": "{{count}} needs you", "needsYou_other": "{{count}} need you", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 8bb502e5fbf..398e0a480fc 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20849,7 +20849,9 @@ "workspaceLinkCopied": "Workspace link copied", "you": "You", "youAreTyping": "You are typing", - "youAreViewing": "You are viewing" + "youAreViewing": "You are viewing", + "view": "View", + "viewAsleep": "View read-only copy" }, "orcaCloud": { "QueuedPrompt": { @@ -23149,6 +23151,44 @@ "readOnly": "Read-only", "terminalOutput": "Saved output of {{title}}", "noGit": "No source control state was saved." + }, + "read": { + "wakeToContinue": "Wake to continue", + "unreadable": "Couldn't open the saved copy on this computer. Your files are safe.", + "asOf": "Asleep · As of {{when}}", + "note": "Read-only copy saved when it went to sleep.", + "prTitle": "#{{number}} {{title}}", + "untitledChat": "Untitled chat", + "noMessages": "No messages were saved for this chat.", + "roleUser": "Person:", + "roleAgent": "Agent:", + "showLess": "Show less", + "showMore_one": "Show {{count}} earlier message", + "showMore_other": "Show {{count}} earlier messages", + "truncated": "Older messages are in the workspace. Wake it to read them.", + "noSessions": "No agent chats were open.", + "loading": "Loading the saved copy", + "agents": "Agents", + "changes": "Changes", + "region": "Asleep workspace (read-only)", + "asleep": "Asleep", + "empty": "Nothing saved yet. Orca saves a read-only copy each time this workspace goes to sleep.", + "notSealedForKey": "This device was added after the workspace went to sleep. Wake it once to read it here.", + "unavailable": "Reading a sleeping workspace needs the OS keychain on this computer.", + "tryAgain": "Try again", + "checksPassed": "Checks passed", + "checksFailed": "Checks failed", + "checksPending": "Checks running", + "checksNone": "No checks", + "agentWorking": "Was working", + "agentAttention": "Needs input", + "agentDone": "Done", + "agentIdle": "Idle", + "agentUnknown": "Status unknown", + "prOpen": "Open", + "prDraft": "Draft", + "prMerged": "Merged", + "prClosed": "Closed" } }, "runtimeDownload": { @@ -26554,7 +26594,6 @@ "unarchiveFailed": "Couldn’t unarchive the workspace", "asleep": { "noCopy": "Asleep · nothing cached yet", - "copyFrom": "Asleep · copy from {{when}}", "readOnly": "Read-only copy kept on this computer." }, "bytes": { diff --git a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts index 058c223acf7..00cd81460b7 100644 --- a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts +++ b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts @@ -13,6 +13,7 @@ export function createWebCloudWorkspacesApi(): PreloadApi['cloudWorkspaces'] { patch: () => Promise.resolve(NOT_CONFIGURED), resolveLink: () => Promise.resolve(NOT_CONFIGURED), openGrant: () => Promise.resolve(NOT_CONFIGURED), + readSnapshot: () => Promise.resolve(NOT_CONFIGURED), listGrants: () => Promise.resolve(NOT_CONFIGURED), revokeGrant: () => Promise.resolve(NOT_CONFIGURED), localWorkspaces: () => Promise.resolve([]), diff --git a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts index b7cb4f9a518..0f9da6ad93f 100644 --- a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts +++ b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts @@ -50,7 +50,10 @@ export const CloudWorkspaceSchema = z.object({ presence: z.array(CloudWorkspacePresenceSchema), // Display names (each member's token `name` claim) for the ids above. Labels only, and the org // roster wins where it has an entry. Older control planes omit it. - memberNames: z.record(z.string(), z.string().max(80)).optional().catch(undefined) + memberNames: z.record(z.string(), z.string().max(80)).optional().catch(undefined), + // When the last sleeping read snapshot was stored (ms), present only when the caller can open the + // workspace; drives "As of" in lists without fetching the blob. Older control planes omit it. + readSnapshotAt: z.number().nullable().optional().catch(undefined) }) export type CloudWorkspace = z.infer @@ -94,6 +97,34 @@ export const CloudWorkspaceGrantListSchema = z.object({ grants: z.array(CloudWorkspaceGrantSchema) }) +// Reader keys: this device's long-lived X25519 key that sleeping workspaces seal their read snapshot to. +export const CloudReaderKeySchema = z.object({ + id: z.string().regex(/^rk_[0-9a-f]{24}$/), + deviceKind: z.enum(['desktop', 'mobile']), + deviceLabel: z.string(), + createdAt: z.number(), + lastSeenAt: z.number() +}) +export type CloudReaderKeyRegistration = z.infer +export const CloudReaderKeyResponseSchema = z.object({ readerKey: CloudReaderKeySchema }) + +/** Mirrors SealedReadSnapshot in read-snapshot.ts (the opener re-checks every length). */ +export const SealedReadSnapshotSchema = z.object({ + v: z.literal(1), + snapshotId: Id, + workspaceId: Id, + storedAt: z.number(), + nonceB64: z.string().max(64), + ciphertextB64: z.string().max(16 * 1024 * 1024), + recipient: z.object({ + keyId: Id, + ephemeralPublicKeyB64: z.string().max(64), + nonceB64: z.string().max(64), + wrappedKeyB64: z.string().max(128) + }) +}) +export const CloudReadSnapshotResponseSchema = z.object({ snapshot: SealedReadSnapshotSchema }) + export type CloudWorkspaceListQuery = { scope?: 'mine' | 'team' | 'all' by?: string diff --git a/src/shared/cloud-workspaces/read-snapshot-state.ts b/src/shared/cloud-workspaces/read-snapshot-state.ts new file mode 100644 index 00000000000..46d41a7ff04 --- /dev/null +++ b/src/shared/cloud-workspaces/read-snapshot-state.ts @@ -0,0 +1,18 @@ +// What reading a sleeping workspace's sealed snapshot can come back as (main -> renderer). +import type { ReadSnapshot } from './read-snapshot' + +export type CloudReadSnapshotState = + /** Opened on this device. `storedAt`: when the control plane stored it; show snapshot.capturedAt. */ + | { state: 'ready'; snapshot: ReadSnapshot; storedAt: number } + /** Nothing captured yet (one is saved each time the workspace goes to sleep). */ + | { state: 'no_snapshot' } + /** A snapshot exists but predates this device's key (or the key was pruned). Wake once to fix. */ + | { state: 'not_sealed_for_key' } + /** No such workspace, or this account may not open it (removed, private, archived). */ + | { state: 'not_found' } + /** This device cannot hold a reader key (no OS keychain); the feature is off here. */ + | { + state: 'unavailable' + reason: 'keychain_unavailable' | 'storage_failed' + message: string + } diff --git a/src/shared/cloud-workspaces/read-snapshot.ts b/src/shared/cloud-workspaces/read-snapshot.ts new file mode 100644 index 00000000000..8473bea4f6a --- /dev/null +++ b/src/shared/cloud-workspaces/read-snapshot.ts @@ -0,0 +1,340 @@ +// Opens the read snapshot a sleeping Orca Cloud workspace left behind: what its chats, agents, git +// and PR looked like when it went to sleep, so any authorized device can read it without waking the +// VM. The VM seals it (image/vm/orca-read-snapshot.js in the sandbox control plane) to every reader +// key allowed to open the workspace; the control plane stores and relays only ciphertext. +// +// Exact construction (keep in sync with the VM sealer): +// dek = 32 random bytes; body = AES-256-GCM(dek, nonce(12), utf8 JSON payload, +// AAD = utf8 "orca-cloud-read-v1:" + workspaceId + ":" + snapshotId) +// per reader key (fresh ephemeral X25519 each): +// shared = X25519(ephemeralSecret, readerPublic) (all-zero result is rejected) +// kek = HKDF-SHA256(ikm = shared, salt = ephemeralPublic(32) || readerPublic(32), +// info = utf8 "orca-cloud-read-wrap-v1", length = 32) +// wrapped = AES-256-GCM(kek, nonce(12), dek, +// AAD = utf8 "orca-cloud-read-wrap-v1:" + workspaceId + ":" + snapshotId + ":" + keyId) +// ciphertexts are ct || tag(16). +// Free of node:crypto and Buffer so mobile (Hermes) can use it with the same primitives as grants. +import { + base64ToBytes, + type SealedGrantPrimitives +} from './sealed-grant' + +export const READ_SNAPSHOT_INFO = 'orca-cloud-read-v1' +export const READ_SNAPSHOT_WRAP_INFO = 'orca-cloud-read-wrap-v1' + +/** Plaintext bounds the VM keeps to (the opener re-checks them; anything over is cut, not trusted). */ +export const READ_SNAPSHOT_LIMITS = { + sessions: 12, + messagesPerSession: 60, + messageChars: 4000, + changes: 200, + commits: 10, + titleChars: 200 +} as const + +export type ReadSnapshotRole = 'user' | 'assistant' | 'system' +export type ReadSnapshotMessage = { itemId: string; role: ReadSnapshotRole; text: string; at: number } +/** `attention`: waiting on a person (approval, question). `idle` + turnOutcome is "done". */ +export type ReadSnapshotAgentStatus = 'working' | 'attention' | 'idle' | 'unknown' +export type ReadSnapshotSession = { + sessionId: string + /** Agent kind as orcad names it (claude, codex, …); free text, display only. */ + agent: string | null + title: string | null + status: ReadSnapshotAgentStatus + turnOutcome: string | null + updatedAt: number | null + /** Oldest first; only the tail of a long chat. */ + messages: ReadSnapshotMessage[] + /** Older messages exist that are not in this snapshot. */ + truncated: boolean +} +export type ReadSnapshotChange = { + path: string + status: string + area: string + added: number | null + removed: number | null +} +export type ReadSnapshotGit = { + branch: string | null + head: string | null + changes: ReadSnapshotChange[] + changeCount: number + added: number | null + removed: number | null + commits: { id: string; subject: string; author: string | null; at: number | null }[] +} +export type ReadSnapshotPr = { + number: number + title: string + state: string + url: string + checksStatus: string | null + checksSummary: string | null +} +export type ReadSnapshot = { + v: 1 + workspaceId: string + snapshotId: string + /** When the VM captured it (ms). "As of" on every surface. */ + capturedAt: number + reason: string + git: ReadSnapshotGit | null + pr: ReadSnapshotPr | null + sessions: ReadSnapshotSession[] +} + +/** What the control plane hands one device: the body plus only that device's wrapped key. */ +export type SealedReadSnapshot = { + v: 1 + snapshotId: string + workspaceId: string + /** When the control plane stored it (ms); the payload's own capturedAt is the one to show. */ + storedAt: number + nonceB64: string + ciphertextB64: string + recipient: { + keyId: string + ephemeralPublicKeyB64: string + nonceB64: string + wrappedKeyB64: string + } +} + +export class ReadSnapshotError extends Error { + constructor(readonly code: 'malformed' | 'decrypt_failed' | 'invalid_payload' | 'wrong_workspace') { + super(code) + this.name = 'ReadSnapshotError' + } +} + +function concat(a: Uint8Array, b: Uint8Array): Uint8Array { + const out = new Uint8Array(a.length + b.length) + out.set(a, 0) + out.set(b, a.length) + return out +} + +function decodeB64(value: string): Uint8Array { + try { + return base64ToBytes(value) + } catch { + throw new ReadSnapshotError('malformed') + } +} + +export async function openReadSnapshot( + sealed: SealedReadSnapshot, + /** The workspace the caller asked for; a snapshot of any other workspace is refused. */ + workspaceId: string, + readerSecretKey: Uint8Array, + primitives: SealedGrantPrimitives +): Promise { + if (sealed.v !== 1 || readerSecretKey.length !== 32) { + throw new ReadSnapshotError('malformed') + } + if (sealed.workspaceId !== workspaceId) { + throw new ReadSnapshotError('wrong_workspace') + } + const { recipient } = sealed + const ephemeral = decodeB64(recipient.ephemeralPublicKeyB64) + const wrapNonce = decodeB64(recipient.nonceB64) + const wrapped = decodeB64(recipient.wrappedKeyB64) + const nonce = decodeB64(sealed.nonceB64) + const ciphertext = decodeB64(sealed.ciphertextB64) + if ( + ephemeral.length !== 32 || + wrapNonce.length !== 12 || + wrapped.length !== 48 || + nonce.length !== 12 || + ciphertext.length < 17 + ) { + throw new ReadSnapshotError('malformed') + } + const encoder = new TextEncoder() + const readerPublic = await primitives.x25519PublicKey(readerSecretKey) + const shared = await primitives.x25519(readerSecretKey, ephemeral) + // A low-order ephemeral key yields an all-zero secret anyone can compute. + if (shared.every((byte) => byte === 0)) { + throw new ReadSnapshotError('decrypt_failed') + } + const kek = await primitives.hkdfSha256( + shared, + concat(ephemeral, readerPublic), + encoder.encode(READ_SNAPSHOT_WRAP_INFO), + 32 + ) + const scope = `${workspaceId}:${sealed.snapshotId}` + let plaintext: Uint8Array + try { + const dek = await primitives.aesGcmDecrypt( + kek, + wrapNonce, + wrapped, + encoder.encode(`${READ_SNAPSHOT_WRAP_INFO}:${scope}:${recipient.keyId}`) + ) + plaintext = await primitives.aesGcmDecrypt( + dek, + nonce, + ciphertext, + encoder.encode(`${READ_SNAPSHOT_INFO}:${scope}`) + ) + dek.fill(0) + } catch { + throw new ReadSnapshotError('decrypt_failed') + } + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder().decode(plaintext)) + } catch { + throw new ReadSnapshotError('invalid_payload') + } + const snapshot = parseReadSnapshot(parsed) + // The AAD already binds these; a mismatch means the VM itself wrote something odd. + if (!snapshot || snapshot.workspaceId !== workspaceId || snapshot.snapshotId !== sealed.snapshotId) { + throw new ReadSnapshotError('invalid_payload') + } + return snapshot +} + +// The payload came from the VM: parse leniently field by field, cut to the limits, never trust it. +type Obj = Record +const isObj = (value: unknown): value is Obj => + typeof value === 'object' && value !== null && !Array.isArray(value) +const str = (value: unknown, max: number): string | null => + typeof value === 'string' ? value.slice(0, max) : null +const num = (value: unknown): number | null => + typeof value === 'number' && Number.isFinite(value) ? value : null +const arr = (value: unknown): unknown[] => (Array.isArray(value) ? value : []) + +const ROLES: ReadonlySet = new Set(['user', 'assistant', 'system']) +const STATUSES: ReadonlySet = new Set(['working', 'attention', 'idle']) + +function messageOf(value: unknown): ReadSnapshotMessage | null { + if (!isObj(value) || typeof value.role !== 'string' || !ROLES.has(value.role)) { + return null + } + const text = str(value.text, READ_SNAPSHOT_LIMITS.messageChars) + const itemId = str(value.itemId, 200) + if (!text || !itemId) { + return null + } + return { itemId, role: value.role as ReadSnapshotRole, text, at: num(value.at) ?? 0 } +} + +function sessionOf(value: unknown): ReadSnapshotSession | null { + if (!isObj(value)) { + return null + } + const sessionId = str(value.sessionId, 200) + if (!sessionId) { + return null + } + const all = arr(value.messages) + .map(messageOf) + .filter((m): m is ReadSnapshotMessage => m !== null) + const messages = all.slice(-READ_SNAPSHOT_LIMITS.messagesPerSession) + const status = typeof value.status === 'string' && STATUSES.has(value.status) ? value.status : 'unknown' + return { + sessionId, + agent: str(value.agent, 40), + title: str(value.title, READ_SNAPSHOT_LIMITS.titleChars), + status: status as ReadSnapshotAgentStatus, + turnOutcome: str(value.turnOutcome, 40), + updatedAt: num(value.updatedAt), + messages, + truncated: value.truncated === true || messages.length < all.length + } +} + +function gitOf(value: unknown): ReadSnapshotGit | null { + if (!isObj(value)) { + return null + } + const changes = arr(value.changes) + .flatMap((raw): ReadSnapshotChange[] => { + if (!isObj(raw)) { + return [] + } + const path = str(raw.path, 1024) + return path + ? [ + { + path, + status: str(raw.status, 20) ?? 'modified', + area: str(raw.area, 20) ?? 'unstaged', + added: num(raw.added), + removed: num(raw.removed) + } + ] + : [] + }) + .slice(0, READ_SNAPSHOT_LIMITS.changes) + const commits = arr(value.commits) + .flatMap((raw) => { + if (!isObj(raw)) { + return [] + } + const id = str(raw.id, 64) + const subject = str(raw.subject, 300) + return id && subject !== null + ? [{ id, subject, author: str(raw.author, 120), at: num(raw.at) }] + : [] + }) + .slice(0, READ_SNAPSHOT_LIMITS.commits) + return { + branch: str(value.branch, 255), + head: str(value.head, 64), + changes, + changeCount: Math.max(num(value.changeCount) ?? changes.length, changes.length), + added: num(value.added), + removed: num(value.removed), + commits + } +} + +function prOf(value: unknown): ReadSnapshotPr | null { + if (!isObj(value)) { + return null + } + const number = num(value.number) + const url = str(value.url, 500) + // Only links a person can safely tap. + if (number === null || !url || !url.startsWith('https://')) { + return null + } + return { + number, + title: str(value.title, 300) ?? '', + state: str(value.state, 20) ?? 'open', + url, + checksStatus: str(value.checksStatus, 20), + checksSummary: str(value.checksSummary, 200) + } +} + +export function parseReadSnapshot(value: unknown): ReadSnapshot | null { + if (!isObj(value) || value.v !== 1) { + return null + } + const workspaceId = str(value.workspaceId, 64) + const snapshotId = str(value.snapshotId, 64) + const capturedAt = num(value.capturedAt) + if (!workspaceId || !snapshotId || capturedAt === null) { + return null + } + return { + v: 1, + workspaceId, + snapshotId, + capturedAt, + reason: str(value.reason, 20) ?? 'sleep', + git: gitOf(value.git), + pr: prOf(value.pr), + sessions: arr(value.sessions) + .map(sessionOf) + .filter((s): s is ReadSnapshotSession => s !== null) + .slice(0, READ_SNAPSHOT_LIMITS.sessions) + } +} diff --git a/src/shared/hosted-sandbox/cloud-workspace-offline-api.ts b/src/shared/hosted-sandbox/cloud-workspace-offline-api.ts index 5c386ea33a1..08d7ff37305 100644 --- a/src/shared/hosted-sandbox/cloud-workspace-offline-api.ts +++ b/src/shared/hosted-sandbox/cloud-workspace-offline-api.ts @@ -13,6 +13,9 @@ export type CloudOfflineChat = { /** When this transcript was last read from the VM. */ at: number messages: CloudOfflineChatMessage[] + /** From the workspace's own sleep snapshot (absent for this computer's cache). */ + agent?: string | null + title?: string | null } export type CloudOfflineTerminal = { @@ -23,7 +26,14 @@ export type CloudOfflineTerminal = { at: number } -export type CloudOfflineGitChange = { path: string; status: string; area: string } +export type CloudOfflineGitChange = { + path: string + status: string + area: string + /** Lines, when the workspace's sleep snapshot counted them. */ + added?: number | null + removed?: number | null +} export type CloudOfflineCommit = { id: string subject: string @@ -38,6 +48,19 @@ export type CloudOfflineGit = { changeCount: number commits: CloudOfflineCommit[] at: number + /** Total lines added/removed across `changes`, when known. */ + added?: number | null + removed?: number | null +} + +export type CloudOfflinePr = { + number: number + title: string + state: string + /** Always https (checked where it is parsed). */ + url: string + checksStatus: string | null + checksSummary: string | null } export type CloudOfflineSnapshot = { @@ -49,6 +72,13 @@ export type CloudOfflineSnapshot = { git: CloudOfflineGit | null terminals: CloudOfflineTerminal[] chats: CloudOfflineChat[] + /** The pull request as of the workspace's last sleep (older builds omit it). */ + pr?: CloudOfflinePr | null + /** + * Where the sections came from: this computer's cache, the workspace's own sealed sleep snapshot + * (Orca Cloud), or both. Older builds omit it (= device). + */ + source?: 'device' | 'cloud' | 'mixed' } /** `unconfirmed`: it may have reached the agent (sent, but the reply never came back). */ From 1bc418da8a31945140df75734d85ec3d4d83de26 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 00:13:19 -0800 Subject: [PATCH 02/46] feat(cloud): seal a read snapshot at drain; reader keys, read endpoint, revocation pruning --- .../sandbox-control/image/golden-image.ts | 2 + .../sandbox-control/image/provision-golden.sh | 2 +- .../image/vm-scripts.generated.ts | 4 +- .../image/vm/orca-read-snapshot.cjs | 329 +++++++++++++ .../image/vm/orca-sandbox-read-snapshot | 11 + .../migrations/0039_read_snapshots.sql | 45 ++ cloud/apps/sandbox-control/src/index.ts | 27 +- cloud/apps/sandbox-control/src/lifecycle.ts | 12 +- .../sandbox-control/src/member-removal.ts | 7 +- .../sandbox-control/src/read-snapshots.ts | 447 ++++++++++++++++++ .../src/workspace-lifecycle.ts | 4 +- cloud/apps/sandbox-control/src/workspaces.ts | 10 +- cloud/apps/sandbox-control/test/api.test.ts | 2 +- .../test/read-snapshots.test.ts | 300 ++++++++++++ .../sandbox-control/test/workspaces.test.ts | 2 +- 15 files changed, 1190 insertions(+), 14 deletions(-) create mode 100644 cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs create mode 100755 cloud/apps/sandbox-control/image/vm/orca-sandbox-read-snapshot create mode 100644 cloud/apps/sandbox-control/migrations/0039_read_snapshots.sql create mode 100644 cloud/apps/sandbox-control/src/read-snapshots.ts create mode 100644 cloud/apps/sandbox-control/test/read-snapshots.test.ts diff --git a/cloud/apps/sandbox-control/image/golden-image.ts b/cloud/apps/sandbox-control/image/golden-image.ts index 7590301648e..e8b642d2258 100644 --- a/cloud/apps/sandbox-control/image/golden-image.ts +++ b/cloud/apps/sandbox-control/image/golden-image.ts @@ -20,6 +20,8 @@ export const VM_SCRIPTS = [ 'orca-sandbox-grant', 'orca-sandbox-revoke', 'orca-sandbox-members', + 'orca-sandbox-read-snapshot', + 'orca-read-snapshot.cjs', 'orca-git-as', 'orca-git-identity', 'orcad-boot', diff --git a/cloud/apps/sandbox-control/image/provision-golden.sh b/cloud/apps/sandbox-control/image/provision-golden.sh index 17e6eb8cb42..bb23c6a2b55 100755 --- a/cloud/apps/sandbox-control/image/provision-golden.sh +++ b/cloud/apps/sandbox-control/image/provision-golden.sh @@ -158,7 +158,7 @@ if [ -n "${NOVNC_VERSION:-}" ]; then fi log 'Orca entry points' -for name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as orca-git-identity orcad-boot git; do +for name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do var="ORCA_VM_SCRIPT_${name//[-.]/_}" printf '%s' "${!var}" | base64 -d >"$ORCA_HOME/bin/$name" chmod 0755 "$ORCA_HOME/bin/$name" diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 51199b5cf73..e0912c8d64d 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -2,8 +2,8 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0"],"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} -export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" -export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_key_tail=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code: first-run screens answered once (theme picker, folder trust, bypass-mode warning,\n# the \"use this API key?\" question). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} +export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_key_tail=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code: first-run screens answered once (theme picker, folder trust, bypass-mode warning,\n# the \"use this API key?\" question). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline }) {\n const timeLeft = () => deadline - Date.now()\n const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })])\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : []\n // Newest activity first; chats with nothing in them still list (agent + status).\n const picked = summaries\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n const { messages, hasOlder } = messagesOf(history)\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: str(s.agent, 40),\n title: str(s.conversationName, 200) || str(s.latestPrompt, 200),\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: str(s.turnOutcome, 40),\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline }))\n const out = seal(payload, recipients, workspaceId, snapshotId)\n out.stats = {\n sessions: payload.sessions.length,\n messages: payload.sessions.reduce((n, s) => n + s.messages.length, 0),\n plainBytes: Buffer.byteLength(JSON.stringify(payload)),\n collectMs: Date.now() - started\n }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc }\n\nif (require.main === module) {\n main().catch((error) => {\n process.stderr.write(`read snapshot failed: ${String(error && error.message ? error.message : error).slice(0, 200)}\\n`)\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs new file mode 100644 index 00000000000..7ec54dfdd0b --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs @@ -0,0 +1,329 @@ +#!/usr/bin/env node +// Gathers what a sleeping workspace should still show (recent chats per agent session, agent +// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals +// it to the reader keys the control plane passed, so only ciphertext leaves the VM. +// Run by orca-sandbox-read-snapshot right before the drain. Env: +// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex> +// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover +// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there) +// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}. +// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app): +// body = AES-256-GCM(dek, nonce, JSON, AAD "orca-cloud-read-v1::") +// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, "orca-cloud-read-wrap-v1"), +// nonce_i, dek, AAD "orca-cloud-read-wrap-v1:::") +'use strict' +const crypto = require('node:crypto') +const fs = require('node:fs') +const net = require('node:net') +const path = require('node:path') + +const INFO = 'orca-cloud-read-v1' +const WRAP_INFO = 'orca-cloud-read-wrap-v1' +const PROJECT = '/vercel/sandbox/project' +const LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 } +/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */ +const MAX_PLAIN_BYTES = 150_000 +const CALL_TIMEOUT_MS = 5_000 +const TOTAL_BUDGET_MS = 20_000 + +function b64(bytes) { + return Buffer.from(bytes).toString('base64') +} + +function x25519PublicKey(raw) { + return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' }) +} + +function gcmSeal(key, nonce, plain, aad) { + const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce) + cipher.setAAD(Buffer.from(aad)) + return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()]) +} + +/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */ +function seal(payload, recipients, workspaceId, snapshotId) { + const scope = `${workspaceId}:${snapshotId}` + const dek = crypto.randomBytes(32) + const nonce = crypto.randomBytes(12) + const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`) + const sealedTo = [] + for (const recipient of recipients) { + const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64') + if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) { + continue + } + let shared + const eph = crypto.generateKeyPairSync('x25519') + try { + shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) }) + } catch { + continue + } + if (shared.every((byte) => byte === 0)) { + continue + } + const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url') + const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32)) + const wrapNonce = crypto.randomBytes(12) + const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`) + sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) }) + } + dek.fill(0) + return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo } +} + +// --- gathering ------------------------------------------------------------------------------- + +/** One request per connection, like the CLI. A streaming method resolves on its first frame. */ +function rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) { + return new Promise((resolve) => { + const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe')) + if (!transport) { + resolve(null) + return + } + const socket = net.createConnection(transport.endpoint) + const id = crypto.randomUUID() + let buffer = '' + let done = false + const finish = (value) => { + if (!done) { + done = true + clearTimeout(timer) + socket.destroy() + resolve(value) + } + } + const timer = setTimeout(() => finish(null), timeoutMs) + socket.setEncoding('utf8') + socket.on('error', () => finish(null)) + socket.on('close', () => finish(null)) + socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\n`)) + socket.on('data', (chunk) => { + buffer += chunk + let newline + while ((newline = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, newline) + buffer = buffer.slice(newline + 1) + let frame + try { + frame = JSON.parse(line) + } catch { + continue + } + if (!frame || frame.id !== id) { + continue + } + finish(frame.ok === true ? frame.result : null) + return + } + }) + }) +} + +const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v) +const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null) +const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null) + +function messagesOf(history) { + const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : [] + const out = [] + for (const item of items) { + const body = isObj(item) && isObj(item.body) ? item.body : null + if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) { + continue + } + const role = body.role + if (role !== 'user' && role !== 'assistant' && role !== 'system') { + continue + } + const text = body.blocks + .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string') + .map((b) => b.text) + .join('\n') + .trim() + if (text) { + out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 }) + } + } + return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true } +} + +function gitOf(status, log) { + if (!isObj(status) && !isObj(log)) { + return null + } + const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : [] + let added = 0 + let removed = 0 + let counted = false + const changes = entries.slice(0, LIMITS.changes).map((e) => { + const a = num(e.added) + const r = num(e.removed) + if (a !== null || r !== null) { + counted = true + } + return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r } + }) + for (const e of entries) { + added += num(e.added) || 0 + removed += num(e.removed) || 0 + } + const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : [] + return { + branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\/heads\//, '') : null, + head: isObj(status) ? str(status.head, 64) : null, + changes, + changeCount: entries.length, + added: counted ? added : null, + removed: counted ? removed : null, + commits: items.slice(0, LIMITS.commits).map((c) => ({ + id: String(c.id).slice(0, 64), + subject: String(c.subject ?? '').slice(0, 300), + author: str(c.author, 120), + at: num(c.timestamp) + })) + } +} + +function prOf(linked) { + if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) { + return null + } + return { + number: linked.number, + title: String(linked.title ?? '').slice(0, 300), + state: str(linked.state, 20) || 'open', + url: linked.url.slice(0, 500), + checksStatus: str(linked.checksStatus, 20), + checksSummary: str(linked.checksSummary, 200) + } +} + +const STATUSES = new Set(['working', 'attention', 'idle']) + +/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */ +async function gather(call, { workspaceId, snapshotId, reason, now, deadline }) { + const timeLeft = () => deadline - Date.now() + const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })]) + const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : [] + const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null + const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}` + const [status, log] = await Promise.all([ + call('git.status', { worktree: selector, includeLineStats: true }), + call('git.history', { worktree: selector, limit: LIMITS.commits }) + ]) + const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : [] + // Newest activity first; chats with nothing in them still list (agent + status). + const picked = summaries + .filter((s) => typeof s.sessionId === 'string') + .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0)) + .slice(0, LIMITS.sessions) + const sessions = [] + for (const s of picked) { + const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null + const { messages, hasOlder } = messagesOf(history) + sessions.push({ + sessionId: s.sessionId.slice(0, 200), + agent: str(s.agent, 40), + title: str(s.conversationName, 200) || str(s.latestPrompt, 200), + status: STATUSES.has(s.status) ? s.status : 'unknown', + turnOutcome: str(s.turnOutcome, 40), + updatedAt: num(s.updatedAt), + messages: messages.slice(-LIMITS.messagesPerSession), + truncated: hasOlder || messages.length > LIMITS.messagesPerSession + }) + } + return { + v: 1, + workspaceId, + snapshotId, + capturedAt: now, + reason, + git: gitOf(status, log), + pr: prOf(project && project.linkedPR), + sessions + } +} + +/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */ +function fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) { + const size = () => Buffer.byteLength(JSON.stringify(payload)) + let guard = 0 + while (size() > maxBytes && guard++ < 10_000) { + const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null) + if (longest && longest.messages.length > 4) { + longest.messages.shift() + longest.truncated = true + continue + } + const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500) + if (longText) { + longText.text = `${longText.text.slice(0, 500)}…` + continue + } + if (payload.git && payload.git.changes.length > 20) { + payload.git.changes = payload.git.changes.slice(0, 20) + continue + } + if (payload.sessions.length > 1) { + payload.sessions.pop() + continue + } + payload.sessions = [] + break + } + return payload +} + +async function main() { + const started = Date.now() + const env = process.env + const snapshotId = env.ORCA_READ_SNAPSHOT_ID || '' + const workspaceId = env.ORCA_READ_WORKSPACE_ID || '' + if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) { + process.stderr.write('bad ids\n') + process.exit(2) + } + let recipients + try { + recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]') + } catch { + recipients = null + } + if (!Array.isArray(recipients) || recipients.length === 0) { + process.stderr.write('no recipients\n') + process.exit(2) + } + const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data') + let metadata + try { + metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8')) + } catch { + metadata = null + } + if (!metadata || !metadata.authToken) { + process.stderr.write('orcad not running\n') + process.exit(3) + } + const deadline = started + TOTAL_BUDGET_MS + const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now()))) + const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline })) + const out = seal(payload, recipients, workspaceId, snapshotId) + out.stats = { + sessions: payload.sessions.length, + messages: payload.sessions.reduce((n, s) => n + s.messages.length, 0), + plainBytes: Buffer.byteLength(JSON.stringify(payload)), + collectMs: Date.now() - started + } + process.stdout.write(`${JSON.stringify(out)}\n`) +} + +module.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc } + +if (require.main === module) { + main().catch((error) => { + process.stderr.write(`read snapshot failed: ${String(error && error.message ? error.message : error).slice(0, 200)}\n`) + process.exit(1) + }) +} diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-read-snapshot b/cloud/apps/sandbox-control/image/vm/orca-sandbox-read-snapshot new file mode 100755 index 00000000000..697d142463d --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-read-snapshot @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the +# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see +# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read). +set -euo pipefail +umask 077 +ORCA_HOME=/opt/orca +export ORCA_USER_DATA_PATH="${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}" +node="$(find "$ORCA_HOME/runtime/runtimes" -type f -name node | head -n 1)" +[ -n "$node" ] || { echo 'node not found' >&2; exit 1; } +exec timeout 35 "$node" "$ORCA_HOME/bin/orca-read-snapshot.cjs" diff --git a/cloud/apps/sandbox-control/migrations/0039_read_snapshots.sql b/cloud/apps/sandbox-control/migrations/0039_read_snapshots.sql new file mode 100644 index 00000000000..ab388527cb9 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0039_read_snapshots.sql @@ -0,0 +1,45 @@ +-- Read a sleeping workspace without waking it (gap 5). Every device keeps one X25519 "reader key"; +-- only the public half is stored here. At each drain the VM seals a compact snapshot (chats, agent +-- status, git, PR) to the reader keys allowed to open the workspace; this database keeps only that +-- ciphertext and one wrapped content key per reader key, never plaintext. +CREATE TABLE IF NOT EXISTS reader_keys ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + account_id TEXT NOT NULL, + dev INTEGER NOT NULL DEFAULT 0, + public_key TEXT NOT NULL, + device_kind TEXT NOT NULL, + device_label TEXT NOT NULL, + -- A phone's key dies with its device session (unpair, revoke, member removal). + device_session_id TEXT, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + revoked_at INTEGER, + revoked_by TEXT +); +CREATE UNIQUE INDEX IF NOT EXISTS reader_keys_live ON reader_keys (account_id, user_id, public_key) WHERE revoked_at IS NULL; +CREATE INDEX IF NOT EXISTS reader_keys_account ON reader_keys (account_id, revoked_at); +CREATE INDEX IF NOT EXISTS reader_keys_device_session ON reader_keys (device_session_id); + +-- One snapshot per workspace, replaced at every drain. +CREATE TABLE IF NOT EXISTS read_snapshots ( + sandbox_id TEXT PRIMARY KEY, + snapshot_id TEXT NOT NULL, + stored_at INTEGER NOT NULL, + bytes INTEGER NOT NULL, + nonce TEXT NOT NULL, + ciphertext TEXT NOT NULL +); + +-- The snapshot's content key wrapped to one reader key. Deleting a row is how access is pruned +-- (member removed, workspace made private, key revoked) without waking the VM. +CREATE TABLE IF NOT EXISTS read_snapshot_keys ( + sandbox_id TEXT NOT NULL, + key_id TEXT NOT NULL, + snapshot_id TEXT NOT NULL, + ephemeral_public_key TEXT NOT NULL, + nonce TEXT NOT NULL, + wrapped_key TEXT NOT NULL, + PRIMARY KEY (sandbox_id, key_id) +); +CREATE INDEX IF NOT EXISTS read_snapshot_keys_key ON read_snapshot_keys (key_id); diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index e4a68988527..ecc6485aae1 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -32,6 +32,7 @@ // Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts) // Public share links (src/share-gateway.ts): /s//*, plus the root-path cookie fallback // Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy +import { ReadSnapshotRouteError, getReadSnapshot, handleReaderKeysRoute, pruneReadSnapshotToOwner, revokeDeviceSessionReaderKeys } from './read-snapshots' import { refreshStaleEnvironments } from './environment-golden-refresh' import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { z } from 'zod' @@ -836,6 +837,14 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) const state = await createConnectState(env.SANDBOX_DB, connect.stateSecret, { accountId: `dev:${sub}`, userId: sub }, (deps.now ?? Date.now)()) return Response.redirect(authorizeUrl(connect, url.origin, state), 302) } + if (url.pathname === '/v1/reader-keys' || url.pathname.startsWith('/v1/reader-keys/')) { + const now = (deps.now ?? Date.now)() + const caller = await authenticateDesktop(env, request, now) + if (!caller) { + return fail('unauthorized', 401) + } + return await handleReaderKeysRoute(request, url, { db: env.SANDBOX_DB, caller, now, readJson: () => readJson(request) }) + } if (url.pathname === '/v1/device-sessions' || url.pathname.startsWith('/v1/device-sessions/')) { const now = (deps.now ?? Date.now)() const caller = await authenticateDesktop(env, request, now) @@ -851,6 +860,8 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) onRevoked: deps.onDeviceSessionRevoked ?? (async (deviceSessionId) => { + // Its reader key first: no VM involved, so this can't be held up by a sleeping workspace. + await revokeDeviceSessionReaderKeys(env.SANDBOX_DB, deviceSessionId, now) const life = await lifecycleDeps(env, deps) if (life) { await revokeGrantsForDeviceSession(life, deviceSessionId) @@ -1283,7 +1294,7 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, if (url.pathname === '/v1/team/workspaces') { return request.method === 'GET' ? json(await listWorkspaces(db, caller, url, now)) : fail('not_found', 404) } - const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname) + const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent|read-snapshot)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname) if (!match) { return fail('not_found', 404) } @@ -1294,6 +1305,16 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, if (route === 'GET ') { return json({ workspace: await view() }) } + if (route === 'GET read-snapshot') { + try { + return json(await getReadSnapshot(db, caller, row, url.searchParams.get('keyId'), now)) + } catch (error) { + if (error instanceof ReadSnapshotRouteError) { + return fail(error.code, error.status) + } + throw error + } + } if (route === 'POST sent') { // The caller's own client: "I just sent a message here" (opens their git-as-sender window). if (!canOpen(caller, row)) { @@ -1320,6 +1341,10 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, return fail('invalid_request', 400) } const patched = await patchWorkspace(db, caller, row, body.data, now) + if (patched.revoke !== 'none') { + // Readers lose the sleeping copy at once, before (and regardless of) the VM-side revokes. + await pruneReadSnapshotToOwner(db, patched.row) + } const revoked = patched.revoke === 'none' ? null : await revokeForAccessChange(life, patched.row, patched.revoke, caller.userId) return json({ workspace: await view(patched.row), ...(revoked ? { revoked } : {}) }) diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index d70c4e15c07..c0a62e2e5d7 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -20,6 +20,7 @@ import type { ProviderSandboxState, SandboxProviderApi } from './sandbox-provide import { egressSecretHosts, secretPlaceholder } from './secret-egress' import { egressAllowHosts, sessionSecretEnv, type SessionSecrets } from './session-env' import type { Keyring } from './secrets-crypto' +import { captureReadSnapshot, deleteReadSnapshot } from './read-snapshots' import { ORCAD_PORT, SHARE_PROXY_PORT, drainOrcad, runningOrcad, startOrcad, type OrcadReady, type StartInputs } from './sandbox-vm-commands' import { WORKSPACE_PRELUDE_SCRIPT } from '../image/vm-scripts.generated' import { resolveEnvironmentBoot, type BootSource } from './environments' @@ -624,9 +625,14 @@ export async function failAndRelease(deps: LifecycleDeps, row: SandboxRow): Prom export async function stopForSuspend( deps: LifecycleDeps, row: SandboxRow, - options: { drainSeconds?: number } = {} + options: { drainSeconds?: number; reason?: 'sleep' | 'rollover'; captureRead?: boolean } = {} ): Promise { if (row.session_id) { + // While orcad still serves: what a sleeping workspace shows to readers (sealed on the VM). + // Skipped for Restart (orcad isn't answering) and Archive (an archived workspace isn't readable). + if (options.captureRead !== false) { + await captureReadSnapshot(deps, row, options.reason ?? 'sleep').catch(() => undefined) + } await drainOrcad(deps.provider, row.session_id, options.drainSeconds) const stopped = await deps.provider.stopSession(row.session_id) if (stopped.snapshotId) { @@ -743,7 +749,7 @@ export async function rolloverSandbox(deps: LifecycleDeps, row: SandboxRow): Pro throw new GuardrailError('maintenance') } const suspending = await claim(deps, row, { status: 'suspending' }) - const stopped = await stopForSuspend(deps, suspending) + const stopped = await stopForSuspend(deps, suspending, { reason: 'rollover' }) await flushUsage(deps.db, deps.entitlements, deps.now(), row.id) return wake(deps, await claim(deps, stopped, { status: 'resuming' })) } @@ -790,6 +796,8 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom await markSnapshotsDeleted(deps.db, row.id, deps.now()) // Archive metadata (repo state, file tree) goes with the workspace. await deps.db.prepare('DELETE FROM sandbox_archives WHERE sandbox_id = ?').bind(row.id).run() + // So does its sealed read snapshot. + await deleteReadSnapshot(deps.db, row.id) const destroyed = await claim(deps, destroying, { status: 'destroyed', ...NO_SESSION, diff --git a/cloud/apps/sandbox-control/src/member-removal.ts b/cloud/apps/sandbox-control/src/member-removal.ts index 2e878195057..d63234aa1ff 100644 --- a/cloud/apps/sandbox-control/src/member-removal.ts +++ b/cloud/apps/sandbox-control/src/member-removal.ts @@ -6,6 +6,7 @@ import { revokeMemberDeviceSessions } from './device-sessions' import { revokeGrantsForMember } from './grants' import type { LifecycleDeps } from './lifecycle' import { memberChangeTime, recordMemberChange } from './member-changes' +import { revokeMemberReaderKeys } from './read-snapshots' import { disableMemberRoutines } from './routines/runs' export type MemberRemoval = { @@ -14,6 +15,7 @@ export type MemberRemoval = { grantsRevoked: number grantsQueued: number routinesDisabled: number + readerKeysRevoked: number } export async function removeMember( @@ -37,6 +39,8 @@ export async function removeMember( ]) // Their phones sign as them; then every workspace device they were granted (phones' included). const devicesRevoked = await revokeMemberDeviceSessions(life.db, accountId, userId, now) + // No device of theirs can open a sleeping workspace's read snapshot again (wrapped keys deleted). + const readerKeysRevoked = await revokeMemberReaderKeys(life.db, accountId, userId, now) const grants = await revokeGrantsForMember(life, accountId, userId) // Routines run with their creator's secrets: a departed member's stop, and nothing of theirs keeps running. const routines = await disableMemberRoutines({ life }, accountId, userId) @@ -45,7 +49,8 @@ export async function removeMember( devicesRevoked, grantsRevoked: grants.revoked, grantsQueued: grants.queued, - routinesDisabled: routines.disabled + routinesDisabled: routines.disabled, + readerKeysRevoked } await audit(life.db, { accountId, type: 'system', id: 'auth', userId }, { action: 'member.removed', detail: { ...result, runsCancelled: routines.cancelled } }, now) return result diff --git a/cloud/apps/sandbox-control/src/read-snapshots.ts b/cloud/apps/sandbox-control/src/read-snapshots.ts new file mode 100644 index 00000000000..19cf3bcaf43 --- /dev/null +++ b/cloud/apps/sandbox-control/src/read-snapshots.ts @@ -0,0 +1,447 @@ +// Read a sleeping workspace without waking it (gap 5), end-to-end encrypted: +// PUT /v1/reader-keys {publicKeyB64, deviceLabel, deviceKind} register this device's X25519 key +// GET /v1/reader-keys the caller's live keys +// DELETE /v1/reader-keys/:id +// GET /v1/team/workspaces/:id/read-snapshot?keyId=rk_… the body + only that key's wrapped key +// At every drain the control plane asks the VM (image/vm/orca-sandbox-read-snapshot) to seal a +// compact snapshot to the reader keys allowed to open the workspace, and stores the ciphertext. It +// never holds a reader secret, so it can't read a snapshot. Access mirrors canOpen at read time, and +// pruning (removal, private, revoke) deletes wrapped keys at once, without the VM. +import { z } from 'zod' +import type { SandboxCaller } from './auth' +import { ensureEntryPoints } from './golden-images' +import type { LifecycleDeps } from './lifecycle' +import type { SandboxRow } from './store' +import { WorkspaceError, canOpen, isOwner } from './workspaces' + +export const READ_SNAPSHOT_COMMAND = '/opt/orca/bin/orca-sandbox-read-snapshot' +const READ_SNAPSHOT_TIMEOUT_MS = 40_000 +/** Above this the VM trims the payload; anything bigger here is refused (D1 rows stay small). */ +export const MAX_READ_SNAPSHOT_BYTES = 220_000 +/** A sleeping workspace is sealed to at most this many devices (newest first). */ +export const MAX_READ_RECIPIENTS = 64 +const MAX_KEYS_PER_USER = 12 + +const B64_32 = z + .string() + .regex(/^[A-Za-z0-9+/]{43}=$/) + .refine((value) => atob(value).length === 32, 'expected 32 bytes') +const B64_NONCE = z.string().regex(/^[A-Za-z0-9+/]{16}$/) +const KEY_ID = /^rk_[0-9a-f]{24}$/ +const SNAPSHOT_ID = /^rsn_[0-9a-f]{24}$/ + +export const ReaderKeyRequestSchema = z + .object({ + publicKeyB64: B64_32, + deviceLabel: z.string().trim().min(1).max(80).regex(/^[^\u0000-\u001f]+$/), + deviceKind: z.enum(['desktop', 'mobile']) + }) + .strict() + +export type ReaderKeyRow = { + id: string + user_id: string + account_id: string + dev: number + public_key: string + device_kind: string + device_label: string + device_session_id: string | null + created_at: number + last_seen_at: number + revoked_at: number | null + revoked_by: string | null +} + +export class ReadSnapshotRouteError extends Error { + constructor( + readonly code: 'not_found' | 'no_snapshot' | 'not_sealed_for_key' | 'invalid_request', + readonly status: number + ) { + super(code) + } +} + +function randomHexId(prefix: string): string { + const bytes = crypto.getRandomValues(new Uint8Array(12)) + return `${prefix}_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}` +} + +function readerKeyView(row: ReaderKeyRow) { + return { + id: row.id, + deviceKind: row.device_kind, + deviceLabel: row.device_label, + createdAt: row.created_at, + lastSeenAt: row.last_seen_at + } +} + +/** Idempotent per (caller, public key): the same id comes back and lastSeenAt moves. */ +export async function registerReaderKey( + db: D1Database, + caller: SandboxCaller, + body: z.infer, + now: number +): Promise { + const live = await db + .prepare('SELECT * FROM reader_keys WHERE account_id = ? AND user_id = ? AND public_key = ? AND revoked_at IS NULL') + .bind(caller.accountId, caller.userId, body.publicKeyB64) + .first() + if (live) { + // A phone's key must stay bound to the session that registered it; another session (or a + // desktop token) presenting the same public key is refused rather than rebinding it. + if ((live.device_session_id ?? null) !== (caller.deviceSessionId ?? null)) { + throw new ReadSnapshotRouteError('invalid_request', 409) + } + await db + .prepare('UPDATE reader_keys SET last_seen_at = ?, device_label = ? WHERE id = ?') + .bind(now, body.deviceLabel, live.id) + .run() + return { ...live, last_seen_at: now, device_label: body.deviceLabel } + } + const row: ReaderKeyRow = { + id: randomHexId('rk'), + user_id: caller.userId, + account_id: caller.accountId, + dev: caller.dev ? 1 : 0, + public_key: body.publicKeyB64, + device_kind: body.deviceKind, + device_label: body.deviceLabel, + device_session_id: caller.deviceSessionId ?? null, + created_at: now, + last_seen_at: now, + revoked_at: null, + revoked_by: null + } + await db + .prepare( + `INSERT INTO reader_keys (id, user_id, account_id, dev, public_key, device_kind, device_label, device_session_id, created_at, last_seen_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .bind(row.id, row.user_id, row.account_id, row.dev, row.public_key, row.device_kind, row.device_label, row.device_session_id, now, now) + .run() + // Bounded per member: the least recently seen keys beyond the cap are retired. + const { results: stale } = await db + .prepare( + `SELECT id FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL + ORDER BY last_seen_at DESC, created_at DESC LIMIT -1 OFFSET ?` + ) + .bind(caller.accountId, caller.userId, MAX_KEYS_PER_USER) + .all<{ id: string }>() + if (stale.length > 0) { + await revokeReaderKeys(db, stale.map((s) => s.id), 'system:key_limit', now) + } + return row +} + +/** Revokes the keys and deletes every wrapped snapshot key they had (no VM involved). */ +export async function revokeReaderKeys(db: D1Database, ids: readonly string[], by: string, now: number): Promise { + let revoked = 0 + for (let i = 0; i < ids.length; i += 50) { + const chunk = ids.slice(i, i + 50) + const marks = chunk.map(() => '?').join(',') + const [update] = await db.batch([ + db.prepare(`UPDATE reader_keys SET revoked_at = ?, revoked_by = ? WHERE id IN (${marks}) AND revoked_at IS NULL`).bind(now, by, ...chunk), + db.prepare(`DELETE FROM read_snapshot_keys WHERE key_id IN (${marks})`).bind(...chunk) + ]) + revoked += update?.meta.changes ?? 0 + } + return revoked +} + +async function revokeWhere(db: D1Database, where: string, binds: (string | number)[], by: string, now: number): Promise { + const { results } = await db + .prepare(`SELECT id FROM reader_keys WHERE ${where} AND revoked_at IS NULL`) + .bind(...binds) + .all<{ id: string }>() + return revokeReaderKeys(db, results.map((r) => r.id), by, now) +} + +/** A member left the account: none of their devices may read any of its workspaces again. */ +export function revokeMemberReaderKeys(db: D1Database, accountId: string, userId: string, now: number): Promise { + return revokeWhere(db, 'account_id = ? AND user_id = ?', [accountId, userId], 'system:member_removed', now) +} + +/** A phone was unpaired or revoked: its reader key goes with it. */ +export function revokeDeviceSessionReaderKeys(db: D1Database, deviceSessionId: string, now: number): Promise { + return revokeWhere(db, 'device_session_id = ?', [deviceSessionId], 'system:device_revoked', now) +} + +/** + * Visibility or owner changed: drop every wrapped key of this workspace whose holder is not its + * (new) owner. Team members get back in at the next drain if it becomes team-visible again. + */ +export async function pruneReadSnapshotToOwner(db: D1Database, row: SandboxRow): Promise { + const result = await db + .prepare( + `DELETE FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id NOT IN + (SELECT id FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL)` + ) + .bind(row.id, row.account_id, row.user_id) + .run() + return result.meta.changes +} + +export async function deleteReadSnapshot(db: D1Database, sandboxId: string): Promise { + await db.batch([ + db.prepare('DELETE FROM read_snapshot_keys WHERE sandbox_id = ?').bind(sandboxId), + db.prepare('DELETE FROM read_snapshots WHERE sandbox_id = ?').bind(sandboxId) + ]) +} + +/** The live keys allowed to open this workspace right now (owner; every member when team-visible). */ +export async function readerKeysFor(db: D1Database, row: SandboxRow): Promise<{ id: string; public_key: string }[]> { + if (row.archived_at !== null) { + return [] + } + const team = row.visibility === 'team' + const { results } = await db + .prepare( + `SELECT id, public_key FROM reader_keys + WHERE account_id = ? AND revoked_at IS NULL ${team ? '' : 'AND user_id = ?'} + ORDER BY (user_id = ?) DESC, last_seen_at DESC LIMIT ?` + ) + .bind(...(team ? [row.account_id] : [row.account_id, row.user_id]), row.user_id, MAX_READ_RECIPIENTS) + .all<{ id: string; public_key: string }>() + return results +} + +const VmOutputSchema = z + .object({ + v: z.literal(1), + snapshotId: z.string().regex(SNAPSHOT_ID), + workspaceId: z.string(), + nonceB64: B64_NONCE, + ciphertextB64: z.string().regex(/^[A-Za-z0-9+/]+=*$/).max(MAX_READ_SNAPSHOT_BYTES), + recipients: z + .array( + z + .object({ + keyId: z.string().regex(KEY_ID), + ephemeralPublicKeyB64: B64_32, + nonceB64: B64_NONCE, + wrappedKeyB64: z.string().regex(/^[A-Za-z0-9+/]{64}$/) + }) + .strict() + ) + .max(MAX_READ_RECIPIENTS), + stats: z.record(z.string(), z.number()).optional() + }) + .strict() + +type CaptureOutcome = + | { captured: true; snapshotId: string; recipients: number; bytes: number; stats?: Record } + | { captured: false; reason: string } +export type CaptureResult = CaptureOutcome & { ms: number } + +/** + * Best effort, before orcad drains: the VM gathers and seals the snapshot (it never leaves the VM + * in plaintext); this stores the ciphertext and replaces the previous one. A failure keeps the old + * snapshot and never blocks the sleep. + */ +export async function captureReadSnapshot(deps: LifecycleDeps, row: SandboxRow, reason: string): Promise { + const started = deps.now() + const done = (r: CaptureOutcome): CaptureResult => { + const result: CaptureResult = { ...r, ms: deps.now() - started } + console.log(JSON.stringify({ event: 'read_snapshot', sandboxId: row.id, reason, ...result })) + return result + } + if (!row.session_id) { + return done({ captured: false, reason: 'no_session' }) + } + const keys = await readerKeysFor(deps.db, row) + if (keys.length === 0) { + return done({ captured: false, reason: 'no_reader_keys' }) + } + const snapshotId = randomHexId('rsn') + const sessionId = row.session_id + let stdout: string + try { + // VMs booted from an older image get the current entry points (this script) first. + await ensureEntryPoints(deps, sessionId).catch(() => undefined) + const result = await deps.provider.runCommand(sessionId, { + command: READ_SNAPSHOT_COMMAND, + env: { + ORCA_READ_SNAPSHOT_ID: snapshotId, + ORCA_READ_WORKSPACE_ID: row.id, + ORCA_READ_REASON: reason, + ORCA_READ_RECIPIENTS: JSON.stringify(keys.map((k) => ({ keyId: k.id, publicKeyB64: k.public_key }))) + }, + timeoutMs: READ_SNAPSHOT_TIMEOUT_MS + }) + if (result.exitCode !== 0) { + return done({ captured: false, reason: `exit_${result.exitCode}:${result.stderr.trim().slice(0, 120)}` }) + } + stdout = result.stdout + } catch (error) { + return done({ captured: false, reason: `run_failed:${String(error).slice(0, 120)}` }) + } + let parsed: z.infer + try { + const line = stdout.trim().split('\n').pop() ?? '' + const out = VmOutputSchema.safeParse(JSON.parse(line)) + if (!out.success) { + return done({ captured: false, reason: 'bad_output' }) + } + parsed = out.data + } catch { + return done({ captured: false, reason: 'bad_output' }) + } + const asked = new Set(keys.map((k) => k.id)) + if (parsed.snapshotId !== snapshotId || parsed.workspaceId !== row.id || parsed.recipients.some((r) => !asked.has(r.keyId))) { + return done({ captured: false, reason: 'mismatched_output' }) + } + const now = deps.now() + const statements = [ + deps.db.prepare('DELETE FROM read_snapshot_keys WHERE sandbox_id = ?').bind(row.id), + deps.db + .prepare( + `INSERT INTO read_snapshots (sandbox_id, snapshot_id, stored_at, bytes, nonce, ciphertext) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(sandbox_id) DO UPDATE SET snapshot_id = excluded.snapshot_id, stored_at = excluded.stored_at, + bytes = excluded.bytes, nonce = excluded.nonce, ciphertext = excluded.ciphertext` + ) + .bind(row.id, snapshotId, now, parsed.ciphertextB64.length, parsed.nonceB64, parsed.ciphertextB64), + ...parsed.recipients.map((r) => + deps.db + .prepare( + 'INSERT INTO read_snapshot_keys (sandbox_id, key_id, snapshot_id, ephemeral_public_key, nonce, wrapped_key) VALUES (?, ?, ?, ?, ?, ?)' + ) + .bind(row.id, r.keyId, snapshotId, r.ephemeralPublicKeyB64, r.nonceB64, r.wrappedKeyB64) + ), + // A key revoked (or a member removed) while the VM was sealing must not slip back in. + deps.db + .prepare( + `DELETE FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id IN (SELECT id FROM reader_keys WHERE revoked_at IS NOT NULL)` + ) + .bind(row.id) + ] + await deps.db.batch(statements) + // The workspace may have been made private while sealing: re-apply the current rule. + const current = await deps.db.prepare('SELECT * FROM sandboxes WHERE id = ?').bind(row.id).first() + if (current && current.visibility !== 'team') { + await pruneReadSnapshotToOwner(deps.db, current) + } + return done({ + captured: true, + snapshotId, + recipients: parsed.recipients.length, + bytes: parsed.ciphertextB64.length, + ...(parsed.stats ? { stats: parsed.stats } : {}) + }) +} + +/** For workspace views: when each workspace's snapshot was stored (only rows the caller can open). */ +export async function readSnapshotTimes(db: D1Database, ids: readonly string[]): Promise> { + const out = new Map() + for (let i = 0; i < ids.length; i += 90) { + const chunk = ids.slice(i, i + 90) + if (chunk.length === 0) { + continue + } + const { results } = await db + .prepare(`SELECT sandbox_id, stored_at FROM read_snapshots WHERE sandbox_id IN (${chunk.map(() => '?').join(',')})`) + .bind(...chunk) + .all<{ sandbox_id: string; stored_at: number }>() + for (const r of results) { + out.set(r.sandbox_id, r.stored_at) + } + } + return out +} + +export async function getReadSnapshot(db: D1Database, caller: SandboxCaller, row: SandboxRow, keyId: string | null, now: number) { + // Belt and braces over canOpen: a private workspace's snapshot opens only for its owner. + if (!canOpen(caller, row) || (row.visibility !== 'team' && !isOwner(caller, row))) { + throw new WorkspaceError('not_found') + } + if (!keyId || !KEY_ID.test(keyId)) { + throw new ReadSnapshotRouteError('invalid_request', 400) + } + // The key must be the caller's own, live one: nobody fetches another member's wrapped key. + const key = await db + .prepare('SELECT * FROM reader_keys WHERE id = ? AND account_id = ? AND user_id = ? AND revoked_at IS NULL') + .bind(keyId, caller.accountId, caller.userId) + .first() + if (!key) { + throw new ReadSnapshotRouteError('invalid_request', 400) + } + const snapshot = await db + .prepare('SELECT * FROM read_snapshots WHERE sandbox_id = ?') + .bind(row.id) + .first<{ snapshot_id: string; stored_at: number; nonce: string; ciphertext: string }>() + if (!snapshot) { + throw new ReadSnapshotRouteError('no_snapshot', 404) + } + const wrapped = await db + .prepare('SELECT * FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id = ? AND snapshot_id = ?') + .bind(row.id, keyId, snapshot.snapshot_id) + .first<{ ephemeral_public_key: string; nonce: string; wrapped_key: string }>() + if (!wrapped) { + throw new ReadSnapshotRouteError('not_sealed_for_key', 404) + } + if (now - key.last_seen_at > 60 * 60_000) { + await db.prepare('UPDATE reader_keys SET last_seen_at = ? WHERE id = ?').bind(now, key.id).run() + } + return { + snapshot: { + v: 1 as const, + snapshotId: snapshot.snapshot_id, + workspaceId: row.id, + storedAt: snapshot.stored_at, + nonceB64: snapshot.nonce, + ciphertextB64: snapshot.ciphertext, + recipient: { + keyId, + ephemeralPublicKeyB64: wrapped.ephemeral_public_key, + nonceB64: wrapped.nonce, + wrappedKeyB64: wrapped.wrapped_key + } + } + } +} + + +export type ReaderKeysRouteDeps = { db: D1Database; caller: SandboxCaller; now: number; readJson: () => Promise } + +export async function handleReaderKeysRoute(request: Request, url: URL, deps: ReaderKeysRouteDeps): Promise { + const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { 'cache-control': 'no-store' } }) + const match = /^\/v1\/reader-keys(?:\/(rk_[0-9a-f]{24}))?$/.exec(url.pathname) + if (!match) { + return json({ error: 'not_found' }, 404) + } + const [, id] = match + try { + if (!id && request.method === 'PUT') { + const body = ReaderKeyRequestSchema.safeParse(await deps.readJson()) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + return json({ readerKey: readerKeyView(await registerReaderKey(deps.db, deps.caller, body.data, deps.now)) }) + } + if (!id && request.method === 'GET') { + const { results } = await deps.db + .prepare('SELECT * FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL ORDER BY last_seen_at DESC') + .bind(deps.caller.accountId, deps.caller.userId) + .all() + return json({ readerKeys: results.map(readerKeyView) }) + } + if (id && request.method === 'DELETE') { + const owned = await deps.db + .prepare('SELECT id FROM reader_keys WHERE id = ? AND account_id = ? AND user_id = ? AND revoked_at IS NULL') + .bind(id, deps.caller.accountId, deps.caller.userId) + .first<{ id: string }>() + if (!owned) { + return json({ error: 'not_found' }, 404) + } + await revokeReaderKeys(deps.db, [id], deps.caller.userId, deps.now) + return json({ ok: true }) + } + return json({ error: 'not_found' }, 404) + } catch (error) { + if (error instanceof ReadSnapshotRouteError) { + return json({ error: error.code }, error.status) + } + throw error + } +} diff --git a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts index 1b4343cee49..62f48d7c5e8 100644 --- a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts +++ b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts @@ -227,7 +227,7 @@ export async function restartSandbox(deps: LifecycleDeps, row: SandboxRow): Prom throw new LifecycleError('conflict', `sandbox_${current.status}`) } const suspending = await claim(deps, current, { status: 'suspending' }) - const stopped = await stopForSuspend(deps, suspending, { drainSeconds: RESTART_DRAIN_SECONDS }) + const stopped = await stopForSuspend(deps, suspending, { drainSeconds: RESTART_DRAIN_SECONDS, captureRead: false }) await flushUsage(deps.db, deps.entitlements, deps.now(), row.id) return wake(deps, await claim(deps, stopped, { status: 'resuming' })) } @@ -294,7 +294,7 @@ export async function archiveSandbox( let stopped = row if (row.status === 'running') { // Short drain: the desktop's Sleep normally ran first; a long drain would outlive the caller. - stopped = await stopForSuspend(deps, await claim(deps, row, { status: 'suspending' }), { drainSeconds: ARCHIVE_DRAIN_SECONDS }) + stopped = await stopForSuspend(deps, await claim(deps, row, { status: 'suspending' }), { drainSeconds: ARCHIVE_DRAIN_SECONDS, captureRead: false }) await flushUsage(deps.db, deps.entitlements, deps.now(), row.id) } const ttl = config.archiveTtlMs ?? DEFAULT_ARCHIVE_TTL_MS diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index ff6082b17be..f5049cc58c5 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -13,6 +13,7 @@ import type { SandboxCaller } from './auth' import type { MachineSize } from './entitlements' import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './store' import { memberNamesFor } from './member-names' +import { readSnapshotTimes } from './read-snapshots' import { sandboxView } from './wire' export const PRESENCE_TTL_MS = 45_000 @@ -158,10 +159,11 @@ function repoView(row: SandboxRow) { export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) { const ids = rows.map((r) => r.id) - const [presence, compute, granted] = await Promise.all([ + const [presence, compute, granted, readAt] = await Promise.all([ presenceFor(db, ids, now), computeMsFor(db, ids), - activeGrantUsers(db, ids, caller.userId) + activeGrantUsers(db, ids, caller.userId), + readSnapshotTimes(db, ids) ]) const referenced = (row: SandboxRow, live: readonly PresenceRow[]) => [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter( @@ -195,7 +197,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows access, presence: live.map((p) => ({ userId: p.user_id, clientId: p.client_id, state: p.state, chatId: p.chat_id, at: p.updated_at })), // Display names (token `name` claim) for the ids above; the roster wins where it has one. - memberNames + memberNames, + // When its sleeping read-only copy was saved ("As of"); only for those who may read it. + readSnapshotAt: canOpen(caller, row) ? (readAt.get(row.id) ?? null) : null } }) } diff --git a/cloud/apps/sandbox-control/test/api.test.ts b/cloud/apps/sandbox-control/test/api.test.ts index 0f830cbfc0d..2644d27d9a1 100644 --- a/cloud/apps/sandbox-control/test/api.test.ts +++ b/cloud/apps/sandbox-control/test/api.test.ts @@ -191,7 +191,7 @@ describe('member removal', () => { const { secret } = (await h.call('POST', '/v1/api-keys', { bearer: member, body: { name: 'bob ci', scopes: ['workspaces:read'] } })).body expect((await h.call('GET', '/v1/me', { bearer: secret })).status).toBe(200) const removed = await h.call('POST', '/v1/internal/members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } }) - expect(removed.body).toEqual({ revoked: 1, keysRevoked: 1, devicesRevoked: 0, grantsRevoked: 0, grantsQueued: 0, routinesDisabled: 0 }) + expect(removed.body).toEqual({ revoked: 1, keysRevoked: 1, devicesRevoked: 0, grantsRevoked: 0, grantsQueued: 0, routinesDisabled: 0, readerKeysRevoked: 0 }) expect((await h.call('GET', '/v1/me', { bearer: secret })).status).toBe(401) }) }) diff --git a/cloud/apps/sandbox-control/test/read-snapshots.test.ts b/cloud/apps/sandbox-control/test/read-snapshots.test.ts new file mode 100644 index 00000000000..a5887f9d5a6 --- /dev/null +++ b/cloud/apps/sandbox-control/test/read-snapshots.test.ts @@ -0,0 +1,300 @@ +import { createRequire } from 'node:module' +import { SignJWT, exportJWK, generateKeyPair } from 'jose' +import { describe, expect, it, vi } from 'vitest' +import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from '../../../../src/main/cloud-workspaces/sealed-grant-node' +import { openReadSnapshot, type ReadSnapshot } from '../../../../src/shared/cloud-workspaces/read-snapshot' +import type { RunCommandParams } from '../src/sandbox-provider' +import { MAX_READ_RECIPIENTS, READ_SNAPSHOT_COMMAND } from '../src/read-snapshots' +import { createHarness } from './harness' + +// The real VM collector + sealer (image/vm/orca-read-snapshot.cjs), fed a fake orcad. +const require = createRequire(import.meta.url) +const vm = require('../image/vm/orca-read-snapshot.cjs') as { + seal: (payload: unknown, recipients: unknown[], workspaceId: string, snapshotId: string) => Record + gather: (call: (method: string, params: unknown) => Promise, opts: Record) => Promise> + fitToBudget: (payload: T, maxBytes?: number) => T +} + +const SECRET_LINE = 'the deploy key is in 1password, not in the repo' + +function fakeOrcad(method: string): unknown { + switch (method) { + case 'agentSession.subscribeStatus': + return { + type: 'snapshot', + sessions: [ + { sessionId: 'chat-1', agent: 'claude', status: 'idle', conversationName: 'Fix login', turnOutcome: 'completed', updatedAt: 2 }, + { sessionId: 'chat-2', agent: 'codex', status: 'working', conversationName: 'Add tests', updatedAt: 1 } + ] + } + case 'worktree.ps': + return { + worktrees: [ + { + path: '/vercel/sandbox/project', + linkedPR: { number: 42, title: 'Fix login', state: 'open', url: 'https://github.com/acme/app/pull/42', checksStatus: 'success', checksSummary: '3/3 passed' } + } + ] + } + case 'git.status': + return { branch: 'refs/heads/fix/login', head: 'abc1234', entries: [{ path: 'src/login.ts', status: 'modified', area: 'unstaged', added: 12, removed: 3 }] } + case 'git.history': + return { items: [{ id: 'abc1234', subject: 'Fix the login redirect', author: 'Alice', timestamp: 1 }] } + case 'agentSession.history': + return { + page: { + hasOlder: false, + items: [ + { itemId: 'i1', observedAt: 1, body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Why does login loop?' }] } }, + { itemId: 'i2', observedAt: 2, body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: SECRET_LINE }] } }, + { itemId: 'i3', observedAt: 3, body: { kind: 'tool', blocks: [] } } + ] + } + } + default: + return null + } +} + +/** What orca-sandbox-read-snapshot does on a VM, minus the socket: gather from orcad, then seal. */ +async function runVmSealer(params: RunCommandParams): Promise { + const env = params.env ?? {} + const payload = vm.fitToBudget( + await vm.gather(async (method) => fakeOrcad(method), { + workspaceId: env.ORCA_READ_WORKSPACE_ID, + snapshotId: env.ORCA_READ_SNAPSHOT_ID, + reason: env.ORCA_READ_REASON, + now: 1_800_000_000_000, + deadline: Date.now() + 10_000 + }) + ) + const out = vm.seal(payload, JSON.parse(env.ORCA_READ_RECIPIENTS ?? '[]'), env.ORCA_READ_WORKSPACE_ID!, env.ORCA_READ_SNAPSHOT_ID!) + return `${JSON.stringify(out)}\n` +} + +async function setup() { + vi.spyOn(console, 'log').mockImplementation((line: string) => { if (process.env.DBG && String(line).includes('read_snapshot')) process.stderr.write(line + '\n') }) + const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40) }) + // The fake's runCommand awaits whatever the handler returns, so the real (async) sealer can run. + let vmUp = true + h.vercel.commandHandler = ((params: RunCommandParams) => { + if (params.command !== READ_SNAPSHOT_COMMAND) { + return undefined + } + return vmUp + ? runVmSealer(params).then((stdout) => ({ exitCode: 0, stdout, stderr: '' })) + : { exitCode: 3, stdout: '', stderr: 'orcad not running' } + }) as never + type Who = { sub: string; org: string; role: 'owner' | 'admin' | 'member' } + const as = (sub: string, role: Who['role'] = 'member', org = 'acme'): Who => ({ sub, org, role }) + const req = async (who: Who, method: string, path: string, body?: unknown) => + h.call(method, path, { bearer: await h.token(who.sub, who.org, 'sandbox', { org_role: who.role }), body }) + const alice = as('alice') + const bob = as('bob') + const created = await req(alice, 'POST', '/v1/sandboxes', { + workspaceId: 'ws-1', + machineSize: 'standard', + title: 'Fix login', + repo: { url: 'https://github.com/acme/app', ref: 'fix/login' } + }) + expect(created.status).toBe(200) + const id = created.body.sandbox.id as string + const register = async (who: Who, kind: 'desktop' | 'mobile' = 'desktop', bearer?: string) => { + const key = generateGrantRecipientKey() + const res = bearer + ? await h.call('PUT', '/v1/reader-keys', { bearer, body: { publicKeyB64: key.publicKeyB64, deviceLabel: `${who.sub} ${kind}`, deviceKind: kind } }) + : await req(who, 'PUT', '/v1/reader-keys', { publicKeyB64: key.publicKeyB64, deviceLabel: `${who.sub} ${kind}`, deviceKind: kind }) + expect(res.status).toBe(200) + return { ...key, id: res.body.readerKey.id as string } + } + /** Sleep the workspace (the drain seals first). `orcadDown`: the VM script finds no orcad. */ + const sleep = async (who: Who = alice, orcadDown = false) => { + vmUp = !orcadDown + return req(who, 'POST', `/v1/sandboxes/${id}/suspend`) + } + const read = (who: Who, keyId: string, bearer?: string) => + bearer + ? h.call('GET', `/v1/team/workspaces/${id}/read-snapshot?keyId=${keyId}`, { bearer }) + : req(who, 'GET', `/v1/team/workspaces/${id}/read-snapshot?keyId=${keyId}`) + const open = async (body: { snapshot: never }, secretKey: Uint8Array): Promise => + openReadSnapshot(body.snapshot, id, secretKey, nodeSealedGrantPrimitives) + return { h, req, as, alice, bob, id, register, sleep, read, open } +} + +describe('read snapshots of sleeping workspaces (E2EE)', () => { + it('seals at sleep to the owner devices; the control plane stores only ciphertext; the VM stays asleep', async () => { + const t = await setup() + const laptop = await t.register(t.alice) + const phone = await t.register(t.alice, 'mobile') + expect((await t.sleep()).status).toBe(200) + const row = t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id) as { status: string } + expect(row.status).toBe('suspended') + + const before = t.h.vercel.commands.length + for (const key of [laptop, phone]) { + const res = await t.read(t.alice, key.id) + expect(res.status).toBe(200) + const snap = await t.open(res.body, key.secretKey) + expect(snap.sessions.map((s) => [s.agent, s.title, s.status])).toEqual([ + ['claude', 'Fix login', 'idle'], + ['codex', 'Add tests', 'working'] + ]) + expect(snap.sessions[0]!.messages.map((m) => m.text)).toEqual(['Why does login loop?', SECRET_LINE]) + expect(snap.git).toMatchObject({ branch: 'fix/login', changeCount: 1, added: 12, removed: 3 }) + expect(snap.pr).toMatchObject({ number: 42, url: 'https://github.com/acme/app/pull/42', checksStatus: 'success' }) + // Only this device's wrapped key is handed out. + expect(res.body.snapshot.recipient.keyId).toBe(key.id) + } + // Reading never touched the VM. + expect(t.h.vercel.commands.length).toBe(before) + expect((t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id) as { status: string }).status).toBe('suspended') + // Nothing readable at rest. + const dump = JSON.stringify([ + t.h.raw.prepare('SELECT * FROM read_snapshots').all(), + t.h.raw.prepare('SELECT * FROM read_snapshot_keys').all() + ]) + expect(dump).not.toContain('1password') + expect(dump).not.toContain('login loop') + // The list says when, for "As of" without fetching the blob. + const list = await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine') + expect(list.body.workspaces[0].readSnapshotAt).toBe(t.h.now()) + }) + + it('opens for teammates only on team workspaces; private stays owner-only; bad keys and other people’s keys are refused', async () => { + const t = await setup() + const own = await t.register(t.alice) + const bobs = await t.register(t.bob) + await t.sleep() + // Private: Bob can't see it at all, and was never a recipient. + expect((await t.read(t.bob, bobs.id)).body).toEqual({ error: 'not_found' }) + await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + await t.sleep() + const res = await t.read(t.bob, bobs.id) + expect(res.status).toBe(200) + expect((await t.open(res.body, bobs.secretKey)).sessions).toHaveLength(2) + // Bob can't fetch Alice's wrapped key, nor open his blob with another key. + expect((await t.read(t.bob, own.id)).status).toBe(400) + await expect(t.open(res.body, own.secretKey)).rejects.toThrow('decrypt_failed') + // Another org's member sees nothing. + const mallory = t.as('mallory', 'member', 'evil') + const mk = await t.register(mallory) + expect((await t.read(mallory, mk.id)).status).toBe(404) + }) + + it('making it private prunes teammates at once, without the VM', async () => { + const t = await setup() + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + const own = await t.register(t.alice) + const bobs = await t.register(t.bob) + await t.sleep() + expect((await t.read(t.bob, bobs.id)).status).toBe(200) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'private' }) + expect((await t.read(t.bob, bobs.id)).status).toBe(404) + expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys').all()).toEqual([{ key_id: own.id }]) + // Even back to team: Bob's wrapped key is gone until the next sleep re-seals. + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + expect((await t.read(t.bob, bobs.id)).body).toEqual({ error: 'not_sealed_for_key' }) + }) + + it('a removed member can no longer read, and their wrapped keys are deleted', async () => { + const t = await setup() + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + await t.register(t.alice) + const bobs = await t.register(t.bob) + await t.sleep() + expect((await t.read(t.bob, bobs.id)).status).toBe(200) + const removed = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } }) + expect(removed.body.readerKeysRevoked).toBe(1) + // A token minted after removal (stale org claim) still gets nothing: key revoked, wrapped key gone. + t.h.advance(1000) + const again = await t.read(t.bob, bobs.id) + expect(again.status).not.toBe(200) + expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys WHERE key_id = ?').all(bobs.id)).toEqual([]) + // Next sleep is not sealed to him either. + await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`) + await t.sleep() + expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys WHERE key_id = ?').all(bobs.id)).toEqual([]) + }) + + it('a device added after the last sleep gets not_sealed_for_key; no snapshot yet is no_snapshot', async () => { + const t = await setup() + const first = await t.register(t.alice) + expect((await t.read(t.alice, first.id)).body).toEqual({ error: 'no_snapshot' }) + await t.sleep() + const later = await t.register(t.alice) + expect((await t.read(t.alice, later.id)).body).toEqual({ error: 'not_sealed_for_key' }) + expect((await t.read(t.alice, 'rk_nope')).status).toBe(400) + }) + + it('registration is idempotent, per member capped, and a key revoke drops its wrapped key', async () => { + const t = await setup() + const key = generateGrantRecipientKey() + const body = { publicKeyB64: key.publicKeyB64, deviceLabel: 'Mac', deviceKind: 'desktop' } + const a = await t.req(t.alice, 'PUT', '/v1/reader-keys', body) + const b = await t.req(t.alice, 'PUT', '/v1/reader-keys', body) + expect(a.body.readerKey.id).toBe(b.body.readerKey.id) + expect((await t.req(t.alice, 'PUT', '/v1/reader-keys', { ...body, publicKeyB64: 'AAAA' })).status).toBe(400) + await t.sleep() + expect((await t.read(t.alice, a.body.readerKey.id)).status).toBe(200) + expect((await t.req(t.bob, 'DELETE', `/v1/reader-keys/${a.body.readerKey.id}`)).status).toBe(404) + expect((await t.req(t.alice, 'DELETE', `/v1/reader-keys/${a.body.readerKey.id}`)).body).toEqual({ ok: true }) + expect((await t.read(t.alice, a.body.readerKey.id)).status).toBe(400) + // Re-registering a revoked key yields a new id (never resurrected), with nothing sealed to it. + const c = await t.req(t.alice, 'PUT', '/v1/reader-keys', body) + expect(c.body.readerKey.id).not.toBe(a.body.readerKey.id) + for (let i = 0; i < 14; i++) { + await t.register(t.alice) + } + expect((await t.req(t.alice, 'GET', '/v1/reader-keys')).body.readerKeys).toHaveLength(12) + }) + + it('a phone key dies with its device session', async () => { + const t = await setup() + const { privateKey, publicKey } = await generateKeyPair('Ed25519', { extractable: true }) + const publicKeyB64 = Buffer.from((await exportJWK(publicKey)).x!, 'base64url').toString('base64') + const enrolled = await t.h.call('POST', '/v1/device-sessions', { + body: { label: 'iPhone', platform: 'ios', publicKeyB64 }, + bearer: await t.h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + }) + const sessionId = enrolled.body.deviceSession.id as string + const phoneToken = async () => { + const iat = Math.floor(t.h.now() / 1000) + return new SignJWT({}).setProtectedHeader({ alg: 'EdDSA', kid: sessionId }).setIssuer('orca-device').setSubject(sessionId) + .setAudience('orca-sandbox').setIssuedAt(iat).setExpirationTime(iat + 120).sign(privateKey) + } + const key = await t.register(t.alice, 'mobile', await phoneToken()) + await t.sleep() + const res = await t.read(t.alice, key.id, await phoneToken()) + expect(res.status).toBe(200) + expect((await t.open(res.body, key.secretKey)).sessions[0]!.messages[1]!.text).toBe(SECRET_LINE) + await t.h.call('DELETE', `/v1/device-sessions/${sessionId}`, { bearer: await t.h.token('alice', 'acme') }) + expect(t.h.raw.prepare('SELECT revoked_by FROM reader_keys WHERE id = ?').get(key.id)).toEqual({ revoked_by: 'system:device_revoked' }) + expect(t.h.raw.prepare('SELECT * FROM read_snapshot_keys WHERE key_id = ?').all(key.id)).toEqual([]) + }) + + it('a failed capture keeps the previous snapshot and never blocks the sleep', async () => { + const t = await setup() + const key = await t.register(t.alice) + await t.sleep() + const first = (await t.read(t.alice, key.id)).body.snapshot.snapshotId + await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`) + // The VM script finds no orcad (exit 3). + expect((await t.sleep(t.alice, true)).status).toBe(200) + expect((await t.read(t.alice, key.id)).body.snapshot.snapshotId).toBe(first) + }) + + it('the VM sealer bounds what it seals and caps recipients', () => { + const big = { + v: 1, + sessions: Array.from({ length: 3 }, (_, i) => ({ sessionId: `s${i}`, messages: Array.from({ length: 60 }, (_, j) => ({ itemId: `${j}`, role: 'user', text: 'x'.repeat(4000), at: j })) })), + git: { changes: [] } + } + const fitted = vm.fitToBudget(big, 150_000) + expect(Buffer.byteLength(JSON.stringify(fitted))).toBeLessThanOrEqual(150_000) + expect(MAX_READ_RECIPIENTS).toBe(64) + // A malformed recipient is skipped, not fatal. + const out = vm.seal({ v: 1 }, [{ keyId: 'rk_bad', publicKeyB64: 'x' }, { keyId: 'rk_000000000000000000000000', publicKeyB64: generateGrantRecipientKey().publicKeyB64 }], 'sbx_0', 'rsn_0') as { recipients: unknown[] } + expect(out.recipients).toHaveLength(1) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspaces.test.ts b/cloud/apps/sandbox-control/test/workspaces.test.ts index 17fe65774f2..2a400751559 100644 --- a/cloud/apps/sandbox-control/test/workspaces.test.ts +++ b/cloud/apps/sandbox-control/test/workspaces.test.ts @@ -233,7 +233,7 @@ describe('workspace grants (E2EE pairing through the control plane)', () => { await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) await t.req(t.bob, 'POST', `/v1/team/workspaces/${t.id}/grants`, { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' }) const res = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } }) - expect(res.body).toEqual({ revoked: 1, queued: 0, keysRevoked: 0, devicesRevoked: 0, grantsRevoked: 1, grantsQueued: 0, routinesDisabled: 0 }) + expect(res.body).toEqual({ revoked: 1, queued: 0, keysRevoked: 0, devicesRevoked: 0, grantsRevoked: 1, grantsQueued: 0, routinesDisabled: 0, readerKeysRevoked: 0 }) }) }) From cedec8398b3b59431b52e7fcfbf59bff45df571f Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 00:17:45 -0800 Subject: [PATCH 03/46] fix(cloud): read snapshot security review follow-ups (trust wording, timing-only stats, live phone keys, races) --- .../image/vm-scripts.generated.ts | 2 +- .../image/vm/orca-read-snapshot.cjs | 13 +++--- cloud/apps/sandbox-control/src/index.ts | 6 ++- .../sandbox-control/src/read-snapshots.ts | 42 ++++++++++++------- src/shared/cloud-workspaces/read-snapshot.ts | 10 ++++- 5 files changed, 45 insertions(+), 28 deletions(-) diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index e0912c8d64d..0d140f8810f 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -3,7 +3,7 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0"],"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" -export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_key_tail=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code: first-run screens answered once (theme picker, folder trust, bypass-mode warning,\n# the \"use this API key?\" question). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline }) {\n const timeLeft = () => deadline - Date.now()\n const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })])\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : []\n // Newest activity first; chats with nothing in them still list (agent + status).\n const picked = summaries\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n const { messages, hasOlder } = messagesOf(history)\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: str(s.agent, 40),\n title: str(s.conversationName, 200) || str(s.latestPrompt, 200),\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: str(s.turnOutcome, 40),\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline }))\n const out = seal(payload, recipients, workspaceId, snapshotId)\n out.stats = {\n sessions: payload.sessions.length,\n messages: payload.sessions.reduce((n, s) => n + s.messages.length, 0),\n plainBytes: Buffer.byteLength(JSON.stringify(payload)),\n collectMs: Date.now() - started\n }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc }\n\nif (require.main === module) {\n main().catch((error) => {\n process.stderr.write(`read snapshot failed: ${String(error && error.message ? error.message : error).slice(0, 200)}\\n`)\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_key_tail=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code: first-run screens answered once (theme picker, folder trust, bypass-mode warning,\n# the \"use this API key?\" question). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline }) {\n const timeLeft = () => deadline - Date.now()\n const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })])\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : []\n // Newest activity first; chats with nothing in them still list (agent + status).\n const picked = summaries\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n const { messages, hasOlder } = messagesOf(history)\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: str(s.agent, 40),\n title: str(s.conversationName, 200) || str(s.latestPrompt, 200),\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: str(s.turnOutcome, 40),\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline }))\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs index 7ec54dfdd0b..b12c08577e5 100644 --- a/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs +++ b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs @@ -310,20 +310,17 @@ async function main() { const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now()))) const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline })) const out = seal(payload, recipients, workspaceId, snapshotId) - out.stats = { - sessions: payload.sessions.length, - messages: payload.sessions.reduce((n, s) => n + s.messages.length, 0), - plainBytes: Buffer.byteLength(JSON.stringify(payload)), - collectMs: Date.now() - started - } + // Timing only: counts and sizes would describe the plaintext to the control plane's logs. + out.stats = { collectMs: Date.now() - started } process.stdout.write(`${JSON.stringify(out)}\n`) } module.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc } if (require.main === module) { - main().catch((error) => { - process.stderr.write(`read snapshot failed: ${String(error && error.message ? error.message : error).slice(0, 200)}\n`) + // A fixed message: an error text could carry workspace content into the control plane's logs. + main().catch(() => { + process.stderr.write('read snapshot failed\n') process.exit(1) }) } diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index ecc6485aae1..ba91cd5c13b 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -860,8 +860,10 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) onRevoked: deps.onDeviceSessionRevoked ?? (async (deviceSessionId) => { - // Its reader key first: no VM involved, so this can't be held up by a sleeping workspace. - await revokeDeviceSessionReaderKeys(env.SANDBOX_DB, deviceSessionId, now) + // Its reader key: independent of the grant cleanup below, so neither failure blocks the other. + await revokeDeviceSessionReaderKeys(env.SANDBOX_DB, deviceSessionId, now).catch((error: unknown) => + console.log(JSON.stringify({ event: 'device_reader_key_revoke_failed', id: deviceSessionId, error: String(error).slice(0, 120) })) + ) const life = await lifecycleDeps(env, deps) if (life) { await revokeGrantsForDeviceSession(life, deviceSessionId) diff --git a/cloud/apps/sandbox-control/src/read-snapshots.ts b/cloud/apps/sandbox-control/src/read-snapshots.ts index 19cf3bcaf43..c11b9959af9 100644 --- a/cloud/apps/sandbox-control/src/read-snapshots.ts +++ b/cloud/apps/sandbox-control/src/read-snapshots.ts @@ -4,9 +4,11 @@ // DELETE /v1/reader-keys/:id // GET /v1/team/workspaces/:id/read-snapshot?keyId=rk_… the body + only that key's wrapped key // At every drain the control plane asks the VM (image/vm/orca-sandbox-read-snapshot) to seal a -// compact snapshot to the reader keys allowed to open the workspace, and stores the ciphertext. It -// never holds a reader secret, so it can't read a snapshot. Access mirrors canOpen at read time, and -// pruning (removal, private, revoke) deletes wrapped keys at once, without the VM. +// compact snapshot to the reader keys allowed to open the workspace, and stores the ciphertext. +// D1, backups and logs hold only ciphertext and never a reader secret. Trust model: like W4 grants, +// the control plane at runtime chooses the recipient keys and drives the VM, so it is trusted not to +// add its own key (same as relaying grant keys). Access mirrors canOpen at read time, and pruning +// (removal, private, revoke) deletes wrapped keys at once, without the VM. import { z } from 'zod' import type { SandboxCaller } from './auth' import { ensureEntryPoints } from './golden-images' @@ -106,7 +108,8 @@ export async function registerReaderKey( account_id: caller.accountId, dev: caller.dev ? 1 : 0, public_key: body.publicKeyB64, - device_kind: body.deviceKind, + // A phone token is a phone, whatever it claims. + device_kind: caller.deviceSessionId ? 'mobile' : body.deviceKind, device_label: body.deviceLabel, device_session_id: caller.deviceSessionId ?? null, created_at: now, @@ -114,13 +117,17 @@ export async function registerReaderKey( revoked_at: null, revoked_by: null } - await db + const inserted = await db .prepare( `INSERT INTO reader_keys (id, user_id, account_id, dev, public_key, device_kind, device_label, device_session_id, created_at, last_seen_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING` ) .bind(row.id, row.user_id, row.account_id, row.dev, row.public_key, row.device_kind, row.device_label, row.device_session_id, now, now) .run() + if (inserted.meta.changes === 0) { + // A concurrent PUT of the same key won the race: answer with its row. + return registerReaderKey(db, caller, body, now) + } // Bounded per member: the least recently seen keys beyond the cap are retired. const { results: stale } = await db .prepare( @@ -191,18 +198,21 @@ export async function deleteReadSnapshot(db: D1Database, sandboxId: string): Pro } /** The live keys allowed to open this workspace right now (owner; every member when team-visible). */ -export async function readerKeysFor(db: D1Database, row: SandboxRow): Promise<{ id: string; public_key: string }[]> { +export async function readerKeysFor(db: D1Database, row: SandboxRow, now: number): Promise<{ id: string; public_key: string }[]> { if (row.archived_at !== null) { return [] } const team = row.visibility === 'team' const { results } = await db .prepare( - `SELECT id, public_key FROM reader_keys - WHERE account_id = ? AND revoked_at IS NULL ${team ? '' : 'AND user_id = ?'} - ORDER BY (user_id = ?) DESC, last_seen_at DESC LIMIT ?` + `SELECT k.id, k.public_key FROM reader_keys k + LEFT JOIN device_sessions d ON d.id = k.device_session_id + WHERE k.account_id = ? AND k.revoked_at IS NULL ${team ? '' : 'AND k.user_id = ?'} + -- A phone key counts only while its device session is live (not revoked, not expired). + AND (k.device_session_id IS NULL OR (d.revoked_at IS NULL AND d.expires_at > ?)) + ORDER BY (k.user_id = ?) DESC, k.last_seen_at DESC LIMIT ?` ) - .bind(...(team ? [row.account_id] : [row.account_id, row.user_id]), row.user_id, MAX_READ_RECIPIENTS) + .bind(...(team ? [row.account_id] : [row.account_id, row.user_id]), now, row.user_id, MAX_READ_RECIPIENTS) .all<{ id: string; public_key: string }>() return results } @@ -226,12 +236,13 @@ const VmOutputSchema = z .strict() ) .max(MAX_READ_RECIPIENTS), - stats: z.record(z.string(), z.number()).optional() + // Timing only: nothing about the plaintext's shape is logged here. + stats: z.object({ collectMs: z.number().int().min(0).max(600_000) }).strict().optional() }) .strict() type CaptureOutcome = - | { captured: true; snapshotId: string; recipients: number; bytes: number; stats?: Record } + | { captured: true; snapshotId: string; recipients: number; bytes: number; stats?: { collectMs: number } } | { captured: false; reason: string } export type CaptureResult = CaptureOutcome & { ms: number } @@ -250,7 +261,7 @@ export async function captureReadSnapshot(deps: LifecycleDeps, row: SandboxRow, if (!row.session_id) { return done({ captured: false, reason: 'no_session' }) } - const keys = await readerKeysFor(deps.db, row) + const keys = await readerKeysFor(deps.db, row, deps.now()) if (keys.length === 0) { return done({ captured: false, reason: 'no_reader_keys' }) } @@ -363,7 +374,8 @@ export async function getReadSnapshot(db: D1Database, caller: SandboxCaller, row .prepare('SELECT * FROM reader_keys WHERE id = ? AND account_id = ? AND user_id = ? AND revoked_at IS NULL') .bind(keyId, caller.accountId, caller.userId) .first() - if (!key) { + // A phone reads only with its own key (least privilege; desktop tokens have no device session). + if (!key || (caller.deviceSessionId && key.device_session_id !== caller.deviceSessionId)) { throw new ReadSnapshotRouteError('invalid_request', 400) } const snapshot = await db diff --git a/src/shared/cloud-workspaces/read-snapshot.ts b/src/shared/cloud-workspaces/read-snapshot.ts index 8473bea4f6a..a6f30df9cf6 100644 --- a/src/shared/cloud-workspaces/read-snapshot.ts +++ b/src/shared/cloud-workspaces/read-snapshot.ts @@ -153,8 +153,14 @@ export async function openReadSnapshot( throw new ReadSnapshotError('malformed') } const encoder = new TextEncoder() - const readerPublic = await primitives.x25519PublicKey(readerSecretKey) - const shared = await primitives.x25519(readerSecretKey, ephemeral) + let readerPublic: Uint8Array + let shared: Uint8Array + try { + readerPublic = await primitives.x25519PublicKey(readerSecretKey) + shared = await primitives.x25519(readerSecretKey, ephemeral) + } catch { + throw new ReadSnapshotError('decrypt_failed') + } // A low-order ephemeral key yields an all-zero secret anyone can compute. if (shared.every((byte) => byte === 0)) { throw new ReadSnapshotError('decrypt_failed') From 691e4282695d91b575ac79beb971f3d1298eb70c Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 00:27:19 -0800 Subject: [PATCH 04/46] fix(cloud): rollback pin, reader-key revoke on sign-out, no re-register on not_sealed_for_key; read view polish --- mobile/src/cloud/cloud-read-snapshot.test.ts | 42 +++++++++-- mobile/src/cloud/cloud-read-snapshot.ts | 33 +++++++-- .../cloud-read-snapshot-reader.test.ts | 70 ++++++++++++++++--- .../cloud-read-snapshot-reader.ts | 56 +++++++++++---- .../cloud-reader-key-store.test.ts | 42 ++++++++++- .../cloud-reader-key-store.ts | 47 +++++++++++++ .../cloud-workspaces-client.test.ts | 8 +++ .../cloud-workspaces-client.ts | 10 +++ .../cloud-workspaces-service.ts | 2 + src/main/ipc/cloud-workspaces.ts | 11 ++- .../orca-profiles/profile-cloud-service.ts | 10 ++- .../CloudReadSnapshotSheet.tsx | 10 ++- .../components/orca-cloud/CloudGitChanges.tsx | 5 +- .../CloudReadSnapshotView.fixture.tsx | 3 +- .../read-snapshot/CloudReadSnapshotView.tsx | 11 +++ .../src/i18n/en-runtime-required.json | 5 ++ src/renderer/src/i18n/locales/en.json | 7 +- .../cloud-workspaces/read-snapshot-state.ts | 5 ++ 18 files changed, 335 insertions(+), 42 deletions(-) diff --git a/mobile/src/cloud/cloud-read-snapshot.test.ts b/mobile/src/cloud/cloud-read-snapshot.test.ts index 9987029479c..042b2774182 100644 --- a/mobile/src/cloud/cloud-read-snapshot.test.ts +++ b/mobile/src/cloud/cloud-read-snapshot.test.ts @@ -33,7 +33,8 @@ import type { CloudControlPlane } from './cloud-control-plane-request' import { CLOUD_READER_KEY_REFRESH_MS, ensureCloudReaderKey, - readCloudWorkspaceSnapshot + readCloudWorkspaceSnapshot, + resetCloudReadSnapshotPins } from './cloud-read-snapshot' import { loadCloudReaderKey } from './cloud-reader-key' @@ -150,7 +151,10 @@ const registered = (id = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa') => ({ } }) -beforeEach(() => store.clear()) +beforeEach(() => { + store.clear() + resetCloudReadSnapshotPins() +}) describe('ensureCloudReaderKey', () => { it('registers once as a mobile key, then only again after 6 h or when forced', async () => { @@ -252,12 +256,42 @@ describe('readCloudWorkspaceSnapshot', () => { } ) - it('renews the key after not_sealed_for_key so the next sleep seals to it', async () => { + it('does not renew the key on not_sealed_for_key', async () => { const { plane, calls } = fakePlane((call) => call.method === 'PUT' ? registered() : { status: 404, body: { error: 'not_sealed_for_key' } } ) await readCloudWorkspaceSnapshot(plane, 'sbx_1') - await vi.waitFor(() => expect(calls.filter((c) => c.method === 'PUT')).toHaveLength(2)) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(calls.map((c) => c.method)).toEqual(['PUT', 'GET']) + }) + + it('refuses a snapshot older than one already shown for the workspace (rollback pin)', async () => { + const key = await loadCloudReaderKey('ds_1') + const keyId = 'rk_' + 'c'.repeat(24) + const seal = (snapshotId: string, capturedAt: number) => + sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId, + workspaceId: 'sbx_pin', + snapshotId, + payload: { ...PAYLOAD, workspaceId: 'sbx_pin', snapshotId, capturedAt } + }) + let next = seal('snap_new', 2_000) + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered(keyId) : { status: 200, body: { snapshot: next } } + ) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready') + next = seal('snap_old', 1_000) + expect(await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).toMatchObject({ + state: 'error', + error: { name: 'CloudReadSnapshotRollbackError', capturedAt: 1_000, newestShownAt: 2_000 } + }) + next = seal('snap_same', 2_000) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready') + next = seal('snap_newer', 3_000) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready') + next = seal('snap_same', 2_000) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('error') }) it('re-registers once on invalid_request and asks again', async () => { diff --git a/mobile/src/cloud/cloud-read-snapshot.ts b/mobile/src/cloud/cloud-read-snapshot.ts index e7c34490f4a..6f2adbe107e 100644 --- a/mobile/src/cloud/cloud-read-snapshot.ts +++ b/mobile/src/cloud/cloud-read-snapshot.ts @@ -105,6 +105,26 @@ async function fetchSealed( return reply.snapshot } +/** A snapshot older than one this phone already showed for the workspace: a rollback, refused. */ +export class CloudReadSnapshotRollbackError extends Error { + constructor( + readonly capturedAt: number, + readonly newestShownAt: number + ) { + super('read_snapshot_rollback') + this.name = 'CloudReadSnapshotRollbackError' + } +} + +// Per workspace, the newest capturedAt opened this app session. The control plane relays the +// ciphertext, so it could replay an older (validly sealed) snapshot; this pins it forward. +const newestShown = new Map() + +/** Test seam: forget the per-workspace rollback pins. */ +export function resetCloudReadSnapshotPins(): void { + newestShown.clear() +} + const NOT_FOUND_STATES = new Set(['no_snapshot', 'not_sealed_for_key', 'not_found']) type MissingState = 'no_snapshot' | 'not_sealed_for_key' | 'not_found' @@ -153,13 +173,18 @@ export async function readCloudWorkspaceSnapshot( reader.secretKey, CLOUD_SEALED_PRIMITIVES ) + const pinned = newestShown.get(sandboxId) + if (pinned !== undefined && snapshot.capturedAt < pinned) { + return { + state: 'error', + error: new CloudReadSnapshotRollbackError(snapshot.capturedAt, pinned) + } + } + newestShown.set(sandboxId, snapshot.capturedAt) return { state: 'ready', snapshot } } catch (error) { + // not_sealed_for_key only means the snapshot predates this key: nothing to renew here. const missing = missingState(error) - if (missing === 'not_sealed_for_key') { - // The key may have been revoked or pruned: renewing it now gets it into the next sleep. - void ensureCloudReaderKey(plane, { force: true, now }).catch(() => undefined) - } return missing ? { state: missing } : { state: 'error', error } } } diff --git a/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts b/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts index 3faa0fee11a..81745c5ec68 100644 --- a/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts +++ b/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts @@ -57,7 +57,8 @@ function setup(options: { identity?: string | null; keychain?: boolean } = {}) { load: () => options.keychain === false ? { ok: false, reason: 'keychain_unavailable', message: 'no keychain' } - : { ok: true, key } + : { ok: true, key }, + peek: () => (options.keychain === false ? null : key) } let now = 10_000 const ids = [KEY_A] @@ -68,10 +69,11 @@ function setup(options: { identity?: string | null; keychain?: boolean } = {}) { createdAt: 1, lastSeenAt: 1 })) + let capturedAt = payload.capturedAt const getReadSnapshot = vi.fn(async (_id: string, keyId: string): Promise => ({ kind: 'sealed', sealed: sealReadSnapshotForTest({ - payload, + payload: { ...payload, capturedAt }, workspaceId: SBX, snapshotId: 'snap_1', readerPublicKeyB64: key.publicKeyB64, @@ -79,8 +81,9 @@ function setup(options: { identity?: string | null; keychain?: boolean } = {}) { storedAt: 5 }) })) + const deleteReaderKey = vi.fn(async (_keyId: string, _timeoutMs?: number) => {}) const reader = createReadSnapshotReader({ - client: { registerReaderKey, getReadSnapshot }, + client: { registerReaderKey, getReadSnapshot, deleteReaderKey }, readerKey, deviceLabel: () => 'test-mac', now: () => now @@ -91,6 +94,10 @@ function setup(options: { identity?: string | null; keychain?: boolean } = {}) { ids, registerReaderKey, getReadSnapshot, + deleteReaderKey, + setCapturedAt: (at: number) => { + capturedAt = at + }, tick: (ms: number) => { now += ms }, @@ -158,22 +165,63 @@ describe('createReadSnapshotReader', () => { expect(t.registerReaderKey).toHaveBeenCalledTimes(1) }) - it('re-registers a remembered key the server dropped and retries with the new id', async () => { + it('never re-registers on not_sealed_for_key (the snapshot just predates the key)', async () => { const t = setup() await t.reader.register() t.ids[0] = KEY_B t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' }) - const result = await t.reader.read(SBX) - expect(result.state).toBe('ready') - expect(t.getReadSnapshot).toHaveBeenLastCalledWith(SBX, KEY_B) + expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' }) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + expect(t.getReadSnapshot).toHaveBeenCalledTimes(1) }) - it('keeps not_sealed_for_key when re-registering returns the same id', async () => { + it('re-registers at most once on invalid_request', async () => { const t = setup() await t.reader.register() - t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' }) - expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' }) - expect(t.getReadSnapshot).toHaveBeenCalledTimes(1) + t.getReadSnapshot + .mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request')) + .mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request')) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ code: 'invalid_request' }) + expect(t.registerReaderKey).toHaveBeenCalledTimes(2) + expect(t.getReadSnapshot).toHaveBeenCalledTimes(2) + }) + + it('refuses a snapshot older than one already shown (rollback pin), per workspace and account', async () => { + const t = setup() + t.setCapturedAt(2_000) + expect((await t.reader.read(SBX)).state).toBe('ready') + // The same snapshot again is fine; a newer one moves the pin. + expect((await t.reader.read(SBX)).state).toBe('ready') + t.setCapturedAt(3_000) + expect((await t.reader.read(SBX)).state).toBe('ready') + t.setCapturedAt(2_500) + expect(await t.reader.read(SBX)).toEqual({ state: 'stale' }) + // Another account on this computer has its own pin. + t.setIdentity('someone-else') + expect((await t.reader.read(SBX)).state).toBe('ready') + }) + + it('revokes the registered key server-side on sign-out', async () => { + const t = setup() + await t.reader.register() + await t.reader.revoke(1_000) + expect(t.deleteReaderKey).toHaveBeenCalledWith(KEY_A, 1_000) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + }) + + it('learns the key id before revoking when this run never registered', async () => { + const t = setup() + await t.reader.revoke(1_000) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + expect(t.deleteReaderKey).toHaveBeenCalledWith(KEY_A, 1_000) + }) + + it('revokes nothing without a key or when signed out', async () => { + await setup({ keychain: false }).reader.revoke(1_000) + const signedOut = setup({ identity: null }) + await signedOut.reader.revoke(1_000) + expect(signedOut.deleteReaderKey).not.toHaveBeenCalled() + expect(signedOut.registerReaderKey).not.toHaveBeenCalled() }) it('re-registers on invalid_request for a remembered key id', async () => { diff --git a/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts index dae0d872054..a89c3484261 100644 --- a/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts +++ b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts @@ -16,14 +16,16 @@ export type ReaderKeyAccess = { identity: () => string | null /** This profile's key (created on first use), or why there can be none. */ load: () => ReaderKeyLoad + /** The key only if one already exists (sign-out must not create one just to delete it). */ + peek?: () => CloudReaderKey | null } type Registration = { identity: string; publicKeyB64: string; keyId: string; at: number } -type Ready = { key: CloudReaderKey; keyId: string; fresh: boolean } +type Ready = { key: CloudReaderKey; keyId: string; fresh: boolean; identity: string } type Unavailable = { unavailable: Extract } export function createReadSnapshotReader(deps: { - client: Pick + client: Pick readerKey: ReaderKeyAccess deviceLabel?: () => string now?: () => number @@ -31,6 +33,9 @@ export function createReadSnapshotReader(deps: { const now = deps.now ?? Date.now let registration: Registration | null = null let inflight: { tag: string; promise: Promise } | null = null + // Highest payload capturedAt opened per (profile/user/account, workspace). Memory only: a + // restart forgets it, but within a run a replayed older snapshot is refused. + const newestShown = new Map() async function ensure(force = false): Promise { const identity = deps.readerKey.identity() @@ -50,7 +55,7 @@ export function createReadSnapshotReader(deps: { known.publicKeyB64 === key.publicKeyB64 && now() - known.at < READER_KEY_REFRESH_MS ) { - return { key, keyId: known.keyId, fresh: false } + return { key, keyId: known.keyId, fresh: false, identity } } // Concurrent reads (and the start-up registration) share one PUT per identity and key. const tag = `${identity}\0${key.publicKeyB64}` @@ -87,7 +92,7 @@ export function createReadSnapshotReader(deps: { }) } const done = await shared.promise - return { key, keyId: done.keyId, fresh: true } + return { key, keyId: done.keyId, fresh: true, identity } } async function fetchWith(sandboxId: string, ready: Ready) { @@ -117,6 +122,31 @@ export function createReadSnapshotReader(deps: { await ensure().catch(() => undefined) }, + /** + * Sign-out: revoke this device's key server-side so no later sleep seals to it. Learns the id + * (idempotent PUT) when this run never registered. Throws on failure; callers bound and ignore. + */ + async revoke(timeoutMs: number): Promise { + const identity = deps.readerKey.identity() + const key = deps.readerKey.peek?.() ?? null + if (!identity || !key) { + return + } + const known = registration + const keyId = + known && known.identity === identity && known.publicKeyB64 === key.publicKeyB64 + ? known.keyId + : ( + await deps.client.registerReaderKey({ + publicKeyB64: key.publicKeyB64, + deviceLabel: (deps.deviceLabel?.() ?? hostname()).slice(0, 80) || 'Desktop', + deviceKind: 'desktop' + }) + ).id + registration = null + await deps.client.deleteReaderKey(keyId, timeoutMs) + }, + async read(sandboxId: string): Promise { const first = await ensure() if ('unavailable' in first) { @@ -128,18 +158,11 @@ export function createReadSnapshotReader(deps: { } let ready = first const answer = await fetchWith(sandboxId, ready) - let fetched = 'ready' in answer ? answer.fetched : answer + const fetched = 'ready' in answer ? answer.fetched : answer if ('ready' in answer) { ready = answer.ready } - // The id we remembered may have been revoked server-side; re-registering hands out a new one. - if (fetched.kind === 'not_sealed_for_key' && !ready.fresh) { - const again = await ensure(true) - if (!('unavailable' in again) && again.keyId !== ready.keyId) { - ready = again - fetched = await deps.client.getReadSnapshot(sandboxId, again.keyId) - } - } + // not_sealed_for_key only means the snapshot predates this key: report it, never re-register. if (fetched.kind !== 'sealed') { return { state: fetched.kind } } @@ -150,6 +173,13 @@ export function createReadSnapshotReader(deps: { ready.key.secretKey, nodeSealedGrantPrimitives ) + // Rollback pin: never show a copy older than one already shown for this workspace here. + const pinKey = `${first.identity}\0${sandboxId}` + const pinned = newestShown.get(pinKey) + if (pinned !== undefined && snapshot.capturedAt < pinned) { + return { state: 'stale' } + } + newestShown.set(pinKey, snapshot.capturedAt) return { state: 'ready', snapshot, storedAt: fetched.sealed.storedAt } } catch (error) { if (error instanceof ReadSnapshotError) { diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.test.ts b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts index 6f2d41c7f9e..900b5f6d39b 100644 --- a/src/main/cloud-workspaces/cloud-reader-key-store.test.ts +++ b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts @@ -12,7 +12,12 @@ vi.mock('electron', () => ({ } })) -import { createCloudReaderKeyStore, type ReaderKeyCodec } from './cloud-reader-key-store' +import { + createCloudReaderKeyStore, + revokeCloudReaderKeyBestEffort, + setCloudReaderKeyRevoker, + type ReaderKeyCodec +} from './cloud-reader-key-store' import { nodeSealedGrantPrimitives } from './sealed-grant-node' import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant' @@ -99,3 +104,38 @@ describe('createCloudReaderKeyStore', () => { expect(first.ok && next.ok && next.key.publicKeyB64 !== first.key.publicKeyB64).toBe(true) }) }) + +describe('revokeCloudReaderKeyBestEffort', () => { + afterEach(() => setCloudReaderKeyRevoker(null)) + + it('runs the registered revoker with the timeout', async () => { + const revoke = vi.fn(async (_timeoutMs: number) => {}) + setCloudReaderKeyRevoker(revoke) + await revokeCloudReaderKeyBestEffort(500) + expect(revoke).toHaveBeenCalledWith(500) + }) + + it('never blocks sign-out: a hung or failing revoke resolves within the timeout', async () => { + setCloudReaderKeyRevoker(() => new Promise(() => {})) + const started = Date.now() + await revokeCloudReaderKeyBestEffort(30) + expect(Date.now() - started).toBeLessThan(1_000) + setCloudReaderKeyRevoker(async () => { + throw new Error('offline') + }) + await expect(revokeCloudReaderKeyBestEffort(30)).resolves.toBeUndefined() + setCloudReaderKeyRevoker(null) + await expect(revokeCloudReaderKeyBestEffort(30)).resolves.toBeUndefined() + }) +}) + +describe('peek', () => { + it('returns the existing key and never creates one', () => { + const store = storeWith() + expect(store.peek('p1')).toBeNull() + expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) + const loaded = store.load('p1') + const fresh = storeWith().peek('p1') + expect(loaded.ok && fresh?.publicKeyB64 === loaded.key.publicKeyB64).toBe(true) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.ts b/src/main/cloud-workspaces/cloud-reader-key-store.ts index 72b1672ae1a..31752b9fcc9 100644 --- a/src/main/cloud-workspaces/cloud-reader-key-store.ts +++ b/src/main/cloud-workspaces/cloud-reader-key-store.ts @@ -90,6 +90,20 @@ export function createCloudReaderKeyStore(deps: { } return { + /** The profile's existing key, if any; never creates one. */ + peek(profileId: string): CloudReaderKey | null { + const codec = deps.codec() + const path = deps.pathFor(profileId) + const cached = cache.get(path) + if (cached || !codec || !existsSync(path)) { + return cached ?? null + } + const existing = decode(path, codec) + if (existing) { + cache.set(path, existing) + } + return existing + }, /** The profile's key, created on first use. A key the keychain can no longer open is replaced. */ load(profileId: string): ReaderKeyLoad { const codec = deps.codec() @@ -156,6 +170,39 @@ export function getCloudReaderKeyStore(userDataPath: string): CloudReaderKeyStor return defaultStore.store } +// Sign-out revokes the key server-side through the cloud workspaces service (it owns the client +// and the registration id). A seam so profile code never loads that service. +let revoker: ((timeoutMs: number) => Promise) | null = null + +export function setCloudReaderKeyRevoker(next: typeof revoker): void { + revoker = next +} + +export const READER_KEY_REVOKE_TIMEOUT_MS = 2_500 + +/** Best effort and bounded: resolves within `timeoutMs` whatever the network does. */ +export async function revokeCloudReaderKeyBestEffort( + timeoutMs = READER_KEY_REVOKE_TIMEOUT_MS +): Promise { + const run = revoker + if (!run) { + return + } + let timer: ReturnType | undefined + try { + await Promise.race([ + Promise.resolve() + .then(() => run(timeoutMs)) + .catch(() => undefined), + new Promise((resolve) => { + timer = setTimeout(resolve, timeoutMs) + }) + ]) + } finally { + clearTimeout(timer) + } +} + /** Sign-out / profile reset hook: drop the profile's reader key (memory and disk). */ export function clearCloudReaderKey(profileId: string, userDataPath: string): void { try { diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts index d1c9b8c5645..62e427723fd 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts @@ -54,6 +54,14 @@ describe('cloud workspaces client: read snapshots', () => { }) }) + it('DELETEs a reader key by id', async () => { + const { client, fetch } = clientAnswering(200, { ok: true }) + await client.deleteReaderKey(KEY, 2_000) + const [url, init] = fetch.mock.calls[0]! + expect(String(url)).toBe(`https://cp.example.test/v1/reader-keys/${KEY}`) + expect(init?.method).toBe('DELETE') + }) + it('GETs the sealed snapshot for this key', async () => { const { client, fetch } = clientAnswering(200, { snapshot: sealed }) expect(await client.getReadSnapshot(SBX, KEY)).toEqual({ kind: 'sealed', sealed }) diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.ts b/src/main/cloud-workspaces/cloud-workspaces-client.ts index 5d536db6f7a..94f16ecfdd1 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.ts @@ -198,6 +198,16 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption }) { return (await call('PUT', '/v1/reader-keys', CloudReaderKeyResponseSchema, body)).readerKey }, + /** Server-side revoke: wrapped keys for it are pruned and it is never resurrected. */ + async deleteReaderKey(keyId: string, timeoutMs = CONTROL_TIMEOUT_MS): Promise { + await call( + 'DELETE', + `/v1/reader-keys/${encodeURIComponent(keyId)}`, + NoteSentSchema.passthrough(), + undefined, + timeoutMs + ) + }, async getReadSnapshot(id: string, keyId: string): Promise { try { const { snapshot } = await call( diff --git a/src/main/cloud-workspaces/cloud-workspaces-service.ts b/src/main/cloud-workspaces/cloud-workspaces-service.ts index 495fec84340..564fed8a6a4 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-service.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-service.ts @@ -141,6 +141,8 @@ export function createCloudWorkspacesService(deps: { void reader?.register() return workspaces }), + /** Sign-out: revoke this device's reader key server-side (callers bound the wait). */ + revokeReaderKey: (timeoutMs: number) => reader?.revoke(timeoutMs) ?? Promise.resolve(), /** A sleeping workspace's sealed snapshot, opened on this device; never wakes it. */ readSnapshot: (id: string) => wrap(async () => { diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index 9a9c44831b1..67fc4eb7201 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -11,7 +11,10 @@ import { createCloudWorkspacesService, type CloudWorkspacesService } from '../cloud-workspaces/cloud-workspaces-service' -import { getCloudReaderKeyStore } from '../cloud-workspaces/cloud-reader-key-store' +import { + getCloudReaderKeyStore, + setCloudReaderKeyRevoker +} from '../cloud-workspaces/cloud-reader-key-store' import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' @@ -67,6 +70,8 @@ function getService(): Promise { clientId: await clientIdFor(userDataPath), readerKey: profileReaderKey(userDataPath) }) + const started = service + setCloudReaderKeyRevoker((timeoutMs) => started.revokeReaderKey(timeoutMs)) return service })() servicePromise = starting @@ -90,7 +95,9 @@ function profileReaderKey(userDataPath: string): ReaderKeyAccess { : null }, load: () => - getCloudReaderKeyStore(userDataPath).load(ensureActiveOrcaProfile(userDataPath).profile.id) + getCloudReaderKeyStore(userDataPath).load(ensureActiveOrcaProfile(userDataPath).profile.id), + peek: () => + getCloudReaderKeyStore(userDataPath).peek(ensureActiveOrcaProfile(userDataPath).profile.id) } } diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index f39e47f7337..ae38131cbd2 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -1,5 +1,8 @@ import { resetCloudOfflineData } from '../hosted-sandbox/cloud-offline-reset' -import { clearCloudReaderKey } from '../cloud-workspaces/cloud-reader-key-store' +import { + clearCloudReaderKey, + revokeCloudReaderKeyBestEffort +} from '../cloud-workspaces/cloud-reader-key-store' import type { ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileArgs, @@ -158,6 +161,11 @@ export async function signOutCurrentOrcaProfile( const active = ensureActiveOrcaProfile(userDataPath) const configState = getOrcaCloudAuthConfig() const session = readCloudSession(active.profile.id, userDataPath) + if (session.status === 'found') { + // While the session still mints tokens: revoke this device's reader key server-side so no + // later sleep seals to it. Bounded (a couple of seconds) and never fails the sign-out. + await revokeCloudReaderKeyBestEffort() + } // Fence before network I/O so in-flight refreshes cannot save after sign-out. invalidateCloudSessionChanges(active.profile.id, userDataPath) if (!isOrcaCloudDevAuthEnabled() && configState.configured && session.status === 'found') { diff --git a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx index 688f0153c35..256547de80f 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx @@ -1,7 +1,7 @@ // The team list's read-only view of an Asleep workspace: what it looked like when it went to // sleep, read from the copy it sealed to this computer's key. Opening it never wakes the sandbox; // "Wake to continue" runs the normal open flow. -import React, { useEffect, useState } from 'react' +import React, { useEffect, useRef, useState } from 'react' import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' @@ -23,6 +23,7 @@ export function CloudReadSnapshotSheet({ }): React.JSX.Element { const { state, retry, retrying } = useCloudReadSnapshot(workspace?.id ?? null) const [now, setNow] = useState(() => Date.now()) + const headingRef = useRef(null) useEffect(() => { if (!workspace) { return @@ -36,6 +37,12 @@ export function CloudReadSnapshotSheet({ { + event.preventDefault() + headingRef.current?.focus() + }} > {/* The view's own heading is the visible title; Radix needs one for the dialog name. */} {title} @@ -49,6 +56,7 @@ export function CloudReadSnapshotSheet({ onWake={() => onWake(workspace)} onRetry={retry} retrying={retrying} + headingRef={headingRef} /> ) : null} diff --git a/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx b/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx index 0bb70063c05..97e833dbcd2 100644 --- a/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx +++ b/src/renderer/src/components/orca-cloud/CloudGitChanges.tsx @@ -102,7 +102,10 @@ export function CloudGitChanges({ ) : null} {stat ? ( - {t('orcaCloudWorkspace.archived.files', '{{count}} files', { count: stat.files })}{' '} + {t('orcaCloudWorkspace.archived.files', '{{count}} files', { + count: stat.files, + defaultValue_one: '{{count}} file' + })}{' '} +{stat.insertions}{' '} −{stat.deletions} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx index c4070685ea2..ac873986b88 100644 --- a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx @@ -169,8 +169,7 @@ export const keychainUnavailable = defineFixture({ export const error = defineFixture({ width: WIDTH, - render: () => - view({ kind: 'error', message: "Couldn't reach Orca Cloud. Your files are safe. Try again." }) + render: () => view({ kind: 'error', message: "Couldn't reach Orca Cloud. Your files are safe." }) }) export const waking = defineFixture({ diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx index f1b3447ff65..412809cfec4 100644 --- a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx @@ -17,6 +17,8 @@ export type CloudReadViewState = | { kind: 'no_snapshot' } | { kind: 'not_sealed_for_key' } | { kind: 'not_found' } + /** Older than a copy already shown here (a rollback); refused. */ + | { kind: 'stale' } /** This computer cannot hold a reader key (no OS keychain). */ | { kind: 'unavailable'; message: string } | { kind: 'error'; message: string } @@ -169,6 +171,15 @@ export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React. )} /> ) : null} + {state.kind === 'stale' ? ( + + ) : null} {state.kind === 'not_found' ? ( Date: Tue, 10 Nov 2026 00:42:30 -0800 Subject: [PATCH 05/46] fix(cloud): W10 review of the read view: waking state, Wake to continue everywhere, plainer copy, agent display names --- mobile/src/cloud/CloudReadSnapshotSection.tsx | 29 +++++- .../src/cloud/CloudReadSnapshotSessions.tsx | 6 +- mobile/src/cloud/CloudWorkspaceScreen.tsx | 41 +++++++-- .../src/cloud/cloud-read-snapshot-styles.ts | 10 ++ mobile/src/i18n/locales/en.json | 1 + .../CloudReadSnapshotSheet.tsx | 11 ++- .../cloud-workspaces/CloudWorkspacesHome.tsx | 65 +++++++++---- .../offline/CloudWorkspaceOfflineView.tsx | 2 +- .../read-snapshot/CloudReadSessions.tsx | 11 ++- .../CloudReadSnapshotView.fixture.tsx | 42 ++++++++- .../read-snapshot/CloudReadSnapshotView.tsx | 91 ++++++++++++++++--- src/renderer/src/i18n/locales/en.json | 8 +- 12 files changed, 251 insertions(+), 66 deletions(-) diff --git a/mobile/src/cloud/CloudReadSnapshotSection.tsx b/mobile/src/cloud/CloudReadSnapshotSection.tsx index 9f8ec991ad4..a3dac41565c 100644 --- a/mobile/src/cloud/CloudReadSnapshotSection.tsx +++ b/mobile/src/cloud/CloudReadSnapshotSection.tsx @@ -14,9 +14,11 @@ import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { formatTimeAgo } from '../worktree/agent-row-display' import { CloudErrorBanner } from './CloudErrorBanner' +import { CloudStatusDot } from './CloudStatusDot' import { CloudReadSnapshotSessions } from './CloudReadSnapshotSessions' -import type { CloudReadSnapshotResult } from './cloud-read-snapshot' +import { CloudReadSnapshotRollbackError, type CloudReadSnapshotResult } from './cloud-read-snapshot' import { readSnapshotStyles as styles } from './cloud-read-snapshot-styles' +import { cloudStatusLabel } from './cloud-workspace-display' import { cloudWorkspaceScreenStyles as screen } from './cloud-workspace-screen-styles' const GIT_PATHS_SHOWN = 5 @@ -48,6 +50,8 @@ export function CloudReadSnapshotSection(props: { /** When the result was fetched: the clock "As of" counts from (no impure clock read in render). */ fetchedAt: number loading: boolean + /** Wake was tapped: the header says Waking (the copy stays readable until it is open). */ + waking: boolean onRetry: () => void }) { useMobileColorScheme() @@ -59,9 +63,17 @@ export function CloudReadSnapshotSection(props: { } return ( - - {t('cloud.snapshot.heading', 'Latest from this workspace')} - + + + {t('cloud.snapshot.heading', 'Latest from this workspace')} + + + + + {cloudStatusLabel(props.waking ? 'waking' : 'sleeping', t)} + + + {props.loading || !result ? ( ) : result.state === 'ready' ? ( @@ -80,6 +92,15 @@ export function CloudReadSnapshotSection(props: { 'This device was added after the workspace went to sleep. Wake it once to read it here.' )} /> + ) : result.state === 'error' && result.error instanceof CloudReadSnapshotRollbackError ? ( + // Trying again cannot help: the newer copy only comes back from the workspace itself. + ) : ( ([]) + // The run as it was when wake was tapped: until the run moves on (start() first reads the + // keychain), the button already reads Waking rather than keeping "Wake to continue". + const [wakeTappedAt, setWakeTappedAt] = useState(null) + const wakePending = wakeTappedAt !== null && wakeTappedAt === run const [busyAction, setBusyAction] = useState<'sleep' | 'archive' | null>(null) useEffect(() => { @@ -188,8 +192,17 @@ export function CloudWorkspaceScreen({ workspace.status === 'creating' || workspace.status === 'stopping' || workspace.status === 'archived' - const primaryLabel = - run.kind === 'launched' + const waking = + wakePending || + run.kind === 'attaching' || + run.kind === 'delivering' || + workspace.status === 'waking' + // Asleep, or waking from it: the read-only copy stays readable (header says Waking) until it opens. + const showSnapshot = asleep || (waking && !awake && snapshot.data !== undefined) + const busy = active || wakePending + const primaryLabel = wakePending + ? phaseLabel('waking', t) + : run.kind === 'launched' ? t('cloud.action.openSession', 'Open session') : run.kind === 'attaching' ? phaseLabel(run.phase, t) @@ -204,7 +217,7 @@ export function CloudWorkspaceScreen({ : asleep ? t('cloud.action.wakeToContinue', 'Wake to continue') : t('cloud.action.wakeOpen', 'Wake and open workspace') - const primaryDisabled = active || unavailable + const primaryDisabled = busy || unavailable return ( @@ -240,8 +253,9 @@ export function CloudWorkspaceScreen({ onRetry={run.retry ? () => void start(run.retry ?? 'open') : null} /> ) : null} - {asleep ? ( + {showSnapshot ? ( (run.kind === 'launched' ? openSession('chat') : void start('open'))} + onPress={() => { + if (run.kind === 'launched') { + openSession('chat') + return + } + setWakeTappedAt(run) + void start('open').finally(() => setWakeTappedAt(null)) + }} style={({ pressed }) => [ styles.primary, - primaryDisabled && !active && styles.primaryDisabled, + primaryDisabled && !busy && styles.primaryDisabled, pressed && styles.pressed ]} > - {active ? : null} + {busy ? : null} {primaryLabel} diff --git a/mobile/src/cloud/cloud-read-snapshot-styles.ts b/mobile/src/cloud/cloud-read-snapshot-styles.ts index 3eb5e7c3505..922b3cdfb2e 100644 --- a/mobile/src/cloud/cloud-read-snapshot-styles.ts +++ b/mobile/src/cloud/cloud-read-snapshot-styles.ts @@ -4,6 +4,16 @@ import { themedStyleSheet } from '../theme/themed-styles' // The asleep workspace's read-only "Latest from this workspace" area; scheme-aware like every cloud card. export const readSnapshotStyles = themedStyleSheet(() => ({ + headingRow: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm }, + headingText: { flex: 1 }, + headingState: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + marginBottom: spacing.sm, + paddingHorizontal: spacing.xs + }, + headingStateText: { fontSize: 13, color: colors.textSecondary }, asOf: { fontSize: 13, lineHeight: 18, diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 44124429e9a..328655e2306 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -5166,6 +5166,7 @@ "empty": "Nothing saved yet. Orca saves a read-only copy each time this workspace goes to sleep.", "notSealedForKey": "This device was added after the workspace went to sleep. Wake it once to read it here.", "error": "Couldn’t load the latest from this workspace. Your files are safe.", + "rollback": "Orca Cloud sent an older copy than the one you last saw, so it isn’t shown. Wake the workspace to see it as it is now.", "asOf": "As of {{ago}} ago", "asOfJustNow": "As of just now", "asOfExact": "As of {{time}}", diff --git a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx index 256547de80f..c848cd3feed 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx @@ -5,19 +5,22 @@ import React, { useEffect, useRef, useState } from 'react' import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' -import { CloudReadSnapshotView } from '../orca-cloud/read-snapshot/CloudReadSnapshotView' +import { + CloudReadSnapshotView, + type CloudReadWake +} from '../orca-cloud/read-snapshot/CloudReadSnapshotView' import { cloudWorkspaceTitle } from './open-cloud-workspace' import { useCloudReadSnapshot } from './use-cloud-read-snapshot' export function CloudReadSnapshotSheet({ workspace, - waking, + wake, onWake, onClose }: { /** Null keeps the sheet closed. */ workspace: CloudWorkspace | null - waking: boolean + wake: CloudReadWake | null onWake: (w: CloudWorkspace) => void onClose: () => void }): React.JSX.Element { @@ -52,7 +55,7 @@ export function CloudReadSnapshotSheet({ title={title} state={state} now={now} - waking={waking} + wake={wake} onWake={() => onWake(workspace)} onRetry={retry} retrying={retrying} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index 49ff2e5a1da..8e6cf1c7a96 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -1,6 +1,6 @@ // Home: the org's cloud workspaces (registry on the control plane), filterable by who owns them, // which repo they are in, Mine/Team and archived, grouped by section, with live presence and cost. -import React, { useCallback, useEffect, useMemo, useState } from 'react' +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' @@ -18,6 +18,7 @@ import { ANY, CloudWorkspacesToolbar, type CloudWorkspacesFilters } from './Clou import { EmptyState, ErrorState, NewSectionDialog, SkeletonRows } from './CloudWorkspacesStates' import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog' import { CloudReadSnapshotSheet } from './CloudReadSnapshotSheet' +import type { CloudReadWake } from '../orca-cloud/read-snapshot/CloudReadSnapshotView' import { formatUsdMicros, type MemberDirectory } from './cloud-workspace-format' import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender' import { describeError } from './cloud-workspace-errors' @@ -87,7 +88,21 @@ export function CloudWorkspacesHome({ const [sectionFor, setSectionFor] = useState(null) const [confirm, setConfirm] = useState(null) // The Asleep workspace whose read-only copy is open (never wakes it). - const [readingId, setReadingId] = useState(null) + const [readingId, setReadingIdState] = useState(null) + // A wake started from the read panel: shown there (elapsed, slow, failed) until it opens. + const [readWake, setReadWake] = useState(null) + const readingRef = useRef(null) + const setReadingId = useCallback( + (next: string | null | ((id: string | null) => string | null)) => { + const value = typeof next === 'function' ? next(readingRef.current) : next + if (value !== readingRef.current) { + setReadWake(null) + } + readingRef.current = value + setReadingIdState(value) + }, + [] + ) const signIn = useAppStore((s) => s.connectCurrentOrcaProfile) const scope = orgId ? filters.scope : 'mine' const { state, stale, reading, refresh, replace } = useCloudWorkspaces( @@ -168,23 +183,35 @@ export function CloudWorkspacesHome({ const totalCost = visible.reduce((sum, w) => sum + w.cost.totalUsdMicros, 0) /** Opens the workspace, then (going to a teammate's chat) the chat they have in front. */ - const open = useCallback(async (w: CloudWorkspace, chatId?: string | null) => { - setOpening(w.id) - try { - const outcome = await openCloudWorkspace(w) - if (!outcome.ok) { - toast.error(outcome.message) - return + const open = useCallback( + async (w: CloudWorkspace, chatId?: string | null) => { + setOpening(w.id) + const fromPanel = readingRef.current === w.id + if (fromPanel) { + setReadWake({ phase: 'waking', startedAt: Date.now() }) } - // Woken from its read-only copy: the live workspace replaces it. - setReadingId((current) => (current === w.id ? null : current)) - if (chatId) { - await focusCloudChat(outcome.worktreeId, chatId) + try { + const outcome = await openCloudWorkspace(w) + if (!outcome.ok) { + if (fromPanel && readingRef.current === w.id) { + // The panel shows the failure in place (with the reason) instead of a toast. + setReadWake({ phase: 'failed', message: outcome.message }) + } else { + toast.error(outcome.message) + } + return + } + // Woken from its read-only copy: the live workspace replaces it. + setReadingId((current) => (current === w.id ? null : current)) + if (chatId) { + await focusCloudChat(outcome.worktreeId, chatId) + } + } finally { + setOpening((current) => (current === w.id ? null : current)) } - } finally { - setOpening((current) => (current === w.id ? null : current)) - } - }, []) + }, + [setReadingId] + ) const patch = useCallback( async (w: CloudWorkspace, change: CloudWorkspacePatch, confirmed = false) => { @@ -248,7 +275,7 @@ export function CloudWorkspacesHome({ goToChat: (w: CloudWorkspace, member: CloudWorkspacePresence) => void open(w, member.chatId), patch: (w: CloudWorkspace, change: CloudWorkspacePatch) => void patch(w, change) }), - [open, patch] + [open, patch, setReadingId] ) // Nothing (not even a skeleton) until we know this build has a control plane and you are in. @@ -368,7 +395,7 @@ export function CloudWorkspacesHome({ w.id === readingId) ?? null) : null} - waking={opening !== null && opening === readingId} + wake={readWake} onWake={(w) => void open(w)} onClose={() => setReadingId(null)} /> diff --git a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx index 989bd4b54f7..a8ae22c9f7e 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx @@ -73,7 +73,7 @@ export function CloudWorkspaceOfflineView(props: CloudOfflineViewProps): React.J action={ } /> diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx index 6d2f2e6bc9b..5fef577f32c 100644 --- a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx @@ -7,8 +7,15 @@ import type { ReadSnapshotAgentStatus, ReadSnapshotSession } from '../../../../../shared/cloud-workspaces/read-snapshot' +import { getAgentLabel } from '@/lib/agent-catalog/agent-catalog' +import type { TerminalAgent } from '../../../../../shared/agent-status/identity/terminal-agent' import { agentStatusLabel } from './cloud-read-snapshot-format' +/** The app's agent names ("Claude", "Codex"); an id it does not know is shown as sent. */ +function agentDisplayName(agent: string): string { + return getAgentLabel(agent as TerminalAgent) +} + /** Messages shown before "Show more": enough to see where the agent left off. */ const COLLAPSED_MESSAGES = 2 @@ -38,9 +45,7 @@ function SessionCard({ session }: { session: ReadSnapshotSession }): React.JSX.E {title} {session.agent ? ( - - {session.agent} - + {agentDisplayName(session.agent)} ) : null} {agentStatusLabel(session.status, session.turnOutcome, t)} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx index ac873986b88..58f6305db38 100644 --- a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx @@ -1,6 +1,10 @@ import { defineFixture } from '../../../component-fixtures/component-fixture' import type { ReadSnapshot } from '../../../../../shared/cloud-workspaces/read-snapshot' -import { CloudReadSnapshotView, type CloudReadViewState } from './CloudReadSnapshotView' +import { + CloudReadSnapshotView, + type CloudReadViewState, + type CloudReadWake +} from './CloudReadSnapshotView' const NOW = 1_794_230_000_000 const MIN = 60_000 @@ -111,7 +115,10 @@ const snapshot: ReadSnapshot = { const noop = (): void => {} -function view(state: CloudReadViewState, extra: { waking?: boolean; retrying?: boolean } = {}) { +function view( + state: CloudReadViewState, + extra: { wake?: CloudReadWake; retrying?: boolean; linux?: boolean } = {} +) { return (
    ) @@ -172,7 +180,31 @@ export const error = defineFixture({ render: () => view({ kind: 'error', message: "Couldn't reach Orca Cloud. Your files are safe." }) }) -export const waking = defineFixture({ +/** Keychain missing on Linux: also names the keyring to set up. */ +export const keychainUnavailableLinux = defineFixture({ width: WIDTH, - render: () => view({ kind: 'ready', snapshot }, { waking: true }) + render: () => view({ kind: 'unavailable', message: 'no keychain' }, { linux: true }) }) + +/** "Wake to continue" pressed 3 s ago: Waking dot, elapsed time on the busy button. */ +export const waking3s = defineFixture({ + width: WIDTH, + render: () => + view({ kind: 'ready', snapshot }, { wake: { phase: 'waking', startedAt: Date.now() - 3_000 } }) +}) + +/** Past 10 s: the "Taking longer than usual" line under the header. */ +export const waking12s = defineFixture({ + width: WIDTH, + render: () => + view({ kind: 'ready', snapshot }, { wake: { phase: 'waking', startedAt: Date.now() - 12_000 } }) +}) + +/** The wake failed: shared "Couldn't wake" copy with Try again; the copy stays readable. */ +export const wakeFailed = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'ready', snapshot }, { wake: { phase: 'failed' } }) +}) + +/** A rollback was refused. */ +export const stale = defineFixture({ width: WIDTH, render: () => view({ kind: 'stale' }) }) diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx index 412809cfec4..383889f20a0 100644 --- a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx @@ -3,7 +3,11 @@ import { Loader2, Moon, Play } from 'lucide-react' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' +import { formatElapsedTime } from '@/components/worktree-creation/worktree-creation-clock' +import { useNow } from '@/hooks/use-now' import { useTranslate } from '@/i18n/use-translate' +import { isLinuxUserAgent } from '@/lib/user-agent-platform' +import { WAKE_SLOW_S } from '../CloudWakingOverlay' import type { ReadSnapshot } from '../../../../../shared/cloud-workspaces/read-snapshot' import { CloudGitChanges } from '../CloudGitChanges' import { CloudWorkspaceHeader } from '../CloudWorkspaceHeader' @@ -27,14 +31,22 @@ export type CloudReadSnapshotViewProps = { title: string state: CloudReadViewState now: number - /** Wakes, then the normal open. */ + /** Wakes, then the normal open (and the live workspace replaces this view). */ onWake: () => void - waking: boolean + /** A wake started here: in flight since `startedAt`, or failed. */ + wake?: CloudReadWake | null onRetry: () => void retrying: boolean headingRef?: React.Ref + /** Linux names the keyring to set up; defaults to this renderer's platform. */ + linux?: boolean } +export type CloudReadWake = + | { phase: 'waking'; startedAt: number } + /** `message`: why, when the open flow said (e.g. the team's running limit). */ + | { phase: 'failed'; message?: string } + function LoadingBody(): React.JSX.Element { const t = useTranslate() return ( @@ -115,6 +127,15 @@ export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React. const t = useTranslate() const { state, now } = props const asOf = state.kind === 'ready' ? asOfParts(state.snapshot.capturedAt, now) : null + const waking = props.wake?.phase === 'waking' ? props.wake : null + const failed = props.wake?.phase === 'failed' ? props.wake : null + const clock = useNow(1_000, waking !== null) + const elapsedMs = waking ? Math.max(0, clock - waking.startedAt) : 0 + const slow = waking !== null && elapsedMs >= WAKE_SLOW_S * 1_000 + const lifecycle = waking + ? t('orcaCloudWorkspace.state.waking', 'Waking') + : t('components.orcaCloud.read.asleep', 'Asleep') + const linux = props.linux ?? isLinuxUserAgent() return (
    - {props.waking ? : } - {t('components.orcaCloud.read.wakeToContinue', 'Wake to continue')} + {waking ? : } + {waking ? ( + + {t('components.orcaCloud.read.wakingElapsed', 'Waking… {{elapsed}}', { + elapsed: formatElapsedTime(elapsedMs) + })} + + ) : ( + t('components.orcaCloud.read.wakeToContinue', 'Wake to continue') + )} } /> + {/* Announced once when the wake crosses the slow mark (the text changes only then). */} +

    + {slow + ? t( + 'orcaCloudWorkspace.overlay.slow', + 'Taking longer than usual. Your files and chats are safe.' + ) + : ''} +

    + {failed ? ( + + {t('orcaCloudWorkspace.overlay.failedDetail', 'Your files and chats are saved.')} + {failed.message ? {failed.message} : null} + + } + retryLabel={t('orcaCloudWorkspace.overlay.tryAgain', 'Try again')} + onRetry={props.onWake} + /> + ) : null} {state.kind === 'loading' ? : null} {state.kind === 'ready' ? : null} {state.kind === 'no_snapshot' ? ( @@ -175,8 +230,8 @@ export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React. ) : null} @@ -193,9 +248,17 @@ export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React. ) : null} {state.kind === 'error' ? ( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b860af188f7..2c900a7e841 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23142,7 +23142,6 @@ "composerLabel": "Message to queue", "sendAndWake": "Send and wake", "region": "Asleep workspace (read-only)", - "wake": "Wake", "emptyBody": "Orca keeps a copy of chats, terminals and changes once you have used this workspace while it was awake.", "tabChat": "Chat", "tabTerminals": "Terminals", @@ -23174,7 +23173,6 @@ "asleep": "Asleep", "empty": "Nothing saved yet. Orca saves a read-only copy each time this workspace goes to sleep.", "notSealedForKey": "This device was added after the workspace went to sleep. Wake it once to read it here.", - "unavailable": "Reading a sleeping workspace needs the OS keychain on this computer.", "tryAgain": "Try again", "checksPassed": "Checks passed", "checksFailed": "Checks failed", @@ -23189,7 +23187,11 @@ "prDraft": "Draft", "prMerged": "Merged", "prClosed": "Closed", - "stale": "Orca Cloud returned an older copy than the one already shown here, so it is hidden. Wake the workspace to see it as it is now." + "stateAsOf": "{{state}} · As of {{when}}", + "wakingElapsed": "Waking… {{elapsed}}", + "staleCopy": "Orca Cloud sent an older copy than the one you last saw, so it isn’t shown. Wake the workspace to see it as it is now.", + "keychainUnavailable": "Orca can’t open the saved copy because this computer’s keychain isn’t available. Wake the workspace to see it.", + "keychainLinux": "Or set up a keyring (like GNOME Keyring) and reopen Orca." } }, "runtimeDownload": { From 0559156ce2a8dd6bff591858f4e62fe98f68e61e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 00:49:53 -0800 Subject: [PATCH 06/46] chore(cloud): read snapshot lint/quality gates (no casts, async key store, split parser, l10n) --- mobile/src/cloud/cloud-read-snapshot.test.ts | 24 +-- mobile/src/cloud/cloud-read-snapshot.ts | 10 +- mobile/src/cloud/cloud-reader-key.test.ts | 8 +- mobile/src/i18n/en-runtime-required.json | 10 + .../cloud-read-snapshot-reader.test.ts | 4 +- .../cloud-read-snapshot-reader.ts | 8 +- .../cloud-reader-key-store.test.ts | 78 +++++--- .../cloud-reader-key-store.ts | 107 ++++++----- .../cloud-workspaces-client.test.ts | 7 +- .../cloud-workspaces/sealed-grant-node.ts | 7 +- .../cloud-offline-cloud-read.test.ts | 11 +- .../orca-profiles/profile-cloud-service.ts | 2 +- .../CloudReadSnapshotSheet.tsx | 5 +- .../use-cloud-read-snapshot.ts | 5 +- .../read-snapshot/CloudReadSessions.tsx | 5 +- .../cloud-workspaces/read-snapshot-parse.ts | 172 +++++++++++++++++ src/shared/cloud-workspaces/read-snapshot.ts | 177 ++---------------- 17 files changed, 368 insertions(+), 272 deletions(-) create mode 100644 src/shared/cloud-workspaces/read-snapshot-parse.ts diff --git a/mobile/src/cloud/cloud-read-snapshot.test.ts b/mobile/src/cloud/cloud-read-snapshot.test.ts index 042b2774182..473775cc9f6 100644 --- a/mobile/src/cloud/cloud-read-snapshot.test.ts +++ b/mobile/src/cloud/cloud-read-snapshot.test.ts @@ -127,19 +127,20 @@ function fakePlane(handle: (call: Call) => { status: number; body: unknown }): { calls: Call[] } { const calls: Call[] = [] + const fakeFetch: typeof fetch = async (input, init) => { + const call = { + method: init?.method ?? 'GET', + url: String(input), + body: init?.body ? JSON.parse(String(init.body)) : undefined + } + calls.push(call) + const reply = handle(call) + return new Response(JSON.stringify(reply.body), { status: reply.status }) + } const plane: CloudControlPlane = { baseUrl: 'https://cloud.test', token: () => 'tok', - fetch: (async (url: string, init: RequestInit) => { - const call = { - method: init.method ?? 'GET', - url, - body: init.body ? JSON.parse(String(init.body)) : undefined - } - calls.push(call) - const reply = handle(call) - return new Response(JSON.stringify(reply.body), { status: reply.status }) - }) as typeof fetch + fetch: fakeFetch } return { plane, calls } } @@ -261,13 +262,12 @@ describe('readCloudWorkspaceSnapshot', () => { call.method === 'PUT' ? registered() : { status: 404, body: { error: 'not_sealed_for_key' } } ) await readCloudWorkspaceSnapshot(plane, 'sbx_1') - await new Promise((resolve) => setTimeout(resolve, 20)) expect(calls.map((c) => c.method)).toEqual(['PUT', 'GET']) }) it('refuses a snapshot older than one already shown for the workspace (rollback pin)', async () => { const key = await loadCloudReaderKey('ds_1') - const keyId = 'rk_' + 'c'.repeat(24) + const keyId = `rk_${'c'.repeat(24)}` const seal = (snapshotId: string, capturedAt: number) => sealLikeVm({ readerPublicKeyB64: key.publicKeyB64, diff --git a/mobile/src/cloud/cloud-read-snapshot.ts b/mobile/src/cloud/cloud-read-snapshot.ts index 6f2adbe107e..cc64e4e9b19 100644 --- a/mobile/src/cloud/cloud-read-snapshot.ts +++ b/mobile/src/cloud/cloud-read-snapshot.ts @@ -125,14 +125,14 @@ export function resetCloudReadSnapshotPins(): void { newestShown.clear() } -const NOT_FOUND_STATES = new Set(['no_snapshot', 'not_sealed_for_key', 'not_found']) type MissingState = 'no_snapshot' | 'not_sealed_for_key' | 'not_found' +const isMissingState = (code: string): code is MissingState => + code === 'no_snapshot' || code === 'not_sealed_for_key' || code === 'not_found' + function missingState(error: unknown): MissingState | null { - return error instanceof CloudRequestError && - error.status === 404 && - NOT_FOUND_STATES.has(error.code) - ? (error.code as MissingState) + return error instanceof CloudRequestError && error.status === 404 && isMissingState(error.code) + ? error.code : null } diff --git a/mobile/src/cloud/cloud-reader-key.test.ts b/mobile/src/cloud/cloud-reader-key.test.ts index 311b3c69c04..803381a097e 100644 --- a/mobile/src/cloud/cloud-reader-key.test.ts +++ b/mobile/src/cloud/cloud-reader-key.test.ts @@ -1,9 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -const { store, options } = vi.hoisted(() => ({ - store: new Map(), - options: [] as unknown[] -})) +const { store, options } = vi.hoisted(() => { + const options: unknown[] = [] + return { store: new Map(), options } +}) vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY', getItemAsync: vi.fn(async (key: string, opts: unknown) => { diff --git a/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index ff6c952994d..4322c21548c 100644 --- a/mobile/src/i18n/en-runtime-required.json +++ b/mobile/src/i18n/en-runtime-required.json @@ -140,6 +140,16 @@ "seconds_other": "{{count}}s" } }, + "cloud": { + "snapshot": { + "git": { + "files_one": "{{count}} changed file", + "files_other": "{{count}} changed files", + "more_one": "and {{count}} more", + "more_other": "and {{count}} more" + } + } + }, "components": { "codexResetCredit": { "available_one": "{{count}} reset available", diff --git a/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts b/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts index 81745c5ec68..682443282d7 100644 --- a/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts +++ b/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts @@ -54,11 +54,11 @@ function setup(options: { identity?: string | null; keychain?: boolean } = {}) { let identity: string | null = options.identity === undefined ? 'me' : options.identity const readerKey: ReaderKeyAccess = { identity: () => identity, - load: () => + load: async () => options.keychain === false ? { ok: false, reason: 'keychain_unavailable', message: 'no keychain' } : { ok: true, key }, - peek: () => (options.keychain === false ? null : key) + peek: async () => (options.keychain === false ? null : key) } let now = 10_000 const ids = [KEY_A] diff --git a/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts index a89c3484261..01d2cebcc70 100644 --- a/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts +++ b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts @@ -15,9 +15,9 @@ export type ReaderKeyAccess = { /** Who is asking (profile, user, account); null when signed out. Registrations are per identity. */ identity: () => string | null /** This profile's key (created on first use), or why there can be none. */ - load: () => ReaderKeyLoad + load: () => Promise /** The key only if one already exists (sign-out must not create one just to delete it). */ - peek?: () => CloudReaderKey | null + peek?: () => Promise } type Registration = { identity: string; publicKeyB64: string; keyId: string; at: number } @@ -42,7 +42,7 @@ export function createReadSnapshotReader(deps: { if (!identity) { throw new CloudWorkspacesError(401, 'unauthorized') } - const loaded = deps.readerKey.load() + const loaded = await deps.readerKey.load() if (!loaded.ok) { return { unavailable: loaded } } @@ -128,7 +128,7 @@ export function createReadSnapshotReader(deps: { */ async revoke(timeoutMs: number): Promise { const identity = deps.readerKey.identity() - const key = deps.readerKey.peek?.() ?? null + const key = (await deps.readerKey.peek?.()) ?? null if (!identity || !key) { return } diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.test.ts b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts index 900b5f6d39b..7fd62418f64 100644 --- a/src/main/cloud-workspaces/cloud-reader-key-store.test.ts +++ b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts @@ -18,7 +18,7 @@ import { setCloudReaderKeyRevoker, type ReaderKeyCodec } from './cloud-reader-key-store' -import { nodeSealedGrantPrimitives } from './sealed-grant-node' +import { x25519PublicKeyOf } from './sealed-grant-node' import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant' // Reversible stand-in for the OS keychain: the file must never hold the raw secret. @@ -44,31 +44,32 @@ afterEach(() => { const storeWith = (next: () => ReaderKeyCodec | null = () => codec) => createCloudReaderKeyStore({ pathFor: (profileId) => join(dir, profileId, 'key.enc'), - codec: next + codec: next, + now: () => 1_700_000_000_000 }) -describe('createCloudReaderKeyStore', () => { - it('creates one key per profile lazily and keeps it sealed on disk', () => { +describe('createCloudReaderKeyStore', async () => { + it('creates one key per profile lazily and keeps it sealed on disk', async () => { const store = storeWith() - const first = store.load('p1') + const first = await store.load('p1') expect(first.ok).toBe(true) if (!first.ok) { return } expect(first.key.secretKey).toHaveLength(32) - const derived = nodeSealedGrantPrimitives.x25519PublicKey(first.key.secretKey) as Uint8Array + const derived = x25519PublicKeyOf(first.key.secretKey) expect(first.key.publicKeyB64).toBe(bytesToBase64(derived)) const file = readFileSync(join(dir, 'p1', 'key.enc'), 'utf8') expect(file).not.toContain(bytesToBase64(first.key.secretKey)) expect(JSON.parse(file)).toMatchObject({ version: 1, format: 'electron-safe-storage-v1' }) - const second = store.load('p2') + const second = await store.load('p2') expect(second.ok && second.key.publicKeyB64).not.toBe(first.key.publicKeyB64) }) - it('reads the same key back after a restart', () => { - const first = storeWith().load('p1') - const again = storeWith().load('p1') + it('reads the same key back after a restart', async () => { + const first = await storeWith().load('p1') + const again = await storeWith().load('p1') expect(first.ok && again.ok).toBe(true) if (first.ok && again.ok) { expect(again.key.publicKeyB64).toBe(first.key.publicKeyB64) @@ -76,36 +77,36 @@ describe('createCloudReaderKeyStore', () => { } }) - it('is off with a reason when the OS keychain is missing, and writes nothing', () => { + it('is off with a reason when the OS keychain is missing, and writes nothing', async () => { const store = storeWith(() => null) - expect(store.load('p1')).toMatchObject({ ok: false, reason: 'keychain_unavailable' }) + expect(await store.load('p1')).toMatchObject({ ok: false, reason: 'keychain_unavailable' }) expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) }) - it('replaces a key the keychain can no longer open', () => { - const first = storeWith().load('p1') + it('replaces a key the keychain can no longer open', async () => { + const first = await storeWith().load('p1') writeFileSync( join(dir, 'p1', 'key.enc'), JSON.stringify({ version: 1, format: 'electron-safe-storage-v1', ciphertext: 'AAAA' }) ) - const replaced = storeWith().load('p1') + const replaced = await storeWith().load('p1') expect(replaced.ok).toBe(true) expect(first.ok && replaced.ok && replaced.key.publicKeyB64 !== first.key.publicKeyB64).toBe( true ) }) - it('clear drops the key from memory and disk (sign-out)', () => { + it('clear drops the key from memory and disk (sign-out)', async () => { const store = storeWith() - const first = store.load('p1') - store.clear('p1') + const first = await store.load('p1') + await store.clear('p1') expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) - const next = store.load('p1') + const next = await store.load('p1') expect(first.ok && next.ok && next.key.publicKeyB64 !== first.key.publicKeyB64).toBe(true) }) }) -describe('revokeCloudReaderKeyBestEffort', () => { +describe('revokeCloudReaderKeyBestEffort', async () => { afterEach(() => setCloudReaderKeyRevoker(null)) it('runs the registered revoker with the timeout', async () => { @@ -116,10 +117,21 @@ describe('revokeCloudReaderKeyBestEffort', () => { }) it('never blocks sign-out: a hung or failing revoke resolves within the timeout', async () => { - setCloudReaderKeyRevoker(() => new Promise(() => {})) - const started = Date.now() - await revokeCloudReaderKeyBestEffort(30) - expect(Date.now() - started).toBeLessThan(1_000) + vi.useFakeTimers() + try { + setCloudReaderKeyRevoker(() => new Promise(() => {})) + let settled = false + const done = revokeCloudReaderKeyBestEffort(30).then(() => { + settled = true + }) + await vi.advanceTimersByTimeAsync(29) + expect(settled).toBe(false) + await vi.advanceTimersByTimeAsync(1) + await done + expect(settled).toBe(true) + } finally { + vi.useRealTimers() + } setCloudReaderKeyRevoker(async () => { throw new Error('offline') }) @@ -129,13 +141,21 @@ describe('revokeCloudReaderKeyBestEffort', () => { }) }) -describe('peek', () => { - it('returns the existing key and never creates one', () => { +describe('peek', async () => { + it('returns the existing key and never creates one', async () => { const store = storeWith() - expect(store.peek('p1')).toBeNull() + expect(await store.peek('p1')).toBeNull() expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) - const loaded = store.load('p1') - const fresh = storeWith().peek('p1') + const loaded = await store.load('p1') + const fresh = await storeWith().peek('p1') expect(loaded.ok && fresh?.publicKeyB64 === loaded.key.publicKeyB64).toBe(true) }) }) + +describe('concurrent first loads', () => { + it('mint a single key', async () => { + const store = storeWith() + const [a, b] = await Promise.all([store.load('p1'), store.load('p1')]) + expect(a.ok && b.ok && a.key.publicKeyB64 === b.key.publicKeyB64).toBe(true) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.ts b/src/main/cloud-workspaces/cloud-reader-key-store.ts index 31752b9fcc9..3f570aa9156 100644 --- a/src/main/cloud-workspaces/cloud-reader-key-store.ts +++ b/src/main/cloud-workspaces/cloud-reader-key-store.ts @@ -2,14 +2,14 @@ // workspace seals its read snapshot to every registered reader key allowed to open it; the secret // half never leaves this machine. It is sealed by the OS keychain (safeStorage at level 'os'); with // no real keychain the feature is off rather than keeping a long-lived secret in the clear. -import { existsSync, readFileSync, rmSync } from 'node:fs' +import { readFile, rm } from 'node:fs/promises' import { join } from 'node:path' import { assessSecretProtection } from '../host/electron-secret-store' import { guardedSafeStorage } from '../host/safe-storage-availability' import { writeSecureJsonFile } from '../../shared/secure-storage/secure-file' import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant' import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths' -import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from './sealed-grant-node' +import { generateGrantRecipientKey, x25519PublicKeyOf } from './sealed-grant-node' export const READER_KEY_FILE_NAME = 'cloud-reader-key.json.enc' @@ -63,11 +63,21 @@ export function createCloudReaderKeyStore(deps: { now?: () => number }) { const cache = new Map() + // One load per key file at a time, so two first reads can never mint two keys. + const loading = new Map>() - function decode(path: string, codec: ReaderKeyCodec): CloudReaderKey | null { + /** The sealed key on disk, or null when there is none or this keychain cannot open it. */ + async function readExisting(path: string, codec: ReaderKeyCodec): Promise { + let text: string try { - const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial + text = await readFile(path, 'utf8') + } catch { + return null + } + try { + const parsed: unknown = JSON.parse(text) if ( + !isRecord(parsed) || parsed.version !== 1 || parsed.format !== 'electron-safe-storage-v1' || typeof parsed.ciphertext !== 'string' @@ -78,34 +88,59 @@ export function createCloudReaderKeyStore(deps: { if (secretKey.length !== 32) { return null } - return { - secretKey, - publicKeyB64: bytesToBase64( - nodeSealedGrantPrimitives.x25519PublicKey(secretKey) as Uint8Array - ) - } + return { secretKey, publicKeyB64: bytesToBase64(x25519PublicKeyOf(secretKey)) } } catch { return null } } + async function loadUncached(path: string, codec: ReaderKeyCodec): Promise { + const existing = await readExisting(path, codec) + if (existing) { + cache.set(path, existing) + return { ok: true, key: existing } + } + // A new key only means snapshots taken before it are not readable here until the next sleep. + const fresh = generateGrantRecipientKey() + try { + const persisted: PersistedReaderKey = { + version: 1, + format: 'electron-safe-storage-v1', + createdAt: (deps.now ?? Date.now)(), + ciphertext: codec.encrypt(bytesToBase64(fresh.secretKey)).toString('base64') + } + // Once per profile; the shared writer applies owner-only permissions (and Windows ACLs). + writeSecureJsonFile(path, persisted) + } catch (error) { + fresh.secretKey.fill(0) + return { + ok: false, + reason: 'storage_failed', + message: `Could not save this device’s reader key: ${String(error).slice(0, 120)}` + } + } + const key = { secretKey: fresh.secretKey, publicKeyB64: fresh.publicKeyB64 } + cache.set(path, key) + return { ok: true, key } + } + return { /** The profile's existing key, if any; never creates one. */ - peek(profileId: string): CloudReaderKey | null { + async peek(profileId: string): Promise { const codec = deps.codec() const path = deps.pathFor(profileId) const cached = cache.get(path) - if (cached || !codec || !existsSync(path)) { + if (cached || !codec) { return cached ?? null } - const existing = decode(path, codec) + const existing = await readExisting(path, codec) if (existing) { cache.set(path, existing) } return existing }, /** The profile's key, created on first use. A key the keychain can no longer open is replaced. */ - load(profileId: string): ReaderKeyLoad { + async load(profileId: string): Promise { const codec = deps.codec() if (!codec) { return { ok: false, reason: 'keychain_unavailable', message: KEYCHAIN_MESSAGE } @@ -115,43 +150,29 @@ export function createCloudReaderKeyStore(deps: { if (cached) { return { ok: true, key: cached } } - const existing = existsSync(path) ? decode(path, codec) : null - if (existing) { - cache.set(path, existing) - return { ok: true, key: existing } + let pending = loading.get(path) + if (!pending) { + pending = loadUncached(path, codec).finally(() => loading.delete(path)) + loading.set(path, pending) } - // A new key only means snapshots taken before it are not readable here until the next sleep. - const fresh = generateGrantRecipientKey() - try { - const persisted: PersistedReaderKey = { - version: 1, - format: 'electron-safe-storage-v1', - createdAt: (deps.now ?? Date.now)(), - ciphertext: codec.encrypt(bytesToBase64(fresh.secretKey)).toString('base64') - } - writeSecureJsonFile(path, persisted) - } catch (error) { - fresh.secretKey.fill(0) - return { - ok: false, - reason: 'storage_failed', - message: `Could not save this device’s reader key: ${String(error).slice(0, 120)}` - } - } - const key = { secretKey: fresh.secretKey, publicKeyB64: fresh.publicKeyB64 } - cache.set(path, key) - return { ok: true, key } + return pending }, /** Sign-out: the next account on this profile gets a new key (never one an old account knew). */ - clear(profileId: string): void { + async clear(profileId: string): Promise { const path = deps.pathFor(profileId) + // A first load still in flight would otherwise write its key back after this. + await loading.get(path) cache.get(path)?.secretKey.fill(0) cache.delete(path) - rmSync(path, { force: true }) + await rm(path, { force: true }) } } } +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + export type CloudReaderKeyStore = ReturnType let defaultStore: { userDataPath: string; store: CloudReaderKeyStore } | null = null @@ -204,9 +225,9 @@ export async function revokeCloudReaderKeyBestEffort( } /** Sign-out / profile reset hook: drop the profile's reader key (memory and disk). */ -export function clearCloudReaderKey(profileId: string, userDataPath: string): void { +export async function clearCloudReaderKey(profileId: string, userDataPath: string): Promise { try { - getCloudReaderKeyStore(userDataPath).clear(profileId) + await getCloudReaderKeyStore(userDataPath).clear(profileId) } catch (error) { console.error(`[orca-cloud] clearing the reader key failed: ${String(error)}`) } diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts index 62e427723fd..a858d51898f 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts @@ -6,14 +6,13 @@ const SBX = 'sbx_0123456789abcdef01234567' const KEY = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa' function clientAnswering(status: number, body: unknown) { - const fetch = vi.fn( - async (_url: URL | RequestInfo, _init?: RequestInit) => - new Response(JSON.stringify(body), { status }) + const fetch = vi.fn( + async () => new Response(JSON.stringify(body), { status }) ) const client = createCloudWorkspacesClient({ baseUrl: 'https://cp.example.test', getAccessToken: async () => 'tok', - fetch: fetch as unknown as typeof globalThis.fetch + fetch }) return { client, fetch } } diff --git a/src/main/cloud-workspaces/sealed-grant-node.ts b/src/main/cloud-workspaces/sealed-grant-node.ts index d615d396ed7..b7eb5590dc5 100644 --- a/src/main/cloud-workspaces/sealed-grant-node.ts +++ b/src/main/cloud-workspaces/sealed-grant-node.ts @@ -21,7 +21,8 @@ function privateKeyFor(secret: Uint8Array, publicKey: Uint8Array) { }) } -function publicKeyOf(secret: Uint8Array): Uint8Array { +/** X25519 public key for a 32-byte secret (synchronous, unlike the primitives' contract). */ +export function x25519PublicKeyOf(secret: Uint8Array): Uint8Array { // Node derives the public half when only `d` is given via PKCS#8; JWK import needs `x`, so go through DER. const pkcs8 = Buffer.concat([ Buffer.from('302e020100300506032b656e04220420', 'hex'), @@ -33,10 +34,10 @@ function publicKeyOf(secret: Uint8Array): Uint8Array { } export const nodeSealedGrantPrimitives: SealedGrantPrimitives = { - x25519PublicKey: publicKeyOf, + x25519PublicKey: x25519PublicKeyOf, x25519(secret, peer) { const shared = diffieHellman({ - privateKey: privateKeyFor(secret, publicKeyOf(secret)), + privateKey: privateKeyFor(secret, x25519PublicKeyOf(secret)), publicKey: createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: b64url(peer) }, format: 'jwk' diff --git a/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts b/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts index 8a6b03d142a..aca5e7aff79 100644 --- a/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts +++ b/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts @@ -2,7 +2,16 @@ import { describe, expect, it, vi } from 'vitest' import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' import { createCloudReadMemo } from './cloud-offline-cloud-read' -const snap = { v: 1, capturedAt: 1 } as ReadSnapshot +const snap: ReadSnapshot = { + v: 1, + workspaceId: 'sbx', + snapshotId: 'snap', + capturedAt: 1, + reason: 'sleep', + git: null, + pr: null, + sessions: [] +} describe('createCloudReadMemo', () => { it('reads once per workspace while fresh, again after forget', async () => { diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index ae38131cbd2..b5b6b097f65 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -185,7 +185,7 @@ export async function signOutCurrentOrcaProfile( // Cached Orca Cloud transcripts and queued prompts belong to the signed-out account. resetCloudOfflineData() // The next account signed in on this profile gets its own reader key. - clearCloudReaderKey(active.profile.id, userDataPath) + await clearCloudReaderKey(active.profile.id, userDataPath) try { clearRelayRegionPreferenceCache(userDataPath) } catch { diff --git a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx index c848cd3feed..36ac9eff10a 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx @@ -38,7 +38,7 @@ export function CloudReadSnapshotSheet({ return ( !open && onClose()}> {title} {workspace ? ( -
    + // The sheet owns its frame; this wrapper scrolls and pads (clear of the close button). +
    ({ ok: false, - error: 'unavailable' + error: IPC_FAILED_CODE })) .then((result) => { if (!live || asked.current !== id) { diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx index 5fef577f32c..6b4d8b26204 100644 --- a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx @@ -7,13 +7,12 @@ import type { ReadSnapshotAgentStatus, ReadSnapshotSession } from '../../../../../shared/cloud-workspaces/read-snapshot' -import { getAgentLabel } from '@/lib/agent-catalog/agent-catalog' -import type { TerminalAgent } from '../../../../../shared/agent-status/identity/terminal-agent' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { agentStatusLabel } from './cloud-read-snapshot-format' /** The app's agent names ("Claude", "Codex"); an id it does not know is shown as sent. */ function agentDisplayName(agent: string): string { - return getAgentLabel(agent as TerminalAgent) + return getAgentCatalog().find((entry) => entry.id === agent)?.label ?? agent } /** Messages shown before "Show more": enough to see where the agent left off. */ diff --git a/src/shared/cloud-workspaces/read-snapshot-parse.ts b/src/shared/cloud-workspaces/read-snapshot-parse.ts new file mode 100644 index 00000000000..ad40c97b2b9 --- /dev/null +++ b/src/shared/cloud-workspaces/read-snapshot-parse.ts @@ -0,0 +1,172 @@ +// Lenient parser for the read snapshot payload a sleeping workspace's VM wrote (see read-snapshot.ts +// for the sealed construction). Free of node:crypto and Buffer, like the opener. +import type { + ReadSnapshot, + ReadSnapshotAgentStatus, + ReadSnapshotChange, + ReadSnapshotGit, + ReadSnapshotMessage, + ReadSnapshotPr, + ReadSnapshotRole, + ReadSnapshotSession +} from './read-snapshot' + +/** Plaintext bounds the VM keeps to (the opener re-checks them; anything over is cut, not trusted). */ +export const READ_SNAPSHOT_LIMITS = { + sessions: 12, + messagesPerSession: 60, + messageChars: 4000, + changes: 200, + commits: 10, + titleChars: 200 +} as const + +// The payload came from the VM: parse leniently field by field, cut to the limits, never trust it. +type Obj = Record +const isObj = (value: unknown): value is Obj => + typeof value === 'object' && value !== null && !Array.isArray(value) +const str = (value: unknown, max: number): string | null => + typeof value === 'string' ? value.slice(0, max) : null +const num = (value: unknown): number | null => + typeof value === 'number' && Number.isFinite(value) ? value : null +const arr = (value: unknown): unknown[] => (Array.isArray(value) ? value : []) + +const ROLES: ReadonlySet = new Set(['user', 'assistant', 'system']) +const STATUSES: ReadonlySet = new Set([ + 'working', + 'attention', + 'idle' +]) +const isRole = (value: unknown): value is ReadSnapshotRole => + typeof value === 'string' && ROLES.has(value) +const isStatus = (value: unknown): value is ReadSnapshotAgentStatus => + typeof value === 'string' && STATUSES.has(value) + +function messageOf(value: unknown): ReadSnapshotMessage | null { + if (!isObj(value) || !isRole(value.role)) { + return null + } + const text = str(value.text, READ_SNAPSHOT_LIMITS.messageChars) + const itemId = str(value.itemId, 200) + if (!text || !itemId) { + return null + } + return { itemId, role: value.role, text, at: num(value.at) ?? 0 } +} + +function sessionOf(value: unknown): ReadSnapshotSession | null { + if (!isObj(value)) { + return null + } + const sessionId = str(value.sessionId, 200) + if (!sessionId) { + return null + } + const all = arr(value.messages) + .map(messageOf) + .filter((m): m is ReadSnapshotMessage => m !== null) + const messages = all.slice(-READ_SNAPSHOT_LIMITS.messagesPerSession) + const status: ReadSnapshotAgentStatus = isStatus(value.status) ? value.status : 'unknown' + + return { + sessionId, + agent: str(value.agent, 40), + title: str(value.title, READ_SNAPSHOT_LIMITS.titleChars), + status, + turnOutcome: str(value.turnOutcome, 40), + updatedAt: num(value.updatedAt), + messages, + truncated: value.truncated === true || messages.length < all.length + } +} + +function gitOf(value: unknown): ReadSnapshotGit | null { + if (!isObj(value)) { + return null + } + const changes = arr(value.changes) + .flatMap((raw): ReadSnapshotChange[] => { + if (!isObj(raw)) { + return [] + } + const path = str(raw.path, 1024) + return path + ? [ + { + path, + status: str(raw.status, 20) ?? 'modified', + area: str(raw.area, 20) ?? 'unstaged', + added: num(raw.added), + removed: num(raw.removed) + } + ] + : [] + }) + .slice(0, READ_SNAPSHOT_LIMITS.changes) + const commits = arr(value.commits) + .flatMap((raw) => { + if (!isObj(raw)) { + return [] + } + const id = str(raw.id, 64) + const subject = str(raw.subject, 300) + return id && subject !== null + ? [{ id, subject, author: str(raw.author, 120), at: num(raw.at) }] + : [] + }) + .slice(0, READ_SNAPSHOT_LIMITS.commits) + return { + branch: str(value.branch, 255), + head: str(value.head, 64), + changes, + changeCount: Math.max(num(value.changeCount) ?? changes.length, changes.length), + added: num(value.added), + removed: num(value.removed), + commits + } +} + +function prOf(value: unknown): ReadSnapshotPr | null { + if (!isObj(value)) { + return null + } + const number = num(value.number) + const url = str(value.url, 500) + // Only links a person can safely tap. + if (number === null || !url || !url.startsWith('https://')) { + return null + } + return { + number, + title: str(value.title, 300) ?? '', + state: str(value.state, 20) ?? 'open', + url, + checksStatus: str(value.checksStatus, 20), + checksSummary: str(value.checksSummary, 200) + } +} + +export function parseReadSnapshot(value: unknown): ReadSnapshot | null { + if (!isObj(value) || value.v !== 1) { + return null + } + const workspaceId = str(value.workspaceId, 64) + const snapshotId = str(value.snapshotId, 64) + const capturedAt = num(value.capturedAt) + if (!workspaceId || !snapshotId || capturedAt === null) { + return null + } + return { + v: 1, + workspaceId, + snapshotId, + capturedAt, + reason: str(value.reason, 20) ?? 'sleep', + git: gitOf(value.git), + pr: prOf(value.pr), + sessions: arr(value.sessions) + .map(sessionOf) + .filter((s): s is ReadSnapshotSession => s !== null) + .slice(0, READ_SNAPSHOT_LIMITS.sessions) + } +} diff --git a/src/shared/cloud-workspaces/read-snapshot.ts b/src/shared/cloud-workspaces/read-snapshot.ts index a6f30df9cf6..f5ef5ec68a4 100644 --- a/src/shared/cloud-workspaces/read-snapshot.ts +++ b/src/shared/cloud-workspaces/read-snapshot.ts @@ -14,26 +14,22 @@ // AAD = utf8 "orca-cloud-read-wrap-v1:" + workspaceId + ":" + snapshotId + ":" + keyId) // ciphertexts are ct || tag(16). // Free of node:crypto and Buffer so mobile (Hermes) can use it with the same primitives as grants. -import { - base64ToBytes, - type SealedGrantPrimitives -} from './sealed-grant' +import { parseReadSnapshot } from './read-snapshot-parse' +import { base64ToBytes, type SealedGrantPrimitives } from './sealed-grant' + +// The payload parser and its bounds live in read-snapshot-parse.ts; existing imports keep working. +export { parseReadSnapshot, READ_SNAPSHOT_LIMITS } from './read-snapshot-parse' export const READ_SNAPSHOT_INFO = 'orca-cloud-read-v1' export const READ_SNAPSHOT_WRAP_INFO = 'orca-cloud-read-wrap-v1' -/** Plaintext bounds the VM keeps to (the opener re-checks them; anything over is cut, not trusted). */ -export const READ_SNAPSHOT_LIMITS = { - sessions: 12, - messagesPerSession: 60, - messageChars: 4000, - changes: 200, - commits: 10, - titleChars: 200 -} as const - export type ReadSnapshotRole = 'user' | 'assistant' | 'system' -export type ReadSnapshotMessage = { itemId: string; role: ReadSnapshotRole; text: string; at: number } +export type ReadSnapshotMessage = { + itemId: string + role: ReadSnapshotRole + text: string + at: number +} /** `attention`: waiting on a person (approval, question). `idle` + turnOutcome is "done". */ export type ReadSnapshotAgentStatus = 'working' | 'attention' | 'idle' | 'unknown' export type ReadSnapshotSession = { @@ -103,7 +99,9 @@ export type SealedReadSnapshot = { } export class ReadSnapshotError extends Error { - constructor(readonly code: 'malformed' | 'decrypt_failed' | 'invalid_payload' | 'wrong_workspace') { + constructor( + readonly code: 'malformed' | 'decrypt_failed' | 'invalid_payload' | 'wrong_workspace' + ) { super(code) this.name = 'ReadSnapshotError' } @@ -198,149 +196,12 @@ export async function openReadSnapshot( } const snapshot = parseReadSnapshot(parsed) // The AAD already binds these; a mismatch means the VM itself wrote something odd. - if (!snapshot || snapshot.workspaceId !== workspaceId || snapshot.snapshotId !== sealed.snapshotId) { + if ( + !snapshot || + snapshot.workspaceId !== workspaceId || + snapshot.snapshotId !== sealed.snapshotId + ) { throw new ReadSnapshotError('invalid_payload') } return snapshot } - -// The payload came from the VM: parse leniently field by field, cut to the limits, never trust it. -type Obj = Record -const isObj = (value: unknown): value is Obj => - typeof value === 'object' && value !== null && !Array.isArray(value) -const str = (value: unknown, max: number): string | null => - typeof value === 'string' ? value.slice(0, max) : null -const num = (value: unknown): number | null => - typeof value === 'number' && Number.isFinite(value) ? value : null -const arr = (value: unknown): unknown[] => (Array.isArray(value) ? value : []) - -const ROLES: ReadonlySet = new Set(['user', 'assistant', 'system']) -const STATUSES: ReadonlySet = new Set(['working', 'attention', 'idle']) - -function messageOf(value: unknown): ReadSnapshotMessage | null { - if (!isObj(value) || typeof value.role !== 'string' || !ROLES.has(value.role)) { - return null - } - const text = str(value.text, READ_SNAPSHOT_LIMITS.messageChars) - const itemId = str(value.itemId, 200) - if (!text || !itemId) { - return null - } - return { itemId, role: value.role as ReadSnapshotRole, text, at: num(value.at) ?? 0 } -} - -function sessionOf(value: unknown): ReadSnapshotSession | null { - if (!isObj(value)) { - return null - } - const sessionId = str(value.sessionId, 200) - if (!sessionId) { - return null - } - const all = arr(value.messages) - .map(messageOf) - .filter((m): m is ReadSnapshotMessage => m !== null) - const messages = all.slice(-READ_SNAPSHOT_LIMITS.messagesPerSession) - const status = typeof value.status === 'string' && STATUSES.has(value.status) ? value.status : 'unknown' - return { - sessionId, - agent: str(value.agent, 40), - title: str(value.title, READ_SNAPSHOT_LIMITS.titleChars), - status: status as ReadSnapshotAgentStatus, - turnOutcome: str(value.turnOutcome, 40), - updatedAt: num(value.updatedAt), - messages, - truncated: value.truncated === true || messages.length < all.length - } -} - -function gitOf(value: unknown): ReadSnapshotGit | null { - if (!isObj(value)) { - return null - } - const changes = arr(value.changes) - .flatMap((raw): ReadSnapshotChange[] => { - if (!isObj(raw)) { - return [] - } - const path = str(raw.path, 1024) - return path - ? [ - { - path, - status: str(raw.status, 20) ?? 'modified', - area: str(raw.area, 20) ?? 'unstaged', - added: num(raw.added), - removed: num(raw.removed) - } - ] - : [] - }) - .slice(0, READ_SNAPSHOT_LIMITS.changes) - const commits = arr(value.commits) - .flatMap((raw) => { - if (!isObj(raw)) { - return [] - } - const id = str(raw.id, 64) - const subject = str(raw.subject, 300) - return id && subject !== null - ? [{ id, subject, author: str(raw.author, 120), at: num(raw.at) }] - : [] - }) - .slice(0, READ_SNAPSHOT_LIMITS.commits) - return { - branch: str(value.branch, 255), - head: str(value.head, 64), - changes, - changeCount: Math.max(num(value.changeCount) ?? changes.length, changes.length), - added: num(value.added), - removed: num(value.removed), - commits - } -} - -function prOf(value: unknown): ReadSnapshotPr | null { - if (!isObj(value)) { - return null - } - const number = num(value.number) - const url = str(value.url, 500) - // Only links a person can safely tap. - if (number === null || !url || !url.startsWith('https://')) { - return null - } - return { - number, - title: str(value.title, 300) ?? '', - state: str(value.state, 20) ?? 'open', - url, - checksStatus: str(value.checksStatus, 20), - checksSummary: str(value.checksSummary, 200) - } -} - -export function parseReadSnapshot(value: unknown): ReadSnapshot | null { - if (!isObj(value) || value.v !== 1) { - return null - } - const workspaceId = str(value.workspaceId, 64) - const snapshotId = str(value.snapshotId, 64) - const capturedAt = num(value.capturedAt) - if (!workspaceId || !snapshotId || capturedAt === null) { - return null - } - return { - v: 1, - workspaceId, - snapshotId, - capturedAt, - reason: str(value.reason, 20) ?? 'sleep', - git: gitOf(value.git), - pr: prOf(value.pr), - sessions: arr(value.sessions) - .map(sessionOf) - .filter((s): s is ReadSnapshotSession => s !== null) - .slice(0, READ_SNAPSHOT_LIMITS.sessions) - } -} From e35ff0844a52675b44da75ff8ffe5b43870d6905 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:08:00 -0800 Subject: [PATCH 07/46] feat(cloud): COPILOT_GITHUB_TOKEN and GOOGLE_API_KEY swapped at egress; routines run all six image agents; AWS keys marked stored on workspace - COPILOT_GITHUB_TOKEN: placeholder in the VM, swapped on api.github.com (Bearer or token form, next to the workspace token's own route) and on the Copilot API hosts (left open for Copilot's own session token). GOOGLE_API_KEY: swapped on generativelanguage.googleapis.com and aiplatform.googleapis.com (Vertex express). A credential may now route to several hosts. - Routines accept claude, codex, opencode, gemini, cursor and copilot; the in-VM runner has a headless command for each (checked against a local stand-in model: prompts starting with '-' stay prompts). The editor picks the agent from a list. - AWS_* keys (SigV4, signed in the VM) and Bedrock API keys can't be swapped: the secrets UI marks them 'Stored on workspace' with the reason, in the list, the .env preview, the effective view and the editor. - Gemini's auth method is seeded for GOOGLE_API_KEY too (vertex-ai with GOOGLE_GENAI_USE_VERTEXAI); headless Gemini refuses to start without one. --- .../image/vm-scripts.generated.ts | 2 +- .../sandbox-control/image/vm/orca-sandbox-env | 7 +- cloud/apps/sandbox-control/src/index.ts | 31 ++++--- cloud/apps/sandbox-control/src/lifecycle.ts | 8 +- .../sandbox-control/src/network-policy.ts | 2 + .../apps/sandbox-control/src/provider-env.ts | 84 ++++++++++++++----- .../sandbox-control/src/routines/vm-runner.ts | 20 +++++ .../apps/sandbox-control/src/secret-egress.ts | 25 ++++-- cloud/apps/sandbox-control/src/secrets.ts | 1 + .../test/agent-credentials-more.test.ts | 34 ++++++++ .../sandbox-control/test/routines.test.ts | 21 +++++ .../settings/cloud-api/CloudRoutineRow.tsx | 5 +- .../cloud-api/RoutineAgentSection.tsx | 50 +++++++---- .../cloud-secrets/CloudSecretEditor.tsx | 8 ++ .../cloud-secrets/CloudSecretList.tsx | 2 + .../cloud-secrets/CloudSecretVmBadge.tsx | 27 ++++++ .../CloudSecretsEffectiveView.tsx | 2 + .../cloud-secrets/CloudSecretsPasteRow.tsx | 2 + src/renderer/src/i18n/locales/en.json | 6 +- .../cloud-api/cloud-api-routine-types.ts | 4 +- .../cloud-secrets/cloud-secret-rules.ts | 24 +++++- .../cloud-secret-stored-on-vm.test.ts | 37 ++++++++ 22 files changed, 328 insertions(+), 74 deletions(-) create mode 100644 src/renderer/src/components/settings/cloud-secrets/CloudSecretVmBadge.tsx create mode 100644 src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index bc0c2ae96f4..fd75182bdb0 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -3,7 +3,7 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0","opencode-ai@1.19.5","@google/gemini-cli@0.67.0","@github/copilot@1.0.108"],"cursorAgent":{"version":"2026.11.05-86047df","sha256":"170b77786cbf4c93064d64fff12b71a178b968730561c64afc2e8e752535442e"},"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" -export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY) gemini_key=1 ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= \"gemini-api-key\"\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-env b/cloud/apps/sandbox-control/image/vm/orca-sandbox-env index 149f6379ebe..3385bc365bb 100644 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-env +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-env @@ -44,7 +44,8 @@ while IFS= read -r line; do OPENAI_MODEL) openai_model="$(printf '%s' "$b64" | base64 -d)" ;; ANTHROPIC_MODEL) anthropic_model="$(printf '%s' "$b64" | base64 -d)" ;; AI_GATEWAY_API_KEY) gateway_key=1 ;; - GEMINI_API_KEY) gemini_key=1 ;; + GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key="${gemini_key:-gemini-api-key}" ;; + GOOGLE_GENAI_USE_VERTEXAI) case "$(printf '%s' "$b64" | base64 -d)" in true | 1) gemini_key=vertex-ai ;; esac ;; # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars. ANTHROPIC_API_KEY) anthropic_key_tail="$(printf '%s' "$b64" | base64 -d | tail -c 20)" ;; esac @@ -160,7 +161,9 @@ if (isObject(g)) { general.disableAutoUpdate ??= true general.disableUpdateNag ??= true section(g, "privacy").usageStatisticsEnabled ??= false - if (process.env.ORCA_GEMINI_KEY) section(section(g, "security"), "auth").selectedType ??= "gemini-api-key" + // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs + // refuse to start without a method ("Invalid auth method selected"). + if (process.env.ORCA_GEMINI_KEY) section(section(g, "security"), "auth").selectedType ??= process.env.ORCA_GEMINI_KEY if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g) } diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index d4b1bbd130b..35f1ba4f133 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -89,7 +89,7 @@ import { GuardrailError, consumeCreateToken, guardrailsFromEnv } from './guardra import { handleOperator, isOperator } from './operator' import { DEFAULT_RETENTION, type RetentionConfig } from './retention' import { reconcile } from './reconcile' -import { egressSecretHosts, secretPlaceholder } from './secret-egress' +import { egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress' import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets' import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh' import { EgressHostsSchema, egressUserHosts, normalizeUserHosts, setEgressUserHosts } from './egress-hosts' @@ -250,17 +250,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => : null } }) - return async (row, host) => { - if (host === 'github.com') { - return members.routes(row, host) - } - if (host === 'api.github.com') { - return [ - // Members first: a member placeholder must never fall through to the app's token. - ...(await members.routes(row, host)), - { header: 'authorization', placeholders: githubPlaceholderHeaders(row), credential: () => broker.authorizationFor(row, host) } - ] - } + const secretRoutes = (row: SandboxRow, host: string): ProxiedRoute[] => { const entries = egressSecretHosts(row).filter((candidate) => candidate.host === host) const keyring = keyringFor(env) if (entries.length === 0 || !keyring) { @@ -269,7 +259,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => return entries.flatMap((entry) => Object.entries(entry.headers).map(([header, format]): ProxiedRoute => ({ header, - placeholders: [format(secretPlaceholder(row, entry.secret))], + placeholders: placeholderValues(entry, header, secretPlaceholder(row, entry.secret)), label: entry.secret, ...(entry.paths ? { pathAllowed: requestMatches(entry.paths) } : {}), ...(entry.keepResponseFields ? { keepResponseFields: entry.keepResponseFields } : {}), @@ -286,6 +276,21 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => })) ) } + return async (row, host) => { + if (host === 'github.com') { + return members.routes(row, host) + } + if (host === 'api.github.com') { + return [ + // Members first: a member placeholder must never fall through to the app's token. + ...(await members.routes(row, host)), + { header: 'authorization', placeholders: githubPlaceholderHeaders(row), credential: () => broker.authorizationFor(row, host) }, + // A user's own GitHub token for Copilot CLI (COPILOT_GITHUB_TOKEN), on its own placeholder. + ...secretRoutes(row, host) + ] + } + return secretRoutes(row, host) + } } /** Exact method and path (the query string is ignored). */ diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index bd24826d129..380c76991e4 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -17,7 +17,7 @@ import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens' import { connectedMembers, memberGitConfigs } from './member-git' import type { RetentionConfig } from './retention' import type { ProviderSandboxState, SandboxProviderApi } from './sandbox-provider' -import { egressSecretHosts, secretPlaceholder } from './secret-egress' +import { egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress' import { egressAllowHosts, sessionSecretEnv, type SessionSecrets } from './session-env' import type { Keyring } from './secrets-crypto' import { ORCAD_PORT, SHARE_PROXY_PORT, drainOrcad, runningOrcad, startOrcad, type OrcadReady, type StartInputs } from './sandbox-vm-commands' @@ -232,11 +232,11 @@ export function egressPolicy(deps: LifecycleDeps, row: SandboxRow, gitToken?: st // Model API keys swapped at egress (phase 2); each host also ends in the 403 deny rule, except a // host whose client sends its own short-lived token on later calls (Cursor). ...egressSecretHosts(row).flatMap((entry) => - Object.entries(entry.headers).map( - ([header, format]): CredentialRoute => ({ + Object.keys(entry.headers).map( + (header): CredentialRoute => ({ host: entry.host, header, - placeholders: [format(secretPlaceholder(row, entry.secret))], + placeholders: placeholderValues(entry, header, secretPlaceholder(row, entry.secret)), via: 'forward', forwardURL: proxyUrl, ...(entry.allowUnclaimed ? { allowUnclaimed: true } : {}) diff --git a/cloud/apps/sandbox-control/src/network-policy.ts b/cloud/apps/sandbox-control/src/network-policy.ts index 024cebdeaaa..19bb7f5f967 100644 --- a/cloud/apps/sandbox-control/src/network-policy.ts +++ b/cloud/apps/sandbox-control/src/network-policy.ts @@ -80,6 +80,8 @@ export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = [ 'accounts.google.com', // Vercel AI Gateway: Anthropic/OpenAI-compatible endpoint teams point agents at (ANTHROPIC_BASE_URL). 'ai-gateway.vercel.sh', + // Vertex AI express mode (GOOGLE_API_KEY with GOOGLE_GENAI_USE_VERTEXAI=true). + 'aiplatform.googleapis.com', // Gemini CLI signed in with Google: Code Assist API and the account lookup after OAuth. 'cloudcode-pa.googleapis.com', 'www.googleapis.com', diff --git a/cloud/apps/sandbox-control/src/provider-env.ts b/cloud/apps/sandbox-control/src/provider-env.ts index df75f6d64e0..f92adff6897 100644 --- a/cloud/apps/sandbox-control/src/provider-env.ts +++ b/cloud/apps/sandbox-control/src/provider-env.ts @@ -8,6 +8,14 @@ const AI_GATEWAY_OPENAI_BASE_URL = `https://${AI_GATEWAY_HOST}/v1` export const GEMINI_HOST = 'generativelanguage.googleapis.com' export const CURSOR_API_HOST = 'api2.cursor.sh' +export const VERTEX_HOST = 'aiplatform.googleapis.com' +/** Copilot's API, per plan; which one a token uses comes from GitHub at sign-in. */ +export const COPILOT_API_HOSTS = [ + 'api.githubcopilot.com', + 'api.individual.githubcopilot.com', + 'api.business.githubcopilot.com', + 'api.enterprise.githubcopilot.com' +] as const export const BASE_URL_NAMES: ReadonlySet = new Set(['ANTHROPIC_BASE_URL', 'OPENAI_BASE_URL', 'COPILOT_PROVIDER_BASE_URL']) const HOST = /^([a-z0-9-]+\.)+[a-z]{2,63}$/ @@ -93,6 +101,8 @@ export type CredentialPolicy = { * headers that set state either); anything else is refused. */ keepResponseFields?: readonly string[] + /** More ways the client may send the key in a header (gh-style `token `). */ + altHeaderFormats?: Record string)[]> } const bearer = (value: string) => `Bearer ${value}` @@ -102,11 +112,13 @@ const raw = (value: string) => value export type ValueScopes = Readonly> type CredentialSpec = CredentialPolicy & { + /** Hosts (of the default ones) that stay open without the placeholder. */ + allowUnclaimedHosts?: readonly string[] secret: string /** Env var that may point this key at a custom host (honoured only from the key's own scope). */ baseUrl?: string - /** Host without a base URL; null: the key is only routed together with its base URL. */ - defaultHost: string | null + /** Hosts without a base URL (a base URL replaces them); empty: only routed with its base URL. */ + defaultHosts: readonly string[] headers: Record string> } @@ -120,23 +132,23 @@ const CREDENTIALS: readonly CredentialSpec[] = [ { secret: 'ANTHROPIC_API_KEY', baseUrl: 'ANTHROPIC_BASE_URL', - defaultHost: 'api.anthropic.com', + defaultHosts: ['api.anthropic.com'], headers: { 'x-api-key': raw, authorization: bearer } }, { secret: 'ANTHROPIC_AUTH_TOKEN', baseUrl: 'ANTHROPIC_BASE_URL', - defaultHost: 'api.anthropic.com', + defaultHosts: ['api.anthropic.com'], headers: { authorization: bearer, 'x-api-key': raw } }, // AI SDK clients (OpenCode's `vercel/...` models) read the gateway key directly. - { secret: 'AI_GATEWAY_API_KEY', defaultHost: AI_GATEWAY_HOST, headers: { authorization: bearer, 'x-api-key': raw } }, - { secret: 'OPENAI_API_KEY', baseUrl: 'OPENAI_BASE_URL', defaultHost: 'api.openai.com', headers: { authorization: bearer } }, - { secret: 'GEMINI_API_KEY', defaultHost: GEMINI_HOST, headers: { 'x-goog-api-key': raw } }, - { secret: 'GOOGLE_GENERATIVE_AI_API_KEY', defaultHost: GEMINI_HOST, headers: { 'x-goog-api-key': raw } }, + { secret: 'AI_GATEWAY_API_KEY', defaultHosts: [AI_GATEWAY_HOST], headers: { authorization: bearer, 'x-api-key': raw } }, + { secret: 'OPENAI_API_KEY', baseUrl: 'OPENAI_BASE_URL', defaultHosts: ['api.openai.com'], headers: { authorization: bearer } }, + { secret: 'GEMINI_API_KEY', defaultHosts: [GEMINI_HOST], headers: { 'x-goog-api-key': raw } }, + { secret: 'GOOGLE_GENERATIVE_AI_API_KEY', defaultHosts: [GEMINI_HOST], headers: { 'x-goog-api-key': raw } }, { secret: 'CURSOR_API_KEY', - defaultHost: CURSOR_API_HOST, + defaultHosts: [CURSOR_API_HOST], headers: { authorization: bearer }, paths: [{ method: 'POST', path: '/auth/exchange_user_api_key' }], allowUnclaimed: true, @@ -144,16 +156,29 @@ const CREDENTIALS: readonly CredentialSpec[] = [ // and exchanges the key again when it expires; with one it would persist a long-lived credential. keepResponseFields: ['accessToken'] }, + // Gemini CLI and the Google GenAI SDK read GOOGLE_API_KEY for the Gemini API and for Vertex AI + // express mode (GOOGLE_GENAI_USE_VERTEXAI=true). + { secret: 'GOOGLE_API_KEY', defaultHosts: [GEMINI_HOST, VERTEX_HOST], headers: { 'x-goog-api-key': raw } }, + { + // A user's own GitHub token for Copilot CLI (fine-grained PAT with Copilot Requests). Copilot + // checks it on api.github.com, then calls its API with it. The Copilot hosts stay open without + // the placeholder: a session token Copilot gets back is sent there too. + secret: 'COPILOT_GITHUB_TOKEN', + defaultHosts: ['api.github.com', ...COPILOT_API_HOSTS], + headers: { authorization: bearer }, + altHeaderFormats: { authorization: [(value: string) => `token ${value}`] }, + allowUnclaimedHosts: [...COPILOT_API_HOSTS] + }, { secret: 'COPILOT_PROVIDER_API_KEY', baseUrl: 'COPILOT_PROVIDER_BASE_URL', - defaultHost: null, + defaultHosts: [], headers: { authorization: bearer, 'api-key': raw } }, { secret: 'COPILOT_PROVIDER_BEARER_TOKEN', baseUrl: 'COPILOT_PROVIDER_BASE_URL', - defaultHost: null, + defaultHosts: [], headers: { authorization: bearer } } ] @@ -167,7 +192,7 @@ export function credentialShape(secret: string): Omit if (!spec) { return null } - const { baseUrl: _baseUrl, defaultHost: _defaultHost, ...shape } = spec + const { baseUrl: _baseUrl, defaultHosts: _defaultHosts, allowUnclaimedHosts: _openHosts, ...shape } = spec return shape } @@ -175,25 +200,42 @@ export function credentialShape(secret: string): Omit * A base URL only redirects a credential from the same scope: a member's personal base URL must * never route the org's shared key to a host the member picked (the proxy would hand it over). */ -function hostFor(env: Record, spec: CredentialSpec, scopes?: ValueScopes): string | null { +function hostsFor(env: Record, spec: CredentialSpec, scopes?: ValueScopes): readonly string[] { const base = spec.baseUrl ? env[spec.baseUrl] : undefined if (!base || !spec.baseUrl) { - return spec.defaultHost + return spec.defaultHosts } if (scopes && scopes[spec.baseUrl] !== scopes[spec.secret]) { - return spec.defaultHost + return spec.defaultHosts } - return baseUrlHost(base) + const host = baseUrlHost(base) + return host ? [host] : [] } -/** Where each model credential in `env` is used, so the egress proxy can swap it in on that host only. */ +/** How a credential is sent and policed on one of its hosts. */ +export function credentialTarget(secret: string, host: string): CredentialTarget | null { + const spec = CREDENTIALS.find((candidate) => candidate.secret === secret) + const shape = credentialShape(secret) + if (!spec || !shape) { + return null + } + const { allowUnclaimed: _open, ...rest } = shape + const open = spec.allowUnclaimed || spec.allowUnclaimedHosts?.includes(host) + return { ...rest, ...(open ? { allowUnclaimed: true as const } : {}), host } +} + +/** Where each model credential in `env` is used, so the egress proxy can swap it in on those hosts only. */ export function credentialTargets(env: Record, scopes?: ValueScopes): CredentialTarget[] { const targets: CredentialTarget[] = [] for (const spec of CREDENTIALS) { - const host = env[spec.secret] ? hostFor(env, spec, scopes) : null - const shape = host ? credentialShape(spec.secret) : null - if (host && shape) { - targets.push({ ...shape, host }) + if (!env[spec.secret]) { + continue + } + for (const host of hostsFor(env, spec, scopes)) { + const target = credentialTarget(spec.secret, host) + if (target) { + targets.push(target) + } } } return targets diff --git a/cloud/apps/sandbox-control/src/routines/vm-runner.ts b/cloud/apps/sandbox-control/src/routines/vm-runner.ts index 6354ba9d63d..72e0a0538e5 100644 --- a/cloud/apps/sandbox-control/src/routines/vm-runner.ts +++ b/cloud/apps/sandbox-control/src/routines/vm-runner.ts @@ -95,6 +95,26 @@ codex) --output-last-message "$D/last.txt" - >"$D/agent.out" 2>"$D/agent.err" <"$D/prompt.txt" || code=$? summary="$(head -c 6000 "$D/last.txt" 2>/dev/null || true)" ;; +opencode) + # "--" ends the flags, so a prompt starting with "-" stays the message. + timeout --kill-after=20 "$limit" opencode run --auto -- "$(cat "$D/prompt.txt")" \ + >"$D/agent.out" 2>"$D/agent.err" "$D/agent.out" 2>"$D/agent.err" /dev/null | head -c 6000)" + if [ "$code" = 0 ] && [ -n "$(jq -r '.error // empty' "$D/agent.out" 2>/dev/null)" ]; then code=1; fi + ;; +cursor) + timeout --kill-after=20 "$limit" cursor-agent --print --force --trust --output-format text -- "$(cat "$D/prompt.txt")" \ + >"$D/agent.out" 2>"$D/agent.err" "$D/agent.out" 2>"$D/agent.err" /dev/null || true)" diff --git a/cloud/apps/sandbox-control/src/secret-egress.ts b/cloud/apps/sandbox-control/src/secret-egress.ts index de81ea5dc87..19a9553b8b0 100644 --- a/cloud/apps/sandbox-control/src/secret-egress.ts +++ b/cloud/apps/sandbox-control/src/secret-egress.ts @@ -5,7 +5,7 @@ // Codex) hang under Vercel transform rules, so these hosts always take the forwardURL path through // /v1/egress/proxy, the same path api.github.com uses. Placeholders are not secrets: the proxy // authenticates the sandbox by Vercel's OIDC token, the placeholder only marks which header to swap. -import { SWAPPED_CREDENTIALS, credentialShape, credentialTargets, type CredentialTarget, type ValueScopes } from './provider-env' +import { SWAPPED_CREDENTIALS, credentialTarget, credentialTargets, type CredentialTarget, type ValueScopes } from './provider-env' import type { SandboxRow } from './store' export type SecretEgressHost = CredentialTarget @@ -24,21 +24,28 @@ export function encodeEgressSecretHosts(targets: readonly CredentialTarget[]): s /** Credential routes recorded on the row for this session. */ export function egressSecretHosts(row: Pick): SecretEgressHost[] { - const recorded: Record = {} + const recorded = new Map>() for (const entry of (row.egress_secret_hosts ?? '').split(',').filter(Boolean)) { const at = entry.indexOf('@') const [secret, host] = at === -1 ? [LEGACY_HOSTS[entry], entry] : [entry.slice(0, at), entry.slice(at + 1)] if (secret && host) { - recorded[secret] = host + recorded.set(secret, (recorded.get(secret) ?? new Set()).add(host)) } } // Header shapes and policies come from the code, never from the row. The base URL value is only - // used to pick the default-vs-custom host, and the recorded host is what was allowlisted at boot. - return SWAPPED_CREDENTIALS.flatMap((secret) => { - const host = recorded[secret] - const shape = host ? credentialShape(secret) : null - return host && shape ? [{ ...shape, host }] : [] - }) + // used to pick the default-vs-custom host, and the recorded hosts are what was allowlisted at boot. + return SWAPPED_CREDENTIALS.flatMap((secret) => + [...(recorded.get(secret) ?? [])].flatMap((host) => { + const target = credentialTarget(secret, host) + return target ? [target] : [] + }) + ) +} + +/** Every header value the VM may send a credential's placeholder in. */ +export function placeholderValues(target: CredentialTarget, header: string, placeholder: string): string[] { + const format = target.headers[header] + return format ? [format(placeholder), ...(target.altHeaderFormats?.[header] ?? []).map((alt) => alt(placeholder))] : [] } /** diff --git a/cloud/apps/sandbox-control/src/secrets.ts b/cloud/apps/sandbox-control/src/secrets.ts index 81b765b1d5d..fe7a9cab71f 100644 --- a/cloud/apps/sandbox-control/src/secrets.ts +++ b/cloud/apps/sandbox-control/src/secrets.ts @@ -48,6 +48,7 @@ export const AGENT_KEY_NAMES: ReadonlySet = new Set([ 'OPENAI_BASE_URL', 'OPENAI_MODEL', 'GOOGLE_GENERATIVE_AI_API_KEY', + 'COPILOT_GITHUB_TOKEN', 'COPILOT_PROVIDER_BASE_URL', 'COPILOT_PROVIDER_API_KEY', 'COPILOT_PROVIDER_BEARER_TOKEN', diff --git a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts index 801615fec1f..8a43ba9bc82 100644 --- a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts +++ b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts @@ -59,6 +59,22 @@ describe('credential routes for Gemini, Cursor and Copilot BYOK', () => { expect(credentialTargets(env, { COPILOT_PROVIDER_BASE_URL: 'user:mia', COPILOT_PROVIDER_API_KEY: 'org:acme' })).toEqual([]) }) + it('routes GOOGLE_API_KEY to the Gemini API and Vertex AI, and COPILOT_GITHUB_TOKEN to GitHub and the Copilot API', () => { + const targets = credentialTargets({ GOOGLE_API_KEY: GEMINI_KEY, COPILOT_GITHUB_TOKEN: COPILOT_KEY }) + expect(targets.map((t) => `${t.secret}@${t.host}${t.allowUnclaimed ? ' open' : ''}`)).toEqual([ + 'GOOGLE_API_KEY@generativelanguage.googleapis.com', + 'GOOGLE_API_KEY@aiplatform.googleapis.com', + 'COPILOT_GITHUB_TOKEN@api.github.com', + 'COPILOT_GITHUB_TOKEN@api.githubcopilot.com open', + 'COPILOT_GITHUB_TOKEN@api.individual.githubcopilot.com open', + 'COPILOT_GITHUB_TOKEN@api.business.githubcopilot.com open', + 'COPILOT_GITHUB_TOKEN@api.enterprise.githubcopilot.com open' + ]) + // Several hosts per credential survive the row encoding. + const row = { egress_secret_hosts: encodeEgressSecretHosts(targets) } + expect(egressSecretHosts(row).map((t) => `${t.secret}@${t.host}`)).toEqual(targets.map((t) => `${t.secret}@${t.host}`)) + }) + it('round-trips through the row with the policy taken from code, never from the row', () => { const row = { egress_secret_hosts: encodeEgressSecretHosts(credentialTargets({ CURSOR_API_KEY: CURSOR_KEY, GEMINI_API_KEY: GEMINI_KEY })) @@ -174,6 +190,24 @@ describe('egress swap on a sandbox with the new keys', () => { expect(logs.some((line) => line.includes('"event":"egress_swap"') && line.includes('"credential":"GEMINI_API_KEY"'))).toBe(true) }) + it('Copilot token: swapped on api.github.com next to the workspace token, in Bearer or gh-style token form', async () => { + const { h, id, send, upstream } = await setup() + const mia = await h.token('mia', undefined, 'sandbox') + expect((await h.call('PUT', '/v1/secrets/personal/COPILOT_GITHUB_TOKEN', { body: { value: COPILOT_KEY }, bearer: mia })).status).toBe(200) + const ph = `orca-ph-copilot-github-token-${id}` + const policy = [...h.vercel.boxes.values()][0]!.policy + const values = policy.allow['api.github.com']!.flatMap((rule) => ('match' in rule && rule.match?.headers ? [rule.match.headers[0]!.value.exact] : [])) + expect(values).toEqual(expect.arrayContaining([`Bearer ${ph}`, `token ${ph}`, `Bearer orca-ph-${id}`])) + expect(policy.allow['api.github.com']!.at(-1)).toEqual(DENY) + expect(policy.allow['api.individual.githubcopilot.com']!.some((rule) => 'response' in rule)).toBe(false) + for (const header of [`Bearer ${ph}`, `token ${ph}`]) { + expect((await send('api.github.com', 'GET', '/copilot_internal/user', { authorization: header })).status).toBe(200) + expect(upstream.at(-1)!.headers.get('authorization')).toBe(`Bearer ${COPILOT_KEY}`) + } + expect((await send('api.individual.githubcopilot.com', 'POST', '/chat/completions', { authorization: `Bearer ${ph}` })).status).toBe(200) + expect(upstream.at(-1)!.url).toBe('https://api.individual.githubcopilot.com/chat/completions') + }) + it('Cursor: only the key exchange carries the key, and the refresh token never reaches the VM', async () => { const { id, send, upstream, setReply } = await setup() setReply(() => new Response(JSON.stringify({ accessToken: 'at-short', refreshToken: 'rt-long-lived' }), { status: 200, headers: { 'content-type': 'application/json', 'content-length': '60' } })) diff --git a/cloud/apps/sandbox-control/test/routines.test.ts b/cloud/apps/sandbox-control/test/routines.test.ts index 82f3c51c1d8..7fa4f9eb95d 100644 --- a/cloud/apps/sandbox-control/test/routines.test.ts +++ b/cloud/apps/sandbox-control/test/routines.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { ORCA_CLOUD_IMAGE_AGENTS } from '../../../../src/shared/hosted-sandbox/orca-cloud-image-agents' import type { GitHubAppMinter } from '../src/github-app' import type { RunCommandParams } from '../src/sandbox-provider' import { redactLog } from '../src/routines/vm-runner' @@ -199,6 +200,26 @@ describe('routine runs (state machine on the fake provider)', () => { ]) }) + it('runs every agent the image ships, headless, and refuses any other', async () => { + const h = await harness() + for (const agent of ORCA_CLOUD_IMAGE_AGENTS) { + const created = await h.create({ name: `r-${agent}`, agent }) + expect(created.status, agent).toBe(201) + expect(created.body.routine.agent).toBe(agent) + const run = (await h.call('POST', `/v1/routines/${created.body.routine.id}/run`)).body.run + await h.tick() + const start = h.runnerCalls.find((c) => c.mode === 'start' && c.args.includes(run.id))! + expect(start.args[5]).toBe(agent) + // The worker has a headless command for it (an unknown agent ends as unknown_agent). + expect(start.args.at(-1)).toMatch(new RegExp(`^${agent}\\)$`, 'm')) + h.runs.set(run.id, h.done()) + await h.tick() + } + expect((await h.create({ agent: 'aider' })).body.reason).toMatch(/^agent/) + const routine = (await h.create({ name: 'patch-me' })).body.routine + expect((await h.call('PATCH', `/v1/routines/${routine.id}`, { body: { agent: 'gemini' } })).body.routine.agent).toBe('gemini') + }) + it('pr mode: falls back to opening the PR from the control plane when gh did not report one', async () => { const h = await harness() const routine = (await h.create({ postResults: 'pr' })).body.routine diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx index adfe8708936..af301a4084e 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from 'react' +import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' import { CalendarClock, Github, @@ -161,9 +162,7 @@ export function RoutineRow({ {where ? · {where} : null} {' · '} - {routine.agent === 'codex' - ? t('auto.components.settings.cloudRoutines.agentCodex', 'Codex') - : t('auto.components.settings.cloudRoutines.agentClaude', 'Claude Code')} + {formatAgentTypeLabel(routine.agent)} {viewerUserId && routine.createdBy !== viewerUserId ? ( diff --git a/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx b/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx index 5d571c3e1e4..6e81a411bc8 100644 --- a/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx +++ b/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx @@ -1,12 +1,29 @@ import { useId } from 'react' import { Input } from '@/components/ui/input' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from '@/components/ui/select' import { Textarea } from '@/components/ui/textarea' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls' import { FormField } from './cloud-api-parts' +import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' +import { + ROUTINE_AGENTS, + type RoutineAgent +} from '../../../../../shared/cloud-api/cloud-api-routine-types' import type { RoutineDraft, RoutineDraftField } from './routine-draft' +/** The Select hands back a string; only the image's agents are routine agents. */ +export function agentFrom(value: string): RoutineAgent { + return ROUTINE_AGENTS.find((agent) => agent === value) ?? 'claude' +} + export function routineFieldError( code: string | undefined, field: RoutineDraftField, @@ -84,23 +101,22 @@ export function RoutineAgentSection({

    {t('auto.components.settings.cloudRoutines.editor.agent', 'Agent')}

    - - size="sm" - value={draft.agent} - onChange={(agent) => update({ agent })} - equalWidth - ariaLabelledBy={`${ids}-agent`} - options={[ - { - value: 'claude', - label: t('auto.components.settings.cloudRoutines.agentClaude', 'Claude Code') - }, - { - value: 'codex', - label: t('auto.components.settings.cloudRoutines.agentCodex', 'Codex') - } - ]} - /> +
    {t('cloudSecrets.editor.help', 'Write-only. You won’t see it again after saving.')} + {cloudSecretStoredOnVm(name.trim()) ? ( + <> + {' '} + {cloudSecretVmWarning(t)} + + ) : null}

    )}
    diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx index ce73e1dd2bc..3ce9c10baad 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx @@ -14,6 +14,7 @@ import { cloudSecretKindLabel, cloudSecretsErrorCopy } from './cloud-secrets-cop import { CloudSecretEditor, type CloudSecretEditorTarget } from './CloudSecretEditor' import { CloudApiEmptyState } from '../cloud-api/cloud-api-parts' import { CloudSecretsPasteEnv } from './CloudSecretsPasteEnv' +import { CloudSecretVmBadge } from './CloudSecretVmBadge' import type { CloudSecretListModel } from './use-cloud-secrets' export type CloudSecretPeople = { @@ -85,6 +86,7 @@ function SecretRow({ {cloudSecretKindLabel(secret.name, t)} ) : null} + {maskedHint(secret.hint)} diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretVmBadge.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretVmBadge.tsx new file mode 100644 index 00000000000..51a4596b8db --- /dev/null +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretVmBadge.tsx @@ -0,0 +1,27 @@ +import { TriangleAlert } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { cloudSecretStoredOnVm } from '../../../../../shared/cloud-secrets/cloud-secret-rules' +import { Badge } from '../../ui/badge' + +/** Marks a key the workspace VM holds in full (it can't be swapped at egress), never silently. */ +export function CloudSecretVmBadge({ name }: { name: string }): React.JSX.Element | null { + const t = useTranslate() + if (!cloudSecretStoredOnVm(name)) { + return null + } + const why = cloudSecretVmWarning(t) + return ( + + + {t('cloudSecrets.vm.badge', 'Stored on workspace')} + {why} + + ) +} + +export function cloudSecretVmWarning(t: ReturnType): string { + return t( + 'cloudSecrets.vm.warning', + 'Orca can’t swap this key at the network edge, so cloud workspaces get the real value. Anything running in the workspace can read it.' + ) +} diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx index c534e8a0275..e2c19391871 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx @@ -5,6 +5,7 @@ import type { CloudSecretsEffective } from '../../../../../shared/cloud-secrets/cloud-secrets-wire' import { Badge } from '../../ui/badge' +import { CloudSecretVmBadge } from './CloudSecretVmBadge' import { InlineError } from '../../ui/inline-error' import { Skeleton } from '../../ui/skeleton' import { CloudApiEmptyState } from '../cloud-api/cloud-api-parts' @@ -132,6 +133,7 @@ export function CloudSecretsEffectiveView({ {cloudSecretKindLabel(secret.name, t)} ) : null} + diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx index de3a8341635..e1f9577b3be 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx @@ -12,6 +12,7 @@ import { type DotenvPasteIssue } from '../../../../../shared/cloud-secrets/dotenv-paste' import { Badge } from '../../ui/badge' +import { CloudSecretVmBadge } from './CloudSecretVmBadge' import { Button } from '../../ui/button' import { Input } from '../../ui/input' import { cloudSecretKindLabel, cloudSecretsErrorCopy } from './cloud-secrets-copy' @@ -176,6 +177,7 @@ export function PasteRowEditor({ {row.name && cloudSecretKind(row.name) === 'agent_key' ? ( {cloudSecretKindLabel(row.name, t)} ) : null} + {row.name ? : null} {removeButton}

    ", "lastRun": "Last run:", "neverRun": "Never run", @@ -26826,6 +26824,10 @@ "unterminatedQuote": "The closing quote is missing.", "overridden": "Set again further down; the later line is used.", "unknown": "Something went wrong in Orca Cloud. Nothing was changed. Try again." + }, + "vm": { + "badge": "Stored on workspace", + "warning": "Orca can’t swap this key at the network edge, so cloud workspaces get the real value. Anything running in the workspace can read it." } }, "cloudMcpSync": { diff --git a/src/shared/cloud-api/cloud-api-routine-types.ts b/src/shared/cloud-api/cloud-api-routine-types.ts index c92d4a52013..39f8109580b 100644 --- a/src/shared/cloud-api/cloud-api-routine-types.ts +++ b/src/shared/cloud-api/cloud-api-routine-types.ts @@ -1,5 +1,6 @@ // Orca Cloud routines: /v1/routines wire shapes and the editor's request bodies. import { z } from 'zod' +import { ORCA_CLOUD_IMAGE_AGENTS } from '../hosted-sandbox/orca-cloud-image-agents' import { HttpsUrl, Id, Millis, PersonName, ShortText } from './cloud-api-primitives' // ── Routines ──────────────────────────────────────────────────────────────── @@ -14,7 +15,8 @@ export const ROUTINE_GITHUB_EVENTS = [ ] as const export type RoutineGithubEvent = (typeof ROUTINE_GITHUB_EVENTS)[number] -export const ROUTINE_AGENTS = ['claude', 'codex'] as const +/** A routine runs any agent the Orca Cloud image ships, headless. */ +export const ROUTINE_AGENTS = ORCA_CLOUD_IMAGE_AGENTS export type RoutineAgent = (typeof ROUTINE_AGENTS)[number] export const ROUTINE_POST_RESULTS = ['none', 'comment', 'pr'] as const export type RoutinePostResults = (typeof ROUTINE_POST_RESULTS)[number] diff --git a/src/shared/cloud-secrets/cloud-secret-rules.ts b/src/shared/cloud-secrets/cloud-secret-rules.ts index d0595f63135..8f94494857c 100644 --- a/src/shared/cloud-secrets/cloud-secret-rules.ts +++ b/src/shared/cloud-secrets/cloud-secret-rules.ts @@ -29,9 +29,31 @@ const AGENT_KEY_NAMES: ReadonlySet = new Set([ 'CLAUDE_CODE_USE_VERTEX', 'ANTHROPIC_VERTEX_PROJECT_ID', 'CLOUD_ML_REGION', - 'GOOGLE_CLOUD_PROJECT' + 'GOOGLE_CLOUD_PROJECT', + 'GOOGLE_GENERATIVE_AI_API_KEY', + 'COPILOT_GITHUB_TOKEN', + 'COPILOT_PROVIDER_BASE_URL', + 'COPILOT_PROVIDER_API_KEY', + 'COPILOT_PROVIDER_BEARER_TOKEN', + 'COPILOT_MODEL' ]) +/** + * Agent keys the egress proxy cannot swap, so the workspace VM holds the real value: AWS requests + * are signed in the VM (SigV4) with the secret key, and Bedrock API keys are not routed yet. Every + * other agent key reaches the VM only as a placeholder. Mirrors the control plane's swap list. + */ +const STORED_ON_VM_NAMES: ReadonlySet = new Set([ + 'AWS_ACCESS_KEY_ID', + 'AWS_SECRET_ACCESS_KEY', + 'AWS_SESSION_TOKEN', + 'AWS_BEARER_TOKEN_BEDROCK' +]) + +export function cloudSecretStoredOnVm(name: string): boolean { + return STORED_ON_VM_NAMES.has(name) +} + const RESERVED_NAMES: ReadonlySet = new Set([ 'PATH', 'HOME', diff --git a/src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts b/src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts new file mode 100644 index 00000000000..9752af884d4 --- /dev/null +++ b/src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { cloudSecretKind, cloudSecretStoredOnVm } from './cloud-secret-rules' + +describe('agent keys the workspace VM holds in full', () => { + it('marks only the AWS keys, which the egress proxy cannot swap', () => { + for (const name of [ + 'AWS_ACCESS_KEY_ID', + 'AWS_SECRET_ACCESS_KEY', + 'AWS_SESSION_TOKEN', + 'AWS_BEARER_TOKEN_BEDROCK' + ]) { + expect(cloudSecretStoredOnVm(name)).toBe(true) + } + for (const name of [ + 'ANTHROPIC_API_KEY', + 'GEMINI_API_KEY', + 'GOOGLE_API_KEY', + 'CURSOR_API_KEY', + 'COPILOT_GITHUB_TOKEN', + 'DATABASE_URL', + 'AWS_REGION' + ]) { + expect(cloudSecretStoredOnVm(name)).toBe(false) + } + }) + + it('treats the new agent credentials as agent keys (shared beats personal)', () => { + for (const name of [ + 'GOOGLE_GENERATIVE_AI_API_KEY', + 'COPILOT_GITHUB_TOKEN', + 'COPILOT_PROVIDER_API_KEY', + 'COPILOT_PROVIDER_BASE_URL' + ]) { + expect(cloudSecretKind(name)).toBe('agent_key') + } + }) +}) From df8927b7f56d9efc90fa1a0df06a4c67310ce18c Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:13:11 -0800 Subject: [PATCH 08/46] fix(cloud): security review: Copilot token limited to Copilot's GitHub endpoints; routine summaries are final messages with session secrets redacted; untrusted context capped - COPILOT_GITHUB_TOKEN on api.github.com: GET /user and GET /copilot_internal/* only (normalized paths; dot or encoded segments refused); the Copilot API hosts are unchanged. It resolves like an env variable (personal beats team): it is one person's GitHub identity. - Routine summaries for opencode (JSON events), cursor (JSON result) and copilot (--silent) are the agent's final message, and every summary has the session's secret values replaced before it can be posted as a comment or PR body. - Webhook/GitHub context in a routine prompt is capped at 48 KiB (compact, then cut), so a prompt passed as one argv entry stays under Linux's 128 KiB limit. - A test fails if an agent credential is neither swapped nor marked 'Stored on workspace'. --- cloud/apps/sandbox-control/src/index.ts | 16 +++++++--- .../apps/sandbox-control/src/provider-env.ts | 21 +++++++++--- .../apps/sandbox-control/src/routines/runs.ts | 25 +++++++++++++++ .../sandbox-control/src/routines/vm-runner.ts | 18 +++++++++-- cloud/apps/sandbox-control/src/secrets.ts | 1 - .../test/agent-credentials-more.test.ts | 32 ++++++++++++++++++- .../cloud-secrets/cloud-secret-rules.ts | 1 - .../cloud-secret-stored-on-vm.test.ts | 5 +-- 8 files changed, 102 insertions(+), 17 deletions(-) diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 35f1ba4f133..790bebc5fca 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -94,7 +94,7 @@ import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from ' import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh' import { EgressHostsSchema, egressUserHosts, normalizeUserHosts, setEgressUserHosts } from './egress-hosts' import { cachedProviderEnv } from './session-env' -import { credentialTargets } from './provider-env' +import { credentialTargets, type CredentialTarget } from './provider-env' import type { Keyring } from './secrets-crypto' import { ProviderError, type SandboxProviderApi } from './sandbox-provider' import { DesktopCommandError, VmCommandError, startDesktop } from './sandbox-vm-commands' @@ -293,11 +293,17 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => } } -/** Exact method and path (the query string is ignored). */ -function requestMatches(allowed: readonly { method: string; path: string }[]): (method: string, path: string) => boolean { +/** Method and path (the query string is ignored); a prefix entry matches below a normalized path only. */ +function requestMatches(allowed: NonNullable): (method: string, path: string) => boolean { return (method, path) => { - const pathname = path.split('?')[0] - return allowed.some((entry) => entry.method === method.toUpperCase() && entry.path === pathname) + const pathname = path.split('?')[0] ?? '' + // A prefix grant never stretches across encoded or dot segments into another API. + const plain = /^(\/[A-Za-z0-9._~-]+)+\/?$/.test(pathname) && !/(^|\/)\.\.?(\/|$)/.test(pathname) + return allowed.some( + (entry) => + entry.method === method.toUpperCase() && + (entry.prefix ? plain && pathname.startsWith(entry.path) : entry.path === pathname) + ) } } diff --git a/cloud/apps/sandbox-control/src/provider-env.ts b/cloud/apps/sandbox-control/src/provider-env.ts index f92adff6897..2c766282f92 100644 --- a/cloud/apps/sandbox-control/src/provider-env.ts +++ b/cloud/apps/sandbox-control/src/provider-env.ts @@ -89,8 +89,8 @@ export type CredentialTarget = { } & CredentialPolicy export type CredentialPolicy = { - /** Only these requests may carry the key (exact method, path up to an optional query). Absent: any. */ - paths?: readonly { method: string; path: string }[] + /** Only these requests may carry the key (method, then the path up to its query: exact, or a prefix). Absent: any. */ + paths?: readonly { method: string; path: string; prefix?: true }[] /** * The host stays reachable without the placeholder. Cursor trades the key for a short-lived access * token and sends that on every later call, so a 403 for unclaimed requests would break it. @@ -114,6 +114,8 @@ export type ValueScopes = Readonly> type CredentialSpec = CredentialPolicy & { /** Hosts (of the default ones) that stay open without the placeholder. */ allowUnclaimedHosts?: readonly string[] + /** Per-host request limits, over `paths`. */ + pathsByHost?: Readonly>> secret: string /** Env var that may point this key at a custom host (honoured only from the key's own scope). */ baseUrl?: string @@ -167,7 +169,15 @@ const CREDENTIALS: readonly CredentialSpec[] = [ defaultHosts: ['api.github.com', ...COPILOT_API_HOSTS], headers: { authorization: bearer }, altHeaderFormats: { authorization: [(value: string) => `token ${value}`] }, - allowUnclaimedHosts: [...COPILOT_API_HOSTS] + allowUnclaimedHosts: [...COPILOT_API_HOSTS], + // On GitHub's API the user's token checks Copilot access and nothing else: the rest of the API + // (repos, gists, ...) stays out of reach of whatever runs in the workspace. + pathsByHost: { + 'api.github.com': [ + { method: 'GET', path: '/user' }, + { method: 'GET', path: '/copilot_internal/', prefix: true } + ] + } }, { secret: 'COPILOT_PROVIDER_API_KEY', @@ -192,7 +202,7 @@ export function credentialShape(secret: string): Omit if (!spec) { return null } - const { baseUrl: _baseUrl, defaultHosts: _defaultHosts, allowUnclaimedHosts: _openHosts, ...shape } = spec + const { baseUrl: _baseUrl, defaultHosts: _defaultHosts, allowUnclaimedHosts: _openHosts, pathsByHost: _paths, ...shape } = spec return shape } @@ -221,7 +231,8 @@ export function credentialTarget(secret: string, host: string): CredentialTarget } const { allowUnclaimed: _open, ...rest } = shape const open = spec.allowUnclaimed || spec.allowUnclaimedHosts?.includes(host) - return { ...rest, ...(open ? { allowUnclaimed: true as const } : {}), host } + const paths = spec.pathsByHost?.[host] ?? spec.paths + return { ...rest, ...(open ? { allowUnclaimed: true as const } : {}), ...(paths ? { paths } : {}), host } } /** Where each model credential in `env` is used, so the egress proxy can swap it in on those hosts only. */ diff --git a/cloud/apps/sandbox-control/src/routines/runs.ts b/cloud/apps/sandbox-control/src/routines/runs.ts index 534eaaec818..4af4ed04593 100644 --- a/cloud/apps/sandbox-control/src/routines/runs.ts +++ b/cloud/apps/sandbox-control/src/routines/runs.ts @@ -114,6 +114,23 @@ function detailOf(run: RunRow): RunDetail { } } +/** Untrusted context in a prompt, in UTF-8 bytes; the whole prompt stays far below one argv entry's 128 KiB. */ +export const MAX_CONTEXT_BYTES = 48 * 1024 + +function truncateUtf8(text: string, maxBytes: number): string { + let bytes = 0 + let end = 0 + for (const char of text) { + const size = new TextEncoder().encode(char).length + if (bytes + size > maxBytes) { + break + } + bytes += size + end += char.length + } + return text.slice(0, end) +} + /** The agent's full prompt: the routine's prompt, what happens to its output, and fenced untrusted context. */ export function composePrompt(routine: Pick, detail: RunDetail): string { const parts = [routine.prompt.trim()] @@ -128,6 +145,14 @@ export function composePrompt(routine: Pick MAX_CONTEXT_BYTES) { + context = JSON.stringify(detail.context) + } + if (new TextEncoder().encode(context).length > MAX_CONTEXT_BYTES) { + context = `${truncateUtf8(context, MAX_CONTEXT_BYTES)}\n[truncated]` + } // A payload cannot close the fence early. context = context.replaceAll('', '<\\/untrusted_context>') parts.push( diff --git a/cloud/apps/sandbox-control/src/routines/vm-runner.ts b/cloud/apps/sandbox-control/src/routines/vm-runner.ts index 72e0a0538e5..aaf9f5c93a9 100644 --- a/cloud/apps/sandbox-control/src/routines/vm-runner.ts +++ b/cloud/apps/sandbox-control/src/routines/vm-runner.ts @@ -97,8 +97,10 @@ codex) ;; opencode) # "--" ends the flags, so a prompt starting with "-" stays the message. - timeout --kill-after=20 "$limit" opencode run --auto -- "$(cat "$D/prompt.txt")" \ + timeout --kill-after=20 "$limit" opencode run --auto --format json -- "$(cat "$D/prompt.txt")" \ >"$D/agent.out" 2>"$D/agent.err" /dev/null | head -c 6000)" ;; gemini) # --prompt=TEXT, not "-p TEXT": a prompt starting with "-" would read as a flag. @@ -108,16 +110,28 @@ gemini) if [ "$code" = 0 ] && [ -n "$(jq -r '.error // empty' "$D/agent.out" 2>/dev/null)" ]; then code=1; fi ;; cursor) - timeout --kill-after=20 "$limit" cursor-agent --print --force --trust --output-format text -- "$(cat "$D/prompt.txt")" \ + timeout --kill-after=20 "$limit" cursor-agent --print --force --trust --output-format json -- "$(cat "$D/prompt.txt")" \ >"$D/agent.out" 2>"$D/agent.err" /dev/null | head -c 6000)" ;; copilot) + # --silent: only the agent's response, no tool output or stats. timeout --kill-after=20 "$limit" copilot --allow-all --silent --prompt="$(cat "$D/prompt.txt")" \ >"$D/agent.out" 2>"$D/agent.err" /dev/null || true)" ;; *) code=2; note=unknown_agent; finish ;; esac [ -n "$summary" ] || summary="$(tail -c 2000 "$D/agent.out" 2>/dev/null || true)" +# The summary can be posted publicly (comment / PR body): no session secret value leaves in it, even +# one an agent printed (AWS keys and plain env secrets are real values in this VM). +summary="$(ORCA_SUMMARY="$summary" node -e ' +let s = process.env.ORCA_SUMMARY || "" +for (const name of (process.env.ORCA_SESSION_ENV_NAMES || "").split(/\s+/)) { + const value = process.env[name] + if (value && value.length >= 8) s = s.split(value).join("[redacted]") +} +process.stdout.write(s)' 2>/dev/null)" || summary="" echo "routine: agent exit $code" if [ "$code" = 0 ] && [ "$post" = pr ] && [ -n "$start_sha" ]; then git add -A >/dev/null 2>&1 || true diff --git a/cloud/apps/sandbox-control/src/secrets.ts b/cloud/apps/sandbox-control/src/secrets.ts index fe7a9cab71f..81b765b1d5d 100644 --- a/cloud/apps/sandbox-control/src/secrets.ts +++ b/cloud/apps/sandbox-control/src/secrets.ts @@ -48,7 +48,6 @@ export const AGENT_KEY_NAMES: ReadonlySet = new Set([ 'OPENAI_BASE_URL', 'OPENAI_MODEL', 'GOOGLE_GENERATIVE_AI_API_KEY', - 'COPILOT_GITHUB_TOKEN', 'COPILOT_PROVIDER_BASE_URL', 'COPILOT_PROVIDER_API_KEY', 'COPILOT_PROVIDER_BEARER_TOKEN', diff --git a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts index 8a43ba9bc82..f0234531168 100644 --- a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts +++ b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts @@ -4,7 +4,9 @@ import { SignJWT, createLocalJWKSet, exportJWK, generateKeyPair } from 'jose' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { compileNetworkPolicy } from '../src/network-policy' -import { credentialTargets } from '../src/provider-env' +import { SWAPPED_CREDENTIALS, credentialTargets } from '../src/provider-env' +import { AGENT_KEY_NAMES } from '../src/secrets' +import { cloudSecretStoredOnVm } from '../../../../src/shared/cloud-secrets/cloud-secret-rules' import { egressSecretHosts, encodeEgressSecretHosts } from '../src/secret-egress' import { ENV_COMMAND } from '../src/sandbox-vm-commands' import { createHarness } from './harness' @@ -204,6 +206,20 @@ describe('egress swap on a sandbox with the new keys', () => { expect((await send('api.github.com', 'GET', '/copilot_internal/user', { authorization: header })).status).toBe(200) expect(upstream.at(-1)!.headers.get('authorization')).toBe(`Bearer ${COPILOT_KEY}`) } + expect((await send('api.github.com', 'GET', '/user', { authorization: `Bearer ${ph}` })).status).toBe(200) + // The rest of GitHub's API is out of reach of the user's token, however the path is dressed up. + const sent = upstream.length + for (const [method, path] of [ + ['GET', '/user/repos'], + ['POST', '/copilot_internal/user'], + ['GET', '/copilot_internal/../user/repos'], + ['GET', '/copilot_internal/%2e%2e/user/repos'], + ['GET', '/copilot_internal//../gists'], + ['DELETE', '/repos/acme/app'] + ]) { + expect(await send('api.github.com', method!, path!, { authorization: `Bearer ${ph}` }), path).toEqual({ status: 403, body: 'path_not_allowed' }) + } + expect(upstream).toHaveLength(sent) expect((await send('api.individual.githubcopilot.com', 'POST', '/chat/completions', { authorization: `Bearer ${ph}` })).status).toBe(200) expect(upstream.at(-1)!.url).toBe('https://api.individual.githubcopilot.com/chat/completions') }) @@ -258,3 +274,17 @@ describe('egress swap on a sandbox with the new keys', () => { expect(JSON.stringify(env)).not.toContain(COPILOT_KEY) }) }) + +describe('every agent credential is either swapped or marked "stored on workspace"', () => { + it('leaves no agent key reaching the VM raw without the warning', () => { + const settings = /(_MODEL|_BASE_URL|_REGION|_PROJECT|_PROJECT_ID)$|^CLAUDE_CODE_USE_/ + for (const name of AGENT_KEY_NAMES) { + if (settings.test(name)) { + continue + } + const swapped = SWAPPED_CREDENTIALS.includes(name) + expect(swapped !== cloudSecretStoredOnVm(name), `${name}: swapped=${swapped}`).toBe(true) + } + expect(SWAPPED_CREDENTIALS.includes('COPILOT_GITHUB_TOKEN')).toBe(true) + }) +}) diff --git a/src/shared/cloud-secrets/cloud-secret-rules.ts b/src/shared/cloud-secrets/cloud-secret-rules.ts index 8f94494857c..b40e0351dca 100644 --- a/src/shared/cloud-secrets/cloud-secret-rules.ts +++ b/src/shared/cloud-secrets/cloud-secret-rules.ts @@ -31,7 +31,6 @@ const AGENT_KEY_NAMES: ReadonlySet = new Set([ 'CLOUD_ML_REGION', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_GENERATIVE_AI_API_KEY', - 'COPILOT_GITHUB_TOKEN', 'COPILOT_PROVIDER_BASE_URL', 'COPILOT_PROVIDER_API_KEY', 'COPILOT_PROVIDER_BEARER_TOKEN', diff --git a/src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts b/src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts index 9752af884d4..d75820f39a9 100644 --- a/src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts +++ b/src/shared/cloud-secrets/cloud-secret-stored-on-vm.test.ts @@ -24,14 +24,15 @@ describe('agent keys the workspace VM holds in full', () => { } }) - it('treats the new agent credentials as agent keys (shared beats personal)', () => { + it('treats the new agent credentials as agent keys (shared beats personal), except a personal GitHub token', () => { for (const name of [ 'GOOGLE_GENERATIVE_AI_API_KEY', - 'COPILOT_GITHUB_TOKEN', 'COPILOT_PROVIDER_API_KEY', 'COPILOT_PROVIDER_BASE_URL' ]) { expect(cloudSecretKind(name)).toBe('agent_key') } + // One person's GitHub token: a personal value wins over a team one. + expect(cloudSecretKind('COPILOT_GITHUB_TOKEN')).toBe('env') }) }) From 42b5d606567ae8e22b7453f15032f41c083cdc11 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:14:30 -0800 Subject: [PATCH 09/46] style: one import for cloud-secret-rules --- .../components/settings/cloud-secrets/CloudSecretEditor.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx index 79e202c8fb1..631319eb2d2 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx @@ -1,12 +1,11 @@ import { useId, useState } from 'react' -import { cloudSecretStoredOnVm } from '../../../../../shared/cloud-secrets/cloud-secret-rules' -import { cloudSecretVmWarning } from './CloudSecretVmBadge' import { Loader2 } from 'lucide-react' import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' import { cloudSecretNameError, - cloudSecretValueError + cloudSecretValueError, + cloudSecretStoredOnVm } from '../../../../../shared/cloud-secrets/cloud-secret-rules' import type { CloudSecretsErrorCode } from '../../../../../shared/cloud-secrets/cloud-secrets-wire' import { Button } from '../../ui/button' @@ -14,6 +13,7 @@ import { Input } from '../../ui/input' import { Label } from '../../ui/label' import { cloudSecretsErrorCopy } from './cloud-secrets-copy' import { SecretValueInput } from './SecretValueInput' +import { cloudSecretVmWarning } from './CloudSecretVmBadge' const NAME_EXAMPLE = 'DATABASE_URL' From 92142679a514873b157cec719adf71d122607b74 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:17:30 -0800 Subject: [PATCH 10/46] refactor(cloud): one classifyEntitlementDenial in src/shared/orca-billing.ts (DS-23); run-on access, build failure, build log, workspace errors and the phone keep their own wording --- mobile/src/cloud/cloud-entitlement-copy.ts | 35 ++++++++-------- .../cloud-workspace-errors.ts | 6 ++- .../orca-cloud-run-target-access.ts | 18 ++++---- .../worktree-creation/orca-cloud-build-log.ts | 34 +++++++-------- .../worktree-creation/vm-build-failure.ts | 27 ++++++++---- src/shared/orca-billing-denial.test.ts | 23 ++++++++++ src/shared/orca-billing.ts | 42 +++++++++++++++++++ 7 files changed, 129 insertions(+), 56 deletions(-) create mode 100644 src/shared/orca-billing-denial.test.ts diff --git a/mobile/src/cloud/cloud-entitlement-copy.ts b/mobile/src/cloud/cloud-entitlement-copy.ts index b62e90662e8..c015fbd7165 100644 --- a/mobile/src/cloud/cloud-entitlement-copy.ts +++ b/mobile/src/cloud/cloud-entitlement-copy.ts @@ -1,3 +1,7 @@ +import { + classifyEntitlementDenial, + type OrcaEntitlementDenialKind +} from '../../../src/shared/orca-billing' import type { Translate } from '../i18n/mobile-i18n' import { readCloudRole, @@ -13,25 +17,20 @@ import { CloudRequestError, type CloudControlPlane } from './cloud-control-plane type Denial = 'hours' | 'cap' | 'payment' | 'plan' | 'teamLimit' | 'memberLimit' | 'other' +// The shared classifier names the category; the phone keeps its own wording per category. +const DENIALS: Record = { + plan: 'plan', + hours: 'hours', + spendCap: 'cap', + payment: 'payment', + teamLimit: 'teamLimit', + memberLimit: 'memberLimit', + machineSize: 'other', + other: 'other' +} + function denialOf(reason: string | undefined): Denial { - switch (reason) { - case 'included_hours_exhausted': - return 'hours' - case 'overage_cap_reached': - return 'cap' - case 'payment_past_due': - case 'payment_grace_expired': - return 'payment' - case 'no_subscription': - case 'subscription_inactive': - return 'plan' - case 'concurrency_limit': - return 'teamLimit' - case 'member_concurrency_limit': - return 'memberLimit' - default: - return 'other' - } + return DENIALS[classifyEntitlementDenial(reason)] } export function isEntitlementDenied(error: unknown): error is CloudRequestError { diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts index f363391ec86..71e03df197d 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts @@ -3,6 +3,7 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { getLastBillingStatus } from '@/components/billing/billing-summary-store' import { sandboxLimitFromBilling } from '@/components/worktree-creation/vm-build-failure-copy' +import { classifyEntitlementDenial } from '../../../../shared/orca-billing' /** * Whose seat a start counts against. The per-seat running cap counts the workspace owner's seat, @@ -23,7 +24,8 @@ export function describeError( ) } if (error === 'entitlement_denied') { - if (reason === 'concurrency_limit') { + const denial = classifyEntitlementDenial(reason) + if (denial === 'teamLimit') { const limit = sandboxLimitFromBilling(getLastBillingStatus()) return limit ? t( @@ -36,7 +38,7 @@ export function describeError( "You're at your team's limit of running sandboxes. Put one to sleep or delete it, then try again." ) } - if (reason === 'member_concurrency_limit') { + if (denial === 'memberLimit') { return describeSeatLimit(owner, t) } return t( diff --git a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts index e1aca15b052..fffd884bb82 100644 --- a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts +++ b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts @@ -5,6 +5,7 @@ import { cancelOrcaCloudSelectionAfterSignIn, requestOrcaCloudSelectionAfterSignIn } from '@/lib/orca-cloud-select-after-sign-in' +import { classifyEntitlementDenial } from '../../../../shared/orca-billing' /** Signing in from the row selects Orca Cloud once main offers it (the recipe list reloads). */ function signInThenSelectOrcaCloud(): void { @@ -54,19 +55,16 @@ export function toOrcaCloudRunTargetAccess( } } const { canManageBilling } = entitlement - switch (entitlement.reason) { - case 'included_hours_exhausted': + switch (classifyEntitlementDenial(entitlement.reason)) { + case 'hours': return { state: 'out-of-hours', cause: 'hours', canManageBilling } - case 'overage_cap_reached': + case 'spendCap': return { state: 'out-of-hours', cause: 'cap', canManageBilling } - case 'payment_past_due': - case 'payment_grace_expired': + case 'payment': return { state: 'payment-issue', canManageBilling } - case 'subscription_inactive': - return { state: 'no-plan', lapsed: true } - case 'no_subscription': - case null: - return { state: 'no-plan', lapsed: false } + default: + // No plan (or a reason this build doesn't know): the plan is what fixes it. + return { state: 'no-plan', lapsed: entitlement.reason === 'subscription_inactive' } } } diff --git a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts index 3e593a14c8c..5b506859cbd 100644 --- a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts +++ b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts @@ -1,4 +1,5 @@ import type { Translate } from '@/i18n/use-translate' +import { classifyEntitlementDenial } from '../../../../shared/orca-billing' // The hosted provider writes `[orca-cloud] ` progress, `Orca Cloud: ` and a few // fixed transport messages. Everything else is provider internals that the plain view hides. @@ -59,51 +60,50 @@ function phaseLabel(phase: string, t: Translate): string | null { } function denyLabel(reason: string, t: Translate): string | null { - switch (reason) { - case 'no plan': - case 'no_subscription': - case 'subscription_inactive': + // Not a plan refusal, so not in the shared classifier. + if (reason === 'github_not_connected') { + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyGithub', + 'GitHub isn’t connected to your Orca account.' + ) + } + switch (classifyEntitlementDenial(reason)) { + case 'plan': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.denyNoPlan', 'Your account has no active Team plan.' ) - case 'included_hours_exhausted': + case 'hours': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.denyHours2', 'Your team is out of sandbox hours this month.' ) - case 'overage_cap_reached': + case 'spendCap': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.denySpendCap', 'This month’s spend cap is reached.' ) - case 'payment_past_due': - case 'payment_grace_expired': + case 'payment': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.denyPayment2', 'Payment failed.' ) - case 'concurrency_limit': + case 'teamLimit': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.denyConcurrency2', 'You’re at your team’s limit of running sandboxes.' ) - case 'member_concurrency_limit': + case 'memberLimit': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.denyMemberConcurrency2', 'You’re at your limit of running sandboxes.' ) - case 'github_not_connected': - return t( - 'auto.components.worktree.creation.orcaCloudBuildLog.denyGithub', - 'GitHub isn’t connected to your Orca account.' - ) - case 'machine_size_not_in_plan': + case 'machineSize': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.denyMachineSize2', 'This sandbox size isn’t part of your plan.' ) - default: + case 'other': return null } } diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.ts index db4a9bb6bef..623a60829e9 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.ts @@ -1,5 +1,9 @@ import type { EnvironmentDoctorCheck } from '../../../../shared/environment-doctor-types' import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import { + classifyEntitlementDenial, + type OrcaEntitlementDenialKind +} from '../../../../shared/orca-billing' /** Account and service problems a plain-language card can name, each with one way forward. */ export type VmBuildAccountFailureKind = @@ -36,14 +40,14 @@ const ERROR_CODE_KINDS: Partial> = { // The hosted provider logs the control plane's deny reason as `Orca Cloud: `. const DENY_REASON = /^Orca Cloud: ([a-z_]+)$/m -const DENY_REASON_KINDS: Partial> = { - included_hours_exhausted: 'hoursUsed', - overage_cap_reached: 'spendCap', - payment_past_due: 'payment', - payment_grace_expired: 'payment', - concurrency_limit: 'concurrency', - member_concurrency_limit: 'memberConcurrency' -} +const DENIAL_FAILURE_KINDS: Partial> = + { + hours: 'hoursUsed', + spendCap: 'spendCap', + payment: 'payment', + teamLimit: 'concurrency', + memberLimit: 'memberConcurrency' + } const SNAPSHOT_MISSING = /\bsnapshot\b[^\n]*\bnot found\b/i const NETWORK_FAILURE = @@ -69,7 +73,12 @@ export function classifyVmBuildFailure(args: { const coded = entry.errorCode ? ERROR_CODE_KINDS[entry.errorCode] : undefined if (coded === 'plan' || coded === 'concurrency') { const reason = DENY_REASON.exec(entry.provisioningLog ?? '')?.[1] - return { kind: (reason === undefined ? undefined : DENY_REASON_KINDS[reason]) ?? coded } + return { + kind: + (reason === undefined + ? undefined + : DENIAL_FAILURE_KINDS[classifyEntitlementDenial(reason)]) ?? coded + } } if (coded) { return { kind: coded } diff --git a/src/shared/orca-billing-denial.test.ts b/src/shared/orca-billing-denial.test.ts new file mode 100644 index 00000000000..3202b13ede2 --- /dev/null +++ b/src/shared/orca-billing-denial.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { classifyEntitlementDenial } from './orca-billing' + +describe('classifyEntitlementDenial', () => { + it('maps every billing and start-gate reason to one category', () => { + expect(classifyEntitlementDenial('no_subscription')).toBe('plan') + expect(classifyEntitlementDenial('subscription_inactive')).toBe('plan') + expect(classifyEntitlementDenial('no plan')).toBe('plan') + expect(classifyEntitlementDenial('included_hours_exhausted')).toBe('hours') + expect(classifyEntitlementDenial('overage_cap_reached')).toBe('spendCap') + expect(classifyEntitlementDenial('payment_past_due')).toBe('payment') + expect(classifyEntitlementDenial('payment_grace_expired')).toBe('payment') + expect(classifyEntitlementDenial('concurrency_limit')).toBe('teamLimit') + expect(classifyEntitlementDenial('member_concurrency_limit')).toBe('memberLimit') + expect(classifyEntitlementDenial('machine_size_not_in_plan')).toBe('machineSize') + }) + + it('falls back to other for unknown or missing reasons', () => { + expect(classifyEntitlementDenial('something_new')).toBe('other') + expect(classifyEntitlementDenial(undefined)).toBe('other') + expect(classifyEntitlementDenial(null)).toBe('other') + }) +}) diff --git a/src/shared/orca-billing.ts b/src/shared/orca-billing.ts index 4c35cffabfa..b6a11e7aede 100644 --- a/src/shared/orca-billing.ts +++ b/src/shared/orca-billing.ts @@ -16,6 +16,48 @@ export type OrcaBillingDenyReason = | 'included_hours_exhausted' | 'overage_cap_reached' +/** + * What a plan refusal means, whatever surface shows it. Billing's account reasons plus the control + * plane's start-gate reasons (concurrency, machine size) map to one category; each surface keeps its + * own wording for the category. Unknown reasons (a newer service) fall to `other`. + */ +export type OrcaEntitlementDenialKind = + | 'plan' + | 'hours' + | 'spendCap' + | 'payment' + | 'teamLimit' + | 'memberLimit' + | 'machineSize' + | 'other' + +export function classifyEntitlementDenial( + reason: string | null | undefined +): OrcaEntitlementDenialKind { + // 'no plan' is the hosted provider's older log line for a missing plan. + switch (reason) { + case 'no_subscription': + case 'subscription_inactive': + case 'no plan': + return 'plan' + case 'included_hours_exhausted': + return 'hours' + case 'overage_cap_reached': + return 'spendCap' + case 'payment_past_due': + case 'payment_grace_expired': + return 'payment' + case 'concurrency_limit': + return 'teamLimit' + case 'member_concurrency_limit': + return 'memberLimit' + case 'machine_size_not_in_plan': + return 'machineSize' + default: + return 'other' + } +} + export type OrcaBillingOffers = { team: { label: string From 10a9c7e3a3b3d531368b8a4e70b0938558a4786e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:19:23 -0800 Subject: [PATCH 11/46] fix(cloud): exhaustive switches over the denial classifier --- .../new-workspace/orca-cloud-run-target-access.ts | 9 +++++++-- src/shared/orca-billing.ts | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts index fffd884bb82..53d7af107cf 100644 --- a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts +++ b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts @@ -62,8 +62,13 @@ export function toOrcaCloudRunTargetAccess( return { state: 'out-of-hours', cause: 'cap', canManageBilling } case 'payment': return { state: 'payment-issue', canManageBilling } - default: - // No plan (or a reason this build doesn't know): the plan is what fixes it. + // Billing's account answer never carries the start-gate reasons; anything else is no plan, + // which the plan fixes. + case 'plan': + case 'teamLimit': + case 'memberLimit': + case 'machineSize': + case 'other': return { state: 'no-plan', lapsed: entitlement.reason === 'subscription_inactive' } } } diff --git a/src/shared/orca-billing.ts b/src/shared/orca-billing.ts index b6a11e7aede..07a0249772e 100644 --- a/src/shared/orca-billing.ts +++ b/src/shared/orca-billing.ts @@ -53,6 +53,9 @@ export function classifyEntitlementDenial( return 'memberLimit' case 'machine_size_not_in_plan': return 'machineSize' + case null: + case undefined: + return 'other' default: return 'other' } From 298fbc7cfa2c860bb2a90a847a0d29a8bf4533f0 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:20:25 -0800 Subject: [PATCH 12/46] fix(cloud): DS-38 read-only header marker, queued caption alignment, offline poll catch --- .../offline/CloudOfflineChatPanel.tsx | 10 ++++++---- .../offline/CloudWorkspaceOfflineView.tsx | 4 ++-- .../offline/use-cloud-offline-data.ts | 19 ++++++++++++++----- .../read-snapshot/CloudReadSnapshotView.tsx | 4 ++-- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx b/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx index e4ac3c77f54..652d8815bd7 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx @@ -69,17 +69,19 @@ function QueuedPromptRow({ {prompt.text} )} -

    +
    {prompt.state === 'sending' ? ( - + ) : null} {label} {prompt.error ? ` · ${prompt.error}` : ''} {prompt.state === 'queued' && !editing ? ( - // Quiet until the bubble is hovered or a control has focus. - + // Quiet until the bubble is hovered or a control has focus. Collapsed to no width while + // hidden so the caption sits flush right; still focusable (never display:none), and + // focusing a control expands it. + + ) : null} + + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx index 1f37128ced1..c217e1546be 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx @@ -109,8 +109,11 @@ export function AccessLinks({ export function OrgSettings({ settings, - onToggle + onToggle, + blocked = false }: { + /** The page shows one load error; this section stays quiet instead of repeating it. */ + blocked?: boolean settings: CloudLoadState onToggle: (enabled: boolean) => Promise }): React.JSX.Element { @@ -158,7 +161,7 @@ export function OrgSettings({ ) : null}

    - {settings.status === 'error' ? ( + {settings.status === 'error' && !blocked ? ( ) : null} {error ? : null} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx index e2498455926..9a428951663 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx @@ -1,8 +1,9 @@ import { useRef, useState } from 'react' import { toast } from 'sonner' -import { KeyRound, Plus, RefreshCw, Trash2 } from 'lucide-react' +import { KeyRound, Plus, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' -import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { InlineError } from '@/components/ui/inline-error' +import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import type { CloudApiApproval, @@ -24,12 +25,10 @@ import { CloudConfirmDialog } from './CloudConfirmDialog' import { CloudConnectedApps } from './CloudConnectedApps' import type { CloudLoadState } from './cloud-load-state' import { CreateApiKeyDialog } from './CreateApiKeyDialog' -import { formatAbsoluteTime, formatKeyPrefix, formatRelativeFromNow } from './cloud-api-format' +import { formatKeyPrefix } from './cloud-api-format' import { PersonSentence } from './PersonName' -import { ScopeSummary } from './ScopeSummary' -import { CloudApiEmptyState, CloudApiErrorNotice, CloudApiSkeletonRows } from './cloud-api-parts' - -const EXPIRY_WARNING_MS = 7 * 86_400_000 +import { CloudApiEmptyState, CloudApiSkeletonRows } from './cloud-api-parts' +import { KeyRow } from './ApiKeyRow' export type CloudApiKeysViewProps = { controlPlaneUrl: string @@ -119,8 +118,22 @@ export function CloudApiKeysView(props: CloudApiKeysViewProps): React.JSX.Elemen ) + // One failure, one message: a load error is shown once at the top, not in every section. + const pageError = keys.status === 'error' ? keys.message : null + return (
    + {pageError ? ( + + ) : null} ) : keys.status === 'error' ? ( -
    - -
    +

    + {t( + 'auto.components.settings.cloudApi.keys.unavailable', + 'Your keys appear here once Orca Cloud is reachable.' + )} +

    ) : keys.data.keys.length === 0 ? ( setApproveOpen(true)} /> - setApproveOpen(true)} - onRevoke={props.onRevokeGrant} - onRetry={props.onRefreshGrants} - initialRevokeId={initial?.revokeGrantId} - /> - - - - {props.audit ? ( - + setApproveOpen(true)} + onRevoke={props.onRevokeGrant} + onRetry={props.onRefreshGrants} + initialRevokeId={initial?.revokeGrantId} /> - ) : null} + + + + {props.audit ? ( + + ) : null} +
    ) } - -function KeyRow({ - apiKey, - viewer, - now, - onRevoke -}: { - apiKey: CloudApiKey - viewer: CloudApiMe | null - now: number - onRevoke: () => void -}): React.JSX.Element { - const t = useTranslate() - const locale = useIntlLocale() - const mine = viewer?.userId === apiKey.createdBy - const expiresSoon = apiKey.expiresAt !== null && apiKey.expiresAt - now < EXPIRY_WARNING_MS - const created = formatRelativeFromNow(apiKey.createdAt, now, locale) - return ( -
  • -
    -
    -

    - {apiKey.name} -

    - - {formatKeyPrefix(apiKey.prefix)} - - -
    -

    - - · - - {apiKey.lastUsedAt - ? t('auto.components.settings.cloudApi.keys.lastUsed', 'Last used {{time}}', { - time: formatRelativeFromNow(apiKey.lastUsedAt, now, locale) - }) - : t('auto.components.settings.cloudApi.keys.neverUsed', 'Never used')} - - {apiKey.expiresAt !== null ? ( - <> - · - - {apiKey.expiresAt <= now - ? t('auto.components.settings.cloudApi.keys.expired', 'Expired') - : t('auto.components.settings.cloudApi.keys.expires', 'Expires {{time}}', { - time: formatRelativeFromNow(apiKey.expiresAt, now, locale) - })} - - - ) : null} -

    -
    - -
  • - ) -} diff --git a/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx b/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx index 9a7b3ba9886..0032ed310d3 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx @@ -32,7 +32,8 @@ export function CloudConnectedApps({ onApprove, onRevoke, onRetry, - initialRevokeId + initialRevokeId, + blocked = false }: { grants: CloudLoadState viewer: CloudApiMe | null @@ -41,6 +42,8 @@ export function CloudConnectedApps({ onRevoke: (grant: CloudApiGrant) => Promise onRetry: () => void initialRevokeId?: string + /** The page shows one load error; this section stays quiet instead of repeating it. */ + blocked?: boolean }): React.JSX.Element | null { const t = useTranslate() const locale = useIntlLocale() @@ -81,9 +84,18 @@ export function CloudConnectedApps({ label={t('auto.components.settings.cloudApi.apps.loading', 'Loading connected apps')} /> ) : grants.status === 'error' ? ( -
    - -
    + blocked ? ( +

    + {t( + 'auto.components.settings.cloudApi.apps.unavailable', + 'Connected apps appear here once Orca Cloud is reachable.' + )} +

    + ) : ( +
    + +
    + ) ) : grants.data.length === 0 ? ( ({ ok: true, data: RUNS }) + +/** Every failure code the control plane sends, as people read it (codes never on screen). */ +const FAILED_RUNS: RoutineRunPage = { + nextBefore: null, + runs: [ + run({ + id: 'f1', + status: 'failed', + startedAt: NOW - 1 * HOUR, + durationMs: 21_000, + error: 'start_failed:clone_failed' + }), + run({ + id: 'f2', + status: 'failed', + startedAt: NOW - 3 * HOUR, + durationMs: 412_000, + error: 'workspace_lost:suspended' + }), + run({ + id: 'f3', + status: 'failed', + startedAt: NOW - 5 * HOUR, + durationMs: 380_000, + error: 'post_failed:github_403' + }), + run({ + id: 'f4', + status: 'cancelled', + startedAt: NOW - 8 * HOUR, + durationMs: null, + error: 'queue_expired' + }), + run({ + id: 'f5', + status: 'failed', + startedAt: NOW - 12 * HOUR, + durationMs: 95_000, + error: 'agent_interrupted' + }), + run({ + id: 'f6', + status: 'cancelled', + startedAt: NOW - 20 * HOUR, + durationMs: null, + error: 'routine_changed' + }), + run({ + id: 'f7', + status: 'failed', + startedAt: NOW - 26 * HOUR, + durationMs: 4_000, + error: 'something_new' + }) + ] +} +const loadFailedRuns: LoadRoutineRuns = async () => ({ ok: true, data: FAILED_RUNS }) const loadNoRuns: LoadRoutineRuns = async () => ({ ok: true, data: { runs: [], nextBefore: null } }) const loadRunsFailing: LoadRoutineRuns = async () => ({ ok: false, error: 'network' }) @@ -311,3 +367,10 @@ export const deleteConfirm = defineFixture({ width: 820, render: () => }) + +export const runHistoryFailures = defineFixture({ + width: 820, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx b/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx index fde74e2ca53..e7e0487156c 100644 --- a/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx +++ b/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx @@ -9,7 +9,7 @@ import type { RoutineRun, RoutineRunPage } from '../../../../../shared/cloud-api/cloud-api-types' -import { cloudApiErrorCopy, routineRunTriggerLabel } from './cloud-api-copy' +import { cloudApiErrorCopy, routineRunErrorCopy, routineRunTriggerLabel } from './cloud-api-copy' import { formatAbsoluteTime, formatRelativeFromNow, formatRunDuration } from './cloud-api-format' import { CloudApiErrorNotice, RoutineRunStatusPill } from './cloud-api-parts' import { isActiveRunStatus } from './routine-run-status' @@ -309,14 +309,7 @@ function RunRow({ {run.result?.summary ? (

    {run.result.summary}

    ) : null} - {run.error ? ( -

    - - {t('auto.components.settings.cloudRoutines.runs.why', 'Why:')} - {' '} - {run.error} -

    - ) : null} + {run.error ? : null} ) } diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts index 9cf5ce3d993..be4aef1ab5d 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts @@ -170,3 +170,48 @@ export function routineRunTriggerLabel( return t('auto.components.settings.cloudRoutines.runTrigger.manual', 'Manual') } } + +/** + * A run's failure in plain words. The control plane sends a code, sometimes with detail after a + * colon ("workspace_lost:suspended"); codes and detail never reach the screen. + */ +export function routineRunErrorCopy(error: string, t: Translate = translate): string { + const code = error.split(':', 1)[0]?.trim() ?? '' + if (code === 'start_failed') { + return t( + 'auto.components.settings.cloudRoutines.runError.startFailed', + 'The workspace couldn’t start. Nothing was charged.' + ) + } + if (code === 'workspace_lost') { + return t( + 'auto.components.settings.cloudRoutines.runError.workspaceLost', + 'The workspace went to sleep or was deleted before the run finished.' + ) + } + if (code === 'post_failed') { + return t( + 'auto.components.settings.cloudRoutines.runError.postFailed', + 'The run finished, but Orca couldn’t post the results.' + ) + } + if (code === 'queue_expired') { + return t( + 'auto.components.settings.cloudRoutines.runError.queueExpired', + 'The run waited too long to start and was skipped.' + ) + } + if (code.endsWith('_interrupted')) { + return t( + 'auto.components.settings.cloudRoutines.runError.interrupted', + 'Orca Cloud restarted during the run.' + ) + } + if (code === 'routine_changed') { + return t( + 'auto.components.settings.cloudRoutines.runError.routineChanged', + 'The routine changed while this run was queued.' + ) + } + return t('auto.components.settings.cloudRoutines.runError.generic', 'The run failed.') +} diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts index 1312784f4ab..732a5a90d85 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { CLOUD_API_SCOPES } from '../../../../../shared/cloud-api/cloud-api-types' -import { cloudApiErrorCopy, routineRunTone } from './cloud-api-copy' +import { cloudApiErrorCopy, routineRunErrorCopy, routineRunTone } from './cloud-api-copy' import { describeRoutineTrigger, formatCountdown, @@ -83,3 +83,25 @@ describe('copy', () => { expect(routineRunTone('cancelled')).toBe('neutral') }) }) + +describe('run failure copy', () => { + it('maps control-plane codes (with detail) to plain words and never shows the code', () => { + expect(routineRunErrorCopy('start_failed:clone_failed')).toBe( + 'The workspace couldn’t start. Nothing was charged.' + ) + expect(routineRunErrorCopy('workspace_lost:suspended')).toBe( + 'The workspace went to sleep or was deleted before the run finished.' + ) + expect(routineRunErrorCopy('post_failed')).toBe( + 'The run finished, but Orca couldn’t post the results.' + ) + expect(routineRunErrorCopy('queue_expired')).toBe( + 'The run waited too long to start and was skipped.' + ) + expect(routineRunErrorCopy('agent_interrupted')).toBe('Orca Cloud restarted during the run.') + expect(routineRunErrorCopy('routine_changed')).toBe( + 'The routine changed while this run was queued.' + ) + expect(routineRunErrorCopy('totally_new:detail')).toBe('The run failed.') + }) +}) diff --git a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx index 7344db6d2ad..ef2ecb15032 100644 --- a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx +++ b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx @@ -71,9 +71,7 @@ function ServerRow({ {row.name}
    {mcpSyncRowStateLabel(row, t)} - - {AGENT_LABEL[row.agent]} - + {AGENT_LABEL[row.agent]} {row.target ? ( {row.target} diff --git a/src/renderer/src/hooks/useOrcaCloudApiAvailability.ts b/src/renderer/src/hooks/useOrcaCloudApiAvailability.ts index 6428cb32313..e431371914d 100644 --- a/src/renderer/src/hooks/useOrcaCloudApiAvailability.ts +++ b/src/renderer/src/hooks/useOrcaCloudApiAvailability.ts @@ -5,6 +5,7 @@ import type { CloudApiAvailability } from '../../../shared/cloud-api/cloud-api-t // Settings navigation and the panes share it, so the sections never flicker in and out. let availability: CloudApiAvailability | null = null let probing = false +const RETRY_MS = 5_000 const listeners = new Set<() => void>() function probe(): void { @@ -17,16 +18,20 @@ function probe(): void { return } probing = true - void bridge - .availability() - .catch((): CloudApiAvailability => ({ status: 'unconfigured' })) - .then((next) => { + void bridge.availability().then( + (next) => { availability = next probing = false for (const listener of listeners) { listener() } - }) + }, + () => { + // A failed probe is not "unconfigured": retry shortly instead of hiding the pages for good. + probing = false + setTimeout(probe, RETRY_MS) + } + ) } function subscribe(listener: () => void): () => void { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index a5e002c1791..11bf894ca4c 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -14259,7 +14259,38 @@ "needsAutoForward": "Turn on Auto-forward ports to change this.", "autoForwardDescriptionSandboxes": "Forward dev servers in sandboxes and on remote hosts to this computer." }, + "orcaCloudPredictiveWake": { + "title": "Wake sleeping workspaces early", + "description": "A sleeping cloud workspace starts waking when you point at it or come back to Orca, so it's ready sooner. If you don't open it, it goes back to sleep after the idle time.", + "group": "Orca Cloud", + "description_one": "Starts waking a sleeping sandbox when you point at its workspace or come back to Orca, so it's ready sooner. If you don't open it, it goes back to sleep after {{count}} minute idle. Early wakes count toward your sandbox hours.", + "description_other": "Starts waking a sleeping sandbox when you point at its workspace or come back to Orca, so it's ready sooner. If you don't open it, it goes back to sleep after {{count}} minutes idle. Early wakes count toward your sandbox hours." + }, "cloudApi": { + "keys": { + "createdMine": "Created {{time}}", + "createdByPerson": "Created by {{time}}", + "lastUsed": "Last used {{time}}", + "neverUsed": "Never used", + "expired": "Expired", + "expires": "Expires {{time}}", + "revokeLabel": "Revoke {{keyName}}", + "revoke": "Revoke", + "create": "Create key", + "listTitle": "Keys", + "scopeAdmin": "As a team admin you see every key on your team and can revoke any of them.", + "scopeMember": "You see the keys you created. Team admins see every key on the team.", + "scopePersonal": "Use keys with the Orca Cloud API, the orca CLI and MCP clients.", + "refresh": "Refresh Orca API keys", + "loading": "Loading Orca API keys", + "unavailable": "Your keys appear here once Orca Cloud is reachable.", + "emptyTitle": "No Orca API keys yet", + "emptyBody": "Create a key to start workspaces, message agents and run routines from scripts, CI or any MCP client.", + "listLabel": "Orca API keys", + "customScopeCount_one": "Custom · {{count}} scope", + "customScopeCount_other": "Custom · {{count}} scopes", + "scopesLabel": "{{preset}}: {{scopes}}" + }, "approve": { "title": "Approve an app", "description": "When Claude, Cursor or another MCP client opens the Orca Cloud approval page, paste a one-time code from here instead of an API key. That page shows which website the app will return to; check it before you paste.", @@ -14333,29 +14364,8 @@ "loading": "Loading activity", "empty": "Nothing has happened yet." }, - "keys": { - "create": "Create key", - "listTitle": "Keys", - "scopeAdmin": "As a team admin you see every key on your team and can revoke any of them.", - "scopeMember": "You see the keys you created. Team admins see every key on the team.", - "scopePersonal": "Use keys with the Orca Cloud API, the orca CLI and MCP clients.", - "refresh": "Refresh Orca API keys", - "loading": "Loading Orca API keys", - "emptyTitle": "No Orca API keys yet", - "emptyBody": "Create a key to start workspaces, message agents and run routines from scripts, CI or any MCP client.", - "listLabel": "Orca API keys", - "createdMine": "Created {{time}}", - "createdByPerson": "Created by {{time}}", - "lastUsed": "Last used {{time}}", - "neverUsed": "Never used", - "expired": "Expired", - "expires": "Expires {{time}}", - "revokeLabel": "Revoke {{keyName}}", - "revoke": "Revoke", - "customScopeCount_one": "Custom · {{count}} scope", - "customScopeCount_other": "Custom · {{count}} scopes", - "scopesLabel": "{{preset}}: {{scopes}}" - }, + "pageErrorDetail": "Keys, connected apps and team settings are unavailable until Orca Cloud answers.", + "retry": "Try again", "revoke": { "title": "Revoke “{{keyName}}”?", "body": "Anything using {{keyPrefix}} stops working immediately. This cannot be undone.", @@ -14370,13 +14380,13 @@ "body": "Orca API keys and routines belong to your team. Sign in to manage them.", "signIn": "Sign in to Orca" }, - "retry": "Try again", "apps": { "unnamed": "Unnamed app", "title": "Connected apps", "descriptionAdmin": "MCP clients anyone on your team approved. A connection lasts 90 days, or until you disconnect it or revoke the key that approved it.", "description": "MCP clients you approved. A connection lasts 90 days, or until you disconnect it or revoke the key that approved it.", "loading": "Loading connected apps", + "unavailable": "Connected apps appear here once Orca Cloud is reachable.", "emptyTitle": "No apps connected", "emptyBody": "Add the MCP server URL to Claude, Cursor or another client. When it asks you to approve, use a one-time code.", "listLabel": "Connected apps", @@ -14478,8 +14488,7 @@ "more": "Show older runs", "pr": "Pull request", "comment": "Comment", - "openWorkspace": "Open workspace", - "why": "Why:" + "openWorkspace": "Open workspace" }, "new": "New routine", "listTitle": "Your routines", @@ -14604,6 +14613,15 @@ "webhook": "Webhook", "manual": "Manual" }, + "runError": { + "startFailed": "The workspace couldn’t start. Nothing was charged.", + "workspaceLost": "The workspace went to sleep or was deleted before the run finished.", + "postFailed": "The run finished, but Orca couldn’t post the results.", + "queueExpired": "The run waited too long to start and was skipped.", + "interrupted": "Orca Cloud restarted during the run.", + "routineChanged": "The routine changed while this run was queued.", + "generic": "The run failed." + }, "event": { "prOpened": "PR opened", "prLabeled": "PR labeled", @@ -14621,13 +14639,6 @@ "keywordCloud": "cloud", "sectionTitle": "Routines", "sectionDescription": "Agents that run in Orca Cloud on a schedule, on GitHub events or from a webhook." - }, - "orcaCloudPredictiveWake": { - "title": "Wake sleeping workspaces early", - "description": "A sleeping cloud workspace starts waking when you point at it or come back to Orca, so it's ready sooner. If you don't open it, it goes back to sleep after the idle time.", - "group": "Orca Cloud", - "description_one": "Starts waking a sleeping sandbox when you point at its workspace or come back to Orca, so it's ready sooner. If you don't open it, it goes back to sleep after {{count}} minute idle. Early wakes count toward your sandbox hours.", - "description_other": "Starts waking a sleeping sandbox when you point at its workspace or come back to Orca, so it's ready sooner. If you don't open it, it goes back to sleep after {{count}} minutes idle. Early wakes count toward your sandbox hours." } }, "right": { @@ -20855,7 +20866,8 @@ "workspaceLinkCopied": "Workspace link copied", "you": "You", "youAreTyping": "You are typing", - "youAreViewing": "You are viewing" + "youAreViewing": "You are viewing", + "routines": "Routines" }, "orcaCloud": { "QueuedPrompt": { From 2cf08c221ea774de44f06eb50847933584bf5c45 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:22:07 -0800 Subject: [PATCH 14/46] fix(run-actions): follow cloud tabs adopted as web-terminal-, settle tab-list churn before forgetting a run, retire the dead tab after a relaunch; honor a host-pinned ORCA_PORT Found on a real Orca Cloud VM (m4air): a remote host adopts the run's tab under web-terminal-, so the run was pruned at once and Stop/status/relaunch lost it; a window reload's empty tab list pruned local runs too. Pruning now waits for the list to settle (3 s; 15 s after startup). A one-workspace host (the VM launcher sets ORCA_PORT=3000) keeps its pinned block. --- docs/site/content/docs/model/orca-yaml.mdx | 2 +- src/main/ipc/pty/spawn-pane-env.ts | 4 +- .../workspace-hooks/setup-hook-env-vars.ts | 4 +- .../workspace-port-block-registry.test.ts | 21 +++++++++- .../run-actions/RunActionButton.tsx | 3 +- .../src/lib/run-actions/run-action-config.ts | 7 +++- .../run-actions/run-action-controller.test.ts | 38 ++++++++++++++++--- .../lib/run-actions/run-action-controller.ts | 23 ++++++++--- .../src/lib/run-actions/run-action-events.ts | 33 ++++++++++++---- .../src/lib/run-actions/run-action-tabs.ts | 23 +++++++++++ .../src/lib/run-actions/run-actions-store.ts | 3 +- src/shared/workspace-port-block.ts | 20 ++++++++++ 12 files changed, 154 insertions(+), 27 deletions(-) create mode 100644 src/renderer/src/lib/run-actions/run-action-tabs.ts diff --git a/docs/site/content/docs/model/orca-yaml.mdx b/docs/site/content/docs/model/orca-yaml.mdx index 49bf4c2ca5a..fac76241fc4 100644 --- a/docs/site/content/docs/model/orca-yaml.mdx +++ b/docs/site/content/docs/model/orca-yaml.mdx @@ -133,7 +133,7 @@ scripts: - `autoRunAfterSetup` starts the action once the Setup terminal's script succeeds. - Shared `orca.yaml` actions go through the same approval prompt as setup scripts. Actions imported into local settings are treated as your own. -Every terminal in a worktree gets a stable block of 10 ports: `ORCA_PORT` through `ORCA_PORT+9` (`ORCA_PORT_COUNT` is `10`). Two worktrees on the same host never share a block, so the same dev server can run in each without port collisions. `CONDUCTOR_PORT` is set to the same value, so imported Conductor scripts work unchanged. Ports a run opens appear in the Run menu and the **Ports** panel. +Every terminal in a worktree gets a stable block of 10 ports: `ORCA_PORT` through `ORCA_PORT+9` (`ORCA_PORT_COUNT` is `10`). Two worktrees on the same host never share a block, so the same dev server can run in each without port collisions. `CONDUCTOR_PORT` is set to the same value, so imported Conductor scripts work unchanged. A host that runs a single workspace can pin the block by starting Orca with `ORCA_PORT` (and optionally `ORCA_PORT_COUNT`) set. Ports a run opens appear in the Run menu and the **Ports** panel. ### Terminal defaults and issue commands diff --git a/src/main/ipc/pty/spawn-pane-env.ts b/src/main/ipc/pty/spawn-pane-env.ts index e924857248a..6e435d5707e 100644 --- a/src/main/ipc/pty/spawn-pane-env.ts +++ b/src/main/ipc/pty/spawn-pane-env.ts @@ -8,6 +8,7 @@ import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/ import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-tab-id' import { buildWorkspacePortEnv, + hostPinnedPortBlock, WORKSPACE_PORT_ENV_KEYS } from '../../../shared/workspace-port-block' import { getWorkspacePortBlockForWorktreeId } from '../../workspace-ports/workspace-port-block-registry' @@ -95,7 +96,8 @@ export async function stampWorkspacePortEnv( return } try { - const block = await getWorkspacePortBlockForWorktreeId(worktreeId) + const block = + hostPinnedPortBlock(process.env) ?? (await getWorkspacePortBlockForWorktreeId(worktreeId)) if (block) { Object.assign(env, buildWorkspacePortEnv(block)) } diff --git a/src/main/workspace-hooks/setup-hook-env-vars.ts b/src/main/workspace-hooks/setup-hook-env-vars.ts index 94590520ad0..1b6d7762ec7 100644 --- a/src/main/workspace-hooks/setup-hook-env-vars.ts +++ b/src/main/workspace-hooks/setup-hook-env-vars.ts @@ -1,7 +1,7 @@ import { getRuntimePathBasename } from '../../shared/cross-platform-path' import { TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV } from '../../shared/shell/launch/terminal-git-credential-guard' import type { Repo } from '../../shared/repo-types' -import { buildWorkspacePortEnv } from '../../shared/workspace-port-block' +import { buildWorkspacePortEnv, hostPinnedPortBlock } from '../../shared/workspace-port-block' import { peekWorkspacePortBlock } from '../workspace-ports/workspace-port-block-registry' // Path-valued keys only, so WSL and posix-shell launches translate them; names are not paths. @@ -33,7 +33,7 @@ export function getSetupEnvVars( function getWorkspacePortEnv(worktreePath: string): Record { try { // Setup terminals get the block from their own spawn; this covers hook processes run directly. - const block = peekWorkspacePortBlock(worktreePath) + const block = hostPinnedPortBlock(process.env) ?? peekWorkspacePortBlock(worktreePath) return block ? buildWorkspacePortEnv(block) : {} } catch { return {} diff --git a/src/main/workspace-ports/workspace-port-block-registry.test.ts b/src/main/workspace-ports/workspace-port-block-registry.test.ts index 973187f1601..c422fe296c4 100644 --- a/src/main/workspace-ports/workspace-port-block-registry.test.ts +++ b/src/main/workspace-ports/workspace-port-block-registry.test.ts @@ -6,7 +6,8 @@ import { WORKSPACE_PORT_BLOCK_SIZE, WORKSPACE_PORT_RANGE_END, WORKSPACE_PORT_RANGE_START, - buildWorkspacePortEnv + buildWorkspacePortEnv, + hostPinnedPortBlock } from '../../shared/workspace-port-block' import { WorkspacePortBlockRegistry } from './workspace-port-block-registry' @@ -124,3 +125,21 @@ describe('peekBlock', () => { expect(new Set(blocks.map((block) => block.base)).size).toBe(20) }) }) + +describe('hostPinnedPortBlock', () => { + it('honors a launcher-pinned ORCA_PORT on a one-workspace host', () => { + expect(hostPinnedPortBlock({ ORCA_PORT: '3000' })).toEqual({ base: 3000, count: 10 }) + expect(hostPinnedPortBlock({ ORCA_PORT: '3000', ORCA_PORT_COUNT: '5' })).toEqual({ + base: 3000, + count: 5 + }) + }) + + it('ignores a block inherited from a parent Orca pane, and bad values', () => { + expect(hostPinnedPortBlock({ ORCA_PORT: '28570', ORCA_WORKTREE_ID: 'r::/w' })).toBeNull() + expect(hostPinnedPortBlock({ ORCA_PORT: '28570', ORCA_PANE_KEY: 't:l' })).toBeNull() + expect(hostPinnedPortBlock({ ORCA_PORT: 'abc' })).toBeNull() + expect(hostPinnedPortBlock({ ORCA_PORT: '80' })).toBeNull() + expect(hostPinnedPortBlock({})).toBeNull() + }) +}) diff --git a/src/renderer/src/components/run-actions/RunActionButton.tsx b/src/renderer/src/components/run-actions/RunActionButton.tsx index 9cfe1f9a49f..e803e5c5e41 100644 --- a/src/renderer/src/components/run-actions/RunActionButton.tsx +++ b/src/renderer/src/components/run-actions/RunActionButton.tsx @@ -13,6 +13,7 @@ import { startRunAction, stopRunAction } from '@/lib/run-actions/run-action-cont import { useWorktreeRunActionRuns, type RunActionRun } from '@/lib/run-actions/run-actions-store' import type { WorkspacePort } from '../../../../shared/workspace-ports' import { RunActionButtonView } from './RunActionButtonView' +import { findLiveRunTabId } from '@/lib/run-actions/run-action-tabs' const EMPTY_PORTS: WorkspacePort[] = [] @@ -57,7 +58,7 @@ function useWorktreePorts(worktreeId: string): WorkspacePort[] { function focusRunTab(run: RunActionRun): void { const state = useAppStore.getState() state.setActiveTabType('terminal', run.worktreeId) - state.setActiveTab(run.tabId) + state.setActiveTab(findLiveRunTabId(state, run.worktreeId, run.tabId) ?? run.tabId) } function openPortsPanel(): void { diff --git a/src/renderer/src/lib/run-actions/run-action-config.ts b/src/renderer/src/lib/run-actions/run-action-config.ts index 3ec0453eb8d..9d37f8aab13 100644 --- a/src/renderer/src/lib/run-actions/run-action-config.ts +++ b/src/renderer/src/lib/run-actions/run-action-config.ts @@ -34,7 +34,12 @@ export function resolveRunActionTarget( state: AppState, worktreeId: string ): RunActionTarget | null { - const worktree = findWorktreeById(state, worktreeId) + // The active-host hint can disagree for remote workspaces; fall back to the catalog row itself. + const worktree = + findWorktreeById(state, worktreeId) ?? + Object.values(state.worktreesByRepo ?? {}) + .flat() + .find((candidate) => candidate.id === worktreeId) if (!worktree) { return null } diff --git a/src/renderer/src/lib/run-actions/run-action-controller.test.ts b/src/renderer/src/lib/run-actions/run-action-controller.test.ts index e8bcb5463e7..d6fc27a7354 100644 --- a/src/renderer/src/lib/run-actions/run-action-controller.test.ts +++ b/src/renderer/src/lib/run-actions/run-action-controller.test.ts @@ -318,16 +318,44 @@ describe('run actions', () => { expect(getRunActionRun(WT_A, 'web')?.status).toBe('running') }) - it('forgets a run when its terminal is closed', async () => { + it('forgets a run only when its terminal is still gone after the tab list settles', async () => { await startRunAction(WT_A, web, config([web])) - const previous = { tabsByWorktree: { ...state.tabsByWorktree } } - state.tabsByWorktree = { [WT_A]: [] } - for (const listener of mocks.subscribers) { - listener(state, previous) + const { tabId } = getRunActionRun(WT_A, 'web')! + const notify = (): void => { + const previous = { tabsByWorktree: {} } + for (const listener of mocks.subscribers) { + listener(state, previous) + } } + // A window reload briefly shows an empty list, then the tab comes back: keep the run. + const kept = state.tabsByWorktree[WT_A] + state.tabsByWorktree = { [WT_A]: [] } + notify() + state.tabsByWorktree = { [WT_A]: kept } + await vi.advanceTimersByTimeAsync(16_000) + expect(getRunActionRun(WT_A, 'web')?.tabId).toBe(tabId) + // Really closed: gone after the settle delay. + state.tabsByWorktree = { [WT_A]: [] } + notify() + await vi.advanceTimersByTimeAsync(3_500) expect(getRunActionRun(WT_A, 'web')).toBeNull() }) + it('follows a run whose tab a remote host adopted under a web-terminal- id', async () => { + await startRunAction(WT_A, web, config([web])) + const { tabId } = getRunActionRun(WT_A, 'web')! + const adopted = `web-terminal-${tabId}` + state.tabsByWorktree = { [WT_A]: [{ id: adopted }] } + state.ptyIdsByTabId[adopted] = ['pty-adopted'] + for (const listener of mocks.subscribers) { + listener(state, { tabsByWorktree: {} }) + } + await vi.advanceTimersByTimeAsync(16_000) + expect(getRunActionRun(WT_A, 'web')?.status).toBe('running') + dispatchTerminalCommandFinishedEvent(WT_A, 2, adopted) + expect(getRunActionRun(WT_A, 'web')).toMatchObject({ status: 'failed', exitCode: 2 }) + }) + it('merges local actions over orca.yaml ones and filters by host', async () => { const remoteOnly: OrcaRunAction = { id: 'cloud', diff --git a/src/renderer/src/lib/run-actions/run-action-controller.ts b/src/renderer/src/lib/run-actions/run-action-controller.ts index b326da39784..9e4154a5407 100644 --- a/src/renderer/src/lib/run-actions/run-action-controller.ts +++ b/src/renderer/src/lib/run-actions/run-action-controller.ts @@ -20,10 +20,12 @@ import { type RunActionTarget, type WorktreeRunActions } from './run-action-config' +import { findLiveRunTabId, sameRunTab } from './run-action-tabs' /** Conductor's grace period: an interrupted dev server gets this long before its shell is closed. */ export const RUN_ACTION_STOP_GRACE_MS = 5_000 const INTERRUPT = '\x03' +const RELAUNCH_TAB_SETTLE_MS = 5_000 function joinWorkspacePath(root: string, relative: string | undefined): string | undefined { if (!relative) { @@ -34,21 +36,22 @@ function joinWorkspacePath(root: string, relative: string | undefined): string | } export function tabExists(state: AppState, worktreeId: string, tabId: string): boolean { - return (state.tabsByWorktree[worktreeId] ?? []).some((tab) => tab.id === tabId) + return findLiveRunTabId(state, worktreeId, tabId) !== null } function tabGroupId(state: AppState, worktreeId: string, tabId: string): string | undefined { return ( state.unifiedTabsByWorktree[worktreeId]?.find( - (tab) => tab.entityId === tabId && tab.contentType === 'terminal' + (tab) => sameRunTab(tab.entityId, tabId) && tab.contentType === 'terminal' )?.groupId ?? undefined ) } function closeRunTab(run: RunActionRun): void { const state = useAppStore.getState() - if (tabExists(state, run.worktreeId, run.tabId)) { - state.closeTab(run.tabId, { recordInteraction: false, captureRecentlyClosed: false }) + const liveTabId = findLiveRunTabId(state, run.worktreeId, run.tabId) + if (liveTabId) { + state.closeTab(liveTabId, { recordInteraction: false, captureRecentlyClosed: false }) } } @@ -97,8 +100,9 @@ async function stopRunActionOnce(worktreeId: string, actionId: string): Promise< return } const state = useAppStore.getState() - const ptyId = state.ptyIdsByTabId[run.tabId]?.[0] - if (!ptyId || !tabExists(state, worktreeId, run.tabId)) { + const liveTabId = findLiveRunTabId(state, worktreeId, run.tabId) + const ptyId = liveTabId ? state.ptyIdsByTabId[liveTabId]?.[0] : undefined + if (!ptyId) { deleteRunActionRun(worktreeId, actionId) return } @@ -314,6 +318,13 @@ export async function relaunchInterruptedRunActions(worktreeId: string): Promise }) if (ok) { started += 1 + // The restarted host republishes its old tabs after a moment; retire the dead run tab then. + setTimeout(() => { + const current = getRunActionRun(worktreeId, run.actionId) + if (!current || !sameRunTab(current.tabId, run.tabId)) { + closeRunTab(run) + } + }, RELAUNCH_TAB_SETTLE_MS) } } return started diff --git a/src/renderer/src/lib/run-actions/run-action-events.ts b/src/renderer/src/lib/run-actions/run-action-events.ts index b50452554ec..a29bdf4e3bb 100644 --- a/src/renderer/src/lib/run-actions/run-action-events.ts +++ b/src/renderer/src/lib/run-actions/run-action-events.ts @@ -16,6 +16,7 @@ import { patchRunActionRun } from './run-actions-store' import { loadWorktreeRunActions, pickPrimaryRunAction } from './run-action-config' +import { findLiveRunTabId, sameRunTab } from './run-action-tabs' import { isRunActionRelaunchArmed, notifyRunActionStopped, @@ -46,9 +47,10 @@ function handleCommandFinished(detail: TerminalCommandFinishedEventDetail): void if (!tabId) { return } - const setupWorktreeId = autoRunSetupTabs.get(tabId) - if (setupWorktreeId) { - autoRunSetupTabs.delete(tabId) + const setupTabId = [...autoRunSetupTabs.keys()].find((armed) => sameRunTab(armed, tabId)) + const setupWorktreeId = setupTabId ? autoRunSetupTabs.get(setupTabId) : undefined + if (setupTabId && setupWorktreeId) { + autoRunSetupTabs.delete(setupTabId) if (exitCode === 0) { void autoRunAfterSetup(setupWorktreeId) } @@ -76,14 +78,14 @@ function pruneClosedRunTabs(state: AppState): void { } const tabs = state.tabsByWorktree[run.worktreeId] // Unhydrated workspaces have no tab list yet; only a loaded list proves the tab is gone. - if (tabs && !tabs.some((tab) => tab.id === run.tabId)) { + if (tabs && !findLiveRunTabId(state, run.worktreeId, run.tabId)) { deleteRunActionRun(run.worktreeId, run.actionId) notifyRunActionStopped(run.tabId) } } for (const [tabId, worktreeId] of autoRunSetupTabs) { const tabs = state.tabsByWorktree[worktreeId] - if (tabs && !tabs.some((tab) => tab.id === tabId)) { + if (tabs && !findLiveRunTabId(state, worktreeId, tabId)) { autoRunSetupTabs.delete(tabId) } } @@ -97,10 +99,19 @@ export function installRunActionEvents(): () => void { } } window.addEventListener(ORCA_TERMINAL_COMMAND_FINISHED_EVENT, onFinished) + // Tab lists churn while a window hydrates or a host republishes its tabs: only a tab still + // missing after things settle was really closed. + let pruneTimer: ReturnType | null = null + const installedAt = Date.now() const unsubscribe = useAppStore.subscribe((state, previous) => { - if (state.tabsByWorktree !== previous.tabsByWorktree) { - pruneClosedRunTabs(state) + if (state.tabsByWorktree === previous.tabsByWorktree || pruneTimer) { + return } + const delay = Math.max(PRUNE_SETTLE_MS, installedAt + STARTUP_PRUNE_GRACE_MS - Date.now()) + pruneTimer = setTimeout(() => { + pruneTimer = null + pruneClosedRunTabs(useAppStore.getState()) + }, delay) }) // After a restart, a run recorded as running may have ended while nobody watched its terminal. const reconcileTimer = setTimeout( @@ -111,16 +122,22 @@ export function installRunActionEvents(): () => void { window.removeEventListener(ORCA_TERMINAL_COMMAND_FINISHED_EVENT, onFinished) unsubscribe() clearTimeout(reconcileTimer) + if (pruneTimer) { + clearTimeout(pruneTimer) + } } } const STARTUP_RECONCILE_MS = 5_000 +const PRUNE_SETTLE_MS = 3_000 +const STARTUP_PRUNE_GRACE_MS = 15_000 /** Local terminals can say whether anything still runs under the shell; remote ones are left as recorded. */ async function reconcileLocalRunsAfterStartup(): Promise { const state = useAppStore.getState() for (const run of listRunActionRuns()) { - const ptyId = state.ptyIdsByTabId[run.tabId]?.[0] + const liveTabId = findLiveRunTabId(state, run.worktreeId, run.tabId) + const ptyId = liveTabId ? state.ptyIdsByTabId[liveTabId]?.[0] : undefined if (run.status !== 'running' || !ptyId || getRemoteRuntimePtyOwner(ptyId)) { continue } diff --git a/src/renderer/src/lib/run-actions/run-action-tabs.ts b/src/renderer/src/lib/run-actions/run-action-tabs.ts new file mode 100644 index 00000000000..b1b00ee5471 --- /dev/null +++ b/src/renderer/src/lib/run-actions/run-action-tabs.ts @@ -0,0 +1,23 @@ +import type { AppState } from '@/store/types' + +/** A remote host adopts a tab the window created under `web-terminal-`; both name one tab. */ +const MIRRORED_TAB_PREFIX = 'web-terminal-' + +export function baseRunTabId(tabId: string): string { + return tabId.startsWith(MIRRORED_TAB_PREFIX) ? tabId.slice(MIRRORED_TAB_PREFIX.length) : tabId +} + +export function sameRunTab(a: string, b: string): boolean { + return baseRunTabId(a) === baseRunTabId(b) +} + +/** The id the run's tab has now, or null when the workspace no longer has it. */ +export function findLiveRunTabId( + state: Pick, + worktreeId: string, + tabId: string +): string | null { + return ( + (state.tabsByWorktree[worktreeId] ?? []).find((tab) => sameRunTab(tab.id, tabId))?.id ?? null + ) +} diff --git a/src/renderer/src/lib/run-actions/run-actions-store.ts b/src/renderer/src/lib/run-actions/run-actions-store.ts index 15230f8f563..efc60bcd67f 100644 --- a/src/renderer/src/lib/run-actions/run-actions-store.ts +++ b/src/renderer/src/lib/run-actions/run-actions-store.ts @@ -1,4 +1,5 @@ import { useSyncExternalStore } from 'react' +import { sameRunTab } from './run-action-tabs' /** `stopping` waits for the process to leave after an interrupt; `stopped` was the user's doing. */ export type RunActionStatus = 'running' | 'stopping' | 'stopped' | 'exited' | 'failed' @@ -112,7 +113,7 @@ export function listRunActionRuns(): RunActionRun[] { } export function findRunActionRunByTab(tabId: string): RunActionRun | null { - return listRunActionRuns().find((run) => run.tabId === tabId) ?? null + return listRunActionRuns().find((run) => sameRunTab(run.tabId, tabId)) ?? null } export function setRunActionRun(run: RunActionRun): void { diff --git a/src/shared/workspace-port-block.ts b/src/shared/workspace-port-block.ts index 761370ec365..26a6a4be34e 100644 --- a/src/shared/workspace-port-block.ts +++ b/src/shared/workspace-port-block.ts @@ -24,3 +24,23 @@ export function buildWorkspacePortEnv(block: WorkspacePortBlock): Record= block.base && port < block.base + block.count } + +/** + * A host that runs exactly one workspace (a VM launcher, say) may pin the block by starting Orca + * with ORCA_PORT set. A copy inherited from a parent Orca pane (it also carries pane identity) + * names that pane's workspace and doesn't count. + */ +export function hostPinnedPortBlock(env: NodeJS.ProcessEnv): WorkspacePortBlock | null { + if (env.ORCA_PANE_KEY || env.ORCA_WORKTREE_ID) { + return null + } + const base = Number(env.ORCA_PORT) + if (!Number.isInteger(base) || base < 1024 || base > 65535 - WORKSPACE_PORT_BLOCK_SIZE) { + return null + } + const count = Number(env.ORCA_PORT_COUNT) + return { + base, + count: Number.isInteger(count) && count > 0 && count <= 100 ? count : WORKSPACE_PORT_BLOCK_SIZE + } +} From 519f6f6c9b038290f2a2f7bd59bdb1ac8cb2a564 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:27:05 -0800 Subject: [PATCH 15/46] fix(billing): spell out price formats per DS-18 Line items: '{{seats}} x {{price}} per seat, billed yearly' / 'per seat per month' (plural keys); totals '{{total}} per year' / 'per month'; Worker plan labels '$50 per seat per month' and '$480 per seat, billed yearly'. Drops /mo, /yr, /year and /seat/month strings. --- cloud/apps/billing/src/plans.ts | 4 +-- .../apps/billing/test/billing-config.test.ts | 6 ++-- cloud/apps/billing/test/billing-flow.test.ts | 2 +- src/main/billing/billing-client.test.ts | 4 +-- .../billing/checkout/CheckoutPanel.tsx | 35 ++++++++++++------- .../billing/plan-billing-fixtures.ts | 4 +-- .../components/billing/plans/TeamPlanCard.tsx | 8 ++--- .../billing/team/TeamInviteComposer.tsx | 4 +-- .../billing/team/TeamPlanSummary.tsx | 6 ++-- .../src/i18n/en-runtime-required.json | 6 ++++ src/renderer/src/i18n/locales/en.json | 25 ++++++------- src/shared/orca-billing.ts | 2 +- 12 files changed, 61 insertions(+), 45 deletions(-) diff --git a/cloud/apps/billing/src/plans.ts b/cloud/apps/billing/src/plans.ts index 969e14cb847..e02a322e4f6 100644 --- a/cloud/apps/billing/src/plans.ts +++ b/cloud/apps/billing/src/plans.ts @@ -64,8 +64,8 @@ export type PlanCatalog = { team: TeamPlan; enterprise: EnterpriseOffer } export const DEFAULT_PLANS: PlanCatalog = { team: { label: 'Team', - monthlyPriceLabel: '$50/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$50 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', monthlyPriceCentsPerSeat: 5000, annualPriceCentsPerSeat: 48000, includedHoursPerSeat: 60, diff --git a/cloud/apps/billing/test/billing-config.test.ts b/cloud/apps/billing/test/billing-config.test.ts index 762173fb759..31a2e2b15a9 100644 --- a/cloud/apps/billing/test/billing-config.test.ts +++ b/cloud/apps/billing/test/billing-config.test.ts @@ -24,7 +24,7 @@ describe('config: tax and plan catalog', () => { it('takes Team numbers and labels and the Enterprise contact from BILLING_PLANS', async () => { const h = await createHarness({ BILLING_PLANS: JSON.stringify({ - team: { includedHoursPerSeat: 40, monthlyPriceLabel: '$45/seat/mo', defaultSpendCapCents: 5000 }, + team: { includedHoursPerSeat: 40, monthlyPriceLabel: '$45 per seat per month', defaultSpendCapCents: 5000 }, enterprise: { contactUrl: 'https://example.test/sales' } }) }) @@ -33,8 +33,8 @@ describe('config: tax and plan catalog', () => { expect(entitlement.body.offers).toEqual({ team: { label: 'Team', - monthlyPriceLabel: '$45/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$45 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', monthlyPriceCentsPerSeat: 5000, annualPriceCentsPerSeat: 48000, largeMachineWeight: 1, diff --git a/cloud/apps/billing/test/billing-flow.test.ts b/cloud/apps/billing/test/billing-flow.test.ts index 61605eb041e..baeb58d52bb 100644 --- a/cloud/apps/billing/test/billing-flow.test.ts +++ b/cloud/apps/billing/test/billing-flow.test.ts @@ -221,7 +221,7 @@ describe('entitlements, overage and usage', () => { canManageBilling: true, period: { start: PERIOD_START * 1000, end: PERIOD_END * 1000 } }) - expect(entitlement.body.offers.team).toMatchObject({ monthlyPriceLabel: '$50/seat/mo', annualPriceLabel: '$480/seat/yr' }) + expect(entitlement.body.offers.team).toMatchObject({ monthlyPriceLabel: '$50 per seat per month', annualPriceLabel: '$480 per seat, billed yearly' }) expect(entitlement.body.offers.enterprise).toMatchObject({ label: 'Enterprise', priceLabel: 'Custom' }) for (let i = 0; i < 4; i++) { diff --git a/src/main/billing/billing-client.test.ts b/src/main/billing/billing-client.test.ts index 1bf5c759c24..14d52ed8520 100644 --- a/src/main/billing/billing-client.test.ts +++ b/src/main/billing/billing-client.test.ts @@ -132,8 +132,8 @@ describe('billing client', () => { const offers = { team: { label: 'Team', - monthlyPriceLabel: '$50/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$50 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', includedHoursPerSeat: 60, concurrentSandboxesPerSeat: 3, idleSleepMinutes: 15, diff --git a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx index d3d50bb8f35..955e69bda54 100644 --- a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx +++ b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx @@ -8,7 +8,6 @@ import type { OrcaBillingOffers } from '../../../../../shared/orca-billing' import { openFailureCopy } from '../plan-billing-copy' import { formatCents, periodTotalCents } from '../plans/plans-pricing' import type { CheckoutPhase } from './checkout-flow' -import { seatCountLabel } from '../team/team-copy' export type CheckoutPanelProps = { phase: Exclude @@ -37,6 +36,7 @@ function OrderSummary({ renews.setMonth(renews.getMonth() + 1) } const renewsLabel = new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(renews) + const seatCount = new Intl.NumberFormat(locale).format(seats) return (
    @@ -52,18 +52,27 @@ function OrderSummary({
    {perSeat === null ? null - : t( - 'auto.components.billing.checkout.seatsTimes2', - '{{value0}} × {{value1}}{{value2}}', - { - value0: seatCountLabel(seats, t), - value1: formatCents(perSeat, locale), - value2: - interval === 'year' - ? t('auto.components.billing.checkout.perYr', '/yr') - : t('auto.components.billing.checkout.perMo', '/mo') - } - )} + : interval === 'year' + ? t( + 'auto.components.billing.checkout.lineItemYearly', + '{{seats}} × {{price}} per seat, billed yearly', + { + count: seats, + seats: seatCount, + price: formatCents(perSeat, locale), + defaultValue_one: '{{seats}} × {{price}} per seat, billed yearly' + } + ) + : t( + 'auto.components.billing.checkout.lineItemMonthly', + '{{seats}} × {{price}} per seat per month', + { + count: seats, + seats: seatCount, + price: formatCents(perSeat, locale), + defaultValue_one: '{{seats}} × {{price}} per seat per month' + } + )}
    diff --git a/src/renderer/src/components/billing/plan-billing-fixtures.ts b/src/renderer/src/components/billing/plan-billing-fixtures.ts index bed4b7c4667..1dc2a62e47b 100644 --- a/src/renderer/src/components/billing/plan-billing-fixtures.ts +++ b/src/renderer/src/components/billing/plan-billing-fixtures.ts @@ -7,8 +7,8 @@ const HOUR = 3600 export const sampleOffers: OrcaBillingOffers = { team: { label: 'Team', - monthlyPriceLabel: '$50/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$50 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', monthlyPriceCentsPerSeat: 5000, annualPriceCentsPerSeat: 48000, largeMachineWeight: 1, diff --git a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx index 5d91a56424c..1ab9d0ecbf8 100644 --- a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx +++ b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx @@ -130,11 +130,11 @@ export function TeamPlanCard({ {total === null ? null : (

    {interval === 'year' - ? t('auto.components.billing.plans.totalYear', '{{value0}} / year', { - value0: formatCents(total, locale) + ? t('auto.components.billing.plans.totalPerYear', '{{total}} per year', { + total: formatCents(total, locale) }) - : t('auto.components.billing.plans.totalMonth', '{{value0}} / month', { - value0: formatCents(total, locale) + : t('auto.components.billing.plans.totalPerMonth', '{{total}} per month', { + total: formatCents(total, locale) })}

    )} diff --git a/src/renderer/src/components/billing/team/TeamInviteComposer.tsx b/src/renderer/src/components/billing/team/TeamInviteComposer.tsx index 7eb546947e2..9aca7ee62cc 100644 --- a/src/renderer/src/components/billing/team/TeamInviteComposer.tsx +++ b/src/renderer/src/components/billing/team/TeamInviteComposer.tsx @@ -77,8 +77,8 @@ function impactCopy( const price = formatCents(impact.perSeatPeriodCents, locale) const then = impact.interval === 'year' - ? t('auto.components.billing.team.perYear', '{{value0}}/year', { value0: price }) - : t('auto.components.billing.team.perMonth', '{{value0}}/month', { value0: price }) + ? t('auto.components.billing.team.totalPerYear', '{{total}} per year', { total: price }) + : t('auto.components.billing.team.totalPerMonth', '{{total}} per month', { total: price }) if (count === 1) { const first = candidates[0]!.email.split('@')[0] ?? candidates[0]!.email return t( diff --git a/src/renderer/src/components/billing/team/TeamPlanSummary.tsx b/src/renderer/src/components/billing/team/TeamPlanSummary.tsx index 7b77ce5bb85..ecba2386576 100644 --- a/src/renderer/src/components/billing/team/TeamPlanSummary.tsx +++ b/src/renderer/src/components/billing/team/TeamPlanSummary.tsx @@ -246,9 +246,9 @@ export function TeamUpgradeCard({ 'Hosted sandboxes for the whole team. Agents keep running when you close your laptop.' ) : t( - 'auto.components.billing.upgrade.body2', - 'Hosted sandboxes for the whole team. Agents keep running when you close your laptop. {{value0}}/seat/month.', - { value0: formatCents(monthly, locale) } + 'auto.components.billing.upgrade.body3', + 'Hosted sandboxes for the whole team. Agents keep running when you close your laptop. {{price}} per seat per month.', + { price: formatCents(monthly, locale) } )}

    {entitlement.canManageBilling ? null : ( diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index fb5e777f89e..41616a25b9b 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -205,6 +205,12 @@ } }, "billing": { + "checkout": { + "lineItemMonthly_one": "{{seats}} × {{price}} per seat per month", + "lineItemMonthly_other": "{{seats}} × {{price}} per seat per month", + "lineItemYearly_one": "{{seats}} × {{price}} per seat, billed yearly", + "lineItemYearly_other": "{{seats}} × {{price}} per seat, billed yearly" + }, "plans": { "seatsPerMember_one": "{{count}} seat, one per team member", "seatsPerMember_other": "{{count}} seats, one per team member" diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 11bf894ca4c..b4eeb0eed29 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20519,8 +20519,6 @@ "nextInvoice": "Next invoice (est.)", "nextInvoiceOn": "{{value0}} · {{value1}}", "notAnEmail": "Not an email address", - "perMonth": "{{value0}}/month", - "perYear": "{{value0}}/year", "planEnds": "Plan ends", "rateLimited": "Too many team changes at once. Wait a minute and try again.", "readOnly": "Only owners and admins can invite people or change roles.", @@ -20579,7 +20577,9 @@ "nowOwner": "{{value0}} is now an owner", "perSeatPerMonth": "{{value0}} per seat per month", "createInvalid2": "Use letters, numbers, spaces or underscores (up to 64).", - "nameTaken": "That team name is taken. Try another." + "nameTaken": "That team name is taken. Try another.", + "totalPerMonth": "{{total}} per month", + "totalPerYear": "{{total}} per year" }, "manageBilling": "Manage billing", "comparePlans": "Compare plans", @@ -20600,8 +20600,6 @@ "loadFailed": "Could not load plans. Try again in a moment.", "currentPlan": "Current plan", "billedMonthly": "Billed monthly", - "totalYear": "{{value0}} / year", - "totalMonth": "{{value0}} / month", "checkout": "Continue to checkout", "entLead": "Everything in Team, plus:", "entHint": "Tell us about your team and where you run.", @@ -20635,7 +20633,9 @@ "perSeatPerMonth": "per seat per month", "seatsPerMember_one": "{{count}} seat, one per team member", "seatsPerMember_other": "{{count}} seats, one per team member", - "vpWakeBody2": "Idle sandboxes sleep to save hours and wake with your files as you left them." + "vpWakeBody2": "Idle sandboxes sleep to save hours and wake with your files as you left them.", + "totalPerMonth": "{{total}} per month", + "totalPerYear": "{{total}} per year" }, "capLabel2": "Monthly spend cap", "capSaved": "Saved", @@ -20653,13 +20653,10 @@ "opening": "Opening secure checkout…", "openingBody": "Stripe’s checkout opens in your browser.", "paid": "Payment confirmed", - "perMo": "/mo", - "perYr": "/yr", "planAnnual": "{{value0}} · Annual", "planMonthly": "{{value0}} · Monthly", "renewsNote": "Renews {{value0}}. Before tax. Seats follow your team.", "reopen": "Reopen checkout", - "seatsTimes2": "{{value0}} × {{value1}}{{value2}}", "subtitle": "Pay on Stripe’s secure page in your browser. Orca picks it up the moment it goes through.", "timedOut": "Still waiting for Stripe", "timedOutBody": "If you already paid, confirmation can take a minute. Otherwise reopen checkout.", @@ -20670,7 +20667,11 @@ "secured2": "Payments by Stripe · Cards, Apple Pay and Link · Bank verification", "canceledBody2": "Nothing was charged. You can choose a plan again any time.", "titleCanceled": "Checkout canceled", - "titlePaid": "Welcome to Orca Cloud" + "titlePaid": "Welcome to Orca Cloud", + "lineItemMonthly_one": "{{seats}} × {{price}} per seat per month", + "lineItemMonthly_other": "{{seats}} × {{price}} per seat per month", + "lineItemYearly_one": "{{seats}} × {{price}} per seat, billed yearly", + "lineItemYearly_other": "{{seats}} × {{price}} per seat, billed yearly" }, "health": { "ending": "Ending", @@ -20681,11 +20682,11 @@ "paymentAskAdmin": "Ask an owner or admin to update the payment method.", "upgrade": { "askOwner": "Ask an owner or admin to upgrade.", - "body2": "Hosted sandboxes for the whole team. Agents keep running when you close your laptop. {{value0}}/seat/month.", "bodyNoPrice": "Hosted sandboxes for the whole team. Agents keep running when you close your laptop.", "cta": "See plans", "menuItem": "Upgrade to Orca Cloud", - "title": "Upgrade to use Orca Cloud" + "title": "Upgrade to use Orca Cloud", + "body3": "Hosted sandboxes for the whole team. Agents keep running when you close your laptop. {{price}} per seat per month." }, "upsellLineNoPrice": "Orca Cloud runs agents in hosted sandboxes for your whole team.", "askAdmin2": "Ask an owner or admin to change the plan.", diff --git a/src/shared/orca-billing.ts b/src/shared/orca-billing.ts index 07a0249772e..23252573f91 100644 --- a/src/shared/orca-billing.ts +++ b/src/shared/orca-billing.ts @@ -64,7 +64,7 @@ export function classifyEntitlementDenial( export type OrcaBillingOffers = { team: { label: string - /** Display only, e.g. "$50/seat/mo"; Stripe charges the configured price. */ + /** Display only, e.g. "$50 per seat per month"; Stripe charges the configured price. */ monthlyPriceLabel: string annualPriceLabel: string /** Per-seat prices in cents for totals and the annual saving; null from older services. */ From 16d2a7aebf0c5a496c2c527428cc7d71a6421fa6 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:27:26 -0800 Subject: [PATCH 16/46] =?UTF-8?q?fix(cloud):=20DS-26=20follow-up=20?= =?UTF-8?q?=E2=80=94=20run=20failure=20reasons=20as=20one=20quiet=20line?= =?UTF-8?q?=20(neutral=20for=20skipped/superseded/workspace=20gone),=20cap?= =?UTF-8?q?ped=20availability=20backoff=20that=20stops=20without=20subscri?= =?UTF-8?q?bers,=20"Couldn't=20reach=20Orca=20Cloud."?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cloud-workspaces/use-cloud-workspaces.ts | 19 ++++-- .../cloud-api/CloudApiKeysView.fixture.tsx | 6 +- .../cloud-api/CloudRoutinesView.fixture.tsx | 2 +- .../settings/cloud-api/RoutineRunHistory.tsx | 15 ++++- .../settings/cloud-api/cloud-api-copy.ts | 65 +++++++++++++------ .../cloud-api/cloud-api-format.test.ts | 26 +++++++- .../src/components/ui/inline-error.tsx | 27 +++++++- .../src/hooks/useOrcaCloudApiAvailability.ts | 18 +++-- src/renderer/src/i18n/locales/en.json | 4 +- .../src/lib/availability-retry.test.ts | 10 +++ src/renderer/src/lib/availability-retry.ts | 9 +++ 11 files changed, 161 insertions(+), 40 deletions(-) create mode 100644 src/renderer/src/lib/availability-retry.test.ts create mode 100644 src/renderer/src/lib/availability-retry.ts diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts index 86b75504c4c..b17212dbaf8 100644 --- a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts @@ -3,6 +3,7 @@ import type { CloudWorkspace, CloudWorkspaceListQuery } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { availabilityRetryDelay } from '@/lib/availability-retry' import { installWindowVisibilityTimeoutPoller } from '@/lib/window-visibility-timeout-poller' /** Presence is live; the list re-reads on this beat while visible (and on focus). */ @@ -27,19 +28,29 @@ function setAvailable(value: boolean): void { } } -const AVAILABILITY_RETRY_MS = 5_000 +let failedProbes = 0 +let retryTimer: ReturnType | null = null export function cloudWorkspacesAvailable(): Promise { availability ??= (window.api.cloudWorkspaces?.available() ?? Promise.resolve(false)).then( (value) => { + failedProbes = 0 setAvailable(value) return value }, () => { - // A failed probe is not an answer: forget it and ask again shortly, so one transient - // error doesn't hide Orca Cloud until the app restarts. + // A failed probe is not an answer: forget it and ask again with capped backoff, so one + // transient error doesn't hide Orca Cloud until restart. Stop while nobody is listening; + // the next subscriber asks again. availability = null - setTimeout(() => void cloudWorkspacesAvailable(), AVAILABILITY_RETRY_MS) + if (!retryTimer) { + retryTimer = setTimeout(() => { + retryTimer = null + if (availabilityListeners.size > 0) { + void cloudWorkspacesAvailable() + } + }, availabilityRetryDelay(failedProbes++)) + } return false } ) diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx index bd0a0b095b3..a31156a5809 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx @@ -192,10 +192,10 @@ export const error = defineFixture({ {...base} keys={{ status: 'error', - message: 'Could not reach Orca Cloud. Check your connection and try again.' + message: 'Couldn’t reach Orca Cloud. Check your connection and try again.' }} - settings={{ status: 'error', message: 'Could not reach Orca Cloud.' }} - grants={{ status: 'error', message: 'Could not reach Orca Cloud.' }} + settings={{ status: 'error', message: 'Couldn’t reach Orca Cloud.' }} + grants={{ status: 'error', message: 'Couldn’t reach Orca Cloud.' }} audit={null} /> ) diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx index 403ddf350c8..6bb25768433 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx @@ -262,7 +262,7 @@ export const error = defineFixture({ routines={{ status: 'error', code: 'network', - message: 'Could not reach Orca Cloud. Check your connection and try again.' + message: 'Couldn’t reach Orca Cloud. Check your connection and try again.' }} /> ) diff --git a/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx b/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx index e7e0487156c..21d2e8a2bbf 100644 --- a/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx +++ b/src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx @@ -9,7 +9,11 @@ import type { RoutineRun, RoutineRunPage } from '../../../../../shared/cloud-api/cloud-api-types' -import { cloudApiErrorCopy, routineRunErrorCopy, routineRunTriggerLabel } from './cloud-api-copy' +import { + cloudApiErrorCopy, + describeRoutineRunError, + routineRunTriggerLabel +} from './cloud-api-copy' import { formatAbsoluteTime, formatRelativeFromNow, formatRunDuration } from './cloud-api-format' import { CloudApiErrorNotice, RoutineRunStatusPill } from './cloud-api-parts' import { isActiveRunStatus } from './routine-run-status' @@ -309,7 +313,7 @@ function RunRow({ {run.result?.summary ? (

    {run.result.summary}

    ) : null} - {run.error ? : null} + {run.error ? : null} ) } @@ -334,3 +338,10 @@ function RunAction({ ) } + +/** Why a run didn't succeed: one quiet line under the row; red icon only for real failures. */ +function RunFailure({ error }: { error: string }): React.JSX.Element { + const t = useTranslate() + const { text, tone } = describeRoutineRunError(error, t) + return +} diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts index be4aef1ab5d..a0957e6f7da 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts @@ -71,7 +71,7 @@ export function cloudApiErrorCopy( case 'network': return t( 'auto.components.settings.cloudApi.error.network', - 'Couldn’t reach Orca Cloud, so nothing was changed. Check your connection and try again.' + 'Couldn’t reach Orca Cloud. Check your connection and try again.' ) case 'invalid-response': return t( @@ -176,42 +176,67 @@ export function routineRunTriggerLabel( * colon ("workspace_lost:suspended"); codes and detail never reach the screen. */ export function routineRunErrorCopy(error: string, t: Translate = translate): string { + return describeRoutineRunError(error, t).text +} + +/** + * Copy plus tone: things that went wrong (couldn't start, couldn't post, interrupted, unknown) are + * errors; outcomes that are expected bookkeeping (skipped, superseded, workspace gone) are neutral. + */ +export function describeRoutineRunError( + error: string, + t: Translate = translate +): { text: string; tone: 'error' | 'neutral' } { + const neutral = (text: string) => ({ text, tone: 'neutral' as const }) + const failure = (text: string) => ({ text, tone: 'error' as const }) const code = error.split(':', 1)[0]?.trim() ?? '' if (code === 'start_failed') { - return t( - 'auto.components.settings.cloudRoutines.runError.startFailed', - 'The workspace couldn’t start. Nothing was charged.' + return failure( + t( + 'auto.components.settings.cloudRoutines.runError.startFailed', + 'The workspace couldn’t start, so nothing was charged.' + ) ) } if (code === 'workspace_lost') { - return t( - 'auto.components.settings.cloudRoutines.runError.workspaceLost', - 'The workspace went to sleep or was deleted before the run finished.' + return neutral( + t( + 'auto.components.settings.cloudRoutines.runError.workspaceLost', + 'The workspace went to sleep or was deleted before the run finished.' + ) ) } if (code === 'post_failed') { - return t( - 'auto.components.settings.cloudRoutines.runError.postFailed', - 'The run finished, but Orca couldn’t post the results.' + return failure( + t( + 'auto.components.settings.cloudRoutines.runError.postFailed', + 'The run finished, but Orca couldn’t post the results.' + ) ) } if (code === 'queue_expired') { - return t( - 'auto.components.settings.cloudRoutines.runError.queueExpired', - 'The run waited too long to start and was skipped.' + return neutral( + t( + 'auto.components.settings.cloudRoutines.runError.queueExpired', + 'The run waited too long to start and was skipped.' + ) ) } if (code.endsWith('_interrupted')) { - return t( - 'auto.components.settings.cloudRoutines.runError.interrupted', - 'Orca Cloud restarted during the run.' + return failure( + t( + 'auto.components.settings.cloudRoutines.runError.interrupted', + 'Orca Cloud restarted during the run.' + ) ) } if (code === 'routine_changed') { - return t( - 'auto.components.settings.cloudRoutines.runError.routineChanged', - 'The routine changed while this run was queued.' + return neutral( + t( + 'auto.components.settings.cloudRoutines.runError.routineChanged', + 'The routine changed while this run was queued.' + ) ) } - return t('auto.components.settings.cloudRoutines.runError.generic', 'The run failed.') + return failure(t('auto.components.settings.cloudRoutines.runError.generic', 'The run failed.')) } diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts index 732a5a90d85..38137b52967 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from 'vitest' import { CLOUD_API_SCOPES } from '../../../../../shared/cloud-api/cloud-api-types' -import { cloudApiErrorCopy, routineRunErrorCopy, routineRunTone } from './cloud-api-copy' +import { + cloudApiErrorCopy, + describeRoutineRunError, + routineRunErrorCopy, + routineRunTone +} from './cloud-api-copy' import { describeRoutineTrigger, formatCountdown, @@ -87,7 +92,7 @@ describe('copy', () => { describe('run failure copy', () => { it('maps control-plane codes (with detail) to plain words and never shows the code', () => { expect(routineRunErrorCopy('start_failed:clone_failed')).toBe( - 'The workspace couldn’t start. Nothing was charged.' + 'The workspace couldn’t start, so nothing was charged.' ) expect(routineRunErrorCopy('workspace_lost:suspended')).toBe( 'The workspace went to sleep or was deleted before the run finished.' @@ -105,3 +110,20 @@ describe('run failure copy', () => { expect(routineRunErrorCopy('totally_new:detail')).toBe('The run failed.') }) }) + +describe('run failure tone', () => { + it('keeps red for real failures and neutral for expected outcomes', () => { + const tone = (code: string) => describeRoutineRunError(code).tone + expect(['start_failed', 'post_failed', 'agent_interrupted', 'mystery'].map(tone)).toEqual([ + 'error', + 'error', + 'error', + 'error' + ]) + expect(['queue_expired', 'routine_changed', 'workspace_lost:suspended'].map(tone)).toEqual([ + 'neutral', + 'neutral', + 'neutral' + ]) + }) +}) diff --git a/src/renderer/src/components/ui/inline-error.tsx b/src/renderer/src/components/ui/inline-error.tsx index ee0b67ab366..9a38d8dc069 100644 --- a/src/renderer/src/components/ui/inline-error.tsx +++ b/src/renderer/src/components/ui/inline-error.tsx @@ -17,8 +17,10 @@ type InlineErrorProps = { /** 'compact' for narrow panels (sidebar sections): tighter padding, xs text. */ density?: 'default' | 'compact' /** 'toast' leaves room for the toast's own dismiss button and puts the action under the text. - * 'strip-top' / 'strip-bottom' run edge to edge at the top or bottom of a framed panel. */ - layout?: 'inline' | 'toast' | 'strip-top' | 'strip-bottom' + * 'strip-top' / 'strip-bottom' run edge to edge at the top or bottom of a framed panel. + * 'line' is one muted line with no box, for a reason under a row in a dense list; it is a note + * (not announced) because it describes something that already happened. */ + layout?: 'inline' | 'toast' | 'strip-top' | 'strip-bottom' | 'line' /** A next step other than retry (e.g. "Sign in"), rendered inside the box after the text. * Pass an outline xs Button with a short verb-first label; never a primary button. */ action?: React.ReactNode @@ -43,6 +45,27 @@ function InlineError({ className }: InlineErrorProps): React.JSX.Element { const Icon = tone === 'error' ? CircleAlert : Info + if (layout === 'line') { + return ( +

    + + + {title} + {detail ? {detail} : null} + +

    + ) + } return (
    | null = null const listeners = new Set<() => void>() function probe(): void { - if (probing || availability) { + if (probing || availability || retryTimer) { return } const bridge = typeof window === 'undefined' ? undefined : window.api?.cloudApi @@ -22,14 +24,22 @@ function probe(): void { (next) => { availability = next probing = false + failedAttempts = 0 for (const listener of listeners) { listener() } }, () => { - // A failed probe is not "unconfigured": retry shortly instead of hiding the pages for good. + // A failed probe is not "unconfigured": retry with capped backoff, and only while something + // is subscribed (a new subscriber probes again on its own). probing = false - setTimeout(probe, RETRY_MS) + const delay = availabilityRetryDelay(failedAttempts++) + retryTimer = setTimeout(() => { + retryTimer = null + if (listeners.size > 0) { + probe() + } + }, delay) } ) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 11bf894ca4c..fdc6d96f918 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -14434,7 +14434,7 @@ "invalid": "Orca Cloud rejected that request. Check the fields and try again.", "rateLimitedFor": "Too many requests. Try again in {{seconds}} seconds.", "rateLimited": "Too many requests. Try again in a minute.", - "network": "Couldn’t reach Orca Cloud, so nothing was changed. Check your connection and try again.", + "network": "Couldn’t reach Orca Cloud. Check your connection and try again.", "invalidResponse": "Orca Cloud sent an answer this version of Orca does not understand. Update Orca and try again.", "server": "Orca Cloud had a problem and nothing was changed. Try again in a moment." }, @@ -14614,7 +14614,7 @@ "manual": "Manual" }, "runError": { - "startFailed": "The workspace couldn’t start. Nothing was charged.", + "startFailed": "The workspace couldn’t start, so nothing was charged.", "workspaceLost": "The workspace went to sleep or was deleted before the run finished.", "postFailed": "The run finished, but Orca couldn’t post the results.", "queueExpired": "The run waited too long to start and was skipped.", diff --git a/src/renderer/src/lib/availability-retry.test.ts b/src/renderer/src/lib/availability-retry.test.ts new file mode 100644 index 00000000000..f8ff6bebce2 --- /dev/null +++ b/src/renderer/src/lib/availability-retry.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from 'vitest' +import { availabilityRetryDelay } from './availability-retry' + +describe('availabilityRetryDelay', () => { + it('backs off 5s, 10s, 30s and then holds at 60s', () => { + expect([0, 1, 2, 3, 4, 50].map(availabilityRetryDelay)).toEqual([ + 5_000, 10_000, 30_000, 60_000, 60_000, 60_000 + ]) + }) +}) diff --git a/src/renderer/src/lib/availability-retry.ts b/src/renderer/src/lib/availability-retry.ts new file mode 100644 index 00000000000..0725e685a8b --- /dev/null +++ b/src/renderer/src/lib/availability-retry.ts @@ -0,0 +1,9 @@ +// Capped backoff for "is this feature available here?" probes that failed (not answered "no"). +// A probe that always rejects (missing handler, version skew) settles at one try a minute, and +// callers stop retrying entirely while nothing on screen is waiting for the answer. +const RETRY_STEPS_MS = [5_000, 10_000, 30_000, 60_000] as const + +/** Delay before retry number `attempt` (0-based): 5s, 10s, 30s, then 60s from then on. */ +export function availabilityRetryDelay(attempt: number): number { + return RETRY_STEPS_MS[Math.min(Math.max(0, attempt), RETRY_STEPS_MS.length - 1)]! +} From f364c85f871cda97a62cc9e8a081658215eeb3b5 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:30:08 -0800 Subject: [PATCH 17/46] feat(cloud): this computer's Agent API Keys never reach an Orca Cloud VM; each can be saved as a personal Cloud secret (A6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Desktop-sealed keys (Settings → Agent API Keys) ride every agent launch as plain env on other hosts. An Orca Cloud VM would hold them in plaintext, so they are no longer sent there: runtime calls to Orca Cloud environments skip them (provider record; otherwise any VM-provisioned host or a Vercel Sandbox route counts, failing closed). The Add-an-agent view and the build sheet's key step list each every-host key no Cloud secret covers yet, with its own 'Save as personal Cloud secret' button: main unseals that one key and writes it to the user's personal Cloud secrets; the renderer never sees the value, and nothing is uploaded without the click. The VM then gets a placeholder the egress proxy swaps. Readiness no longer counts desktop keys as cloud access. --- src/main/cloud-secrets/cloud-secrets-ipc.ts | 35 +++++- .../hosted-sandbox/cloud-desktop-keys.test.ts | 92 +++++++++++++++ src/main/hosted-sandbox/cloud-desktop-keys.ts | 80 +++++++++++++ ...ntime-environment-connectivity-handlers.ts | 10 +- src/preload/api/cloud-secrets-bridge.ts | 8 +- .../CloudAgentSetup.fixture.tsx | 31 ++++- .../CloudAgentSetupDialog.tsx | 4 +- .../cloud-agent-setup/CloudAgentSetupView.tsx | 32 ++--- .../CloudDesktopKeysOffer.tsx | 110 ++++++++++++++++++ .../VmBuildCloudAgentStep.tsx | 19 ++- .../cloud-agent-readiness.test.ts | 64 +++++++--- .../cloud-agent-readiness.ts | 37 ++++-- .../use-cloud-agent-setup.ts | 52 ++++++++- .../cloud-secrets-fixture-data.ts | 11 +- 14 files changed, 523 insertions(+), 62 deletions(-) create mode 100644 src/main/hosted-sandbox/cloud-desktop-keys.test.ts create mode 100644 src/main/hosted-sandbox/cloud-desktop-keys.ts create mode 100644 src/renderer/src/components/cloud-agent-setup/CloudDesktopKeysOffer.tsx diff --git a/src/main/cloud-secrets/cloud-secrets-ipc.ts b/src/main/cloud-secrets/cloud-secrets-ipc.ts index 56033281053..39ed3a9bdc6 100644 --- a/src/main/cloud-secrets/cloud-secrets-ipc.ts +++ b/src/main/cloud-secrets/cloud-secrets-ipc.ts @@ -14,6 +14,12 @@ import { withCloudBuildDefaults } from '../cloud-build-defaults' import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config' import { HOSTED_SANDBOX_DRIVER_ID } from '../hosted-sandbox/hosted-sandbox-driver' import { getOrcaCloudAvailability } from '../hosted-sandbox/hosted-sandbox-install' +import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' +import { + cloudSecretNameError, + cloudSecretValueError +} from '../../shared/cloud-secrets/cloud-secret-rules' +import { desktopKeyValueForCloud } from '../hosted-sandbox/cloud-desktop-keys' import { cloudSecretsFailureCode, createCloudSecretsClient, @@ -45,6 +51,10 @@ const BatchRequest = z ) const EffectiveRequest = z.object({ repo: Repo.optional() }) const RefreshRequest = z.object({ runtimeEnvironmentId: z.string().min(1).max(256) }) +const SaveDesktopKeyRequest = z.object({ + agent: z.string().refine(isTuiAgent), + envName: Name +}) const CHANNELS = [ 'cloudSecrets:status', @@ -53,7 +63,8 @@ const CHANNELS = [ 'cloudSecrets:remove', 'cloudSecrets:batch', 'cloudSecrets:effective', - 'cloudSecrets:refreshEnv' + 'cloudSecrets:refreshEnv', + 'cloudSecrets:saveDesktopKey' ] as const async function attempt( @@ -137,6 +148,28 @@ export function registerCloudSecretsHandlers(userDataPath: string): void { const request = EffectiveRequest.safeParse(raw ?? {}) return request.success ? attempt(client, (c) => c.effective(request.data.repo)) : invalid }) + // One desktop-sealed key, unsealed here and sent once to the user's personal Cloud secrets; the + // renderer names it (agent + variable) and never sees the value. Each call is one explicit click. + ipcMain.handle('cloudSecrets:saveDesktopKey', async (_event, raw: unknown) => { + const request = SaveDesktopKeyRequest.safeParse(raw) + if (!request.success || !isTuiAgent(request.data.agent)) { + return invalid + } + const { agent, envName } = request.data + const nameError = cloudSecretNameError(envName) + if (nameError) { + return { ok: false, error: nameError } + } + const value = await desktopKeyValueForCloud(agent, envName) + if (!value) { + return { ok: false, error: 'not_found' } + } + const valueError = cloudSecretValueError(envName, value) + if (valueError) { + return { ok: false, error: valueError } + } + return attempt(client, (c) => c.put({ scope: 'personal' }, envName, value)) + }) ipcMain.handle('cloudSecrets:refreshEnv', (_event, raw: unknown) => { const request = RefreshRequest.safeParse(raw) if (!request.success) { diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts new file mode 100644 index 00000000000..1eb2cb41ab7 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts @@ -0,0 +1,92 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const runtimes: { runtimeEnvironmentId: string; recipe?: { provider?: string } }[] = [] +const environments = new Map() +let launchEnv: Record = {} +const launchCalls: unknown[][] = [] + +vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ + listEphemeralVmRuntimes: () => runtimes +})) +vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ + resolveEnvironment: (_userData: string, id: string) => { + const environment = environments.get(id) + if (!environment) { + throw new Error('unknown environment') + } + return environment + } +})) +vi.mock('../agent-api-keys/agent-api-key-launch-env', () => ({ + resolveAgentApiKeyLaunchEnv: async (...args: unknown[]) => { + launchCalls.push(args) + return launchEnv + } +})) + +const { desktopKeyValueForCloud, isOrcaCloudRuntimeEnvironment } = + await import('./cloud-desktop-keys') + +beforeEach(() => { + runtimes.length = 0 + environments.clear() + launchEnv = {} + launchCalls.length = 0 +}) + +describe('isOrcaCloudRuntimeEnvironment', () => { + it('is true for an Orca Cloud runtime and false for another VM recipe or a paired machine', () => { + runtimes.push({ runtimeEnvironmentId: 'env-cloud', recipe: { provider: 'orca-cloud' } }) + runtimes.push({ runtimeEnvironmentId: 'env-own-vm', recipe: { provider: 'my-recipes' } }) + environments.set('env-mac', { + source: 'manual', + endpoints: [{ endpoint: 'wss://192.168.1.4:6768' }] + }) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-cloud')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-own-vm')).toBe(false) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-mac')).toBe(false) + }) + + it('fails closed: a VM with no provider record, or a host on a Vercel Sandbox route, counts as Orca Cloud', () => { + runtimes.push({ runtimeEnvironmentId: 'env-unknown-recipe' }) + environments.set('env-vm', { source: 'ephemeral-vm', endpoints: [{ endpoint: 'wss://x' }] }) + environments.set('env-paired-cloud', { + source: 'manual', + endpoints: [{ endpoint: 'wss://sb-abc123.vercel.run' }] + }) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-unknown-recipe')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-vm')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-paired-cloud')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-missing')).toBe(false) + }) +}) + +describe('desktopKeyValueForCloud', () => { + it('reads only keys set for every host, for one agent and one variable', async () => { + launchEnv = { GEMINI_API_KEY: 'AIzaSy-real', OTHER: 'x' } + expect(await desktopKeyValueForCloud('gemini', 'GEMINI_API_KEY')).toBe('AIzaSy-real') + expect(await desktopKeyValueForCloud('gemini', 'CURSOR_API_KEY')).toBeNull() + expect(launchCalls[0]).toEqual(['gemini', 'runtime:orca-cloud']) + }) +}) + +describe('withHostAgentApiKeyEnv', () => { + it('adds no desktop keys to a launch on an Orca Cloud VM', async () => { + runtimes.push({ runtimeEnvironmentId: 'env-cloud', recipe: { provider: 'orca-cloud' } }) + launchEnv = { GEMINI_API_KEY: 'AIzaSy-real' } + const params = { agent: 'gemini', kind: 'explicit' } + const { withHostAgentApiKeyEnv } = await import('./cloud-desktop-keys') + const readStatus = vi.fn() + expect( + await withHostAgentApiKeyEnv( + '/u', + 'env-cloud', + 'terminal.createAgentSession', + params, + readStatus + ) + ).toBe(params) + expect(launchCalls).toEqual([]) + expect(readStatus).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.ts b/src/main/hosted-sandbox/cloud-desktop-keys.ts new file mode 100644 index 00000000000..4837108eb5f --- /dev/null +++ b/src/main/hosted-sandbox/cloud-desktop-keys.ts @@ -0,0 +1,80 @@ +// Desktop-sealed agent API keys (Settings → Agent API Keys) and Orca Cloud workspaces. On any other +// host those keys ride each agent launch as plain env. An Orca Cloud VM must never hold a model key, +// so they are not sent there at all: the user saves a key as a personal Cloud secret instead (one key +// per click), and the VM then gets a placeholder the egress proxy swaps. +import { resolveAgentApiKeyLaunchEnv } from '../agent-api-keys/agent-api-key-launch-env' +import { withAgentApiKeyRuntimeEnv } from '../agent-api-keys/agent-api-key-runtime-call' +import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' +import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { toRuntimeExecutionHostId } from '../../shared/execution-host' +import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' + +/** Orca Cloud sandboxes answer on Vercel Sandbox routes. */ +const ORCA_CLOUD_ENDPOINT_HOST = /\.vercel\.run$/i + +function endpointHost(endpoint: string): string | null { + try { + return new URL(endpoint).hostname + } catch { + return null + } +} + +/** + * Whether `environmentId` is an Orca Cloud VM. Fails closed: a VM-provisioned host this desktop has no + * provider record for, or any host on a Vercel Sandbox route, counts as Orca Cloud. + */ +export function isOrcaCloudRuntimeEnvironment( + userDataPath: string, + environmentId: string +): boolean { + const runtime = listEphemeralVmRuntimes(userDataPath).find( + (record) => record.runtimeEnvironmentId === environmentId + ) + if (runtime) { + return runtime.recipe?.provider === 'orca-cloud' || runtime.recipe?.provider === undefined + } + let environment: ReturnType | null = null + try { + environment = resolveEnvironment(userDataPath, environmentId) + } catch { + return false + } + if (environment.source === 'ephemeral-vm') { + return true + } + return (environment.endpoints ?? []).some((endpoint) => { + const host = endpointHost(endpoint.endpoint) + return host !== null && ORCA_CLOUD_ENDPOINT_HOST.test(host) + }) +} + +/** A host id no host-scoped key names, so only keys set for every host match (the ones a new VM would get). */ +const ANY_CLOUD_HOST = toRuntimeExecutionHostId('orca-cloud') + +/** The sealed value of the desktop key `envName` for `agent`, unsealed for one cloud write. */ +export async function desktopKeyValueForCloud( + agent: TuiAgent, + envName: string +): Promise { + const env = await resolveAgentApiKeyLaunchEnv(agent, ANY_CLOUD_HOST) + return env[envName] ?? null +} + +/** + * A runtime call's params with this computer's Agent API Keys for the agent it starts, except on an + * Orca Cloud VM: there they would sit in plaintext, so the user saves them as Cloud secrets instead + * (the VM then only sees egress placeholders). + */ +export async function withHostAgentApiKeyEnv( + userDataPath: string, + environmentId: string, + method: string, + params: unknown, + readStatus: Parameters[3] +): Promise { + if (isOrcaCloudRuntimeEnvironment(userDataPath, environmentId)) { + return params + } + return withAgentApiKeyRuntimeEnv(environmentId, method, params, readStatus) +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts index 74249f8a8f3..5c4fd3e64cb 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts @@ -41,7 +41,7 @@ import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' import { noteRuntimeEnvironmentConnectRequested } from './runtime-environment-pairing-refusal-registry' import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key' import { withWslOrcadAccountEnv } from '../../wsl/orcad/wsl-orcad-account-env' -import { withAgentApiKeyRuntimeEnv } from '../../agent-api-keys/agent-api-key-runtime-call' +import { withHostAgentApiKeyEnv } from '../../hosted-sandbox/cloud-desktop-keys' import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/authentication/ssh-credential-decline' import { disconnectManagedHostOfEnvironmentForUser, @@ -287,8 +287,12 @@ function registerPassiveCallHandler( getUserDataPath(), environment.id, args.method, - await withAgentApiKeyRuntimeEnv(environment.id, args.method, accounts.params, () => - callRuntimeEnvironment(getUserDataPath(), environment.id, 'status.get', undefined) + await withHostAgentApiKeyEnv( + getUserDataPath(), + environment.id, + args.method, + accounts.params, + () => callRuntimeEnvironment(getUserDataPath(), environment.id, 'status.get', undefined) ), args.timeoutMs, args.expectedEnvironmentPairingRevision, diff --git a/src/preload/api/cloud-secrets-bridge.ts b/src/preload/api/cloud-secrets-bridge.ts index 34e663d55c4..a311162c9f2 100644 --- a/src/preload/api/cloud-secrets-bridge.ts +++ b/src/preload/api/cloud-secrets-bridge.ts @@ -29,6 +29,11 @@ export type CloudSecretsApi = { effective: (request: { repo?: string }) => Promise> /** Best-effort nudge so a running workspace picks up new values now; the server also does it on write. */ refreshEnv: (request: { runtimeEnvironmentId: string }) => Promise> + /** Saves one of this computer's Agent API Keys as a personal Cloud secret (the value never leaves main). */ + saveDesktopKey: (request: { + agent: string + envName: string + }) => Promise> } export const cloudSecretsApi: CloudSecretsApi = { @@ -38,5 +43,6 @@ export const cloudSecretsApi: CloudSecretsApi = { remove: (request) => ipcRenderer.invoke('cloudSecrets:remove', request), batch: (request) => ipcRenderer.invoke('cloudSecrets:batch', request), effective: (request) => ipcRenderer.invoke('cloudSecrets:effective', request), - refreshEnv: (request) => ipcRenderer.invoke('cloudSecrets:refreshEnv', request) + refreshEnv: (request) => ipcRenderer.invoke('cloudSecrets:refreshEnv', request), + saveDesktopKey: (request) => ipcRenderer.invoke('cloudSecrets:saveDesktopKey', request) } diff --git a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx index 045af8c6965..2c8e4d23fec 100644 --- a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx +++ b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx @@ -89,10 +89,16 @@ export const buildSaved = sheet( { kind: 'saved', saved: { agents: ['claude'], scope: 'org' } } ) -export const buildReadyDesktopKey = sheet({ - readiness: { claude: 'desktop-key', codex: null }, - canShare: false -}) +const DESKTOP_KEYS = [ + { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' }, + { id: 'k2', agent: 'gemini', envName: 'GEMINI_API_KEY', hint: '9fZk' } +] as const + +/** This computer has Agent API Keys: the key form offers each one as a Cloud secret. */ +export const buildKeysWithDesktopKeys = sheet( + { readiness: NONE, canShare: false, desktopKeys: [...DESKTOP_KEYS] }, + { kind: 'keys' } +) export const buildReadyTeam = sheet({ readiness: { claude: 'team', codex: 'team' }, @@ -150,6 +156,8 @@ function dialog( canShare?: boolean failure?: CloudAgentSetupFailure pendingSave?: boolean + desktopKeys?: boolean + desktopKeyFailure?: boolean interact?: (frame: HTMLElement) => Promise } = {} ) { @@ -161,6 +169,8 @@ function dialog( readiness={options.readiness ?? NONE} canShare={options.canShare ?? false} steadyHeight + desktopKeys={options.desktopKeys ? [...DESKTOP_KEYS] : []} + onSaveDesktopKey={async () => (options.desktopKeyFailure ? 'unavailable' : null)} onSave={options.pendingSave ? () => new Promise(() => {}) : async () => null} onSaved={noop} onCancel={noop} @@ -177,6 +187,19 @@ export const dialogSubscription = dialog('sign-in', { readiness: { claude: 'team export const dialogApiKeyAdmin = dialog('api-key', { canShare: true }) +export const dialogDesktopKeys = dialog('api-key', { desktopKeys: true }) + +/** One key saved, the next one failed: each row keeps its own outcome. */ +export const dialogDesktopKeysSavedAndFailed = dialog('api-key', { + desktopKeys: true, + desktopKeyFailure: true, + interact: async (frame) => { + const buttons = frame.querySelectorAll('[aria-label^="Save "]') + buttons[1]?.click() + await settle() + } +}) + export const dialogApiKeySaving = dialog('api-key', { pendingSave: true, interact: async (frame) => { diff --git a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx index 8d9905fc846..3964bc609f0 100644 --- a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx +++ b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx @@ -19,7 +19,7 @@ function DialogBody({ escapeGuardRef: React.Ref<() => boolean> }): React.JSX.Element { const t = useTranslate() - const { model, save } = useCloudAgentSetup({ repo: null }) + const { model, save, saveDesktopKey } = useCloudAgentSetup({ repo: null }) const [saved, setSaved] = useState(null) if (saved) { return @@ -38,6 +38,8 @@ function DialogBody({ const KEY_OPTIONS: readonly KeyOption[] = ['api-key', 'gateway', 'custom'] +const NO_DESKTOP_KEYS: readonly CloudOfferableDesktopKey[] = [] const EMPTY_DRAFTS: Record = { 'api-key': EMPTY_DRAFT, gateway: EMPTY_DRAFT, @@ -43,18 +47,16 @@ function agentStatusLine(readiness: CloudAgentReadiness, t: Translate): string { const state = source === 'team' ? t('cloudAgentSetup.status.team', 'provided by your team') - : source === 'desktop-key' - ? t('cloudAgentSetup.status.desktopKey', 'API key from Orca on this computer') - : source === 'cloud-secret' - ? t('cloudAgentSetup.status.cloudSecret', 'your cloud secret') - : t('cloudAgentSetup.status.none', 'not set up') + : source === 'cloud-secret' + ? t('cloudAgentSetup.status.cloudSecret', 'your cloud secret') + : t('cloudAgentSetup.status.none', 'not set up') return `${AGENT_NAME[agent]}: ${state}` }).join(' · ') } /** "Your team provides Claude and Codex access · …": one clause per source, agents grouped. */ export function cloudAgentReadinessSummary(readiness: CloudAgentReadiness, t: Translate): string { - const sources: CloudAgentCredentialSource[] = ['desktop-key', 'team', 'cloud-secret'] + const sources: CloudAgentCredentialSource[] = ['team', 'cloud-secret'] return sources .flatMap((source) => { const agents = CLOUD_SETUP_AGENTS.filter((agent) => readiness[agent] === source) @@ -66,16 +68,6 @@ export function cloudAgentReadinessSummary(readiness: CloudAgentReadiness, t: Tr ? t('cloudAgentSetup.source.both', 'Claude and Codex') : AGENT_NAME[agents[0]] switch (source) { - case 'desktop-key': - return [ - t( - 'cloudAgentSetup.source.desktopKey', - '{{agent}} uses the API key from Orca on this computer', - { - agent - } - ) - ] case 'team': return [ t('cloudAgentSetup.source.team', 'Your team provides {{agent}} access', { agent }) @@ -139,6 +131,9 @@ export type CloudAgentSetupViewProps = { * ask before a typed key is thrown away. */ escapeGuardRef?: React.Ref<() => boolean> + /** This computer's Agent API Keys no Cloud secret covers yet, each offered with its own Save. */ + desktopKeys?: readonly CloudOfferableDesktopKey[] + onSaveDesktopKey?: (key: CloudOfferableDesktopKey) => Promise /** Fixtures only. */ initialOption?: CloudAgentSetupOption initialFailure?: CloudAgentSetupFailure | null @@ -155,6 +150,8 @@ export function CloudAgentSetupView({ focusOnOpen = false, steadyHeight = false, escapeGuardRef, + desktopKeys = NO_DESKTOP_KEYS, + onSaveDesktopKey, initialOption, initialFailure = null }: CloudAgentSetupViewProps): React.JSX.Element { @@ -288,6 +285,9 @@ export function CloudAgentSetupView({ {summary}
    ) : null} + {onSaveDesktopKey ? ( + + ) : null} Promise +}): React.JSX.Element | null { + const t = useTranslate() + const [states, setStates] = useState>({}) + if (keys.length === 0) { + return null + } + const save = async (key: CloudOfferableDesktopKey): Promise => { + if (states[key.id]?.kind === 'saving') { + return + } + setStates((current) => ({ ...current, [key.id]: { kind: 'saving' } })) + const error = await onSave(key) + setStates((current) => ({ + ...current, + [key.id]: error ? { kind: 'failed', error } : { kind: 'saved' } + })) + } + return ( +
    +

    + {t('cloudAgentSetup.desktopKeys.title', 'Keys on this computer')} +

    +

    + {t( + 'cloudAgentSetup.desktopKeys.detail', + 'Cloud workspaces don’t get the API keys saved in Orca on this computer. Save one as a personal Cloud secret and the workspace only ever sees a stand-in for it.' + )} +

    +
      + {keys.map((key) => { + const state = states[key.id] ?? { kind: 'idle' } + return ( +
    • +
      + + + {formatAgentTypeLabel(key.agent)}{' '} + {key.envName}{' '} + + ••••{key.hint} + + + {state.kind === 'saved' ? ( + + + {t('cloudAgentSetup.desktopKeys.saved', 'Saved as a Cloud secret')} + + ) : ( + + )} +
      + {state.kind === 'failed' ? ( + void save(key)} + /> + ) : null} +
    • + ) + })} +
    +
    + ) +} diff --git a/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx b/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx index a41c7655da9..a837d418ab7 100644 --- a/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx +++ b/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx @@ -12,7 +12,11 @@ import { HOST_AGENT_SIGN_IN_AGENTS } from '../../../../shared/host-agent-sign-in import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' import { cloudSecretRepoKey } from '../settings/cloud-secrets/cloud-secret-repos' -import { isCloudAgentReady, type CloudAgentReadiness } from './cloud-agent-readiness' +import { + isCloudAgentReady, + type CloudAgentReadiness, + type CloudOfferableDesktopKey +} from './cloud-agent-readiness' import { CloudAgentSetupView, cloudAgentReadinessSummary, @@ -25,6 +29,7 @@ import { useCloudAgentSetup } from './use-cloud-agent-setup' export type VmBuildCloudAgentStepModel = { readiness: CloudAgentReadiness canShare: boolean + desktopKeys?: readonly CloudOfferableDesktopKey[] } export type VmBuildCloudAgentStepMode = @@ -36,6 +41,7 @@ export type VmBuildCloudAgentStepMode = export type VmBuildCloudAgentStepActions = { onSave: CloudAgentSetupViewProps['onSave'] + onSaveDesktopKey?: CloudAgentSetupViewProps['onSaveDesktopKey'] /** The step is done (saved, signing in, or skipped); remember that it ran. */ onDone: () => void onSignIn: () => void @@ -265,6 +271,8 @@ export function VmBuildCloudAgentStepView({ setSignInRequested(true), onCancelSignIn: () => setSignInRequested(false), diff --git a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts index 9c4d977ae24..156479eac72 100644 --- a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts @@ -1,28 +1,54 @@ import { describe, expect, it } from 'vitest' -import { deriveCloudAgentReadiness } from './cloud-agent-readiness' +import type { AgentApiKeySummary } from '../../../../shared/agent-api-keys/agent-api-key-catalog' +import { deriveCloudAgentReadiness, offerableDesktopKeys } from './cloud-agent-readiness' describe('deriveCloudAgentReadiness', () => { - it('prefers an every-host desktop key, then a team key, then the user’s own secret', () => { - expect( - deriveCloudAgentReadiness( - [{ agent: 'claude', hostScope: { kind: 'all' } }], - [{ name: 'OPENAI_API_KEY', scope: 'org' }] - ) - ).toEqual({ claude: 'desktop-key', codex: 'team' }) - expect( - deriveCloudAgentReadiness([], [{ name: 'AI_GATEWAY_API_KEY', scope: 'personal' }]) - ).toEqual({ claude: 'cloud-secret', codex: 'cloud-secret' }) + it('prefers a team key, then the user’s own secret; this computer’s keys never count', () => { + expect(deriveCloudAgentReadiness([{ name: 'OPENAI_API_KEY', scope: 'org' }])).toEqual({ + claude: null, + codex: 'team' + }) + expect(deriveCloudAgentReadiness([{ name: 'AI_GATEWAY_API_KEY', scope: 'personal' }])).toEqual({ + claude: 'cloud-secret', + codex: 'cloud-secret' + }) }) - it('ignores host-scoped desktop keys and variables that are not credentials', () => { + it('ignores variables that are not credentials', () => { expect( - deriveCloudAgentReadiness( - [{ agent: 'codex', hostScope: { kind: 'hosts', hostIds: ['ssh:devbox'] } }], - [ - { name: 'ANTHROPIC_MODEL', scope: 'org' }, - { name: 'DATABASE_URL', scope: 'repo' } - ] - ) + deriveCloudAgentReadiness([ + { name: 'ANTHROPIC_MODEL', scope: 'org' }, + { name: 'DATABASE_URL', scope: 'repo' } + ]) ).toEqual({ claude: null, codex: null }) }) }) + +describe('offerableDesktopKeys', () => { + const key = ( + id: string, + agent: 'claude' | 'gemini' | 'cursor', + envName: string, + all = true + ): Pick => ({ + id, + agent, + envName, + hint: id.slice(-4), + hostScope: all ? { kind: 'all' } : { kind: 'hosts', hostIds: ['ssh:devbox'] } + }) + + it('offers every-host keys whose variable no Cloud secret sets, once per variable', () => { + expect( + offerableDesktopKeys( + [ + key('k-0001', 'claude', 'ANTHROPIC_API_KEY'), + key('k-0002', 'gemini', 'GEMINI_API_KEY'), + key('k-0003', 'cursor', 'CURSOR_API_KEY', false), + key('k-0004', 'claude', 'GEMINI_API_KEY') + ], + [{ name: 'ANTHROPIC_API_KEY' }] + ) + ).toEqual([{ id: 'k-0002', agent: 'gemini', envName: 'GEMINI_API_KEY', hint: '0002' }]) + }) +}) diff --git a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts index 978222035f5..4d07f9aa173 100644 --- a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts @@ -5,7 +5,7 @@ export type CloudSetupAgent = 'claude' | 'codex' export const CLOUD_SETUP_AGENTS: readonly CloudSetupAgent[] = ['claude', 'codex'] /** Where an agent's credential comes from in a new cloud workspace, best first. */ -export type CloudAgentCredentialSource = 'desktop-key' | 'team' | 'cloud-secret' +export type CloudAgentCredentialSource = 'team' | 'cloud-secret' export type CloudAgentReadiness = Record @@ -23,17 +23,13 @@ const CREDENTIAL_NAMES: Record = { } /** - * Desktop keys for every host reach a brand-new VM at agent launch, so they win (zero clicks); host-scoped - * keys cannot name a VM that does not exist yet. Then a team-shared key, then the user's own cloud secret. + * A team-shared key, then the user's own cloud secret. This computer's Agent API Keys never reach a + * cloud VM (they would sit in it in plaintext); they are offered as Cloud secrets instead. */ export function deriveCloudAgentReadiness( - desktopKeys: readonly Pick[], effective: readonly Pick[] ): CloudAgentReadiness { const sourceFor = (agent: CloudSetupAgent): CloudAgentCredentialSource | null => { - if (desktopKeys.some((key) => key.agent === agent && key.hostScope.kind === 'all')) { - return 'desktop-key' - } const names = CREDENTIAL_NAMES[agent] const supplied = effective.filter((secret) => names.includes(secret.name)) if (supplied.some((secret) => secret.scope === 'org')) { @@ -44,6 +40,33 @@ export function deriveCloudAgentReadiness( return { claude: sourceFor('claude'), codex: sourceFor('codex') } } +/** A key on this computer a cloud workspace could use if the user saves it as a Cloud secret. */ +export type CloudOfferableDesktopKey = Pick + +/** + * This computer's keys for every host whose variable no Cloud secret sets yet (a key scoped to some + * hosts was never meant for a VM that does not exist yet). One entry per variable. + */ +export function offerableDesktopKeys( + desktopKeys: readonly Pick< + AgentApiKeySummary, + 'id' | 'agent' | 'envName' | 'hint' | 'hostScope' + >[], + effective: readonly Pick[] +): CloudOfferableDesktopKey[] { + const inCloud = new Set(effective.map((secret) => secret.name)) + const seen = new Set() + const offers: CloudOfferableDesktopKey[] = [] + for (const key of desktopKeys) { + if (key.hostScope.kind !== 'all' || inCloud.has(key.envName) || seen.has(key.envName)) { + continue + } + seen.add(key.envName) + offers.push({ id: key.id, agent: key.agent, envName: key.envName, hint: key.hint }) + } + return offers +} + export function isCloudAgentReady(readiness: CloudAgentReadiness): boolean { return CLOUD_SETUP_AGENTS.some((agent) => readiness[agent] !== null) } diff --git a/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts b/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts index 34d4d0a7bac..bc856aac02c 100644 --- a/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts +++ b/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts @@ -3,7 +3,12 @@ import { cloudSecretsErrorCode, type CloudSecretsErrorCode } from '../../../../shared/cloud-secrets/cloud-secrets-wire' -import { deriveCloudAgentReadiness, type CloudAgentReadiness } from './cloud-agent-readiness' +import { + deriveCloudAgentReadiness, + offerableDesktopKeys, + type CloudAgentReadiness, + type CloudOfferableDesktopKey +} from './cloud-agent-readiness' import { cloudAgentSetupProblem, cloudAgentSetupWrite, @@ -17,7 +22,13 @@ const NOT_CONFIGURED: CloudSecretsErrorCode = 'not_configured' export type CloudAgentSetupModel = | { status: 'loading' } - | { status: 'ready'; readiness: CloudAgentReadiness; canShare: boolean } + | { + status: 'ready' + readiness: CloudAgentReadiness + canShare: boolean + /** This computer's keys that no Cloud secret covers yet: offered, never sent unasked. */ + desktopKeys: CloudOfferableDesktopKey[] + } /** * What a new cloud workspace already has for agents (desktop keys, team and cloud secrets) and how to @@ -33,9 +44,12 @@ export function useCloudAgentSetup(args: { choice: CloudAgentSetupChoice, scope: CloudAgentSetupScope ) => Promise + saveDesktopKey: (key: CloudOfferableDesktopKey) => Promise } { const { repo, runtimeEnvironmentId = null, enabled = true } = args const [model, setModel] = useState({ status: 'loading' }) + // Bumped after a save so the model re-reads what the cloud now has. + const [generation, setGeneration] = useState(0) useEffect(() => { if (!enabled) { @@ -53,14 +67,16 @@ export function useCloudAgentSetup(args: { const view = cloud?.ok ? cloud.value : null setModel({ status: 'ready', - readiness: deriveCloudAgentReadiness(desktop?.keys ?? [], view?.secrets ?? []), - canShare: view?.caller.canWrite.org === true + readiness: deriveCloudAgentReadiness(view?.secrets ?? []), + canShare: view?.caller.canWrite.org === true, + // Without the cloud's answer nothing is offered: a save could shadow a key the team set. + desktopKeys: view ? offerableDesktopKeys(desktop?.keys ?? [], view.secrets) : [] }) }) return () => { cancelled = true } - }, [repo, enabled]) + }, [repo, enabled, generation]) const save = useCallback( async ( @@ -99,5 +115,29 @@ export function useCloudAgentSetup(args: { [runtimeEnvironmentId] ) - return { model, save } + const saveDesktopKey = useCallback( + async (key: CloudOfferableDesktopKey): Promise => { + const api = window.api.cloudSecrets + if (!api?.saveDesktopKey) { + return NOT_CONFIGURED + } + const result = await api + .saveDesktopKey({ agent: key.agent, envName: key.envName }) + .catch(() => null) + if (!result) { + return UNKNOWN + } + if (!result.ok) { + return result.error + } + if (runtimeEnvironmentId) { + void api.refreshEnv({ runtimeEnvironmentId }).catch(() => undefined) + } + setGeneration((value) => value + 1) + return null + }, + [runtimeEnvironmentId] + ) + + return { model, save, saveDesktopKey } } diff --git a/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-fixture-data.ts b/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-fixture-data.ts index 95ba4a6bedb..ab60a0dc43f 100644 --- a/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-fixture-data.ts +++ b/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-fixture-data.ts @@ -151,6 +151,15 @@ export function fixtureCloudSecretsApi(options: { }, secrets: options.effective ?? FIXTURE_EFFECTIVE_SECRETS }), - refreshEnv: () => ok(true) + refreshEnv: () => ok(true), + saveDesktopKey: ({ envName }) => + ok({ + scope: 'personal' as const, + name: envName, + kind: 'agent_key' as const, + hint: 'x4Qa', + updatedAt: 0, + updatedBy: caller.userId + }) } } From 9dcda9941c2592f8d4591b2dfaec53fae6af6cc2 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:32:17 -0800 Subject: [PATCH 18/46] chore(cloud): mobile switch exhaustiveness; extract the read-panel hook --- mobile/src/cloud/CloudReadSnapshotSection.tsx | 2 ++ mobile/src/cloud/cloud-workspace-copy.ts | 7 +++++- .../cloud-workspaces/CloudWorkspacesHome.tsx | 23 ++++-------------- .../cloud-workspaces/use-cloud-read-panel.ts | 24 +++++++++++++++++++ 4 files changed, 36 insertions(+), 20 deletions(-) create mode 100644 src/renderer/src/components/cloud-workspaces/use-cloud-read-panel.ts diff --git a/mobile/src/cloud/CloudReadSnapshotSection.tsx b/mobile/src/cloud/CloudReadSnapshotSection.tsx index a3dac41565c..afad96d971c 100644 --- a/mobile/src/cloud/CloudReadSnapshotSection.tsx +++ b/mobile/src/cloud/CloudReadSnapshotSection.tsx @@ -226,6 +226,8 @@ function prChecksLabel(pr: ReadSnapshotPr, t: Translate): string | null { case 'pending': case 'running': return t('cloud.snapshot.checks.pending', 'Checks running') + // No status, or one this build doesn't name: the VM's own summary line, if any. + case undefined: default: return pr.checksSummary } diff --git a/mobile/src/cloud/cloud-workspace-copy.ts b/mobile/src/cloud/cloud-workspace-copy.ts index 76388468114..7e637d15d41 100644 --- a/mobile/src/cloud/cloud-workspace-copy.ts +++ b/mobile/src/cloud/cloud-workspace-copy.ts @@ -37,7 +37,9 @@ export function attachErrorMessage( 'cloud.error.pairing', 'The workspace is running, but this phone couldn’t connect to it. Your files are safe.' ) - default: + case 'not_found': + return t('cloud.workspace.missing', 'This workspace is gone or you no longer have access.') + case 'failed': return t( 'cloud.error.failed', 'The workspace couldn’t start. Try again, or open it on your desktop.' @@ -128,6 +130,9 @@ export function cloudPromptErrorMessage(code: string | undefined, t: Translate): return t('cloud.prompt.errorNotConnected', 'This phone couldn’t reach the workspace') case 'cloud_agent_unknown': return t('cloud.prompt.errorAgent', 'That agent isn’t installed in this workspace') + // An older queue entry may carry no code: it failed to launch all the same. + case undefined: + case 'launch_failed': default: return t('cloud.prompt.errorLaunch', 'The agent didn’t start') } diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index dfa675417ed..d7d79561217 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -1,6 +1,6 @@ // Home: the org's cloud workspaces (registry on the control plane), filterable by who owns them, // which repo they are in, Mine/Team and archived, grouped by section, with live presence and cost. -import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import React, { useCallback, useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' @@ -18,7 +18,7 @@ import { ANY, CloudWorkspacesToolbar, type CloudWorkspacesFilters } from './Clou import { EmptyState, ErrorState, NewSectionDialog, SkeletonRows } from './CloudWorkspacesStates' import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog' import { CloudReadSnapshotSheet } from './CloudReadSnapshotSheet' -import type { CloudReadWake } from '../orca-cloud/read-snapshot/CloudReadSnapshotView' +import { useCloudReadPanel } from './use-cloud-read-panel' import { formatSandboxHours, sandboxHours, type MemberDirectory } from './cloud-workspace-format' import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender' import { describeError } from './cloud-workspace-errors' @@ -87,22 +87,7 @@ export function CloudWorkspacesHome({ const [now, setNow] = useState(() => Date.now()) const [sectionFor, setSectionFor] = useState(null) const [confirm, setConfirm] = useState(null) - // The Asleep workspace whose read-only copy is open (never wakes it). - const [readingId, setReadingIdState] = useState(null) - // A wake started from the read panel: shown there (elapsed, slow, failed) until it opens. - const [readWake, setReadWake] = useState(null) - const readingRef = useRef(null) - const setReadingId = useCallback( - (next: string | null | ((id: string | null) => string | null)) => { - const value = typeof next === 'function' ? next(readingRef.current) : next - if (value !== readingRef.current) { - setReadWake(null) - } - readingRef.current = value - setReadingIdState(value) - }, - [] - ) + const { readingId, readingRef, setReadingId, readWake, setReadWake } = useCloudReadPanel() const signIn = useAppStore((s) => s.connectCurrentOrcaProfile) const scope = orgId ? filters.scope : 'mine' const { state, stale, reading, refresh, replace } = useCloudWorkspaces( @@ -210,7 +195,7 @@ export function CloudWorkspacesHome({ setOpening((current) => (current === w.id ? null : current)) } }, - [setReadingId] + [readingRef, setReadWake, setReadingId] ) const patch = useCallback( diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-read-panel.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-read-panel.ts new file mode 100644 index 00000000000..ed5689fb32e --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-read-panel.ts @@ -0,0 +1,24 @@ +import { useCallback, useRef, useState } from 'react' +import type { CloudReadWake } from '../orca-cloud/read-snapshot/CloudReadSnapshotView' + +/** + * The Asleep workspace whose read-only copy is open (opening it never wakes it), plus a wake + * started from that panel, shown there (elapsed, slow, failed) until the workspace opens. + */ +export function useCloudReadPanel() { + const [readingId, setReadingIdState] = useState(null) + const [readWake, setReadWake] = useState(null) + const readingRef = useRef(null) + const setReadingId = useCallback( + (next: string | null | ((id: string | null) => string | null)) => { + const value = typeof next === 'function' ? next(readingRef.current) : next + if (value !== readingRef.current) { + setReadWake(null) + } + readingRef.current = value + setReadingIdState(value) + }, + [] + ) + return { readingId, readingRef, setReadingId, readWake, setReadWake } +} From c689f1eddb15bccda91a9314d26abecea49e3153 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:28:59 -0800 Subject: [PATCH 19/46] fix(cloud): reload billing, secrets, API keys and workspaces on team switch (DS-17) Settings and Home kept showing the previous team's plan, secrets, keys and workspaces after a team switch while saves went to the new team, and a billing read from before the switch could land in local state. - useOrcaAccountKey() gives `${userId}:${activeOrgId}`; Plan & billing, Cloud secrets, Cloud environment and Orca API keys remount on it. - useOrcaBillingStatus re-reads on a switch, clears the old plan, and drops (and re-reads) an answer whose billing generation moved. - useCloudWorkspaces keys its read by account, hides another team's list instead of dimming it; Home resets its filters on a switch. - Hook tests cover the stale response being dropped and the new team read. --- .../billing/use-orca-billing-status.test.tsx | 92 +++++++++++++++++++ .../billing/use-orca-billing-status.ts | 30 ++++-- .../cloud-workspaces/CloudWorkspacesHome.tsx | 11 ++- .../use-cloud-workspaces.test.tsx | 75 +++++++++++++++ .../cloud-workspaces/use-cloud-workspaces.ts | 28 +++++- .../accounts/orca/OrcaAccountSettingsPane.tsx | 10 +- .../settings/cloud-api/CloudApiKeysPane.tsx | 6 ++ .../src/hooks/use-orca-account-key.ts | 12 +++ 8 files changed, 249 insertions(+), 15 deletions(-) create mode 100644 src/renderer/src/components/billing/use-orca-billing-status.test.tsx create mode 100644 src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.test.tsx create mode 100644 src/renderer/src/hooks/use-orca-account-key.ts diff --git a/src/renderer/src/components/billing/use-orca-billing-status.test.tsx b/src/renderer/src/components/billing/use-orca-billing-status.test.tsx new file mode 100644 index 00000000000..c9ac1d5ae41 --- /dev/null +++ b/src/renderer/src/components/billing/use-orca-billing-status.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' + +let accountKey = 'user-1:team-a' +vi.mock('@/hooks/use-orca-account-key', () => ({ useOrcaAccountKey: () => accountKey })) + +import { getLastBillingStatus, resetBillingSummary } from './billing-summary-store' +import { sampleTeam } from './plan-billing-fixtures' +import { useOrcaBillingStatus } from './use-orca-billing-status' + +const teamA: OrcaBillingStatusResult = { status: 'ok', entitlement: { ...sampleTeam } } +const teamB: OrcaBillingStatusResult = { + status: 'ok', + entitlement: { ...sampleTeam, plan: null, planLabel: null, status: 'none' } +} + +type Pending = { resolve: (result: OrcaBillingStatusResult) => void } +let pending: Pending[] = [] + +beforeEach(() => { + accountKey = 'user-1:team-a' + pending = [] + resetBillingSummary() + vi.stubGlobal('api', { + orcaProfiles: { + billingStatus: vi.fn( + () => + new Promise((resolve) => { + pending.push({ resolve }) + }) + ) + } + }) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +/** What the auth subscriber does on a team switch: bump the generation, then re-render. */ +function switchTeam(rerender: () => void, next: string): void { + act(() => { + resetBillingSummary() + accountKey = next + rerender() + }) +} + +describe('useOrcaBillingStatus on a team switch', () => { + it('drops the previous team plan and reads the new team', async () => { + const { result, rerender } = renderHook(() => useOrcaBillingStatus(true)) + await act(async () => pending[0].resolve(teamA)) + expect(result.current.result).toEqual(teamA) + + switchTeam(rerender, 'user-1:team-b') + expect(result.current).toMatchObject({ loading: true, result: null }) + expect(pending).toHaveLength(2) + + await act(async () => pending[1].resolve(teamB)) + expect(result.current).toMatchObject({ loading: false, result: teamB }) + expect(getLastBillingStatus()).toEqual(teamB) + }) + + it('never shows or records an answer that started before the switch', async () => { + const { result, rerender } = renderHook(() => useOrcaBillingStatus(true)) + expect(pending).toHaveLength(1) + + switchTeam(rerender, 'user-1:team-b') + await act(async () => pending[0].resolve(teamA)) + expect(result.current).toMatchObject({ loading: true, result: null }) + expect(getLastBillingStatus()).toBeNull() + + await act(async () => pending[1].resolve(teamB)) + expect(result.current).toMatchObject({ loading: false, result: teamB }) + }) + + it('re-reads when the generation moved while a read was in flight', async () => { + const { result } = renderHook(() => useOrcaBillingStatus(true)) + // The account changed under the hook (e.g. reconnect) before its key re-rendered. + act(() => resetBillingSummary()) + await act(async () => pending[0].resolve(teamA)) + expect(result.current.result).toBeNull() + expect(getLastBillingStatus()).toBeNull() + expect(pending).toHaveLength(2) + + await act(async () => pending[1].resolve(teamB)) + expect(result.current).toMatchObject({ loading: false, result: teamB }) + }) +}) diff --git a/src/renderer/src/components/billing/use-orca-billing-status.ts b/src/renderer/src/components/billing/use-orca-billing-status.ts index 41737882049..c3421c097ae 100644 --- a/src/renderer/src/components/billing/use-orca-billing-status.ts +++ b/src/renderer/src/components/billing/use-orca-billing-status.ts @@ -1,4 +1,5 @@ -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' import { getBillingGeneration, @@ -22,7 +23,9 @@ function readBillingStatus(): Promise { /** * Reads the billing status while `enabled`, again on `refresh()`, and whenever the window regains - * focus (the user comes back from Checkout or the Portal in their browser). + * focus (the user comes back from Checkout or the Portal in their browser). A team or account + * switch drops the previous team's status and reads the new one; an answer that started before + * the switch is never shown or recorded. */ export function useOrcaBillingStatus( enabled: boolean @@ -33,6 +36,8 @@ export function useOrcaBillingStatus( })) const [reloadKey, setReloadKey] = useState(0) const refresh = useCallback(() => setReloadKey((key) => key + 1), []) + const accountKey = useOrcaAccountKey() + const loadedAccount = useRef(accountKey) useEffect(() => { if (!enabled) { @@ -40,16 +45,27 @@ export function useOrcaBillingStatus( } let disposed = false let latest = 0 + const switched = loadedAccount.current !== accountKey + loadedAccount.current = accountKey const load = (): void => { const request = ++latest const startedGeneration = getBillingGeneration() - setState((previous) => ({ ...previous, loading: true })) + // The previous team's plan must not stay on screen while the new team's loads. + setState((previous) => + switched && request === 1 ? { loading: true, result: null } : { ...previous, loading: true } + ) void readBillingStatus().then((result) => { // A newer request, or unmounting, supersedes this one. - if (!disposed && request === latest) { - recordBillingStatusIfCurrent(startedGeneration, result) - setState({ loading: false, result }) + if (disposed || request !== latest) { + return } + // The account or team changed while this was in flight: the answer is for the old one. + if (getBillingGeneration() !== startedGeneration) { + load() + return + } + recordBillingStatusIfCurrent(startedGeneration, result) + setState({ loading: false, result }) }) } load() @@ -58,7 +74,7 @@ export function useOrcaBillingStatus( disposed = true window.removeEventListener('focus', load) } - }, [enabled, reloadKey]) + }, [enabled, reloadKey, accountKey]) return { ...state, refresh } } diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index 7fda018ed6a..23fa0d1a19b 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -28,6 +28,7 @@ import { openCloudWorkspace } from './open-cloud-workspace' import { useCloudWorkspaces, useCloudWorkspacesAvailable } from './use-cloud-workspaces' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' const INITIAL_FILTERS: CloudWorkspacesFilters = { scope: 'team', @@ -80,7 +81,14 @@ export function CloudWorkspacesHome({ const available = useCloudWorkspacesAvailable() const orgId = cloud?.activeOrgId const selfId = cloud?.userId ?? null + const account = useOrcaAccountKey() const [filters, setFilters] = useState(INITIAL_FILTERS) + // Owner and repo filters name the previous team's people and repos; a team switch starts over. + const [filtersAccount, setFiltersAccount] = useState(account) + if (filtersAccount !== account) { + setFiltersAccount(account) + setFilters(INITIAL_FILTERS) + } const [opening, setOpening] = useState(null) const [now, setNow] = useState(() => Date.now()) const [sectionFor, setSectionFor] = useState(null) @@ -89,7 +97,8 @@ export function CloudWorkspacesHome({ const scope = orgId ? filters.scope : 'mine' const { state, stale, reading, refresh, replace } = useCloudWorkspaces( { scope, archived: filters.archived ? 'only' : 'exclude' }, - Boolean(cloud) + Boolean(cloud), + account ) // Relative "last active" times tick while the window is visible; hidden windows skip the work. diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.test.tsx b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.test.tsx new file mode 100644 index 00000000000..bea0ebb3dc8 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.test.tsx @@ -0,0 +1,75 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + CloudWorkspace, + CloudWorkspaceListQuery +} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { workspace } from './cloud-workspaces.test-fixture' +import { useCloudWorkspaces } from './use-cloud-workspaces' + +type ListResult = { ok: true; value: CloudWorkspace[] } +let pending: ((result: ListResult) => void)[] = [] +const QUERY: CloudWorkspaceListQuery = { scope: 'team', archived: 'exclude' } + +beforeEach(() => { + pending = [] + vi.stubGlobal('api', { + cloudWorkspaces: { + available: () => Promise.resolve(true), + list: vi.fn( + () => + new Promise((resolve) => { + pending.push(resolve) + }) + ) + } + }) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +const teamA = [workspace({ id: 'ws-a' })] +const teamB = [workspace({ id: 'ws-b' })] + +function render() { + return renderHook(({ account }) => useCloudWorkspaces(QUERY, true, account), { + initialProps: { account: 'user-1:team-a' } + }) +} + +describe('useCloudWorkspaces on a team switch', () => { + it('hides the previous team list and reads the new team at once', async () => { + const { result, rerender } = render() + await act(async () => {}) + await act(async () => pending[0]({ ok: true, value: teamA })) + expect(result.current.state).toMatchObject({ status: 'ready', workspaces: teamA }) + + rerender({ account: 'user-1:team-b' }) + // Not the old team's rows dimmed as "stale": nothing of team A is shown. + expect(result.current.state).toEqual({ status: 'loading' }) + expect(result.current.stale).toBe(false) + await act(async () => {}) + expect(pending).toHaveLength(2) + + await act(async () => pending[1]({ ok: true, value: teamB })) + expect(result.current.state).toMatchObject({ status: 'ready', workspaces: teamB }) + }) + + it('drops a list read for the previous team that lands after the switch', async () => { + const { result, rerender } = render() + await act(async () => {}) + expect(pending).toHaveLength(1) + + rerender({ account: 'user-1:team-b' }) + await act(async () => {}) + await act(async () => pending[0]({ ok: true, value: teamA })) + expect(result.current.state).toEqual({ status: 'loading' }) + + await act(async () => pending[1]({ ok: true, value: teamB })) + expect(result.current.state).toMatchObject({ status: 'ready', workspaces: teamB }) + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts index 86b75504c4c..1e76ace8e54 100644 --- a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts @@ -58,11 +58,24 @@ export function useCloudWorkspacesAvailable(): boolean | null { ) } -export function useCloudWorkspaces(query: CloudWorkspaceListQuery, enabled: boolean) { +/** + * `account` is the signed-in `${userId}:${activeOrgId}`: it is part of the read's key, so a team + * switch re-reads at once and a list read for the previous team is never shown or kept. + */ +function accountOf(key: string): string { + const parsed: { account: string } = JSON.parse(key) + return parsed.account +} + +export function useCloudWorkspaces( + query: CloudWorkspaceListQuery, + enabled: boolean, + account: string +) { const [state, setState] = useState({ status: 'loading' }) const [reading, setReading] = useState(false) const [reloadKey, setReloadKey] = useState(0) - const key = JSON.stringify(query) + const key = JSON.stringify({ account, query }) const keyRef = useRef(key) keyRef.current = key const refresh = useCallback(() => setReloadKey((k) => k + 1), []) @@ -86,7 +99,8 @@ export function useCloudWorkspaces(query: CloudWorkspaceListQuery, enabled: bool return } setReading(true) - const listQuery: CloudWorkspaceListQuery = JSON.parse(key) + const parsed: { query: CloudWorkspaceListQuery } = JSON.parse(key) + const listQuery = parsed.query let result: Awaited> try { result = await window.api.cloudWorkspaces.list(listQuery) @@ -137,6 +151,10 @@ export function useCloudWorkspaces(query: CloudWorkspaceListQuery, enabled: bool }, []) // A list or error read for an earlier filter is shown dimmed and busy until this one lands. - const stale = (state.status === 'ready' || state.status === 'error') && state.key !== key - return { state, stale, reading: reading && enabled, refresh, replace } + // One read for another team is not shown at all: those are not this team's workspaces. + const settled = state.status === 'ready' || state.status === 'error' + const otherAccount = settled && accountOf(state.key) !== account + const shown: CloudWorkspacesState = otherAccount ? { status: 'loading' } : state + const stale = settled && !otherAccount && state.key !== key + return { state: shown, stale, reading: reading && enabled, refresh, replace } } diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx index 37846fb52b9..2f52d8e2a91 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx @@ -4,6 +4,7 @@ import { BookOpen, Check, CircleUserRound, Files, Smartphone } from 'lucide-reac import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { useOrcaProfileAuthStatusRefresh } from '@/hooks/use-orca-profile-auth-status-refresh' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' @@ -75,6 +76,8 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { const [signingOut, setSigningOut] = useState(false) const connected = authStatus?.state === 'connected' const canConnect = authStatus?.configured === true + // Team-scoped sections remount on a team switch so none of them shows the previous team's data. + const accountKey = useOrcaAccountKey() useOrcaProfileAuthStatusRefresh() @@ -134,19 +137,22 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { {connected ? null : }
    - {connected ? : null} + {connected ? : null} {connected && authStatus?.capabilities?.flags?.billing ? ( ) : null} - {connected ? : null} + {connected ? ( + + ) : null} {connected && authStatus?.capabilities?.flags?.sandbox ? ( ) : null} {connected ? ( diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx index b49d8efe499..64ef2dda3bb 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx @@ -13,8 +13,14 @@ import { CloudApiSignedOutNotice } from './CloudApiSignedOutNotice' import { cloudApiErrorCopy } from './cloud-api-copy' import { useOrcaCloudApiAvailability } from '@/hooks/useOrcaCloudApiAvailability' import { useRequestGeneration } from './use-request-generation' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' +/** Keys, settings and grants belong to one team: a team switch remounts and re-reads them. */ export function CloudApiKeysPane(): React.JSX.Element | null { + return +} + +function CloudApiKeysPaneBody(): React.JSX.Element | null { const t = useTranslate() const availability = useOrcaCloudApiAvailability() const api = window.api.cloudApi diff --git a/src/renderer/src/hooks/use-orca-account-key.ts b/src/renderer/src/hooks/use-orca-account-key.ts new file mode 100644 index 00000000000..fcc0c894719 --- /dev/null +++ b/src/renderer/src/hooks/use-orca-account-key.ts @@ -0,0 +1,12 @@ +import { useAppStore } from '@/store' + +/** + * `${userId}:${activeOrgId}` for the signed-in Orca account. Team-scoped views key on it so a + * team switch remounts them: nothing read for the previous team survives into the new one. + */ +export function useOrcaAccountKey(): string { + return useAppStore((state) => { + const cloud = state.orcaProfileAuthStatus?.cloud + return cloud ? `${cloud.userId}:${cloud.activeOrgId ?? ''}` : 'signed-out' + }) +} From dd4baa98ed824bf9b0bc217685e3842017eea19d Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:37:29 -0800 Subject: [PATCH 20/46] fix(cloud): security review of A6: offer and save only keys the proxy swaps; no desktop keys over SSH into a cloud workspace; orcad on a cloud VM drops carried keys - 'Save as personal Cloud secret' is offered, and accepted by main, only for names the egress proxy swaps (a shared list the control-plane test holds equal to the proxy's); anything else would sit on the VM in full, so main answers not_swappable. - SSH launches into an Orca Cloud workspace (orca-* aliases or an 'orca ssh-proxy' ProxyCommand surfaced through ~/.ssh/config Includes) get no desktop keys. - Defense in depth on the VM: orcad with ORCA_IS_CLOUD=1 drops a carried keyEnv. --- .../test/agent-credentials-more.test.ts | 4 +- src/main/cloud-secrets/cloud-secrets-ipc.ts | 4 ++ .../hosted-sandbox/cloud-desktop-keys.test.ts | 40 +++++++++++++++++++ src/main/hosted-sandbox/cloud-desktop-keys.ts | 39 +++++++++++++++++- src/main/ipc/pty/spawn-options-assembly.ts | 9 +---- .../terminal/agent-session-key-env.test.ts | 25 ++++++++++++ .../rpc/methods/terminal/agent-session.ts | 7 +++- .../cloud-agent-readiness.test.ts | 28 +++++++++++++ .../cloud-agent-readiness.ts | 9 ++++- .../cloud-secrets/cloud-secrets-copy.ts | 5 +++ src/renderer/src/i18n/locales/en.json | 15 +++++-- .../cloud-secrets/cloud-secret-rules.ts | 22 ++++++++++ .../cloud-secrets/cloud-secrets-wire.ts | 2 + 13 files changed, 194 insertions(+), 15 deletions(-) create mode 100644 src/main/runtime/rpc/methods/terminal/agent-session-key-env.test.ts diff --git a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts index f0234531168..9eb50a5b13a 100644 --- a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts +++ b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { compileNetworkPolicy } from '../src/network-policy' import { SWAPPED_CREDENTIALS, credentialTargets } from '../src/provider-env' import { AGENT_KEY_NAMES } from '../src/secrets' -import { cloudSecretStoredOnVm } from '../../../../src/shared/cloud-secrets/cloud-secret-rules' +import { CLOUD_SWAPPED_CREDENTIALS, cloudSecretStoredOnVm } from '../../../../src/shared/cloud-secrets/cloud-secret-rules' import { egressSecretHosts, encodeEgressSecretHosts } from '../src/secret-egress' import { ENV_COMMAND } from '../src/sandbox-vm-commands' import { createHarness } from './harness' @@ -286,5 +286,7 @@ describe('every agent credential is either swapped or marked "stored on workspac expect(swapped !== cloudSecretStoredOnVm(name), `${name}: swapped=${swapped}`).toBe(true) } expect(SWAPPED_CREDENTIALS.includes('COPILOT_GITHUB_TOKEN')).toBe(true) + // The desktop's mirror (what it offers to save from this computer) matches the proxy exactly. + expect([...CLOUD_SWAPPED_CREDENTIALS].sort()).toEqual([...SWAPPED_CREDENTIALS].sort()) }) }) diff --git a/src/main/cloud-secrets/cloud-secrets-ipc.ts b/src/main/cloud-secrets/cloud-secrets-ipc.ts index 39ed3a9bdc6..09bf13d8784 100644 --- a/src/main/cloud-secrets/cloud-secrets-ipc.ts +++ b/src/main/cloud-secrets/cloud-secrets-ipc.ts @@ -160,6 +160,10 @@ export function registerCloudSecretsHandlers(userDataPath: string): void { if (nameError) { return { ok: false, error: nameError } } + // Only keys the workspace gets as a stand-in: anything else would sit there in full. + if (!cloudSecretSwapped(envName)) { + return { ok: false, error: 'not_swappable' } + } const value = await desktopKeyValueForCloud(agent, envName) if (!value) { return { ok: false, error: 'not_found' } diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts index 1eb2cb41ab7..96aec6e1168 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts @@ -21,8 +21,19 @@ vi.mock('../agent-api-keys/agent-api-key-launch-env', () => ({ resolveAgentApiKeyLaunchEnv: async (...args: unknown[]) => { launchCalls.push(args) return launchEnv + }, + withAgentApiKeyLaunchEnv: async (env: Record | undefined, ...args: unknown[]) => { + launchCalls.push(args) + return { ...env, ...launchEnv } } })) +const sshTargets = new Map< + string, + { host: string; label: string; configHost?: string; proxyCommand?: string } +>() +vi.mock('../ssh/targets/ssh-target-registry', () => ({ + getSshTargetRegistryStore: () => ({ getSshTarget: (id: string) => sshTargets.get(id) }) +})) const { desktopKeyValueForCloud, isOrcaCloudRuntimeEnvironment } = await import('./cloud-desktop-keys') @@ -32,6 +43,7 @@ beforeEach(() => { environments.clear() launchEnv = {} launchCalls.length = 0 + sshTargets.clear() }) describe('isOrcaCloudRuntimeEnvironment', () => { @@ -90,3 +102,31 @@ describe('withHostAgentApiKeyEnv', () => { expect(readStatus).not.toHaveBeenCalled() }) }) + +describe('withHostAgentApiKeyLaunchEnv (SSH)', () => { + it('sends no desktop keys over SSH into an Orca Cloud workspace, and does elsewhere', async () => { + const { withHostAgentApiKeyLaunchEnv } = await import('./cloud-desktop-keys') + launchEnv = { CURSOR_API_KEY: 'key_real' } + sshTargets.set('t-cloud', { + host: 'orca-api-7f3a', + label: 'orca-api-7f3a', + configHost: 'orca-api-7f3a' + }) + sshTargets.set('t-proxy', { + host: 'box', + label: 'box', + proxyCommand: '/Applications/Orca.app/bin/orca ssh-proxy env-1' + }) + sshTargets.set('t-devbox', { host: 'devbox.lan', label: 'devbox' }) + expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-cloud')).toEqual({ A: '1' }) + expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-proxy')).toEqual({ A: '1' }) + expect(launchCalls).toEqual([]) + expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-devbox')).toEqual({ + A: '1', + CURSOR_API_KEY: 'key_real' + }) + expect(await withHostAgentApiKeyLaunchEnv(undefined, 'cursor', null)).toEqual({ + CURSOR_API_KEY: 'key_real' + }) + }) +}) diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.ts b/src/main/hosted-sandbox/cloud-desktop-keys.ts index 4837108eb5f..95db8e5f1f3 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.ts @@ -2,7 +2,13 @@ // host those keys ride each agent launch as plain env. An Orca Cloud VM must never hold a model key, // so they are not sent there at all: the user saves a key as a personal Cloud secret instead (one key // per click), and the VM then gets a placeholder the egress proxy swaps. -import { resolveAgentApiKeyLaunchEnv } from '../agent-api-keys/agent-api-key-launch-env' +import { + resolveAgentApiKeyLaunchEnv, + withAgentApiKeyLaunchEnv +} from '../agent-api-keys/agent-api-key-launch-env' +import { isCloudSshAlias } from '../cloud-ssh/cloud-ssh-config' +import { getSshTargetRegistryStore } from '../ssh/targets/ssh-target-registry' +import { getConnectionExecutionHostId } from '../../shared/execution-host' import { withAgentApiKeyRuntimeEnv } from '../agent-api-keys/agent-api-key-runtime-call' import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' @@ -78,3 +84,34 @@ export async function withHostAgentApiKeyEnv( } return withAgentApiKeyRuntimeEnv(environmentId, method, params, readStatus) } + +/** + * An SSH target that reaches an Orca Cloud workspace (`orca ssh` writes `orca-*` aliases that proxy + * through the Orca CLI; OpenSSH config Includes can surface them as targets). + */ +export function isOrcaCloudSshConnection(connectionId: string | null | undefined): boolean { + if (!connectionId) { + return false + } + const target = getSshTargetRegistryStore()?.getSshTarget(connectionId) + if (!target) { + return false + } + return ( + [target.configHost, target.host, target.label].some( + (value) => value !== undefined && isCloudSshAlias(value) + ) || /\bssh-proxy\b/.test(target.proxyCommand ?? '') + ) +} + +/** A local or SSH launch env with this computer's Agent API Keys, except over SSH into an Orca Cloud workspace. */ +export async function withHostAgentApiKeyLaunchEnv( + env: Record | undefined, + agent: TuiAgent | undefined, + connectionId: string | null | undefined +): Promise | undefined> { + if (isOrcaCloudSshConnection(connectionId)) { + return env + } + return withAgentApiKeyLaunchEnv(env, agent, getConnectionExecutionHostId(connectionId)) +} diff --git a/src/main/ipc/pty/spawn-options-assembly.ts b/src/main/ipc/pty/spawn-options-assembly.ts index ef3279a6f77..e0dcc651271 100644 --- a/src/main/ipc/pty/spawn-options-assembly.ts +++ b/src/main/ipc/pty/spawn-options-assembly.ts @@ -1,6 +1,5 @@ import { withClaudeAgentViewPlugin } from '../../../shared/claude-agent-view-launch' -import { getConnectionExecutionHostId } from '../../../shared/execution-host' -import { withAgentApiKeyLaunchEnv } from '../../agent-api-keys/agent-api-key-launch-env' +import { withHostAgentApiKeyLaunchEnv } from '../../hosted-sandbox/cloud-desktop-keys' import { resolveStartupShell } from '../../../shared/agent-launch/startup/tui-agent-startup-shell' import { resolveLocalWindowsAgentStartupShell } from '../../../shared/windows-terminal-shell' import { getAppEnvironment } from '../../../shared/app-environment' @@ -156,11 +155,7 @@ export async function assemblePtySpawnLaunchOptions(input: PtySpawnLaunchOptions const env = input.preAdoptedStablePane || input.launchCommand === undefined ? openCodeLaunch.env - : await withAgentApiKeyLaunchEnv( - openCodeLaunch.env, - launchAgent, - getConnectionExecutionHostId(connectionId) - ) + : await withHostAgentApiKeyLaunchEnv(openCodeLaunch.env, launchAgent, connectionId) const pluginDir = !connectionId ? env?.ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR : undefined const launchCommand = pluginDir && openCodeLaunch.command diff --git a/src/main/runtime/rpc/methods/terminal/agent-session-key-env.test.ts b/src/main/runtime/rpc/methods/terminal/agent-session-key-env.test.ts new file mode 100644 index 00000000000..7f5e6f0e7b5 --- /dev/null +++ b/src/main/runtime/rpc/methods/terminal/agent-session-key-env.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { withKeyEnvFolded } from './agent-session' + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('carried agent keys on the host', () => { + it('folds them into the launch env on an ordinary host', () => { + expect(withKeyEnvFolded({ keyEnv: { GEMINI_API_KEY: 'AIzaSy-real' } })).toEqual({ + keyEnv: undefined, + accountEnv: { GEMINI_API_KEY: 'AIzaSy-real' } + }) + }) + + it('drops them on an Orca Cloud VM', () => { + vi.stubEnv('ORCA_IS_CLOUD', '1') + expect( + withKeyEnvFolded({ keyEnv: { GEMINI_API_KEY: 'AIzaSy-real' }, accountEnv: { X: '1' } }) + ).toEqual({ + keyEnv: undefined, + accountEnv: { X: '1' } + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/terminal/agent-session.ts b/src/main/runtime/rpc/methods/terminal/agent-session.ts index 1c4f49cfa16..aee3b21890f 100644 --- a/src/main/runtime/rpc/methods/terminal/agent-session.ts +++ b/src/main/runtime/rpc/methods/terminal/agent-session.ts @@ -34,12 +34,17 @@ function withExecutionHostAgentPresentation; keyEnv?: Record } >(params: T): T { if (!params.keyEnv) { return params } + // An Orca Cloud VM never takes a desktop's keys (they would sit here in plaintext); its agents + // get Cloud secrets as egress placeholders instead. The desktop already withholds them. + if (process.env.ORCA_IS_CLOUD === '1') { + return { ...params, keyEnv: undefined } + } const accountEnv = withAgentKeyLaunchEnv(params.accountEnv, params.keyEnv) const folded: T = { ...params, keyEnv: undefined, ...(accountEnv ? { accountEnv } : {}) } return folded diff --git a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts index 156479eac72..04645ea729e 100644 --- a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts @@ -52,3 +52,31 @@ describe('offerableDesktopKeys', () => { ).toEqual([{ id: 'k-0002', agent: 'gemini', envName: 'GEMINI_API_KEY', hint: '0002' }]) }) }) + +describe('offerableDesktopKeys: only keys a workspace gets as a stand-in', () => { + it('never offers a key the proxy cannot swap (it would sit on the VM in full)', () => { + const all = { kind: 'all' } as const + expect( + offerableDesktopKeys( + [ + { + id: 'a', + agent: 'claude', + envName: 'AWS_BEARER_TOKEN_BEDROCK', + hint: 'aaaa', + hostScope: all + }, + { + id: 'b', + agent: 'opencode', + envName: 'OPENROUTER_API_KEY', + hint: 'bbbb', + hostScope: all + }, + { id: 'c', agent: 'cursor', envName: 'CURSOR_API_KEY', hint: 'cccc', hostScope: all } + ], + [] + ).map((key) => key.envName) + ).toEqual(['CURSOR_API_KEY']) + }) +}) diff --git a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts index 4d07f9aa173..7f068de7b5f 100644 --- a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts @@ -1,4 +1,5 @@ import type { AgentApiKeySummary } from '../../../../shared/agent-api-keys/agent-api-key-catalog' +import { cloudSecretSwapped } from '../../../../shared/cloud-secrets/cloud-secret-rules' import type { CloudEffectiveSecret } from '../../../../shared/cloud-secrets/cloud-secrets-wire' export type CloudSetupAgent = 'claude' | 'codex' @@ -58,7 +59,13 @@ export function offerableDesktopKeys( const seen = new Set() const offers: CloudOfferableDesktopKey[] = [] for (const key of desktopKeys) { - if (key.hostScope.kind !== 'all' || inCloud.has(key.envName) || seen.has(key.envName)) { + // Only keys a workspace gets as a stand-in; anything else would sit on the VM in full. + if ( + key.hostScope.kind !== 'all' || + !cloudSecretSwapped(key.envName) || + inCloud.has(key.envName) || + seen.has(key.envName) + ) { continue } seen.add(key.envName) diff --git a/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts b/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts index d3da00c6023..dd971fd9507 100644 --- a/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts +++ b/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts @@ -31,6 +31,11 @@ export function cloudSecretsErrorCopy( t: Translate ): string { switch (code) { + case 'not_swappable': + return t( + 'cloudSecrets.error.notSwappable', + 'A workspace would get this key in full, so Orca doesn’t save it from here. Add it in Cloud secrets if you accept that.' + ) case 'invalid_name': return t( 'cloudSecrets.error.invalidName', diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 11bf894ca4c..0308f5fccc3 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -26640,13 +26640,11 @@ "shareDetail": "Every teammate’s cloud agents use it.", "status": { "team": "provided by your team", - "desktopKey": "API key from Orca on this computer", "cloudSecret": "your cloud secret", "none": "not set up" }, "source": { "both": "Claude and Codex", - "desktopKey": "{{agent}} uses the API key from Orca on this computer", "team": "Your team provides {{agent}} access", "cloudSecret": "{{agent}} uses your cloud secret" }, @@ -26690,7 +26688,15 @@ "discardQuestion": "Discard the key you typed?", "discard": "Discard", "keepEditing": "Keep editing", - "signInHandedOff": "Continues in the Agent sign-in row below." + "signInHandedOff": "Continues in the Agent sign-in row below.", + "desktopKeys": { + "title": "Keys on this computer", + "detail": "Cloud workspaces don’t get the API keys saved in Orca on this computer. Save one as a personal Cloud secret and the workspace only ever sees a stand-in for it.", + "saved": "Saved as a Cloud secret", + "saveLabel": "Save {{name}} as a personal Cloud secret", + "save": "Save as personal Cloud secret", + "retry": "Try again" + } }, "cloudSecrets": { "editor": { @@ -26837,7 +26843,8 @@ "syntax": "Not a NAME=value line.", "unterminatedQuote": "The closing quote is missing.", "overridden": "Set again further down; the later line is used.", - "unknown": "Something went wrong in Orca Cloud. Nothing was changed. Try again." + "unknown": "Something went wrong in Orca Cloud. Nothing was changed. Try again.", + "notSwappable": "A workspace would get this key in full, so Orca doesn’t save it from here. Add it in Cloud secrets if you accept that." }, "vm": { "badge": "Stored on workspace", diff --git a/src/shared/cloud-secrets/cloud-secret-rules.ts b/src/shared/cloud-secrets/cloud-secret-rules.ts index b40e0351dca..843d5a77f95 100644 --- a/src/shared/cloud-secrets/cloud-secret-rules.ts +++ b/src/shared/cloud-secrets/cloud-secret-rules.ts @@ -169,3 +169,25 @@ export function isPublicHttpsUrl(value: string): boolean { !host.startsWith('[') ) } + +/** + * Variables the Orca Cloud egress proxy swaps (cloud/apps/sandbox-control/src/provider-env.ts, + * checked equal by a control-plane test): a workspace only ever holds a stand-in for these. + */ +export const CLOUD_SWAPPED_CREDENTIALS: readonly string[] = [ + 'ANTHROPIC_API_KEY', + 'ANTHROPIC_AUTH_TOKEN', + 'AI_GATEWAY_API_KEY', + 'OPENAI_API_KEY', + 'GEMINI_API_KEY', + 'GOOGLE_GENERATIVE_AI_API_KEY', + 'CURSOR_API_KEY', + 'GOOGLE_API_KEY', + 'COPILOT_GITHUB_TOKEN', + 'COPILOT_PROVIDER_API_KEY', + 'COPILOT_PROVIDER_BEARER_TOKEN' +] + +export function cloudSecretSwapped(name: string): boolean { + return CLOUD_SWAPPED_CREDENTIALS.includes(name) +} diff --git a/src/shared/cloud-secrets/cloud-secrets-wire.ts b/src/shared/cloud-secrets/cloud-secrets-wire.ts index bcc8482ef5c..6d48c2943eb 100644 --- a/src/shared/cloud-secrets/cloud-secrets-wire.ts +++ b/src/shared/cloud-secrets/cloud-secrets-wire.ts @@ -86,6 +86,8 @@ export type CloudSecretsErrorCode = | 'secret_limit' | 'unauthorized' | 'not_found' + /** Desktop only: a key the workspace would get in full (no egress stand-in), so not saved from here. */ + | 'not_swappable' | 'unavailable' | 'timeout' | 'not_configured' From 046e08f60dfcba43547e0f082affb315d6e13855 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 10 Nov 2026 02:39:06 -0800 Subject: [PATCH 21/46] fix(cloud-ports): keyboard Share and More actions on port rows, W3 copy and contrast (DS-29) (#209) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Port rows get hover/focus buttons: Open in browser, Share… (Orca Cloud), and More actions for port N, which opens the existing row menu. - Drop focus:outline-none on the port row group so the focus-ring shows. - Retry -> Try again; listen failure copy; sentence case for SSH/ports labels. - Remote desktop notCloud/notInstalled/signedOut render neutral, not red. - busy/taken -> in use on this computer. - Expired / Turned off share status keeps full text-muted-foreground. - New i18n keys for changed defaults; stale keys pruned from all locales. - Fixtures: share-links portRowFocused / portRowShareFocused / portRowMoreActions. --- .../auth-callback-forward.ts | 2 +- .../agent-sign-in/AgentSignInCard.fixture.tsx | 7 +- .../agent-sign-in/AgentSignInCard.tsx | 2 +- .../CloudRemoteDesktopToast.tsx | 11 +-- .../components/right-sidebar/PortsPanel.tsx | 13 +++- .../cloud-share/share-link-row.tsx | 12 +++- .../cloud-share/share-links.fixture.tsx | 53 ++++++++++++++ .../cloud-share/shared-links-list.tsx | 2 +- .../cloud-share/use-share-port-action.tsx | 40 +++++++++++ .../right-sidebar/local-port-row.test.tsx | 72 +++++++++++++++++++ .../right-sidebar/local-port-row.tsx | 69 ++++++++++++++---- .../right-sidebar/local-port-section.tsx | 3 + .../local-workspace-ports-panel.tsx | 10 ++- .../runtime-port-forward-status.fixture.tsx | 2 +- .../runtime-port-forward-status.tsx | 2 +- .../right-sidebar/ssh-forwarded-port-row.tsx | 4 +- .../use-runtime-port-row-forwarding.tsx | 6 +- .../components/settings/ports/PortsPane.tsx | 4 +- .../components/settings/ports/ports-search.ts | 2 +- .../cloud-ssh/CloudSshIncludeDialog.tsx | 2 +- .../cloud-ssh/CloudSshMenuItems.tsx | 4 +- .../cloud-ssh/cloud-ssh-actions.tsx | 2 +- src/renderer/src/i18n/locales/de.json | 5 -- src/renderer/src/i18n/locales/en.json | 46 ++++++------ src/renderer/src/i18n/locales/es.json | 5 -- src/renderer/src/i18n/locales/fr.json | 5 -- src/renderer/src/i18n/locales/ja.json | 5 -- src/renderer/src/i18n/locales/ko.json | 5 -- src/renderer/src/i18n/locales/pt.json | 5 -- src/renderer/src/i18n/locales/ru.json | 5 -- src/renderer/src/i18n/locales/tr.json | 5 -- src/renderer/src/i18n/locales/zh-Hant.json | 5 -- src/renderer/src/i18n/locales/zh.json | 5 -- .../runtime-port-forwards-store.ts | 4 +- .../languages/protected-copy-keys.json | 4 +- 35 files changed, 313 insertions(+), 115 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/local-port-row.test.tsx diff --git a/src/main/ipc/runtime-environments/auth-callback-forward.ts b/src/main/ipc/runtime-environments/auth-callback-forward.ts index db72bf4b5bb..689e31f7f6e 100644 --- a/src/main/ipc/runtime-environments/auth-callback-forward.ts +++ b/src/main/ipc/runtime-environments/auth-callback-forward.ts @@ -157,7 +157,7 @@ export class AuthCallbackForward { ok: false, code: busy ? 'port_busy' : 'listen_failed', message: busy - ? `Port ${this.request.port} is busy on this computer.` + ? `Port ${this.request.port} is in use on this computer.` : 'Orca could not listen for the sign-in on this computer.' } } diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx index b3f28ab17bd..6df1f77f717 100644 --- a/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx @@ -61,7 +61,12 @@ export const waitingCodex = shot( export const signedIn = shot(gate({ step: 'signed', email: 'nw@stably.ai' })) export const portBusy = shot( gate( - { step: 'error', kind: 'port_busy', message: 'Port 1455 is busy.', port: 1455 }, + { + step: 'error', + kind: 'port_busy', + message: 'Port 1455 is in use on this computer.', + port: 1455 + }, { agent: 'codex' } ) ) diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx index ee0e671db45..fd6b2ecf5bb 100644 --- a/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx @@ -336,7 +336,7 @@ function AgentSignInError({ case 'port_busy': return ( ( + + ), + [shareAvailable, openShareDialog] + ) const scopedHost = useMemo( () => host.kind === 'host-scoped' && workspaceId @@ -62,6 +72,7 @@ export default function PortsPanel({ isVisible }: { isVisible: boolean }): React runtimeTarget={host.target} sshForwardTargetId={sshForwardTargetId} portMenuItems={shareAvailable ? sharePortMenuItems : undefined} + portActions={shareAvailable ? sharePortActions : undefined} isSandbox={shareAvailable} footer={(activePorts) => (
    -
    -
    +
    + {/* Dim the icon and port only: the Expired / Turned off status keeps full muted contrast. */} +
    -
    +
    {showPort && ( :{share.port} )} diff --git a/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx b/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx index f6df5b7cc5e..62d1df888e3 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx @@ -4,6 +4,7 @@ import type { WorkspacePort } from '../../../../../shared/workspace-ports' import { LocalPortRow } from '../local-port-row' import { SharedLinksList, type SharedLinksListProps } from './shared-links-list' import { SharePortDialog } from './share-port-dialog' +import { SharePortButton, SharePortMenuItem } from './use-share-port-action' const NOW = Date.UTC(2026, 10, 9, 12, 0, 0) const HOUR = 3_600_000 @@ -177,6 +178,58 @@ export const besidePorts = defineFixture({ ) }) +const shareAction = { available: true, openShareDialog: noop } +// Shows the focus-ring as keyboard focus would (Chromium honors focusVisible). +const FOCUS_VISIBLE: FocusOptions & { focusVisible: boolean } = { focusVisible: true } + +/** A cloud port row as keyboard users get it: Open in browser, Share…, Copy, Stop, More actions. */ +function CloudPortRow({ tall = false }: { tall?: boolean }) { + return ( +
    + } + forwardMenuItems={} + /> +
    + ) +} + +/** Tabbing onto the row: the focus-ring outline shows and the row buttons appear. */ +export const portRowFocused = defineFixture({ + width: 300, + render: () => , + interact: (frame) => { + frame.querySelector('[role="group"]')?.focus(FOCUS_VISIBLE) + } +}) + +/** Share… reached from the keyboard: the row's Share button focused. */ +export const portRowShareFocused = defineFixture({ + width: 300, + render: () => , + interact: (frame) => { + frame + .querySelector('button[aria-label="Share port 3000…"]') + ?.focus(FOCUS_VISIBLE) + } +}) + +/** "More actions for port 3000" opens the same menu as right-click, Share… included. */ +export const portRowMoreActions = defineFixture({ + width: 300, + render: () => , + interact: async (frame) => { + frame + .querySelector('button[aria-label="More actions for port 3000"]') + ?.click() + await new Promise((resolve) => setTimeout(resolve, 50)) + } +}) + function Dialog({ port, created, diff --git a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx index 0667d63a06b..611b9193640 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx @@ -142,7 +142,7 @@ export function SharedLinksList({ retryLabel={ needsSignIn ? undefined - : t('auto.components.right.sidebar.CloudShare.retry', 'Retry') + : t('auto.components.right.sidebar.CloudShare.tryAgain', 'Try again') } onRetry={needsSignIn ? undefined : onRetry} retrying={retrying} diff --git a/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx b/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx index f96f1f1dbc2..b9b94722911 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx @@ -1,7 +1,9 @@ import React, { useCallback, useState } from 'react' import { Share2 } from 'lucide-react' import { toast } from 'sonner' +import { Button } from '@/components/ui/button' import { ContextMenuItem } from '@/components/ui/context-menu' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { @@ -144,3 +146,41 @@ export function SharePortMenuItem({ ) } + +/** "Share…" as a port row hover/focus button, so sharing doesn't need a right-click. */ +export function SharePortButton({ + port, + action +}: { + port: number + action: Pick +}): React.JSX.Element | null { + const t = useTranslate() + if (!action.available || SHARE_RESERVED_PORTS.includes(port)) { + return null + } + return ( + + + + + + {t('auto.components.right.sidebar.CloudShare.menuShare', 'Share…')} + + + ) +} diff --git a/src/renderer/src/components/right-sidebar/local-port-row.test.tsx b/src/renderer/src/components/right-sidebar/local-port-row.test.tsx new file mode 100644 index 00000000000..355b2ad4468 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/local-port-row.test.tsx @@ -0,0 +1,72 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { WorkspacePort } from '../../../../shared/workspace-ports' +import { LocalPortRow } from './local-port-row' +import { SharePortButton, SharePortMenuItem } from './cloud-share/use-share-port-action' + +const port: WorkspacePort = { + id: '127.0.0.1:3000:4242', + bindHost: '127.0.0.1', + connectHost: '127.0.0.1', + port: 3000, + pid: 4242, + processName: 'vite', + protocol: 'http', + kind: 'workspace', + owner: { + worktreeId: 'repo::/workspace/app', + repoId: 'repo', + displayName: 'app', + path: '/workspace/app', + confidence: 'cwd' + } +} + +function renderRow(openShareDialog = vi.fn(), available = true) { + const action = { available, openShareDialog } + render( + } + forwardMenuItems={} + /> + ) + return openShareDialog +} + +afterEach(cleanup) + +describe('LocalPortRow keyboard actions', () => { + it('offers Open in browser, Share… and More actions as row buttons', () => { + const openShareDialog = renderRow() + expect(screen.getByRole('button', { name: 'Open in browser' })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Share port 3000…' })) + expect(openShareDialog).toHaveBeenCalledWith(3000) + expect(screen.getByRole('button', { name: 'More actions for port 3000' })).toBeTruthy() + }) + + it('hides Share… when sharing is unavailable', () => { + renderRow(vi.fn(), false) + expect(screen.queryByRole('button', { name: 'Share port 3000…' })).toBeNull() + }) + + it('opens the row menu, Share… included, from the More actions button', async () => { + const openShareDialog = renderRow() + fireEvent.click(screen.getByRole('button', { name: 'More actions for port 3000' })) + const share = await screen.findByRole('menuitem', { name: 'Share…' }) + expect(screen.getByRole('menuitem', { name: 'Copy address' })).toBeTruthy() + fireEvent.click(share) + expect(openShareDialog).toHaveBeenCalledWith(3000) + }) + + it('keeps the focus-ring outline on the row group', () => { + renderRow() + const group = screen.getByRole('group', { name: 'Port 3000 menu' }) + expect(group.className).not.toContain('focus:outline-none') + expect(group.className).toContain('focus-visible:outline-focus-ring') + }) +}) diff --git a/src/renderer/src/components/right-sidebar/local-port-row.tsx b/src/renderer/src/components/right-sidebar/local-port-row.tsx index 3377dd1ccd5..dc83f2e85b3 100644 --- a/src/renderer/src/components/right-sidebar/local-port-row.tsx +++ b/src/renderer/src/components/right-sidebar/local-port-row.tsx @@ -1,5 +1,5 @@ -import React, { useCallback } from 'react' -import { Box, Copy, ExternalLink, Info, Server, Trash2 } from 'lucide-react' +import React, { useCallback, useRef } from 'react' +import { Box, Copy, Ellipsis, ExternalLink, Info, Server, Trash2 } from 'lucide-react' import { getPortOpenBrowserTooltipLabel } from '@/lib/workspace-ports/workspace-port-actions' import { addressForPort } from '@/lib/workspace-ports/workspace-port-urls' import { Button } from '@/components/ui/button' @@ -29,6 +29,7 @@ export function LocalPortRow({ forwardStatus, forwardMenuItems, forwardActions, + shareAction, copyAddress }: { port: WorkspacePort @@ -41,10 +42,13 @@ export function LocalPortRow({ forwardMenuItems?: React.ReactNode /** Hover actions for the forward (Stop Forwarding), next to Open/Copy. */ forwardActions?: React.ReactNode + /** Orca Cloud: a "Share…" hover button after Open (the same action as the menu's Share…). */ + shareAction?: React.ReactNode /** Overrides the copied address, e.g. with the forwarded localhost one. */ copyAddress?: string }): React.JSX.Element { const t = useTranslate() + const menuTriggerRef = useRef(null) const handleCopy = useCallback(() => { void window.api.ui.writeClipboardText(copyAddress ?? addressForPort(port)) }, [copyAddress, port]) @@ -87,6 +91,20 @@ export function LocalPortRow({ [onStop, port] ) + // The row menu is a context menu; this opens it under the button so keyboard and trackpad users reach Share… and the rest. + const handleMoreActionsClick = useCallback((event: React.MouseEvent) => { + const rect = event.currentTarget.getBoundingClientRect() + menuTriggerRef.current?.dispatchEvent( + new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + button: 2, + clientX: rect.left, + clientY: rect.bottom + }) + ) + }, []) + const processLabel = port.processName ?? (port.pid @@ -103,9 +121,15 @@ export function LocalPortRow({ ) : t('auto.components.right.sidebar.PortsPanel.unassigned', 'Unassigned') const openBrowserLabel = t( - 'auto.components.right.sidebar.PortsPanel.b22b128b2a', - 'Open in Browser' + 'auto.components.right.sidebar.PortsPanel.openInBrowser', + 'Open in browser' ) + const moreActionsLabel = t( + 'auto.components.right.sidebar.PortsPanel.moreActionsForPort', + 'More actions for port {{port}}', + { port: port.port } + ) + const stopProcessLabel = t('auto.components.right.sidebar.PortsPanel.stopProcess', 'Stop process') const canStopProcess = port.kind === 'workspace' && Boolean(port.pid) && port.processName !== 'Electron' @@ -114,7 +138,8 @@ export function LocalPortRow({
    )} + {shareAction} - {t('auto.components.right.sidebar.PortsPanel.f9528da632', 'Stop Process')} + {stopProcessLabel} )} + + + + + + {moreActionsLabel} + +
    @@ -231,7 +272,7 @@ export function LocalPortRow({ )} - {t('auto.components.right.sidebar.PortsPanel.792baeb7ed', 'Copy Address')} + {t('auto.components.right.sidebar.PortsPanel.copyAddress', 'Copy address')} {forwardMenuItems} - {t('auto.components.right.sidebar.PortsPanel.bdac206faf', 'Copy Details')} + {t('auto.components.right.sidebar.PortsPanel.copyDetails', 'Copy details')} onShowDetails(port)} > - {t('auto.components.right.sidebar.PortsPanel.a223459512', 'Show Details')} + {t('auto.components.right.sidebar.PortsPanel.showDetails', 'Show details')} onStop(port)} > - {t('auto.components.right.sidebar.PortsPanel.f9528da632', 'Stop Process')} + {stopProcessLabel} diff --git a/src/renderer/src/components/right-sidebar/local-port-section.tsx b/src/renderer/src/components/right-sidebar/local-port-section.tsx index fcc1551dd16..ce94860a1de 100644 --- a/src/renderer/src/components/right-sidebar/local-port-section.tsx +++ b/src/renderer/src/components/right-sidebar/local-port-section.tsx @@ -8,6 +8,8 @@ export type PortRowForwarding = { status: (port: WorkspacePort) => React.ReactNode menuItems: (port: WorkspacePort) => React.ReactNode actions: (port: WorkspacePort) => React.ReactNode + /** Host row buttons after Open (Orca Cloud: Share…). */ + hostActions?: (port: WorkspacePort) => React.ReactNode copyAddress: (port: WorkspacePort) => string | undefined } @@ -72,6 +74,7 @@ export function LocalPortSection({ forwardStatus={forwarding?.status(port)} forwardMenuItems={forwarding?.menuItems(port)} forwardActions={forwarding?.actions(port)} + shareAction={forwarding?.hostActions?.(port)} copyAddress={forwarding?.copyAddress(port)} /> )) diff --git a/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx b/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx index 27c04d9f65d..e3c0d5b3247 100644 --- a/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx +++ b/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx @@ -36,6 +36,7 @@ export function LocalWorkspacePortsPanel({ runtimeTarget, sshForwardTargetId = null, portMenuItems, + portActions, footer, isSandbox = false }: { @@ -46,6 +47,8 @@ export function LocalWorkspacePortsPanel({ sshForwardTargetId?: string | null /** Extra row actions for this host's ports (Orca Cloud: Share…); rides the forwarding menu. */ portMenuItems?: (port: WorkspacePort) => React.ReactNode + /** The same host actions as hover/focus row buttons (Orca Cloud: Share…), after Open. */ + portActions?: (port: WorkspacePort) => React.ReactNode /** Host-specific sections below the ports (Orca Cloud: shared links), given the listening ports. */ footer?: (activePorts: readonly WorkspacePort[]) => React.ReactNode /** An Orca Cloud sandbox: copy says "sandbox" and offers Wake. */ @@ -69,7 +72,12 @@ export function LocalWorkspacePortsPanel({ }) const scanKey = runtimeTarget ? `${workspacePortRuntimeTargetKey(runtimeTarget)}:all` : null - const runtimeForwarding = useRuntimePortRowForwarding(runtimeTarget, portMenuItems, isSandbox) + const runtimeForwarding = useRuntimePortRowForwarding( + runtimeTarget, + portMenuItems, + isSandbox, + portActions + ) const refresh = useCallback(() => { if (!activeRepoId || !runtimeTarget || !scanKey) { diff --git a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx index b3f0505276c..ba606bb5911 100644 --- a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx +++ b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx @@ -58,7 +58,7 @@ const states: Record = { 5173: { kind: 'forwarded', forward: forward(5173) }, 3000: { kind: 'forwarded', forward: forward(3000, { localPort: 3001, reason: 'user' }) }, 8080: { kind: 'pending' }, - 4000: { kind: 'failed', message: 'localhost:4000 in use', busy: true }, + 4000: { kind: 'failed', message: 'localhost:4000 in use on this computer', busy: true }, 9000: { kind: 'failed', message: 'Host not reachable', busy: false }, 9229: { kind: 'unforwarded' } } diff --git a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx index beef4ebd57f..7f65a156922 100644 --- a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx +++ b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx @@ -134,7 +134,7 @@ export function RuntimePortForwardStatus({ } : { icon: , - label: t('auto.components.right.sidebar.RuntimePortForward.retry', 'Retry') + label: t('auto.components.right.sidebar.RuntimePortForward.tryAgain', 'Try again') } : { icon: , diff --git a/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx b/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx index e8c3a8b26d3..0a3260b33f0 100644 --- a/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx +++ b/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx @@ -88,8 +88,8 @@ export function SshForwardedPortRow({ const advertisedBrowserUrl = advertisedBrowserUrlForForwardedRow(entry) const openBrowserLabel = t( - 'auto.components.right.sidebar.PortsPanel.b22b128b2a', - 'Open in Browser' + 'auto.components.right.sidebar.PortsPanel.openInBrowser', + 'Open in browser' ) const openBrowserTitle = getPortOpenBrowserTooltipLabel( advertisedBrowserUrl diff --git a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx index 1bffd0d3471..d957681c442 100644 --- a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx +++ b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx @@ -57,7 +57,9 @@ export function useRuntimePortRowForwarding( /** Host actions after the forward items (Orca Cloud: Share…). */ extraMenuItems?: (port: WorkspacePort) => ReactNode, /** Orca Cloud: copy says "sandbox", and offline offers Wake. */ - isSandbox = false + isSandbox = false, + /** Host row buttons after Open (Orca Cloud: Share…). */ + extraActions?: (port: WorkspacePort) => ReactNode ): RuntimePortRowForwarding | null { const t = useTranslate() const environmentId = runtimeTarget?.kind === 'environment' ? runtimeTarget.environmentId : null @@ -197,6 +199,7 @@ export function useRuntimePortRowForwarding( ) }, + hostActions: extraActions, copyAddress: (port) => { const existing = forwardFor(port) return existing ? `localhost:${existing.localPort}` : undefined @@ -204,6 +207,7 @@ export function useRuntimePortRowForwarding( } }, [ environmentId, + extraActions, extraMenuItems, failures, forward, diff --git a/src/renderer/src/components/settings/ports/PortsPane.tsx b/src/renderer/src/components/settings/ports/PortsPane.tsx index 2e7fa14bd13..89ada6191e8 100644 --- a/src/renderer/src/components/settings/ports/PortsPane.tsx +++ b/src/renderer/src/components/settings/ports/PortsPane.tsx @@ -123,8 +123,8 @@ export function PortsPane({ settings }: { settings: GlobalSettings }): React.JSX [ { - title: translate('auto.components.settings.ports.search.title', 'Port Forwarding'), + title: translate('auto.components.settings.ports.search.titleSentenceCase', 'Port forwarding'), description: translate( 'auto.components.settings.ports.search.descriptionSandboxes', 'Forward dev servers in sandboxes and on remote hosts to this computer.' diff --git a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx index e151b423321..df57cb1f8f6 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx @@ -104,7 +104,7 @@ const CloudSshIncludeDialog = React.memo(function CloudSshIncludeDialog() { {t('auto.components.sidebar.CloudSshIncludeDialog.cancel', 'Cancel')} diff --git a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx index 0c5c986bbe3..c2ee41aa49b 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx @@ -136,7 +136,7 @@ export function CloudSshMenuItems({ aria-describedby={status.hasAccess ? undefined : hintId} > - {t('auto.components.sidebar.CloudSsh.copyCommand', 'Copy SSH Command')} + {t('auto.components.sidebar.CloudSsh.copySshCommand', 'Copy SSH command')} {status.hasAccess ? ( <> @@ -147,7 +147,7 @@ export function CloudSshMenuItems({ disabled={disabled} > - {t('auto.components.sidebar.CloudSsh.revoke', 'Revoke SSH Access')} + {t('auto.components.sidebar.CloudSsh.revokeSshAccess', 'Revoke SSH access')} {status.includeInstalled ? ( Date: Tue, 10 Nov 2026 02:39:51 -0800 Subject: [PATCH 22/46] fix: import and SSH store method name --- src/main/cloud-secrets/cloud-secrets-ipc.ts | 1 + src/main/hosted-sandbox/cloud-desktop-keys.test.ts | 2 +- src/main/hosted-sandbox/cloud-desktop-keys.ts | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/cloud-secrets/cloud-secrets-ipc.ts b/src/main/cloud-secrets/cloud-secrets-ipc.ts index 09bf13d8784..436b2c21250 100644 --- a/src/main/cloud-secrets/cloud-secrets-ipc.ts +++ b/src/main/cloud-secrets/cloud-secrets-ipc.ts @@ -17,6 +17,7 @@ import { getOrcaCloudAvailability } from '../hosted-sandbox/hosted-sandbox-insta import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' import { cloudSecretNameError, + cloudSecretSwapped, cloudSecretValueError } from '../../shared/cloud-secrets/cloud-secret-rules' import { desktopKeyValueForCloud } from '../hosted-sandbox/cloud-desktop-keys' diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts index 96aec6e1168..0703593478c 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts @@ -32,7 +32,7 @@ const sshTargets = new Map< { host: string; label: string; configHost?: string; proxyCommand?: string } >() vi.mock('../ssh/targets/ssh-target-registry', () => ({ - getSshTargetRegistryStore: () => ({ getSshTarget: (id: string) => sshTargets.get(id) }) + getSshTargetRegistryStore: () => ({ getTarget: (id: string) => sshTargets.get(id) }) })) const { desktopKeyValueForCloud, isOrcaCloudRuntimeEnvironment } = diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.ts b/src/main/hosted-sandbox/cloud-desktop-keys.ts index 95db8e5f1f3..b5217dad2eb 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.ts @@ -93,7 +93,7 @@ export function isOrcaCloudSshConnection(connectionId: string | null | undefined if (!connectionId) { return false } - const target = getSshTargetRegistryStore()?.getSshTarget(connectionId) + const target = getSshTargetRegistryStore()?.getTarget(connectionId) if (!target) { return false } From 0c542e83755ecb20f2edbf06c4207b15d9df14d4 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:41:14 -0800 Subject: [PATCH 23/46] copy(billing): overage reads '{{rate}} per sandbox hour' with the rate from the plan (glossary); formatRateCents always shows cents --- .../src/components/billing/PlanBillingUsage.tsx | 16 ++++++++-------- .../components/billing/plans/TeamPlanCard.tsx | 15 ++++++++++----- .../billing/plans/plans-pricing.test.ts | 6 ++++++ .../components/billing/plans/plans-pricing.ts | 10 ++++++++++ src/renderer/src/i18n/locales/en.json | 6 +++--- 5 files changed, 37 insertions(+), 16 deletions(-) diff --git a/src/renderer/src/components/billing/PlanBillingUsage.tsx b/src/renderer/src/components/billing/PlanBillingUsage.tsx index 8f306414235..b56af82d4cd 100644 --- a/src/renderer/src/components/billing/PlanBillingUsage.tsx +++ b/src/renderer/src/components/billing/PlanBillingUsage.tsx @@ -11,7 +11,7 @@ import type { OrcaBillingOverageArgs } from '../../../../shared/orca-billing' import { formatHours, includedUsagePercent } from './plan-billing-format' -import { formatCents } from './plans/plans-pricing' +import { formatCents, formatRateCents } from './plans/plans-pricing' import { ORCA_BILLING_OVERAGE_SECTION_ID } from '../new-workspace/orca-cloud-run-target-access' /** "Resets and renews Dec 2" when both land the same day (monthly); separate parts otherwise. */ @@ -162,17 +162,17 @@ export function OverageControls({ const changed = capValid && capDollars.trim() !== savedDollars const paymentFailed = entitlement.payment.pastDueSince !== null const description = t( - 'auto.components.billing.overageDescription5', - 'Optional overage at {{value0}}/hour, up to a monthly spend cap you set ({{value1}} by default).', + 'auto.components.billing.overageDescription6', + 'Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set ({{cap}} by default).', { - value0: formatCents(overage.centsPerHour, locale), - value1: formatCents(entitlement.offers?.team.defaultSpendCapCents ?? 2500, locale) + rate: formatRateCents(overage.centsPerHour, locale), + cap: formatCents(entitlement.offers?.team.defaultSpendCapCents ?? 2500, locale) } ) const descriptionOn = t( - 'auto.components.billing.overageDescriptionOn2', - 'Optional overage at {{value0}}/hour, up to a monthly spend cap you set.', - { value0: formatCents(overage.centsPerHour, locale) } + 'auto.components.billing.overageDescriptionOn3', + 'Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set.', + { rate: formatRateCents(overage.centsPerHour, locale) } ) const capPercent = overage.spendCapCents > 0 diff --git a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx index 1ab9d0ecbf8..34e4e84771c 100644 --- a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx +++ b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx @@ -7,7 +7,12 @@ import { LoadingSpinner } from '@/components/LoadingSpinner' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { OrcaBillingInterval, OrcaBillingOffers } from '../../../../../shared/orca-billing' import { PlanCardShell } from './PlanCardShell' -import { formatCents, perSeatMonthlyCents, periodTotalCents } from './plans-pricing' +import { + formatCents, + formatRateCents, + perSeatMonthlyCents, + periodTotalCents +} from './plans-pricing' import { ORCA_CLOUD_SANDBOX_SPEC } from '../../../../../shared/hosted-sandbox/hosted-sandbox-wire' export type TeamPlanCardMode = 'choose' | 'current' | 'locked' @@ -65,11 +70,11 @@ export function TeamPlanCard({ ), t('auto.components.billing.plans.featureReady', 'Ready in seconds, nothing to set up or host'), t( - 'auto.components.billing.plans.featureOverage5', - 'Optional overage at {{value0}}/hour, up to a monthly spend cap you set ({{value1}} by default)', + 'auto.components.billing.plans.featureOverage6', + 'Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set ({{cap}} by default)', { - value0: formatCents(team.overageCentsPerHour, locale), - value1: formatCents(team.defaultSpendCapCents, locale) + rate: formatRateCents(team.overageCentsPerHour, locale), + cap: formatCents(team.defaultSpendCapCents, locale) } ) ] diff --git a/src/renderer/src/components/billing/plans/plans-pricing.test.ts b/src/renderer/src/components/billing/plans/plans-pricing.test.ts index 19dd7bb2c5b..047e7075978 100644 --- a/src/renderer/src/components/billing/plans/plans-pricing.test.ts +++ b/src/renderer/src/components/billing/plans/plans-pricing.test.ts @@ -4,6 +4,7 @@ import { annualSavingsPercent, clampSeats, formatCents, + formatRateCents, perSeatMonthlyCents, periodTotalCents } from './plans-pricing' @@ -38,6 +39,11 @@ describe('plans pricing', () => { expect(formatCents(144000, 'en-US')).toBe('$1,440') }) + it('always shows cents on a per-hour rate', () => { + expect(formatRateCents(100, 'en-US')).toBe('$1.00') + expect(formatRateCents(75, 'en-US')).toBe('$0.75') + }) + it('clamps seats to 1..max', () => { expect(clampSeats(0, 500)).toBe(1) expect(clampSeats(Number.NaN, 500)).toBe(1) diff --git a/src/renderer/src/components/billing/plans/plans-pricing.ts b/src/renderer/src/components/billing/plans/plans-pricing.ts index 5e94f0aac1b..1d83adea42b 100644 --- a/src/renderer/src/components/billing/plans/plans-pricing.ts +++ b/src/renderer/src/components/billing/plans/plans-pricing.ts @@ -46,6 +46,16 @@ export function formatCents(cents: number, locale: string): string { }).format(cents / 100) } +/** A per-hour rate always shows cents ("$1.00", "$0.75"), unlike whole-dollar prices. */ +export function formatRateCents(cents: number, locale: string): string { + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 2, + maximumFractionDigits: 2 + }).format(cents / 100) +} + export const MIN_SEATS = 1 export function clampSeats(value: number, max: number): number { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b9bcc9b9409..fa9eb939091 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20624,7 +20624,7 @@ "was": "Was", "featureHours4": "{{value0}} sandbox hours per seat each month, pooled across your team", "featureSpec": "Every sandbox gets {{value0}} vCPU · {{value1}} GB", - "featureOverage5": "Optional overage at {{value0}}/hour, up to a monthly spend cap you set ({{value1}} by default)", + "featureOverage6": "Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set ({{cap}} by default)", "footTerms4": "Prices in USD, before tax. Overage is off until an owner or admin turns it on. Cancel anytime; your plan runs to the end of the billing period.", "lockedBody2": "Only an owner or admin of your team can choose a plan. Ask one of them to open Plan & billing in Orca.", "vpSecretsBody4": "API keys you add to Orca are never written to the sandbox. Agents and terminals get them as environment variables.", @@ -20699,7 +20699,7 @@ "enterpriseContactSales": "Contact sales", "openForbidden2": "Only an owner or admin can manage billing.", "openSignedOut2": "Sign in to Orca again to manage your team.", - "overageDescription5": "Optional overage at {{value0}}/hour, up to a monthly spend cap you set ({{value1}} by default).", + "overageDescription6": "Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set ({{cap}} by default).", "overageHoursOnly": "{{value0}} overage hours this month", "overageMemberHint": "Owners and admins can change overage.", "overageOffRead": "Off", @@ -20719,7 +20719,7 @@ "sandboxHoursUsedMonth": "{{value0}} of {{value1}} sandbox hours used this month", "warn100b": "All of this month’s sandbox hours are used.", "warnPercent2": "You’ve used {{value0}}% of this month’s sandbox hours.", - "overageDescriptionOn2": "Optional overage at {{value0}}/hour, up to a monthly spend cap you set.", + "overageDescriptionOn3": "Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set.", "reasonCapMember3": "Spend cap reached. Ask an owner or admin to raise the spend cap. Your files are safe.", "reasonGraceExpired3": "Payment failed. New sandboxes can’t start and running sandboxes are asleep. Update your payment method. Your files are safe.", "reasonGraceExpiredMember2": "Payment failed. New sandboxes can’t start and running sandboxes are asleep. Ask an owner or admin to update the payment method. Your files are safe.", From 9a4bd94b66c559e1685a61a10e44cb4621068cfb Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:44:23 -0800 Subject: [PATCH 24/46] feat(billing): member billing walls and back-to-work after checkout (DS-15, DS-16) DS-15: no-plan access carries canManageBilling. Members see 'Ask an owner or admin' instead of Upgrade, and the hint says 'Ask an owner or admin to choose one.'; at the cap they're told to raise the spend cap. Every billing failure on the build card offers 'Create on this computer instead' (same prompt, Local), and Dismiss hands the typed prompt back to the composer. DS-16: choosing a plan from an Orca Cloud wall leaves an intent. Once paid, the plans dialog returns to the open composer with Orca Cloud picked, or retries the refused create. The no-plan card adds Try again, and the Team page's create action opens on Orca Cloud. --- .../billing/checkout/checkout-return.ts | 49 +++++++++++ .../billing/plans/PlansDialogHost.tsx | 15 ++-- .../billing/team/TeamDialogHost.tsx | 7 +- .../CloudAgentSetup.fixture.tsx | 1 + ...orkspaceComposerProjectSection.fixture.tsx | 59 ++++++++++++- .../new-workspace/OrcaCloudSelectionHint.tsx | 30 +++++-- .../RunTargetCombobox.fixture.tsx | 42 +++++++++- .../new-workspace/RunTargetCombobox.test.tsx | 13 ++- .../new-workspace/RunTargetOrcaCloudRow.tsx | 30 ++++--- .../orca-cloud-run-target-access.test.ts | 62 ++++++++++++++ .../orca-cloud-run-target-access.ts | 24 ++++-- .../use-run-target-orca-cloud.ts | 14 +++- .../VmBuildFailureActions.tsx | 46 ++++++++--- .../VmBuildFailureCard.test.tsx | 34 +++++++- .../worktree-creation/VmBuildSheet.tsx | 18 +++- .../VmBuildSheetCloudFailures.fixture.tsx | 38 +++++++-- .../WorktreeCreationPanel.tsx | 10 +++ .../vm-build-composer-return.test.ts | 49 +++++++++++ .../vm-build-composer-return.ts | 33 ++++++++ .../vm-build-sheet-fixture-support.tsx | 9 +- .../src/hooks/useEphemeralVmRecipeOptions.ts | 4 + src/renderer/src/i18n/locales/en.json | 7 +- .../src/lib/orca-cloud-after-checkout.test.ts | 62 ++++++++++++++ .../src/lib/orca-cloud-after-checkout.ts | 82 +++++++++++++++++++ 24 files changed, 670 insertions(+), 68 deletions(-) create mode 100644 src/renderer/src/components/billing/checkout/checkout-return.ts create mode 100644 src/renderer/src/components/new-workspace/orca-cloud-run-target-access.test.ts create mode 100644 src/renderer/src/components/worktree-creation/vm-build-composer-return.test.ts create mode 100644 src/renderer/src/components/worktree-creation/vm-build-composer-return.ts create mode 100644 src/renderer/src/lib/orca-cloud-after-checkout.test.ts create mode 100644 src/renderer/src/lib/orca-cloud-after-checkout.ts diff --git a/src/renderer/src/components/billing/checkout/checkout-return.ts b/src/renderer/src/components/billing/checkout/checkout-return.ts new file mode 100644 index 00000000000..e600549131a --- /dev/null +++ b/src/renderer/src/components/billing/checkout/checkout-return.ts @@ -0,0 +1,49 @@ +import { useAppStore } from '@/store/index' +import { + takeOrcaCloudCheckoutReturn, + emitOrcaCloudCheckoutReturn +} from '@/lib/orca-cloud-after-checkout' +import { requestOrcaCloudSelectionAfterSignIn } from '@/lib/orca-cloud-select-after-sign-in' +import { invalidateOrcaCloudBilling } from '@/components/new-workspace/orca-cloud-billing-cache' +import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' +import { closePlansPage } from '../plans/plans-page-store' +import { closeTeamPage, openTeamPage } from '../team/team-page-store' + +/** + * A paid Checkout closes the plans page and goes back to the work that hit the wall: the open + * composer with Orca Cloud picked, or the refused create, retried. Without an intent it lands on + * the Team page's "You're on Team" confirmation. + */ +export function returnAfterPaidCheckout(paidSeats: number): void { + closePlansPage() + const store = useAppStore.getState() + const target = takeOrcaCloudCheckoutReturn({ + composerOpen: store.activeModal === 'new-workspace-composer', + hasCreation: (creationId) => Boolean(store.pendingWorktreeCreations[creationId]) + }) + if (target.kind === 'team-page') { + openTeamPage({ kind: 'checkout-success', seats: paidSeats }) + return + } + closeTeamPage() + // The Run-on row cached "no plan"; read the new entitlement now so it shows hours, not Upgrade. + invalidateOrcaCloudBilling() + switch (target.kind) { + case 'retry': + // Lazy: the creation flow's import graph is heavy and billing never needs it otherwise. + void import('@/lib/workspace/creation/worktree-creation-flow').then( + ({ retryBackgroundWorktreeCreation }) => retryBackgroundWorktreeCreation(target.creationId) + ) + return + case 'select-in-composer': + // The composer's recipe list reloads and consumes this, as it does after signing in. + requestOrcaCloudSelectionAfterSignIn() + emitOrcaCloudCheckoutReturn() + return + case 'open-composer': + store.openModal('new-workspace-composer', { + initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID, + telemetrySource: 'unknown' + }) + } +} diff --git a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx index a18897ec431..33fd15573a7 100644 --- a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx +++ b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react' +import { useState } from 'react' import { Dialog } from '@/components/ui/dialog' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' @@ -7,7 +7,8 @@ import { CheckoutPanel } from '../checkout/CheckoutPanel' import { useCheckoutFlow } from '../checkout/use-checkout-flow' import { openFailureCopy } from '../plan-billing-copy' import type { PlanBillingNotice } from '../PlanBillingSection' -import { openTeamPage } from '../team/team-page-store' +import { returnAfterPaidCheckout } from '../checkout/checkout-return' +import { cancelOrcaCloudAfterCheckout } from '@/lib/orca-cloud-after-checkout' import { useOrcaBillingStatus } from '../use-orca-billing-status' import { PlansDialogContent } from './PlansDialogContent' import { closePlansPage, usePlansPageState } from './plans-page-store' @@ -17,7 +18,7 @@ import { useOrgSeatCount } from './use-org-seat-count' * The plans page. A dialog because choosing a plan is a decision step in front of Checkout; * it reads the billing service's offers, so prices and limits are never hardcoded here. * Checkout itself runs on Stripe's hosted page in the browser; this dialog follows it and, - * once paid, hands over to the Team page. + * once paid, returns to the Orca Cloud wall that opened it, or hands over to the Team page. */ export function PlansDialogHost(): React.JSX.Element { const t = useTranslate() @@ -29,11 +30,7 @@ export function PlansDialogHost(): React.JSX.Element { const [notice, setNotice] = useState(null) const [orderedAt, setOrderedAt] = useState(0) - const onPaid = useCallback((paidSeats: number) => { - closePlansPage() - openTeamPage({ kind: 'checkout-success', seats: paidSeats }) - }, []) - const checkout = useCheckoutFlow({ onPaid }) + const checkout = useCheckoutFlow({ onPaid: returnAfterPaidCheckout }) const openPortal = async (): Promise => { setBusy(true) @@ -69,6 +66,8 @@ export function PlansDialogHost(): React.JSX.Element { // Closing ends the watch: polling stops and the next open starts from the plans. checkout.reset() closePlansPage() + // Leaving without paying: nothing to return to Orca Cloud for. + cancelOrcaCloudAfterCheckout() setNotice(null) } }} diff --git a/src/renderer/src/components/billing/team/TeamDialogHost.tsx b/src/renderer/src/components/billing/team/TeamDialogHost.tsx index 5485dadf76d..dbce53b536d 100644 --- a/src/renderer/src/components/billing/team/TeamDialogHost.tsx +++ b/src/renderer/src/components/billing/team/TeamDialogHost.tsx @@ -14,6 +14,7 @@ import { createTeamFailureCopy, mutationFailureCopy } from './team-copy' import { clearTeamPageArrival, closeTeamPage, useTeamPageState } from './team-page-store' import { useOrgRoster } from './use-org-roster' import { useTeamActions } from './use-team-actions' +import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' function TeamPageBody({ arrival }: { arrival: ReturnType['arrival'] }) { const t = useTranslate() @@ -199,7 +200,11 @@ function TeamPageBody({ arrival }: { arrival: ReturnType { closeTeamPage() - openModal('new-workspace-composer', { telemetrySource: 'unknown' }) + // The plan is for Orca Cloud, so the composer opens on it rather than this computer. + openModal('new-workspace-composer', { + initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID, + telemetrySource: 'unknown' + }) }} onDismissArrival={clearTeamPageArrival} onContactSales={(url) => void window.api.shell.openUrl(url)} diff --git a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx index 045af8c6965..d87e93644ac 100644 --- a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx +++ b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx @@ -55,6 +55,7 @@ function sheet( onCancel={noop} onRetry={noop} onDismiss={noop} + onReturnToComposer={noop} onEditRecipe={noop} cloudAgentStep={ diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx index 25256cbdac5..7248037b064 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx @@ -142,7 +142,16 @@ function ProjectAndHostPreview({ ) } -export const closed = defineFixture({ width: 560, render: () => }) +export const closed = defineFixture({ + width: 560, + // The browser preload answers agent keys and Cloud secrets with stubs the Orca Cloud agent hint + // can't read; without them the hint shows nothing, as it does before they load. + setup: () => { + window.api.agentApiKeys = undefined + window.api.cloudSecrets = undefined + }, + render: () => +}) export const narrow = defineFixture({ width: 360, render: () => }) export const folderOnly = defineFixture({ width: 560, @@ -186,7 +195,11 @@ export const hostMenuOrcaCloud = defineFixture({ }) export const hostMenuOrcaCloudLocked = defineFixture({ ...hostMenu, - render: () => + render: () => ( + + ) }) export const orcaCloudSelected = defineFixture({ ...closed, @@ -196,7 +209,10 @@ export const orcaCloudSelected = defineFixture({ export const orcaCloudSelectedNoPlan = defineFixture({ ...closed, render: () => ( - + ) }) export const orcaCloudSelectedOutOfHoursMember = defineFixture({ @@ -217,3 +233,40 @@ export const orcaCloudSelectedPaymentAdmin = defineFixture({ /> ) }) +// DS-15: a member can't choose a plan or raise the cap, so the hint says who can and offers no fix. +export const orcaCloudSelectedNoPlanMember = defineFixture({ + ...closed, + render: () => ( + + ) +}) +export const orcaCloudSelectedCapMember = defineFixture({ + ...closed, + render: () => ( + + ) +}) +export const hostMenuOrcaCloudNoPlanMember = defineFixture({ + ...hostMenu, + render: () => ( + + ) +}) +// DS-16: back from a paid Checkout, the composer is open again with Orca Cloud picked and its hours. +export const orcaCloudAfterCheckout = defineFixture({ + ...closed, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx b/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx index f353144eea6..34767afbc05 100644 --- a/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx +++ b/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx @@ -28,11 +28,20 @@ function useBlockCopy(access: OrcaCloudRunTargetAccess): BlockCopy | null { 'auto.components.new.workspace.RunTargetCombobox.orcaCloudNeedsTeamPlan', 'Orca Cloud needs a Team plan.' ), - detail: '', + detail: access.canManageBilling + ? '' + : t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskChoosePlan', + 'Ask an owner or admin to choose one.' + ), tone: 'neutral', - action: access.lapsed - ? t('auto.components.new.workspace.RunTargetCombobox.orcaCloudRenew', 'Renew') - : t('auto.components.new.workspace.RunTargetCombobox.orcaCloudUpgrade', 'Upgrade') + ...(access.canManageBilling + ? { + action: access.lapsed + ? t('auto.components.new.workspace.RunTargetCombobox.orcaCloudRenew', 'Renew') + : t('auto.components.new.workspace.RunTargetCombobox.orcaCloudUpgrade', 'Upgrade') + } + : {}) } case 'out-of-hours': { const cap = access.cause === 'cap' @@ -49,10 +58,15 @@ function useBlockCopy(access: OrcaCloudRunTargetAccess): BlockCopy | null { ), detail: access.canManageBilling ? '' - : t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskAddHoursOnly', - 'Ask an owner or admin to add hours.' - ), + : cap + ? t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskRaiseSpendCap', + 'Ask an owner or admin to raise the spend cap.' + ) + : t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskAddHoursOnly', + 'Ask an owner or admin to add hours.' + ), tone: 'neutral', ...(access.canManageBilling ? { diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx index 92e6c1dbcc4..0037f139367 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx @@ -121,7 +121,12 @@ export const orcaCloudEntitled = defineFixture({ }) export const orcaCloudNotEntitled = defineFixture({ width: 420, - render: () => , + render: () => ( + + ), interact: open }) export const orcaCloudOutOfHours = defineFixture({ @@ -153,7 +158,12 @@ export const orcaCloudPaymentIssue = defineFixture({ }) export const orcaCloudLapsed = defineFixture({ width: 420, - render: () => , + render: () => ( + + ), interact: open }) export const orcaCloudSelectedClosed = defineFixture({ @@ -188,7 +198,12 @@ export const orcaCloudSignedOut = defineFixture({ }) export const orcaCloudNoCapability = defineFixture({ width: 420, - render: () => , + render: () => ( + + ), interact: open }) export const orcaCloudCapReached = defineFixture({ @@ -233,3 +248,24 @@ export const needsSetupArmed = defineFixture({ render: () => , interact: pressKeys('ArrowDown', 'ArrowDown') }) +// DS-15: members see who can fix it, not Upgrade, and the row can't be picked. +export const orcaCloudNoPlanMember = defineFixture({ + width: 420, + render: () => ( + + ), + interact: open +}) +export const orcaCloudCapReachedMember = defineFixture({ + width: 420, + render: () => ( + + ), + interact: open +}) diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx index 96eaf67974a..28c12a4b7c3 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx @@ -137,13 +137,24 @@ describe('RunTargetCombobox', () => { it('opens the plans page instead of building when there is no plan', () => { const onRecipeChange = vi.fn() - render({ state: 'no-plan', lapsed: false }, onRecipeChange) + render({ state: 'no-plan', lapsed: false, canManageBilling: true }, onRecipeChange) press('ArrowDown') press('Enter') expect(openPlansPage).toHaveBeenCalledWith('sandbox') expect(onRecipeChange).not.toHaveBeenCalled() }) + it('tells a member without a plan to ask an owner or admin instead of opening plans', () => { + const onRecipeChange = vi.fn() + render({ state: 'no-plan', lapsed: false, canManageBilling: false }, onRecipeChange) + expect(container.textContent).toContain('Ask an owner or admin') + expect(container.textContent).not.toContain('Upgrade') + press('ArrowDown') + press('Enter') + expect(openPlansPage).not.toHaveBeenCalled() + expect(onRecipeChange).not.toHaveBeenCalled() + }) + it('moves keyboard focus into the recipe submenu and commits a recipe with Enter', () => { const onRecipeChange = vi.fn() render({ state: 'entitled', remainingSeconds: 3600 }, onRecipeChange) diff --git a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx index b4beb0ceb9b..3b005030eb3 100644 --- a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx @@ -148,6 +148,19 @@ function OrcaCloudDetail({ access }: { access: OrcaCloudRunTargetAccess }): Reac } } +/** Members can't fix billing; say who can rather than offer a pick that does nothing. */ +function AskOwnerOrAdmin(): React.JSX.Element { + const t = useTranslate() + return ( + + {t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskOwnerOrAdmin', + 'Ask an owner or admin' + )} + + ) +} + function OrcaCloudMeta({ access, onAction @@ -187,6 +200,9 @@ function OrcaCloudMeta({ /> ) case 'no-plan': + if (!access.canManageBilling) { + return + } return ( - {t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskOwnerOrAdmin', - 'Ask an owner or admin' - )} - - ) + return } return ( ({ + openPlansPage: (source: string) => openPlansPage(source) +})) +const requestOrcaCloudAfterCheckout = vi.fn() +vi.mock('@/lib/orca-cloud-after-checkout', () => ({ + requestOrcaCloudAfterCheckout: (intent: unknown) => requestOrcaCloudAfterCheckout(intent) +})) + +function denied( + reason: OrcaBillingEntitlement['reason'], + canManageBilling: boolean +): Parameters[0] { + return { + status: 'ok', + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: access reads only these fields. + entitlement: { + canStartSandbox: false, + remainingIncludedSeconds: 0, + reason, + canManageBilling + } as OrcaBillingEntitlement + } +} + +describe('Orca Cloud run-target access by role', () => { + beforeEach(() => { + openPlansPage.mockReset() + requestOrcaCloudAfterCheckout.mockReset() + }) + + it('carries the role on no plan, so members are not sent to plans they cannot buy', () => { + const owner = toOrcaCloudRunTargetAccess(denied('no_subscription', true)) + const member = toOrcaCloudRunTargetAccess(denied('subscription_inactive', false)) + expect(owner).toEqual({ state: 'no-plan', lapsed: false, canManageBilling: true }) + expect(member).toEqual({ state: 'no-plan', lapsed: true, canManageBilling: false }) + expect(getOrcaCloudPick(member)).toEqual({ kind: 'blocked' }) + expect(openPlansPage).not.toHaveBeenCalled() + }) + + it('sends an owner or admin to plans and leaves a return-to-composer intent', () => { + const pick = getOrcaCloudPick(toOrcaCloudRunTargetAccess(denied('no_subscription', true))) + expect(pick.kind).toBe('act') + if (pick.kind === 'act') { + pick.run() + } + expect(requestOrcaCloudAfterCheckout).toHaveBeenCalledWith({ kind: 'composer' }) + expect(openPlansPage).toHaveBeenCalledWith('sandbox') + }) + + it('blocks members at the spend cap and lets owners act', () => { + const member = toOrcaCloudRunTargetAccess(denied('overage_cap_reached', false)) + expect(member).toEqual({ state: 'out-of-hours', cause: 'cap', canManageBilling: false }) + expect(getOrcaCloudPick(member)).toEqual({ kind: 'blocked' }) + const owner = toOrcaCloudRunTargetAccess(denied('overage_cap_reached', true)) + expect(getOrcaCloudPick(owner).kind).toBe('act') + }) +}) diff --git a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts index 53d7af107cf..fb12e2f3e50 100644 --- a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts +++ b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts @@ -5,6 +5,7 @@ import { cancelOrcaCloudSelectionAfterSignIn, requestOrcaCloudSelectionAfterSignIn } from '@/lib/orca-cloud-select-after-sign-in' +import { requestOrcaCloudAfterCheckout } from '@/lib/orca-cloud-after-checkout' import { classifyEntitlementDenial } from '../../../../shared/orca-billing' /** Signing in from the row selects Orca Cloud once main offers it (the recipe list reloads). */ @@ -21,23 +22,30 @@ function signInThenSelectOrcaCloud(): void { .catch(() => cancelOrcaCloudSelectionAfterSignIn(token)) } +/** Paying from the row returns to this composer with Orca Cloud picked (see PlansDialogHost). */ +function choosePlanThenSelectOrcaCloud(): void { + requestOrcaCloudAfterCheckout({ kind: 'composer' }) + openPlansPage('sandbox') +} + /** * What the Run-on picker knows about the account's Orca Cloud access. * - `loading`: the first billing read is in flight; picking waits briefly for it. * - `unknown`: billing unreachable or not signed in to billing; picking proceeds and the build reports. * - `signed-out`: the build offers Orca Cloud but nobody is signed in; picking starts sign-in. * - `entitled`: can start a sandbox; `remainingSeconds` is the included time left this window. - * - `no-plan`: no active Team subscription (`lapsed` when one existed); routes to the plans page. + * - `no-plan`: no active Team subscription (`lapsed` when one existed); routes owners/admins to the + * plans page and, once paid, back to the composer with Orca Cloud picked. * - `out-of-hours`: included hours are spent (`cause: 'hours'`) or the overage cap is (`'cap'`). * - `payment-issue`: a failed payment blocks new starts. - * Out-of-hours and payment issues are actionable only by owners/admins (`canManageBilling`). + * No plan, out-of-hours and payment issues are actionable only by owners/admins (`canManageBilling`). */ export type OrcaCloudRunTargetAccess = | { state: 'loading' } | { state: 'unknown' } | { state: 'signed-out' } | { state: 'entitled'; remainingSeconds: number } - | { state: 'no-plan'; lapsed: boolean } + | { state: 'no-plan'; lapsed: boolean; canManageBilling: boolean } | { state: 'out-of-hours'; cause: 'hours' | 'cap'; canManageBilling: boolean } | { state: 'payment-issue'; canManageBilling: boolean } @@ -69,7 +77,11 @@ export function toOrcaCloudRunTargetAccess( case 'memberLimit': case 'machineSize': case 'other': - return { state: 'no-plan', lapsed: entitlement.reason === 'subscription_inactive' } + return { + state: 'no-plan', + lapsed: entitlement.reason === 'subscription_inactive', + canManageBilling + } } } @@ -89,7 +101,9 @@ export function getOrcaCloudPick(access: OrcaCloudRunTargetAccess): OrcaCloudPic case 'signed-out': return { kind: 'act', run: signInThenSelectOrcaCloud } case 'no-plan': - return { kind: 'act', run: () => openPlansPage('sandbox') } + return access.canManageBilling + ? { kind: 'act', run: choosePlanThenSelectOrcaCloud } + : { kind: 'blocked' } case 'out-of-hours': return access.canManageBilling ? { kind: 'act', run: openOverageSettings } diff --git a/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts index bacb45b0041..040b4594d03 100644 --- a/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts +++ b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts @@ -28,7 +28,8 @@ export function getRunTargetOrcaCloudOffer({ case 'needs-sign-in': return override ?? { state: 'signed-out' } case 'needs-capability': - return override ?? { state: 'no-plan', lapsed: false } + // No billing read without the capability; unknown roles get the owner's way forward. + return override ?? { state: 'no-plan', lapsed: false, canManageBilling: true } case 'offered': case 'unavailable': return null @@ -65,8 +66,15 @@ export function useRunTargetOrcaCloud({ runBlockedAction: () => void select: (recipe: EphemeralVmRecipeOption | null) => void } { - const fetched = useOrcaCloudRunTargetAccess(!override && recipes.some(isOrcaCloudRecipe)) - const access = offer ?? override ?? fetched + const fetched = useOrcaCloudRunTargetAccess( + !override && (recipes.some(isOrcaCloudRecipe) || offer?.state === 'no-plan') + ) + // Without the capability the offer can't know the role; billing's answer can, so members are + // told to ask an owner or admin instead of being sent to plans they can't buy. + const access = + !override && offer?.state === 'no-plan' && fetched.state === 'no-plan' + ? fetched + : (offer ?? override ?? fetched) const [pending, setPending] = useState(false) const pickToken = useRef(0) const openRef = useRef(open) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index 49ce22447c9..870c7d5c2ec 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -7,6 +7,7 @@ import { Loader2, LifeBuoy, LogIn, + Monitor, PanelLeft, Pencil, RotateCcw, @@ -31,6 +32,8 @@ export type VmBuildFailureActions = { onDismiss: () => void onSeePlans: () => void onOpenBilling: () => void + /** Billing refusals: reopen the composer with the same prompt, on this computer. */ + onCreateLocally: () => void onSignIn: () => void onShowWorkspaces: () => void onContactSupport: () => void @@ -46,6 +49,8 @@ type Action = { disabled?: boolean /** In progress: stays focusable (aria-disabled + aria-busy) so keyboard focus isn't dropped. */ pending?: boolean + /** Outline even when first: a way around the problem, not its fix. */ + secondary?: boolean } /** At most two visible actions; the rest sit in a More menu so the way forward stays obvious. */ @@ -78,18 +83,34 @@ function failureActions( icon: , onClick: actions.onEditRecipe } + // Every billing refusal can still run the same prompt here instead of waiting on billing. + const createLocally: Action = { + key: 'local', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.createOnThisComputer', + 'Create on this computer instead' + ), + icon: , + onClick: actions.onCreateLocally, + secondary: true + } switch (failure.kind) { case 'plan': - return { - primary: [ - { - key: 'plans', - label: t('auto.lib.orcaCloudSession.seePlans', 'See plans'), - onClick: actions.onSeePlans + // Members can't choose a plan; their card tells them who can. + return canManageBilling + ? { + primary: [ + { + key: 'plans', + label: t('auto.lib.orcaCloudSession.seePlans', 'See plans'), + onClick: actions.onSeePlans + }, + // Paying elsewhere (another device, the portal) is picked up by trying again. + tryAgain + ], + more: [createLocally] } - ], - more: [] - } + : { primary: [createLocally], more: [] } case 'hoursUsed': case 'spendCap': case 'payment': @@ -116,9 +137,10 @@ function failureActions( ), icon: , onClick: actions.onOpenBilling - } + }, + createLocally ] - : [], + : [createLocally], more: [] } case 'signIn': @@ -288,7 +310,7 @@ export function FailureActionRow({ key={action.key} type="button" size="xs" - variant={index === 0 ? 'default' : 'outline'} + variant={index === 0 && !action.secondary ? 'default' : 'outline'} onClick={action.pending ? undefined : action.onClick} disabled={action.disabled} aria-disabled={action.pending || undefined} diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx index 80c51125f67..c50f250e083 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx @@ -15,6 +15,7 @@ const actions = (): VmBuildFailureActions => ({ onDismiss: vi.fn(), onSeePlans: vi.fn(), onOpenBilling: vi.fn(), + onCreateLocally: vi.fn(), onSignIn: vi.fn(), onShowWorkspaces: vi.fn(), onContactSupport: vi.fn(), @@ -25,10 +26,12 @@ const actions = (): VmBuildFailureActions => ({ function Sheet({ failure, connectingGitHub = false, + canManageBilling = true, handlers }: { failure: VmBuildFailure | null connectingGitHub?: boolean + canManageBilling?: boolean handlers: VmBuildFailureActions }) { return ( @@ -42,7 +45,7 @@ function Sheet({ vmKept={false} firstErrorLine={null} canFixWithAgent={false} - canManageBilling + canManageBilling={canManageBilling} signingIn={false} connectingGitHub={connectingGitHub} repoName="acme/web" @@ -80,3 +83,32 @@ it('keeps a pending Connect GitHub focusable and ignores repeat clicks', () => { expect(handlers.onConnectGitHub).not.toHaveBeenCalled() expect(document.activeElement).toBe(button) }) + +it('offers an owner See plans then Try again on no plan', () => { + const handlers = actions() + render() + const buttons = screen.getAllByRole('button').map((button) => button.textContent?.trim()) + expect(buttons.slice(0, 2)).toEqual(['See plans', 'Try again']) + fireEvent.click(screen.getByRole('button', { name: /Try again/ })) + expect(handlers.onRetry).toHaveBeenCalledOnce() +}) + +it.each(['plan', 'hoursUsed', 'spendCap', 'payment'] as const)( + 'gives a member running into %s a way to create on this computer, not a billing fix', + (kind) => { + const handlers = actions() + render() + expect( + screen.queryByRole('button', { name: /See plans|Raise spend cap|Turn on overage/ }) + ).toBeNull() + fireEvent.click(screen.getByRole('button', { name: /Create on this computer instead/ })) + expect(handlers.onCreateLocally).toHaveBeenCalledOnce() + } +) + +it("keeps Create on this computer instead beside an owner's billing fix", () => { + const handlers = actions() + render() + const buttons = screen.getAllByRole('button').map((button) => button.textContent?.trim()) + expect(buttons.slice(0, 2)).toEqual(['Raise spend cap', 'Create on this computer instead']) +}) diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 343674b9ebc..e2f3bf70f8c 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -28,6 +28,8 @@ import { import { deriveVmBuildSteps, isOrcaCloudBuild, type VmBuildStep } from './vm-build-steps' import { useMinimumRunningSteps } from './use-minimum-running-steps' import { useRetryAfterCloudSignIn } from './use-retry-after-cloud-sign-in' +import { typedComposerPrompt } from './vm-build-composer-return' +import { requestOrcaCloudAfterCheckout } from '@/lib/orca-cloud-after-checkout' import { connectOrcaCloudGitHub, orcaCloudRepoName, @@ -84,6 +86,7 @@ export function VmBuildSheet({ onCancel, onRetry, onDismiss, + onReturnToComposer, onEditRecipe, agentSignInRow, cloudAgentStep, @@ -98,6 +101,8 @@ export function VmBuildSheet({ onRetry: () => void /** Leaves the build; when a VM is still up the caller confirms before it is deleted. */ onDismiss: () => void + /** Leaves a refused build for the composer with its prompt; `local` runs it on this computer. */ + onReturnToComposer: (options: { local: boolean }) => void onEditRecipe: () => void /** Fixtures only: a fixed sign-in row in place of the live one. */ agentSignInRow?: React.ReactNode @@ -269,8 +274,17 @@ export function VmBuildSheet({ : onRetry, onEditRecipe, onOpenAnyway: () => resolveVmEnvironmentCheckDecision(creationId, 'open-anyway'), - onDismiss, - onSeePlans: () => openPlansPage('sandbox'), + // Nothing was created, so leaving a billing refusal hands the typed prompt back. + onDismiss: + isBillingFailure(failure) && typedComposerPrompt(entry).trim() + ? () => onReturnToComposer({ local: false }) + : onDismiss, + onSeePlans: () => { + // Once paid, the plans dialog closes and retries this create. + requestOrcaCloudAfterCheckout({ kind: 'retry', creationId }) + openPlansPage('sandbox') + }, + onCreateLocally: () => onReturnToComposer({ local: true }), onOpenBilling: () => { const store = useAppStore.getState() store.openSettingsTarget({ pane: 'orca-account', repoId: null }) diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx index fec59dc74aa..fc3505df430 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx @@ -13,12 +13,29 @@ import { // Orca Cloud refusals and failures, one card each. +function stubBillingRole(canManageBilling: boolean): void { + window.api.orcaProfiles.billingStatus = () => + Promise.resolve({ + status: 'ok', + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the card reads only canManageBilling. + entitlement: { canManageBilling } as never + }) +} + +// An owner unless stated: the card's billing fix depends on the role billing reports. function cloudFailure(errorCode: string | undefined, error: string, log = CLOUD_LOG) { - return frame( + const fixture = frame( entry({ status: 'error', errorCode, provisioningLog: log, errorAt: T0 + 2_000 }, CLOUD_RECIPE), error, T0 + 2_000 ) + return defineFixture({ + ...fixture, + setup: () => { + seedFixtureRepo() + stubBillingRole(true) + } + }) } export const cloudPlanRequired = cloudFailure( @@ -63,12 +80,7 @@ function asMember(fixture: ReturnType) { ...fixture, setup: () => { seedFixtureRepo() - window.api.orcaProfiles.billingStatus = () => - Promise.resolve({ - status: 'ok', - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the card reads only canManageBilling. - entitlement: { canManageBilling: false } as never - }) + stubBillingRole(false) } }) } @@ -160,3 +172,15 @@ export const cloudPaymentDue = cloudFailure( ) export const cloudNetwork = cloudFailure(undefined, 'fetch failed', CLOUD_LOG) + +// An owner without a plan gets See plans and Try again; More holds "Create on this computer +// instead", which every billing card offers. +export const cloudPlanRequiredMore = defineFixture({ + ...cloudPlanRequired, + interact: async (frameElement) => { + Array.from(frameElement.querySelectorAll('button')) + .find((button) => button.textContent?.trim() === 'More') + ?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) + await new Promise((resolve) => setTimeout(resolve, 300)) + } +}) diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx index 54dfb17f755..d7aca945fb2 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx @@ -16,6 +16,7 @@ import { } from './worktree-creation-clock' import { VmBuildSheet } from './VmBuildSheet' import { VmDeleteConfirmDialog } from './VmDeleteConfirmDialog' +import { composerDataFromRefusedCreate } from './vm-build-composer-return' /** Debounced in-frame creation placeholder: tab strip names the workspace while body shows status, enabling same-frame handoff without duplicating labels. */ export default function WorktreeCreationPanel({ @@ -91,6 +92,15 @@ export default function WorktreeCreationPanel({ onCancel={dismiss} onRetry={() => retryBackgroundWorktreeCreation(creationId)} onDismiss={leave} + onReturnToComposer={({ local }) => { + const data = composerDataFromRefusedCreate(entry, { local }) + dismiss() + const store = useAppStore.getState() + // Never replace a dialog the user opened meanwhile. + if (store.activeModal === 'none') { + store.openModal('new-workspace-composer', data) + } + }} onEditRecipe={() => { const state = useAppStore.getState() state.openSettingsTarget({ diff --git a/src/renderer/src/components/worktree-creation/vm-build-composer-return.test.ts b/src/renderer/src/components/worktree-creation/vm-build-composer-return.test.ts new file mode 100644 index 00000000000..bd377bf9d55 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-composer-return.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' +import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' +import { composerDataFromRefusedCreate, typedComposerPrompt } from './vm-build-composer-return' + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the fields read here. +const request = { + repoId: 'repo-1', + name: 'otter', + displayName: 'Fix login', + displayNameKind: 'user', + baseBranch: 'main', + agent: 'claude', + note: 'Fix the login redirect', + telemetrySource: 'sidebar', + ephemeralVmRecipe: { + sourceRepoId: 'repo-1', + recipeId: 'cloud', + projectId: 'p', + provider: 'orca-cloud' + } +} as unknown as WorktreeCreationRequest + +describe('composer data for a create billing refused', () => { + it('restores the typed prompt and keeps Orca Cloud on Dismiss', () => { + expect(composerDataFromRefusedCreate({ request }, { local: false })).toEqual({ + initialRepoId: 'repo-1', + initialEphemeralVmRecipeId: 'cloud', + prefilledName: 'Fix login', + initialBaseBranch: 'main', + recovery: { note: 'Fix the login redirect', agent: 'claude' }, + telemetrySource: 'sidebar' + }) + }) + + it('drops the sandbox for Create on this computer instead', () => { + const data = composerDataFromRefusedCreate({ request }, { local: true }) + expect(data.initialEphemeralVmRecipeId).toBeUndefined() + expect(data.recovery?.note).toBe('Fix the login redirect') + }) + + it('prefers a prompt queued during the build and never restores a generated name', () => { + const entry = { + heldChatMessage: 'Queued instead', + request: { ...request, displayNameKind: 'generated' as const } + } + expect(typedComposerPrompt(entry)).toBe('Queued instead') + expect(composerDataFromRefusedCreate(entry, { local: true }).prefilledName).toBeUndefined() + }) +}) diff --git a/src/renderer/src/components/worktree-creation/vm-build-composer-return.ts b/src/renderer/src/components/worktree-creation/vm-build-composer-return.ts new file mode 100644 index 00000000000..1db89f80ec2 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-composer-return.ts @@ -0,0 +1,33 @@ +import type { ComposerModalData } from '@/components/new-workspace/composer-modal-data' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' + +type ReturnSource = Pick + +/** What the user typed for the agent: a prompt queued during the build, else the composer's. */ +export function typedComposerPrompt(entry: ReturnSource): string { + return entry.heldChatMessage ?? entry.request.note +} + +/** + * The composer as it was submitted, for a create billing refused before anything started: same + * project, name, base, agent and prompt. `local` drops the sandbox so it runs on this computer; + * otherwise the same Run-on target is kept. + */ +export function composerDataFromRefusedCreate( + entry: ReturnSource, + { local }: { local: boolean } +): ComposerModalData { + const { request } = entry + const recipe = request.ephemeralVmRecipe + return { + initialRepoId: recipe?.sourceRepoId ?? request.repoId, + ...(!local && recipe ? { initialEphemeralVmRecipeId: recipe.recipeId } : {}), + // A generated name is regenerated; only a name the user typed comes back. + ...(request.displayNameKind === 'user' && request.displayName + ? { prefilledName: request.displayName } + : {}), + ...(request.baseBranch ? { initialBaseBranch: request.baseBranch } : {}), + recovery: { note: typedComposerPrompt(entry), agent: request.agent }, + telemetrySource: request.telemetrySource ?? 'unknown' + } +} diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx index 26f66cb9b16..c9a136dd578 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx @@ -41,8 +41,12 @@ export function entry( provisioningLog: log, provisioningLogStamps: stampsFor(log === '' ? 0 : log.split('\n').length), phaseLog: [{ phase: 'provisioning-vm', at: T0 }], - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sheet reads only name and ephemeralVmRecipe from the request. - request: { name: 'fix-login', ephemeralVmRecipe: recipe } as PendingWorktreeCreation['request'], + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sheet reads only name, note and ephemeralVmRecipe from the request. + request: { + name: 'fix-login', + note: 'Fix the login redirect', + ephemeralVmRecipe: recipe + } as PendingWorktreeCreation['request'], ...patch } } @@ -64,6 +68,7 @@ export function sheet( onCancel={() => {}} onRetry={() => {}} onDismiss={() => {}} + onReturnToComposer={() => {}} onEditRecipe={() => {}} agentSignInRow={agentSignInRow} stepTimings={FIXTURE_STEP_TIMINGS} diff --git a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts index 9737ba987c3..4c12ae15ea6 100644 --- a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts +++ b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts @@ -6,6 +6,7 @@ import type { EphemeralVmFailure } from '../../../shared/ephemeral-vm-failure-co import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' import { takeOrcaCloudSelectionAfterSignIn } from '@/lib/orca-cloud-select-after-sign-in' +import { onOrcaCloudCheckoutReturn } from '@/lib/orca-cloud-after-checkout' type EphemeralVmRecipeOptionsArgs = { enabled: boolean @@ -143,6 +144,9 @@ export function useEphemeralVmRecipeOptions(args: EphemeralVmRecipeOptionsArgs): load(false) }, [authKey, load]) + // A paid Checkout from the Run-on row: reload so the left selection intent picks Orca Cloud. + useEffect(() => onOrcaCloudCheckoutReturn(() => load(false)), [load]) + useEffect(() => { if (!window.api.plugins?.onChanged) { return diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b9bcc9b9409..e40ed058260 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4217,7 +4217,8 @@ "connectGitHubFailed": "Couldn’t open GitHub. Try again in a moment.", "noGithubRemoteBody2": "Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, then try again. Nothing was created, and you weren’t charged.", "howToPushToGitHub": "How to push to GitHub", - "spendCapReachedBodyMember2": "Your team has reached this month’s spend cap. Ask an owner or admin to raise the spend cap. Nothing was created, and you weren’t charged." + "spendCapReachedBodyMember2": "Your team has reached this month’s spend cap. Ask an owner or admin to raise the spend cap. Nothing was created, and you weren’t charged.", + "createOnThisComputer": "Create on this computer instead" }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -16616,7 +16617,9 @@ "orcaCloudAskPayment": "Ask an owner or admin to update the payment method.", "orcaCloudIdleSleep_one": "Sleeps after {{count}} minute idle", "orcaCloudIdleSleep_other": "Sleeps after {{count}} minutes idle", - "orcaCloudAskAddHoursOnly": "Ask an owner or admin to add hours." + "orcaCloudAskAddHoursOnly": "Ask an owner or admin to add hours.", + "orcaCloudAskChoosePlan": "Ask an owner or admin to choose one.", + "orcaCloudAskRaiseSpendCap": "Ask an owner or admin to raise the spend cap." }, "projectCombobox": { "recentHeading": "Recent", diff --git a/src/renderer/src/lib/orca-cloud-after-checkout.test.ts b/src/renderer/src/lib/orca-cloud-after-checkout.test.ts new file mode 100644 index 00000000000..ec6e6d4d060 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud-after-checkout.test.ts @@ -0,0 +1,62 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + cancelOrcaCloudAfterCheckout, + emitOrcaCloudCheckoutReturn, + onOrcaCloudCheckoutReturn, + requestOrcaCloudAfterCheckout, + resetOrcaCloudAfterCheckout, + takeOrcaCloudCheckoutReturn +} from './orca-cloud-after-checkout' + +const composerOpen = { composerOpen: true, hasCreation: () => true } +const composerClosed = { composerOpen: false, hasCreation: () => true } + +describe('select Orca Cloud after checkout', () => { + afterEach(() => resetOrcaCloudAfterCheckout()) + + it('lands on the Team page when no wall asked', () => { + expect(takeOrcaCloudCheckoutReturn(composerOpen)).toEqual({ kind: 'team-page' }) + }) + + it('returns to the open composer once, then the intent is consumed', () => { + requestOrcaCloudAfterCheckout({ kind: 'composer' }, 1_000) + expect(takeOrcaCloudCheckoutReturn(composerOpen, 2_000)).toEqual({ + kind: 'select-in-composer' + }) + expect(takeOrcaCloudCheckoutReturn(composerOpen, 3_000)).toEqual({ kind: 'team-page' }) + }) + + it('reopens the composer on Orca Cloud when it closed while paying', () => { + requestOrcaCloudAfterCheckout({ kind: 'composer' }, 1_000) + expect(takeOrcaCloudCheckoutReturn(composerClosed, 2_000)).toEqual({ kind: 'open-composer' }) + }) + + it('retries the refused creation, or falls back to the composer when it was dismissed', () => { + requestOrcaCloudAfterCheckout({ kind: 'retry', creationId: 'c1' }, 1_000) + expect(takeOrcaCloudCheckoutReturn(composerClosed, 2_000)).toEqual({ + kind: 'retry', + creationId: 'c1' + }) + requestOrcaCloudAfterCheckout({ kind: 'retry', creationId: 'gone' }, 1_000) + expect( + takeOrcaCloudCheckoutReturn({ composerOpen: false, hasCreation: () => false }, 2_000) + ).toEqual({ kind: 'open-composer' }) + }) + + it('drops a cancelled or abandoned intent', () => { + requestOrcaCloudAfterCheckout({ kind: 'composer' }, 1_000) + cancelOrcaCloudAfterCheckout() + expect(takeOrcaCloudCheckoutReturn(composerOpen, 2_000)).toEqual({ kind: 'team-page' }) + requestOrcaCloudAfterCheckout({ kind: 'composer' }, 0) + expect(takeOrcaCloudCheckoutReturn(composerOpen, 31 * 60_000)).toEqual({ kind: 'team-page' }) + }) + + it('notifies listening composers until they unsubscribe', () => { + const listener = vi.fn() + const off = onOrcaCloudCheckoutReturn(listener) + emitOrcaCloudCheckoutReturn() + off() + emitOrcaCloudCheckoutReturn() + expect(listener).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud-after-checkout.ts b/src/renderer/src/lib/orca-cloud-after-checkout.ts new file mode 100644 index 00000000000..3ac5247b793 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud-after-checkout.ts @@ -0,0 +1,82 @@ +// Choosing a plan from an Orca Cloud wall should land back on the work, not on the Team page: +// the Run-on picker returns to its open composer with Orca Cloud picked, and a build card that +// was refused for no plan retries that create. Like signInThenSelectOrcaCloud, the wall leaves +// an intent that the plans dialog consumes once Checkout reports paid. + +/** An intent older than this belongs to an abandoned Checkout and is ignored. */ +const INTENT_TTL_MS = 30 * 60_000 + +export type OrcaCloudCheckoutIntent = + /** From the Run-on picker: select Orca Cloud in the composer. */ + | { kind: 'composer' } + /** From a build card refused for no plan: retry that pending creation. */ + | { kind: 'retry'; creationId: string } + +/** Where a paid Checkout lands. */ +export type OrcaCloudCheckoutReturn = + /** No intent: the Team page's one-time "You're on Team" confirmation. */ + | { kind: 'team-page' } + /** The composer that asked is still open: pick Orca Cloud in it. */ + | { kind: 'select-in-composer' } + /** The composer closed meanwhile: reopen it on Orca Cloud. */ + | { kind: 'open-composer' } + | { kind: 'retry'; creationId: string } + +let pending: { intent: OrcaCloudCheckoutIntent; requestedAt: number } | null = null + +export function requestOrcaCloudAfterCheckout( + intent: OrcaCloudCheckoutIntent, + now = Date.now() +): void { + pending = { intent, requestedAt: now } +} + +/** Closing the plans page without paying drops the intent. */ +export function cancelOrcaCloudAfterCheckout(): void { + pending = null +} + +/** Consumes the intent and says where a paid Checkout should land. */ +export function takeOrcaCloudCheckoutReturn( + context: { + /** The new-workspace composer is the active modal. */ + composerOpen: boolean + /** The creation still exists (not dismissed while paying). */ + hasCreation: (creationId: string) => boolean + }, + now = Date.now() +): OrcaCloudCheckoutReturn { + const taken = pending + pending = null + if (!taken || now - taken.requestedAt > INTENT_TTL_MS) { + return { kind: 'team-page' } + } + const { intent } = taken + if (intent.kind === 'retry' && context.hasCreation(intent.creationId)) { + return { kind: 'retry', creationId: intent.creationId } + } + return context.composerOpen ? { kind: 'select-in-composer' } : { kind: 'open-composer' } +} + +type Listener = () => void +const listeners = new Set() + +/** The open composer's recipe list listens so a paid Checkout can pick Orca Cloud in it. */ +export function onOrcaCloudCheckoutReturn(listener: Listener): () => void { + listeners.add(listener) + return () => { + listeners.delete(listener) + } +} + +export function emitOrcaCloudCheckoutReturn(): void { + for (const listener of listeners) { + listener() + } +} + +/** Test seam. */ +export function resetOrcaCloudAfterCheckout(): void { + pending = null + listeners.clear() +} From dbe94611c5a22c12512485e8706e8faffdf7c7cd Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:48:51 -0800 Subject: [PATCH 25/46] fix(cloud): team-list archive runs the lifecycle first (409 while starting or mid-transition, never a label on a running sandbox); confirm before archiving a teammate's running workspace --- cloud/apps/sandbox-control/src/index.ts | 37 ++++++++++++++----- cloud/apps/sandbox-control/src/workspaces.ts | 7 ++++ .../sandbox-control/test/workspaces.test.ts | 29 +++++++++++++++ .../CloudWorkspaceConfirmDialog.fixture.tsx | 23 ++++++++++++ .../CloudWorkspaceConfirmDialog.tsx | 29 ++++++++++++--- .../cloud-workspaces/CloudWorkspacesHome.tsx | 18 +++++++-- .../cloud-workspace-home-archive.ts | 19 ++++++---- .../orca-cloud/cloud-workspace-actions.ts | 4 ++ src/renderer/src/i18n/locales/en.json | 5 ++- .../orca-cloud-workspace-actions.ts | 13 +++---- .../hosted-sandbox/cloud-workspace-api.ts | 9 ++++- 11 files changed, 158 insertions(+), 35 deletions(-) diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 1939442d0da..a80e4f38b4f 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -150,6 +150,7 @@ import { isOrgAdmin, listWorkspaces, patchWorkspace, + assertCanManageWorkspace, reportPresence, requireVisible, resolveLink, @@ -1374,15 +1375,33 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, return fail('invalid_request', 400) } const { archived, ...rest } = body.data - // Archive/unarchive are lifecycle changes, not labels: the sandbox really stops (snapshot kept - // with a TTL) or comes back asleep. Permissions are checked by patchWorkspace first. - let patched = await patchWorkspace(db, caller, row, archived === undefined ? body.data : { ...rest, archived }, now) - if (archived === true && (patched.row.status === 'running' || patched.row.status === 'suspended')) { - const stopped = await archiveSandbox(life, patched.row, {}, workspaceConfig(env, deps)) - patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, stopped.id)) ?? patched.row } - } else if (archived === false && patched.row.status === 'archived') { - const restored = await restoreArchivedToSleeping(life, patched.row) - patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, restored.id)) ?? patched.row } + // Archive/unarchive are lifecycle changes, not labels. The lifecycle runs FIRST and is what + // sets archived_at, so a failed or refused archive never labels a running sandbox archived. + let archivedNow = false + if (archived !== undefined) { + assertCanManageWorkspace(caller, row) + if (archived && row.archived_at === null) { + if (row.status !== 'running' && row.status !== 'suspended') { + // Starting, waking or going to sleep: nothing changes; the client asks to try again. + return fail('conflict', 409, `sandbox_${row.status}`) + } + await archiveSandbox(life, row, {}, workspaceConfig(env, deps)) + archivedNow = true + } else if (!archived && row.status === 'archived') { + await restoreArchivedToSleeping(life, row) + } else if (!archived && row.archived_at !== null) { + // A label-only archive from before archive stopped the sandbox: clear the label. + await patchWorkspace(db, caller, row, { archived: false }, now) + } + } + const current = (await getSandbox(env.SANDBOX_DB, row.id)) ?? row + let patched: Awaited> = + Object.keys(rest).length > 0 + ? await patchWorkspace(db, caller, current, rest, now) + : { row: current, revoke: 'none' } + if (archivedNow && patched.revoke === 'none') { + // Archiving disconnects teammates' devices, as before. + patched = { ...patched, revoke: 'non_owner' } } const revoked = patched.revoke === 'none' ? null : await revokeForAccessChange(life, patched.row, patched.revoke, caller.userId) diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 8052b6075b0..bc046d880ab 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -68,6 +68,13 @@ function canManage(caller: SandboxCaller, row: SandboxRow): boolean { return row.account_id === caller.accountId && (row.user_id === caller.userId || isOrgAdmin(caller)) } +/** Owner or a team admin; anyone else gets forbidden (or not_found when they can't see it). */ +export function assertCanManageWorkspace(caller: SandboxCaller, row: SandboxRow): void { + if (!canManage(caller, row)) { + throw new WorkspaceError(canSee(caller, row) ? 'forbidden' : 'not_found', 'owner_or_admin_only') + } +} + /** A row the caller may address by id; anything else is indistinguishable from a missing one. */ export async function requireVisible(db: D1Database, caller: SandboxCaller, id: string): Promise { const row = await getSandbox(db, id) diff --git a/cloud/apps/sandbox-control/test/workspaces.test.ts b/cloud/apps/sandbox-control/test/workspaces.test.ts index 1dfeb05f7f9..2f5352ca611 100644 --- a/cloud/apps/sandbox-control/test/workspaces.test.ts +++ b/cloud/apps/sandbox-control/test/workspaces.test.ts @@ -101,6 +101,35 @@ describe('workspace registry', () => { expect(t.h.vercel.snapshotExpirations.get(name)).toBe(104 * 24 * 60 * MIN) }) + it('refuses to archive a sandbox that is starting or mid-transition, and leaves the row unchanged', async () => { + const t = await team() + t.h.raw.prepare(`UPDATE sandboxes SET status = 'resuming' WHERE id = ?`).run(t.id) + const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true }) + expect(res).toMatchObject({ status: 409, body: { error: 'conflict', reason: 'sandbox_resuming' } }) + expect(t.h.raw.prepare('SELECT status, archived_at FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ + status: 'resuming', + archived_at: null + }) + }) + + it('never labels a running sandbox archived when the archive itself fails', async () => { + const t = await team() + const { ProviderError } = await import('../src/sandbox-provider') + t.h.vercel.stopSession = async () => { + throw new ProviderError(500, 'internal_error') + } + const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true }) + expect(res.status).toBeGreaterThanOrEqual(500) + expect((t.h.raw.prepare('SELECT archived_at FROM sandboxes WHERE id = ?').get(t.id) as { archived_at: number | null }).archived_at).toBeNull() + }) + + it('only the owner or a team admin can archive', async () => { + const t = await team() + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + expect((await t.req(t.bob, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })).status).toBe(403) + expect(t.h.vercel.boxes.get(`orca-test-${t.id}`)!.status).toBe('running') + }) + it('reports cost from metered compute at the billing rate, plus reported token spend', async () => { const t = await team() t.h.advance(90 * MIN) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx index f2a64ecea27..ee915e435e5 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx @@ -92,3 +92,26 @@ export const reassignAsAdmin = defineFixture({ /> ) }) + +/** Archiving a teammate's running workspace from the team list stops their agents (DS-01). */ +export const archiveTeammateRunning = defineFixture({ + width: 640, + render: () => + frame( + {}} + onConfirm={() => {}} + /> + ) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx index a5148df374d..14f760692d2 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx @@ -1,5 +1,6 @@ -// Confirmation for the two row actions that take something away from people: making a shared -// workspace private (teammates' computers are disconnected) and handing ownership to someone else. +// Confirmation for row actions that take something away from people: making a shared workspace +// private (teammates' computers are disconnected), handing ownership to someone else, and archiving +// a teammate's running workspace (their agents stop). import React, { useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { @@ -18,6 +19,8 @@ import { cloudWorkspaceTitle } from './open-cloud-workspace' export type PendingConfirm = | { kind: 'private'; workspace: CloudWorkspace } | { kind: 'owner'; workspace: CloudWorkspace; ownerUserId: string } + /** Archiving a teammate's running workspace stops their agents. */ + | { kind: 'archive'; workspace: CloudWorkspace } /** Teammates who would lose access: here now, or holding an active device grant. */ function useConnectedTeammates(workspace: CloudWorkspace, selfId: string | null): string[] { @@ -100,9 +103,13 @@ export function CloudWorkspaceConfirmDialog({ ? t('auto.components.cloudWorkspaces.makePrivateTitle', 'Make {{title}} private?', { title: cloudWorkspaceTitle(w, t) }) - : t('auto.components.cloudWorkspaces.reassignTitle', 'Make {{name}} the owner?', { - name: memberName(directory, pending.ownerUserId, selfId, t) - }) + : pending.kind === 'archive' + ? t('auto.components.cloudWorkspaces.archiveConfirmTitle', 'Archive {{name}}?', { + name: cloudWorkspaceTitle(w, t) + }) + : t('auto.components.cloudWorkspaces.reassignTitle', 'Make {{name}} the owner?', { + name: memberName(directory, pending.ownerUserId, selfId, t) + }) const losesManagement = pending.kind === 'owner' && w.ownerUserId === selfId && !canAdmin return ( !next && onCancel()}> @@ -111,6 +118,14 @@ export function CloudWorkspaceConfirmDialog({ {title} {pending.kind === 'private' ? ( + ) : pending.kind === 'archive' ? ( + + {t( + 'auto.components.cloudWorkspaces.archiveConfirmBody', + "{{owner}}'s agents in this workspace will stop. Files are kept and it can be unarchived.", + { owner: memberName(directory, w.ownerUserId, selfId, t) } + )} + ) : ( {losesManagement @@ -133,7 +148,9 @@ export function CloudWorkspaceConfirmDialog({ diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index 2683d56f479..3ac3d552b3a 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -234,12 +234,18 @@ export function CloudWorkspacesHome({ copyWorkspaceLink: (w: CloudWorkspace) => void copyCloudWorkspaceLink(w.id), goToChat: (w: CloudWorkspace, member: CloudWorkspacePresence) => void open(w, member.chatId), patch: (w: CloudWorkspace, change: CloudWorkspacePatch) => void patch(w, change), - archive: (w: CloudWorkspace) => - void archiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh), + archive: (w: CloudWorkspace) => { + // A teammate's running workspace: their agents stop, so ask first. Your own gets Undo only. + if (w.ownerUserId !== selfId && w.status === 'running') { + setConfirm({ kind: 'archive', workspace: w }) + return + } + void archiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh) + }, unarchive: (w: CloudWorkspace) => void unarchiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh) }), - [open, patch, refresh, t] + [open, patch, refresh, selfId, t] ) // Nothing (not even a skeleton) until we know this build has a control plane and you are in. @@ -372,6 +378,12 @@ export function CloudWorkspacesHome({ canAdmin={canAdmin} onCancel={() => setConfirm(null)} onConfirm={() => { + if (confirm.kind === 'archive') { + const w = confirm.workspace + setConfirm(null) + void archiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh) + return + } const change: CloudWorkspacePatch = confirm.kind === 'private' ? { visibility: 'private' } diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-home-archive.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-home-archive.ts index 93697952e47..0677047e0a4 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-home-archive.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-home-archive.ts @@ -37,13 +37,18 @@ const defaultDeps = (): HomeArchiveDeps => ({ function asResult( result: Awaited> ): CloudWorkspaceResult { - return result.ok - ? { ok: true, value: null } - : { - ok: false, - code: 'failed', - message: describeError(result.error, result.reason, translate) - } + if (result.ok) { + return { ok: true, value: null } + } + const message = + // The control plane refuses while the sandbox is starting or mid-transition (409, nothing changed). + result.error === 'conflict' + ? translate( + 'auto.components.cloudWorkspaces.archiveBusy', + 'This workspace is still starting or going to sleep. Nothing was changed. Try again in a moment.' + ) + : describeError(result.error, result.reason, translate) + return { ok: false, code: 'failed', message, userMessage: message } } export async function archiveFromHome( diff --git a/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts b/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts index a96d8ed2fe5..57f5f256055 100644 --- a/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts +++ b/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts @@ -37,6 +37,10 @@ function failureToast(title: string, result: CloudWorkspaceResult): void { }) return } + if (result.userMessage) { + toast.error(title, { description: result.userMessage }) + return + } toast.error(title, { description: result.code === 'unavailable' diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 4e92c88f838..613fe717dfd 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20857,7 +20857,10 @@ "workspaceLinkCopied": "Workspace link copied", "you": "You", "youAreTyping": "You are typing", - "youAreViewing": "You are viewing" + "youAreViewing": "You are viewing", + "archiveConfirmTitle": "Archive {{name}}?", + "archiveConfirmBody": "{{owner}}'s agents in this workspace will stop. Files are kept and it can be unarchived.", + "archiveBusy": "This workspace is still starting or going to sleep. Nothing was changed. Try again in a moment." }, "orcaCloud": { "QueuedPrompt": { diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-actions.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-actions.ts index 9830142aa4c..9351f431e83 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-actions.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-actions.ts @@ -71,14 +71,11 @@ export function archiveCloudWorkspace( const slept = await deps.sleep(workspaceId) if (slept && !slept.every((result) => result.completed)) { // Never archive a sandbox that is still running: it would keep using hours behind an "Archived" label. - return { - ok: false, - code: 'failed', - message: translate( - 'auto.lib.orcaCloud.workspaceActions.archiveSleepFailed', - 'It’s still running. Your files are safe.' - ) - } + const message = translate( + 'auto.lib.orcaCloud.workspaceActions.archiveSleepFailed', + 'It’s still running. Your files are safe.' + ) + return { ok: false, code: 'failed', message, userMessage: message } } return bridge.archive({ workspaceId, diff --git a/src/shared/hosted-sandbox/cloud-workspace-api.ts b/src/shared/hosted-sandbox/cloud-workspace-api.ts index b369e2dc025..5c9c76f35ae 100644 --- a/src/shared/hosted-sandbox/cloud-workspace-api.ts +++ b/src/shared/hosted-sandbox/cloud-workspace-api.ts @@ -19,7 +19,14 @@ export type CloudWorkspaceErrorCode = export type CloudWorkspaceResult = | { ok: true; value: T } - | { ok: false; code: CloudWorkspaceErrorCode; message: string; reason?: string | null } + | { + ok: false + code: CloudWorkspaceErrorCode + message: string + reason?: string | null + /** Copy written for people (renderer-authored); shown as is. `message` may be raw. */ + userMessage?: string + } /** Why a wake started; every source goes through the control plane's single-flight wake. */ export type CloudWakeSource = 'open' | 'message' | 'ssh' | 'preview' | 'restart' | 'unarchive' From bcfa0cffe7eec4016c0b7dcccb0899acc848abd3 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:39:24 -0800 Subject: [PATCH 26/46] =?UTF-8?q?feat(native-chat):=20DS-39=20rewind=20pol?= =?UTF-8?q?ish=20=E2=80=94=20file=20list,=20files-only=20restore,=20focus?= =?UTF-8?q?=20ring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rewind confirm lists the changed files under the choice (three, then Show N more); the host preview returns up to 200 sorted paths. - 'Restore files to here' in a user message's menu restores files without rewinding the chat (Claude Code's code-only rewind), with Undo. - Rewind hover action uses the --focus-ring outline token. - Disabled unchecked checkboxes keep a full-strength --input border on a muted fill. - Fixture: NativeChatRewindConfirm:restoreFilesOnly; restoreFiles shows six paths. --- .../checkpoints/agent-session-checkpoints.ts | 4 + ...uctured-agent-session-rewind-files.test.ts | 7 +- .../components/confirmation-dialog-context.ts | 3 + .../components/confirmation-dialog-option.tsx | 46 +++++- .../components/confirmation-dialog.test.tsx | 15 ++ .../src/components/confirmation-dialog.tsx | 12 +- .../actions/NativeChatRewindAction.tsx | 2 +- .../NativeChatRewindConfirm.fixture.tsx | 45 +++++- .../actions/native-chat-restore-files-only.ts | 63 ++++++++ .../actions/native-chat-rewind-files.ts | 138 ++++++++++++++---- .../use-native-chat-rewind-files.test.tsx | 46 ++++++ .../actions/use-native-chat-rewind-host.ts | 2 + .../actions/use-native-chat-rewind.ts | 13 +- .../actions/NativeChatContextMenuItems.tsx | 23 ++- src/renderer/src/components/ui/checkbox.tsx | 2 +- .../src/i18n/en-runtime-required.json | 6 + src/renderer/src/i18n/locales/en.json | 23 ++- .../lifecycle/agent-session-checkpoint.ts | 4 + 18 files changed, 414 insertions(+), 40 deletions(-) create mode 100644 src/renderer/src/components/native-chat/messages/actions/native-chat-restore-files-only.ts diff --git a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts index 23b48dd9af6..c372aa82751 100644 --- a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts +++ b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts @@ -5,6 +5,7 @@ import { createHash, randomBytes } from 'node:crypto' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { + AGENT_SESSION_CHECKPOINT_PREVIEW_PATHS, AGENT_SESSION_CHECKPOINT_UNDO_ID, agentSessionCheckpointPartialMessage, agentSessionCheckpointRefusalMessage, @@ -157,6 +158,9 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) return { available: true, changedFiles: changes.length, + paths: [...new Set(changes.map((change) => change.path))] + .sort() + .slice(0, AGENT_SESSION_CHECKPOINT_PREVIEW_PATHS), headMoved, createdAt: found.checkpoint.createdAt, busy: diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts index 98586ac9d60..135597e3748 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts @@ -180,7 +180,12 @@ describe('rewind with file restore', () => { expect(await git('stash', 'list')).toBe('') const preview = await hostAgentSessionCheckpoints(host).preview(HOST_TEST_SESSION, second) - expect(preview).toMatchObject({ available: true, changedFiles: 3, headMoved: false }) + expect(preview).toMatchObject({ + available: true, + changedFiles: 3, + paths: ['app.ts', 'feature.ts', 'refactor/util.ts'], + headMoved: false + }) const restored = await hostAgentSessionCheckpoints(host).restore(HOST_TEST_SESSION, second) expect(restored.changedFiles).toBe(3) expect(await read('app.ts')).toBe('v1\n') diff --git a/src/renderer/src/components/confirmation-dialog-context.ts b/src/renderer/src/components/confirmation-dialog-context.ts index fba1252b34d..5f57d0832e6 100644 --- a/src/renderer/src/components/confirmation-dialog-context.ts +++ b/src/renderer/src/components/confirmation-dialog-context.ts @@ -41,6 +41,9 @@ export type ConfirmationDialogOptions = { disabled?: boolean onConfirmed: (checked: boolean) => void } + /** Names what the action touches (file paths, say), under the option or the description; + * the first three show, the rest behind "Show N more". `total` may exceed `items`. */ + itemList?: { label: string; items: string[]; total: number } /** Runs when the cancel button settles the prompt, unlike Esc, an outside press or an abort. */ onCancelClicked?: () => void /** Renders text inputs; Enter in one confirms. `onConfirmed` gets their values, only on confirm. */ diff --git a/src/renderer/src/components/confirmation-dialog-option.tsx b/src/renderer/src/components/confirmation-dialog-option.tsx index 744f5bdf55e..c6d9670a4a1 100644 --- a/src/renderer/src/components/confirmation-dialog-option.tsx +++ b/src/renderer/src/components/confirmation-dialog-option.tsx @@ -1,4 +1,5 @@ -import React from 'react' +import React, { useState } from 'react' +import { useTranslate } from '@/i18n/use-translate' import { Checkbox } from '@/components/ui/checkbox' import { Label } from '@/components/ui/label' import type { ConfirmationDialogOptions } from '@/components/confirmation-dialog-context' @@ -44,3 +45,46 @@ export function ConfirmationDialogOption({
    ) } + +const COLLAPSED_ITEMS = 3 + +/** The paths (or other names) an action touches: three, then the rest on request. */ +export function ConfirmationDialogItemList({ + list, + indented +}: { + list: NonNullable + /** Lines up under an option's label. */ + indented: boolean +}): React.JSX.Element { + const t = useTranslate() + const [expanded, setExpanded] = useState(false) + const shown = expanded ? list.items : list.items.slice(0, COLLAPSED_ITEMS) + const hidden = list.total - shown.length + return ( +
    +
      + {shown.map((item) => ( +
    • + {item} +
    • + ))} +
    + {list.total > COLLAPSED_ITEMS ? ( + + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/confirmation-dialog.test.tsx b/src/renderer/src/components/confirmation-dialog.test.tsx index 09e1c694f9c..c6545e5b89e 100644 --- a/src/renderer/src/components/confirmation-dialog.test.tsx +++ b/src/renderer/src/components/confirmation-dialog.test.tsx @@ -134,6 +134,21 @@ describe('ConfirmationDialogProvider', () => { await waitFor(() => expect(onSettled).toHaveBeenCalledWith(true)) }) + it('shows three listed items, then the rest on request', async () => { + renderDialog({ + title: 'Rewind to here?', + itemList: { label: 'Changed files', items: ['a', 'b', 'c', 'd', 'e'], total: 7 } + }) + await userEvent.click(screen.getByRole('button', { name: 'ask' })) + const list = await screen.findByRole('list', { name: 'Changed files' }) + expect(list.querySelectorAll('li')).toHaveLength(3) + await userEvent.click(screen.getByRole('button', { name: 'Show 4 more' })) + expect(list.querySelectorAll('li')).toHaveLength(5) + expect(screen.getByRole('button', { name: 'Show fewer' }).getAttribute('aria-expanded')).toBe( + 'true' + ) + }) + it('never saves the preference when the user backs out', async () => { const onConfirmed = vi.fn() const { onSettled } = renderDialog({ diff --git a/src/renderer/src/components/confirmation-dialog.tsx b/src/renderer/src/components/confirmation-dialog.tsx index 1404855494a..45d4fe4a146 100644 --- a/src/renderer/src/components/confirmation-dialog.tsx +++ b/src/renderer/src/components/confirmation-dialog.tsx @@ -20,7 +20,10 @@ import { import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' -import { ConfirmationDialogOption } from '@/components/confirmation-dialog-option' +import { + ConfirmationDialogItemList, + ConfirmationDialogOption +} from '@/components/confirmation-dialog-option' type ConfirmationDialogRequest = { id: number @@ -197,6 +200,13 @@ export function ConfirmationDialogProvider({ onCheckedChange={setOptionChecked} /> ) : null} + {displayedRequest?.options.itemList ? ( + + ) : null} {displayedRequest?.options.fields ? (
    {displayedRequest.options.fields.inputs.map((field) => ( diff --git a/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx b/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx index a3092677604..26900727d1b 100644 --- a/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx @@ -19,7 +19,7 @@ export function NativeChatRewindAction({
    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} +export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers\n # shells that were already open).\n sudo install -d -m 0755 /etc/zsh\n sudo touch /etc/zsh/zshenv\n grep -q zz-orca-session-env /etc/zsh/zshenv ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\nskip_name() {\n case \"$1\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) return 0 ;; esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-env b/cloud/apps/sandbox-control/image/vm/orca-env new file mode 100755 index 00000000000..75ccbdc16a4 --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-env @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets +# saved after the shell started): eval "$(orca-env)" or, in fish: orca-env --fish | source +# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and +# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone. +# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal. +set -euo pipefail +fish='' +case "${1-}" in + '') ;; + --fish) fish=1 ;; + -h | --help) + printf 'usage: eval "$(orca-env)" (fish: orca-env --fish | source)\n' + exit 0 + ;; + *) + printf 'orca-env: unknown option %s\n' "$1" >&2 + exit 2 + ;; +esac +# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names. +file="${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}" +set -f # names are split below, never globbed +# Not written yet (or not a cloud VM): nothing to change, like the shell hook. +[ -r "$file" ] || exit 0 + +# 'it'\''s' for POSIX shells; fish single quotes escape only \ and '. +quote() { + local v="$1" + if [ -n "$fish" ]; then + v="${v//\\/\\\\}" + v="${v//\'/\\\'}" + printf "'%s'" "$v" + else + printf "'%s'" "${v//\'/\'\\\'\'}" + fi +} + +skip_name() { + case "$1" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) return 0 ;; esac + return 1 +} + +names=' ' +while IFS= read -r line || [ -n "$line" ]; do + name="${line%%=*}" + skip_name "$name" && continue + # $(...) drops trailing newlines; the x keeps them. + value="$(printf '%s' "${line#*=}" | base64 -d 2>/dev/null; printf x)" + value="${value%x}" + if [ -n "$fish" ]; then + printf 'set -gx %s %s\n' "$name" "$(quote "$value")" + else + printf 'export %s=%s\n' "$name" "$(quote "$value")" + fi + names="$names$name " +done <"$file" +for name in ${ORCA_SESSION_ENV_NAMES-}; do + skip_name "$name" && continue + case "$names" in *" $name "*) continue ;; esac + if [ -n "$fish" ]; then + printf 'set -e %s\n' "$name" + else + printf 'unset %s\n' "$name" + fi +done +names="${names# }" +names="${names% }" +if [ -n "$fish" ]; then + printf 'set -gx ORCA_SESSION_ENV_NAMES %s\n' "$(quote "$names")" +else + printf 'export ORCA_SESSION_ENV_NAMES=%s\n' "$(quote "$names")" +fi diff --git a/cloud/apps/sandbox-control/test/orca-env.test.ts b/cloud/apps/sandbox-control/test/orca-env.test.ts new file mode 100644 index 00000000000..04bdaec37af --- /dev/null +++ b/cloud/apps/sandbox-control/test/orca-env.test.ts @@ -0,0 +1,134 @@ +// orca-env (image/vm/orca-env): prints lines that bring a running shell up to date with the session +// env file. Values must survive quoting exactly (quotes, newlines, $, backslashes) in POSIX shells +// and fish, and names that were removed must be unset. +import { spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const ORCA_ENV = fileURLToPath(new URL('../image/vm/orca-env', import.meta.url).href) + +const TRICKY: Record = { + SINGLE: "it's a 'quoted' value", + DOUBLE: 'say "hi" and \\"escaped\\"', + DOLLAR: '$HOME $(touch /tmp/orca-env-pwned) `id` ${PATH}', + NEWLINES: 'line one\nline two\n\n', + BACKSLASH: 'C:\\path\\to\\ \\n not-a-newline \\', + SEMI: 'a; echo pwned; b && c | d', + EMPTY: '' +} + +let dir = '' +let envFile = '' + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-env-')) + envFile = join(dir, 'session.env') +}) + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +function writeSessionEnv(values: Record, extraLines: string[] = []): void { + const lines = Object.entries(values).map(([name, value]) => `${name}=${Buffer.from(value).toString('base64')}`) + writeFileSync(envFile, [...lines, ...extraLines].join('\n') + '\n') +} + +function orcaEnv(args: string[], names = ''): string { + const result = spawnSync('bash', [ORCA_ENV, ...args], { + encoding: 'utf8', + env: { PATH: process.env.PATH, ORCA_SESSION_ENV_FILE: envFile, ORCA_SESSION_ENV_NAMES: names } + }) + expect(result.stderr).toBe('') + expect(result.status).toBe(0) + return result.stdout +} + +/** Runs `script` in `shell` and returns the env it ends with, read back as JSON through node. */ +function envAfter(shell: string, args: string[], script: string, initial: Record = {}) { + const dump = `"${process.execPath}" -e 'process.stdout.write(JSON.stringify(process.env))'` + const result = spawnSync(shell, ['-c', `${script}\n${dump}`], { + encoding: 'utf8', + env: { + PATH: process.env.PATH, + // A throwaway HOME keeps this machine's rc files out of it. + HOME: dir, + ORCA_SESSION_ENV_FILE: envFile, + ORCA_ENV_BIN: ORCA_ENV, + ...initial + } + }) + expect(result.stderr, shell).toBe('') + return JSON.parse(result.stdout) as Record +} + +function hasShell(shell: string): boolean { + return !spawnSync(shell, ['-c', 'true']).error +} + +describe('orca-env', () => { + it('exports every session name with its exact value in bash, sh and zsh', () => { + writeSessionEnv(TRICKY) + for (const shell of ['bash', 'sh', 'zsh'].filter(hasShell)) { + const env = envAfter(shell, [], 'eval "$(bash "$ORCA_ENV_BIN")"') + for (const [name, value] of Object.entries(TRICKY)) { + expect(env[name], `${shell} ${name}`).toBe(value) + } + expect(env.ORCA_SESSION_ENV_NAMES).toBe(Object.keys(TRICKY).join(' ')) + } + }) + + it('exports the exact values in fish', () => { + if (!hasShell('fish')) { + return + } + writeSessionEnv(TRICKY) + const env = envAfter('fish', ['--fish'], 'bash $ORCA_ENV_BIN --fish | source') + for (const [name, value] of Object.entries(TRICKY)) { + expect(env[name], name).toBe(value) + } + }) + + it('unsets names the session env no longer has, in POSIX shells and fish', () => { + writeSessionEnv({ KEPT: 'new' }) + const initial = { KEPT: 'old', GONE: 'stale', MINE: 'untouched', ORCA_SESSION_ENV_NAMES: 'KEPT GONE' } + expect(orcaEnv([], 'KEPT GONE')).toContain('unset GONE\n') + expect(orcaEnv(['--fish'], 'KEPT GONE')).toContain('set -e GONE\n') + const shells: [string, string][] = [['bash', 'eval "$(bash "$ORCA_ENV_BIN")"']] + if (hasShell('fish')) { + shells.push(['fish', 'bash $ORCA_ENV_BIN --fish | source']) + } + for (const [shell, script] of shells) { + const env = envAfter(shell, [], script, initial) + expect(env.KEPT, shell).toBe('new') + expect(env.GONE, shell).toBeUndefined() + expect(env.MINE, shell).toBe('untouched') + expect(env.ORCA_SESSION_ENV_NAMES, shell).toBe('KEPT') + } + }) + + it('skips names the shell hook skips and globs nothing', () => { + writeSessionEnv({ GOOD: 'x' }, ['PATH=L3RtcA==', 'ORCA_X=eA==', 'LD_PRELOAD=eA==', 'lower=eA==', 'not a line']) + const out = orcaEnv([], '* ORCA_TOKEN') + expect(out).toBe("export GOOD='x'\nexport ORCA_SESSION_ENV_NAMES='GOOD'\n") + }) + + it('prints nothing before the session env exists and never writes a file', () => { + const result = spawnSync('bash', [ORCA_ENV], { + encoding: 'utf8', + cwd: dir, + env: { PATH: process.env.PATH, ORCA_SESSION_ENV_FILE: join(dir, 'missing'), ORCA_SESSION_ENV_NAMES: 'A B' } + }) + expect(result.status).toBe(0) + expect(result.stdout).toBe('') + expect(spawnSync('ls', ['-A', dir], { encoding: 'utf8' }).stdout).toBe('') + }) + + it('rejects unknown options', () => { + const result = spawnSync('bash', [ORCA_ENV, '--zsh'], { encoding: 'utf8' }) + expect(result.status).toBe(2) + }) +}) diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 60b44102359..515c7c175f4 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -246,6 +246,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ ], load: async () => (await import('./handlers/cloud-env.js')).CLOUD_ENV_HANDLERS }, + { + name: 'secret', + keys: ['secret request'], + load: async () => (await import('./handlers/secret.js')).SECRET_HANDLERS + }, { name: 'speech', keys: ['speech openai-key status', 'speech openai-key set', 'speech openai-key clear'], diff --git a/src/cli/handlers/secret.test.ts b/src/cli/handlers/secret.test.ts new file mode 100644 index 00000000000..c41851a576b --- /dev/null +++ b/src/cli/handlers/secret.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from 'vitest' +import { RuntimeClientError } from '../runtime/types' +import { parseSecretRequestWait, runSecretRequest, type SecretRequestCliInput } from './secret' + +const HINT = + 'STRIPE_KEY is set for new shells in this workspace. To use it in this shell: eval "$(orca-env)" (fish: orca-env --fish | source).' + +function harness(answers: { request: unknown; statuses?: string[] }) { + const clock = { now: 0 } + const calls: { method: string; params: unknown }[] = [] + const printed: string[] = [] + const statuses = [...(answers.statuses ?? [])] + return { + calls, + printed, + deps: { + call: async (method: string, params: unknown): Promise => { + calls.push({ method, params }) + if (method === 'secrets.request') { + if (answers.request instanceof Error) { + throw answers.request + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: canned reply for this method. + return answers.request as T + } + const status = statuses.shift() ?? 'pending' + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: canned requestStatus reply. + return { requestId: 'sr_abcdefgh', name: 'STRIPE_KEY', status, expiresAt: 0 } as T + }, + sleep: async (ms: number) => { + clock.now += ms + }, + now: () => clock.now, + print: (line: string) => printed.push(line) + } + } +} + +const base: SecretRequestCliInput = { + name: 'STRIPE_KEY', + reason: 'Run the checkout tests', + waitSec: null, + json: false, + terminalHandle: 'term-1', + worktreeId: 'wt-1' +} + +describe('orca secret request', () => { + it('sends the terminal handle so orcad can name the agent, and never an agent name', async () => { + const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } }) + await runSecretRequest({ ...base, scope: 'repo' }, h.deps) + expect(h.calls[0]).toEqual({ + method: 'secrets.request', + params: { + name: 'STRIPE_KEY', + reason: 'Run the checkout tests', + scope: 'repo', + worktreeId: 'wt-1', + terminalHandle: 'term-1' + } + }) + }) + + it('without --wait, reports the pending request and exits 0', async () => { + const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } }) + await expect(runSecretRequest(base, h.deps)).resolves.toBe(0) + expect(h.printed).toEqual([ + 'Asked the person for STRIPE_KEY (sr_abcdefgh). Add --wait to wait for the answer.' + ]) + }) + + it('with --wait, polls until provided and prints the D4 reload hint exactly', async () => { + const h = harness({ + request: { requestId: 'sr_abcdefgh', status: 'pending' }, + statuses: ['pending', 'pending', 'provided'] + }) + await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(0) + expect(h.printed).toEqual([HINT]) + expect(h.calls.filter((c) => c.method === 'secrets.requestStatus')).toHaveLength(3) + }) + + it('prints JSON with the hint when provided', async () => { + const h = harness({ + request: { requestId: 'sr_abcdefgh', status: 'pending' }, + statuses: ['provided'] + }) + await runSecretRequest({ ...base, waitSec: 60, json: true }, h.deps) + expect(JSON.parse(h.printed[0])).toEqual({ + requestId: 'sr_abcdefgh', + name: 'STRIPE_KEY', + status: 'provided', + hint: HINT + }) + }) + + it('exits 1 when declined, expired, or the wait runs out', async () => { + for (const [status, line] of [ + ['declined', 'The person declined to provide STRIPE_KEY.'], + ['expired', 'The request for STRIPE_KEY expired before anyone answered it.'] + ]) { + const h = harness({ + request: { requestId: 'sr_abcdefgh', status: 'pending' }, + statuses: [status] + }) + await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(1) + expect(h.printed).toEqual([line]) + } + const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } }) + await expect(runSecretRequest({ ...base, waitSec: 5 }, h.deps)).resolves.toBe(1) + expect(h.printed[0]).toBe( + 'Still waiting for STRIPE_KEY (sr_abcdefgh). Run the same command again to keep waiting.' + ) + }) + + it('reports already-set without polling', async () => { + const h = harness({ request: { requestId: null, status: 'already-set' } }) + await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(0) + expect(h.calls).toHaveLength(1) + expect(h.printed[0]).toContain('STRIPE_KEY is already set in this workspace.') + }) + + it('explains refusals in words', async () => { + const h = harness({ + request: new RuntimeClientError('runtime_error', 'use_sign_in_or_cloud_secrets') + }) + await expect(runSecretRequest({ ...base, name: 'ANTHROPIC_API_KEY' }, h.deps)).rejects.toThrow( + "ANTHROPIC_API_KEY is an agent credential: it comes from the person's sign-in or Orca Cloud secrets and can't be requested." + ) + }) + + it('parses --wait', () => { + expect(parseSecretRequestWait(undefined)).toBeNull() + expect(parseSecretRequestWait(true)).toBe(900) + expect(parseSecretRequestWait('30')).toBe(30) + expect(parseSecretRequestWait('99999')).toBe(3600) + expect(() => parseSecretRequestWait('soon')).toThrow('--wait takes a number of seconds') + expect(() => parseSecretRequestWait('0')).toThrow() + }) +}) diff --git a/src/cli/handlers/secret.ts b/src/cli/handlers/secret.ts new file mode 100644 index 00000000000..2b13825fd80 --- /dev/null +++ b/src/cli/handlers/secret.ts @@ -0,0 +1,200 @@ +import type { CommandHandler } from '../dispatch' +import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { RuntimeClientError } from '../runtime/types' +import { + SECRET_REQUEST_ERRORS, + SECRET_REQUEST_REASON_MAX, + SECRETS_REQUEST_METHOD, + SECRETS_REQUEST_STATUS_METHOD, + secretReloadHint, + type SecretRequestScope, + type SecretRequestStatus, + type SecretsRequestParams, + type SecretsRequestResult, + type SecretsRequestStatusResult +} from '../../shared/secret-request-contract' + +const DEFAULT_WAIT_SEC = 900 +const MAX_WAIT_SEC = 3600 +const POLL_MS = 2000 + +export type SecretRequestOutcome = SecretRequestStatus | 'already-set' + +export type SecretRequestCliDeps = { + call: (method: string, params: unknown) => Promise + sleep: (ms: number) => Promise + now: () => number + print: (line: string) => void +} + +export type SecretRequestCliInput = { + name: string + reason: string + scope?: SecretRequestScope + waitSec: number | null + json: boolean + terminalHandle?: string + worktreeId?: string +} + +/** Returns the exit code. */ +export async function runSecretRequest( + input: SecretRequestCliInput, + deps: SecretRequestCliDeps +): Promise { + const params: SecretsRequestParams = { + name: input.name, + reason: input.reason, + ...(input.scope ? { scope: input.scope } : {}), + ...(input.worktreeId ? { worktreeId: input.worktreeId } : {}), + ...(input.terminalHandle ? { terminalHandle: input.terminalHandle } : {}) + } + let created: SecretsRequestResult + try { + created = await deps.call(SECRETS_REQUEST_METHOD, params) + } catch (error) { + throw explainRequestError(error, input.name) + } + if (created.status === 'already-set') { + return finish(input, deps, { requestId: null, status: 'already-set' }) + } + const requestId = created.requestId + if (input.waitSec === null) { + return finish(input, deps, { requestId, status: 'pending' }) + } + const deadline = deps.now() + input.waitSec * 1000 + for (;;) { + const current = await deps.call(SECRETS_REQUEST_STATUS_METHOD, { + requestId + }) + if (current.status !== 'pending' || deps.now() >= deadline) { + return finish(input, deps, { requestId, status: current.status, waited: true }) + } + await deps.sleep(Math.min(POLL_MS, Math.max(0, deadline - deps.now()))) + } +} + +function finish( + input: SecretRequestCliInput, + deps: SecretRequestCliDeps, + result: { requestId: string | null; status: SecretRequestOutcome; waited?: boolean } +): number { + const answered = result.status === 'provided' || result.status === 'already-set' + const exitCode = answered || (result.status === 'pending' && !result.waited) ? 0 : 1 + if (input.json) { + deps.print( + JSON.stringify( + { + requestId: result.requestId, + name: input.name, + status: result.status, + ...(result.status === 'provided' || result.status === 'already-set' + ? { hint: secretReloadHint(input.name) } + : {}) + }, + null, + 2 + ) + ) + return exitCode + } + deps.print(formatSecretRequestOutcome(input.name, result.requestId, result.status, result.waited)) + return exitCode +} + +export function formatSecretRequestOutcome( + name: string, + requestId: string | null, + status: SecretRequestOutcome, + waited = false +): string { + switch (status) { + case 'provided': + return secretReloadHint(name) + case 'already-set': + return `${name} is already set in this workspace. If this shell doesn't have it yet: eval "$(orca-env)" (fish: orca-env --fish | source).` + case 'declined': + return `The person declined to provide ${name}.` + case 'expired': + return `The request for ${name} expired before anyone answered it.` + case 'pending': + return waited + ? `Still waiting for ${name} (${requestId}). Run the same command again to keep waiting.` + : `Asked the person for ${name} (${requestId}). Add --wait to wait for the answer.` + } +} + +const ERROR_MESSAGES: Record string> = { + [SECRET_REQUEST_ERRORS.invalidName]: (name) => + `${name} is not a valid secret name: use A-Z, 0-9 and _, not starting with a digit.`, + [SECRET_REQUEST_ERRORS.reservedName]: (name) => + `${name} is reserved: Orca or the system manages it, so it can't be a secret.`, + [SECRET_REQUEST_ERRORS.subscriptionTokenRefused]: () => + 'CLAUDE_CODE_OAUTH_TOKEN is never stored. Ask the person to sign Claude in instead.', + [SECRET_REQUEST_ERRORS.agentCredential]: (name) => + `${name} is an agent credential: it comes from the person's sign-in or Orca Cloud secrets and can't be requested.`, + [SECRET_REQUEST_ERRORS.tooManyPending]: () => + 'This workspace already has 3 secret requests waiting. Wait for one to be answered.', + [SECRET_REQUEST_ERRORS.rateLimited]: () => + 'This workspace asked for 10 secrets in the last hour. Try again later.' +} + +function explainRequestError(error: unknown, name: string): unknown { + if (!(error instanceof RuntimeClientError)) { + return error + } + const explain = ERROR_MESSAGES[error.message] + return explain ? new RuntimeClientError(error.message, explain(name)) : error +} + +export function parseSecretRequestWait(value: string | boolean | undefined): number | null { + if (value === undefined) { + return null + } + if (value === true) { + return DEFAULT_WAIT_SEC + } + const seconds = Number(value) + if (typeof value !== 'string' || !/^\d+$/.test(value) || seconds < 1) { + throw new RuntimeClientError('invalid_argument', '--wait takes a number of seconds') + } + return Math.min(seconds, MAX_WAIT_SEC) +} + +function parseScope(value: string | undefined): SecretRequestScope | undefined { + if (value === undefined || value === 'personal' || value === 'repo') { + return value + } + throw new RuntimeClientError('invalid_argument', '--scope is personal or repo') +} + +export const SECRET_HANDLERS: Record = { + 'secret request': async ({ flags, client, json }) => { + const name = getRequiredStringFlag(flags, 'name') + const reason = getRequiredStringFlag(flags, 'reason').trim() + if (reason.length === 0 || reason.length > SECRET_REQUEST_REASON_MAX) { + throw new RuntimeClientError( + 'invalid_argument', + `--reason must be 1-${SECRET_REQUEST_REASON_MAX} characters` + ) + } + process.exitCode = await runSecretRequest( + { + name, + reason, + scope: parseScope(getOptionalStringFlag(flags, 'scope')), + waitSec: parseSecretRequestWait(flags.get('wait')), + json, + terminalHandle: process.env.ORCA_TERMINAL_HANDLE || undefined, + worktreeId: process.env.ORCA_WORKTREE_ID || undefined + }, + { + call: async (method: string, params: unknown) => + (await client.call(method, params)).result, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + now: Date.now, + print: (line) => console.log(line) + } + ) + } +} diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index b28fd7feb1c..bbcbaea79e3 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -93,6 +93,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' cloud messages List or show messages sent to a cloud workspace', ' cloud sessions List agent sessions in a cloud workspace', ' cloud projects list List Orca Cloud projects', + ' secret request Ask the person for a secret this workspace needs', '', 'Automations:', ' automations list List scheduled Orca automations', diff --git a/src/cli/specs/index.ts b/src/cli/specs/index.ts index dfeb0239e7f..89714b6524c 100644 --- a/src/cli/specs/index.ts +++ b/src/cli/specs/index.ts @@ -26,6 +26,7 @@ import { VM_COMMAND_SPECS } from './vm' import { VM_ENV_COMMAND_SPECS } from './vm-env' import { CLOUD_ENV_COMMAND_SPECS } from './cloud-env' import { CLOUD_SSH_COMMAND_SPECS } from './cloud-ssh' +import { SECRET_COMMAND_SPECS } from './secret' import { SKILL_COMMAND_SPECS } from './skills' import { ARTIFACT_COMMAND_SPECS } from './artifacts' import { SEARCH_COMMAND_SPECS } from './search' @@ -66,6 +67,7 @@ export const COMMAND_SPECS: CommandSpec[] = [ ...VM_ENV_COMMAND_SPECS, ...CLOUD_ENV_COMMAND_SPECS, ...CLOUD_SSH_COMMAND_SPECS, + ...SECRET_COMMAND_SPECS, ...EMULATOR_COMMAND_SPECS, ...SKILL_COMMAND_SPECS, ...SEARCH_COMMAND_SPECS, diff --git a/src/cli/specs/secret.ts b/src/cli/specs/secret.ts new file mode 100644 index 00000000000..da2b904c9b0 --- /dev/null +++ b/src/cli/specs/secret.ts @@ -0,0 +1,26 @@ +import type { CommandSpec } from '../args' +import { LOCAL_COMMAND_FLAGS } from '../args' + +export const SECRET_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['secret', 'request'], + summary: 'Ask the person to provide a secret for this workspace', + usage: + 'orca secret request --reason "" [--scope personal|repo] [--wait ] [--json]', + allowedFlags: [...LOCAL_COMMAND_FLAGS, 'name', 'reason', 'scope', 'wait'], + positionalArgs: ['name'], + notes: [ + 'Orca shows the person a card with NAME and your reason; they type the value. The value never passes through you or this command.', + 'Once provided, NAME is set for new shells in this workspace. In the current shell run eval "$(orca-env)" (fish: orca-env --fish | source).', + '--reason (at most 200 characters) is shown to the person as your words. Say what the secret unblocks.', + '--scope is a hint: the person chooses where it is saved.', + '--wait waits for an answer (default without a number: 900). Running the same request again while it is pending waits on it rather than asking twice.', + "Agent keys (ANTHROPIC_*, OPENAI_* and similar) cannot be requested: they come from the person's sign-in or Orca Cloud secrets.", + 'Exits 1 when the request is declined, expires, or --wait ends without an answer.' + ], + examples: [ + 'orca secret request STRIPE_TEST_KEY --reason "Run the checkout integration tests" --wait 600', + 'orca secret request SENTRY_DSN --reason "Upload source maps in the release script" --json' + ] + } +] diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index aeebd8bad02..933d167a211 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -315,6 +315,18 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { return this.store?.getRemoteLayoutSnapshots?.() ?? {} } + /** The agent a terminal runs and its worktree, from host records (never from request params). */ + getTerminalHandleAgent(handle: string): { agent: string | null; worktreeId: string } | null { + const record = this.handles.get(handle) + if (!record) { + return null + } + return { + agent: record.ptyId ? this.getPtyAgent(record.ptyId) : null, + worktreeId: record.worktreeId + } + } + /** Return the already-open record store without waiting. */ openedAgentSessionRecordStore(): AgentSessionRecordStore | null { return peekOpenedAgentSessionRecordStore() diff --git a/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts b/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts new file mode 100644 index 00000000000..147109b0da2 --- /dev/null +++ b/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts @@ -0,0 +1,113 @@ +import { expect, it } from 'vitest' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { getSecretRequestStore } from '../../../secrets/secret-request-store' +import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../../core' +// Import the registry to avoid client-events' module-init cycle through ipc/ssh. +import { ALL_RPC_METHODS } from '../rpc-method-registry' + +const methods = eraseRpcMethods(ALL_RPC_METHODS) +const subscribeMethod = methods + .filter(isStreamingMethod) + .find((method) => method.name === 'runtime.clientEvents.subscribe') + +function makeRuntime(): { runtime: OrcaRuntimeService; cleanups: (() => void)[] } { + const cleanups: (() => void)[] = [] + const fake = { + getRuntimeId: () => 'runtime-a', + onClientEvent: () => () => {}, + getClientSettings: () => ({ nativeChatQueueFollowUps: true }), + registerSubscriptionCleanup: (_id: string, cleanup: () => void) => { + cleanups.push(cleanup) + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the subscribe handler reads only these members. + return { runtime: fake as unknown as OrcaRuntimeService, cleanups } +} + +const secretEvents = (events: unknown[]): Record[] => + events.filter( + (event): event is Record => + typeof event === 'object' && + event !== null && + 'type' in event && + typeof event.type === 'string' && + event.type.startsWith('secrets.') + ) + +it('registers the secrets.* methods', () => { + const names = methods.map((method) => method.name) + for (const name of [ + 'secrets.request', + 'secrets.requestStatus', + 'secrets.touchRequest', + 'secrets.resolveRequest' + ]) { + expect(names).toContain(name) + } +}) + +it('replays pending secret requests on attach, streams new ones, and gives phones status only', async () => { + if (!subscribeMethod) { + throw new Error('runtime.clientEvents.subscribe is not a streaming method') + } + const store = getSecretRequestStore() + // Made while no client was attached. + const early = store.request({ + name: 'EARLY_SECRET', + reason: 'needed before anyone attached', + agent: 'claude', + worktreeId: 'wt-1', + terminalHandle: 'term-1', + sessionEnvNames: new Set() + }) + const { runtime, cleanups } = makeRuntime() + const desktopCtx: RpcContext = { runtime, connectionId: 'conn-1', clientKind: 'runtime' } + const phoneCtx: RpcContext = { runtime, connectionId: 'conn-2', clientKind: 'mobile' } + const desktop: unknown[] = [] + const phone: unknown[] = [] + const done = [ + subscribeMethod.handler({}, desktopCtx, (event) => desktop.push(event)), + subscribeMethod.handler({}, phoneCtx, (event) => phone.push(event)) + ] + + expect(secretEvents(desktop)).toEqual([ + expect.objectContaining({ + type: 'secrets.requested', + requestId: early.requestId, + reason: 'needed before anyone attached' + }) + ]) + expect(secretEvents(phone)).toHaveLength(1) + expect(secretEvents(phone)[0]).not.toHaveProperty('reason') + + const live = store.request({ + name: 'LIVE_SECRET', + reason: 'asked while attached', + agent: null, + worktreeId: null, + terminalHandle: null, + sessionEnvNames: new Set() + }) + if (!live.requestId) { + throw new Error('expected a queued request') + } + store.resolve(live.requestId, 'declined') + expect(secretEvents(desktop).map((event) => event.type)).toEqual([ + 'secrets.requested', + 'secrets.requested', + 'secrets.requestSettled' + ]) + + cleanups.forEach((cleanup) => cleanup()) + await Promise.all(done) + const before = desktop.length + store.request({ + name: 'AFTER_CLOSE', + reason: 'r', + agent: null, + worktreeId: null, + terminalHandle: null, + sessionEnvNames: new Set() + }) + expect(desktop).toHaveLength(before) +}) diff --git a/src/main/runtime/rpc/methods/client-events/client-events.ts b/src/main/runtime/rpc/methods/client-events/client-events.ts index f78a7844631..1f06c6f28fc 100644 --- a/src/main/runtime/rpc/methods/client-events/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events/client-events.ts @@ -16,6 +16,11 @@ import { } from '../../../../../shared/structured-chat-dispatch-telemetry' import { subscribeStructuredChatTelemetry } from '../../../../telemetry/structured-chat-dispatch' import { structuredCallerFor } from '../structured-sessions/creation/structured-agent-session-gate' +import { + getSecretRequestStore, + phoneSecretRequestEvent, + type SecretRequestStoreEvent +} from '../../../secrets/secret-request-store' let clientEventSubscriptionSeq = 0 @@ -60,6 +65,12 @@ export const CLIENT_EVENT_METHODS = [ }) : undefined + // Agent secret requests (secrets.requested): phones get status only. + const emitSecretRequest = (event: SecretRequestStoreEvent): void => + emit(clientKind === 'mobile' ? phoneSecretRequestEvent(event) : event) + const secretRequests = getSecretRequestStore() + const unsubscribeSecretRequests = secretRequests.subscribe(emitSecretRequest) + const seq = ++clientEventSubscriptionSeq const subscriptionId = `runtime-client-events-${connectionId ?? 'inproc'}-${seq}` runtime.registerSubscriptionCleanup( @@ -68,6 +79,7 @@ export const CLIENT_EVENT_METHODS = [ unsubscribe() unregisterHostVolunteer?.() unsubscribeTelemetry?.() + unsubscribeSecretRequests() emit({ type: 'end' }) resolve() }, @@ -75,6 +87,10 @@ export const CLIENT_EVENT_METHODS = [ ) // Listen before snapshotting to close the subscribe race and replay sleep state missed during disconnect. + // Requests made while no client was attached wait here until they expire. + for (const event of secretRequests.pendingEvents()) { + emitSecretRequest(event) + } for (const event of runtime.getTerminalSleepClientEventSnapshot?.() ?? []) { emit(event) } diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index 457fe71b374..8f6474dded0 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -47,6 +47,7 @@ import { MANAGED_SERVER_METHODS } from './host-management/managed-server' import { RECIPE_VM_WAKE_METHODS } from './host-management/recipe-vm-wake' import { ORCA_CLOUD_DEVICE_ENROLLMENT_METHODS } from './orca-cloud/orca-cloud-device-enrollment' import { CLOUD_SSH_METHODS } from './cloud-ssh/cloud-ssh-methods' +import { SECRET_REQUEST_METHODS } from './secrets/secret-requests' import { ENVIRONMENT_DOCTOR_METHODS } from './host-management/environment-doctor' import { CLOUD_ENVIRONMENT_METHODS_RPC } from './cloud-environments/cloud-environments' import { SPEECH_METHODS } from './speech/speech' @@ -150,6 +151,7 @@ export const ALL_RPC_METHODS = [ ...MANAGED_SERVER_METHODS, ...RECIPE_VM_WAKE_METHODS, ...ORCA_CLOUD_DEVICE_ENROLLMENT_METHODS, + ...SECRET_REQUEST_METHODS, ...CLOUD_SSH_METHODS, ...ENVIRONMENT_DOCTOR_METHODS, ...CLOUD_ENVIRONMENT_METHODS_RPC, diff --git a/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts b/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts new file mode 100644 index 00000000000..1bdcbc8ca64 --- /dev/null +++ b/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from 'vitest' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { SecretRequestStore } from '../../../secrets/secret-request-store' +import type { RpcContext, RpcMethod } from '../../core' +import { eraseRpcMethods } from '../../core' +import { createSecretRequestMethods } from './secret-requests' + +function setup(sessionEnv: string[] = []) { + let seq = 0 + const store = new SecretRequestStore(Date.now, () => `sr_rpc${String(++seq).padStart(5, '0')}`) + const methods = new Map( + eraseRpcMethods( + createSecretRequestMethods({ + store: () => store, + sessionEnvNames: async () => new Set(sessionEnv) + }) + ).map((method) => [method.name, method]) + ) + const terminals: Record = { + 'term-codex': { agent: 'codex', worktreeId: 'wt-real' } + } + const fake = { getTerminalHandleAgent: (handle: string) => terminals[handle] ?? null } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handlers read only getTerminalHandleAgent. + const runtime = fake as unknown as OrcaRuntimeService + const call = async (name: string, params: unknown, ctx: Partial = {}) => { + const method = methods.get(name) + if (!method) { + throw new Error(`${name} is not registered`) + } + const parsed = method.params ? method.params.parse(params) : undefined + return method.handler(parsed, { runtime, ...ctx }) + } + const events: unknown[] = [] + store.subscribe((event) => events.push(event)) + return { call, events } +} + +const desktop: Partial = { caller: { kind: 'paired-device', deviceId: 'dev-1' } } +const agentCli: Partial = { caller: { kind: 'local-cli' } } + +describe('secrets.* RPC', () => { + it('derives the agent and worktree from the calling terminal, not from params', async () => { + const { call, events } = setup() + await expect( + call( + 'secrets.request', + { + name: 'STRIPE_KEY', + reason: 'tests', + terminalHandle: 'term-codex', + worktreeId: 'wt-hint' + }, + agentCli + ) + ).resolves.toEqual({ requestId: 'sr_rpc00001', status: 'pending' }) + expect(events[0]).toMatchObject({ + agent: 'codex', + worktreeId: 'wt-real', + terminalHandle: 'term-codex' + }) + }) + + it('leaves the agent unknown for an unrecognized terminal and refuses a caller-named agent', async () => { + const { call, events } = setup() + await call( + 'secrets.request', + { name: 'A', reason: 'r', terminalHandle: 'forged', worktreeId: 'wt-hint' }, + agentCli + ) + expect(events[0]).toMatchObject({ agent: null, worktreeId: 'wt-hint' }) + expect(events[0]).not.toHaveProperty('terminalHandle') + await expect( + call('secrets.request', { name: 'B', reason: 'r', agent: 'claude' }, agentCli) + ).rejects.toThrow() + }) + + it('answers already-set from the session env and refuses agent credentials', async () => { + const { call } = setup(['SENTRY_DSN']) + await expect(call('secrets.request', { name: 'SENTRY_DSN', reason: 'r' })).resolves.toEqual({ + requestId: null, + status: 'already-set' + }) + await expect( + call('secrets.request', { name: 'ANTHROPIC_API_KEY', reason: 'r' }) + ).rejects.toThrow('use_sign_in_or_cloud_secrets') + }) + + it('rejects a reason over 200 characters', async () => { + const { call } = setup() + await expect(call('secrets.request', { name: 'A', reason: 'x'.repeat(201) })).rejects.toThrow() + }) + + it('lets a person, never the agent CLI, touch and resolve; anyone reads status', async () => { + const { call } = setup() + await call('secrets.request', { name: 'A', reason: 'r' }, agentCli) + const id = { requestId: 'sr_rpc00001' } + await expect(call('secrets.touchRequest', id, agentCli)).rejects.toThrow( + 'secret_request_forbidden' + ) + await expect( + call('secrets.resolveRequest', { ...id, outcome: 'provided' }, agentCli) + ).rejects.toThrow('secret_request_forbidden') + await expect(call('secrets.touchRequest', id, desktop)).resolves.toHaveProperty('expiresAt') + await expect( + call('secrets.resolveRequest', { ...id, outcome: 'provided' }, desktop) + ).resolves.toEqual({ outcome: 'provided' }) + await expect(call('secrets.requestStatus', id, agentCli)).resolves.toMatchObject({ + status: 'provided', + name: 'A' + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/secrets/secret-requests.ts b/src/main/runtime/rpc/methods/secrets/secret-requests.ts new file mode 100644 index 00000000000..d489f188fbd --- /dev/null +++ b/src/main/runtime/rpc/methods/secrets/secret-requests.ts @@ -0,0 +1,102 @@ +import { + SECRET_REQUEST_ERRORS, + SECRETS_REQUEST_METHOD, + SECRETS_REQUEST_STATUS_METHOD, + SECRETS_RESOLVE_REQUEST_METHOD, + SECRETS_TOUCH_REQUEST_METHOD, + SecretsRequestIdParamsSchema, + SecretsRequestParamsSchema, + SecretsResolveRequestParamsSchema, + type SecretsRequestResult, + type SecretsRequestStatusResult, + type SecretsResolveRequestResult, + type SecretsTouchRequestResult +} from '../../../../../shared/secret-request-contract' +import { + getSecretRequestStore, + SecretRequestError, + type SecretRequestStore +} from '../../../secrets/secret-request-store' +import { readSessionEnvNames } from '../../../secrets/session-env-names' +import { defineMethod, type RpcContext } from '../../core' +import { isAgentRpcCaller } from '../../rpc-caller-identity' + +export type SecretRequestDeps = { + store: () => SecretRequestStore + sessionEnvNames: () => Promise> +} + +const defaultDeps: SecretRequestDeps = { + store: getSecretRequestStore, + sessionEnvNames: () => readSessionEnvNames() +} + +type TerminalAgentLookup = Pick + +/** The agent comes from the calling terminal's own session record; the caller can't name one. */ +export function callerTerminalIdentity( + runtime: TerminalAgentLookup, + terminalHandle: string | undefined +): { agent: string | null; worktreeId: string | null } | null { + if (!terminalHandle) { + return null + } + return runtime.getTerminalHandleAgent(terminalHandle) +} + +/** Only a person's client (desktop or paired device) answers a request, never the agent's own CLI. */ +function requirePersonCaller(ctx: Pick): void { + if (isAgentRpcCaller(ctx.caller)) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.forbidden) + } +} + +export function createSecretRequestMethods(deps: SecretRequestDeps = defaultDeps) { + return [ + defineMethod({ + name: SECRETS_REQUEST_METHOD, + permission: 'workspace', + params: SecretsRequestParamsSchema, + handler: async (params, ctx): Promise => { + const identity = callerTerminalIdentity(ctx.runtime, params.terminalHandle) + return deps.store().request({ + name: params.name, + reason: params.reason, + scope: params.scope, + agent: identity?.agent ?? null, + // A resolved terminal names its own worktree; otherwise take the hint. + worktreeId: identity?.worktreeId ?? params.worktreeId ?? null, + terminalHandle: identity ? (params.terminalHandle ?? null) : null, + sessionEnvNames: await deps.sessionEnvNames() + }) + } + }), + defineMethod({ + name: SECRETS_REQUEST_STATUS_METHOD, + permission: 'workspace', + params: SecretsRequestIdParamsSchema, + handler: async (params): Promise => + deps.store().status(params.requestId) + }), + defineMethod({ + name: SECRETS_TOUCH_REQUEST_METHOD, + permission: 'workspace', + params: SecretsRequestIdParamsSchema, + handler: async (params, ctx): Promise => { + requirePersonCaller(ctx) + return deps.store().touch(params.requestId) + } + }), + defineMethod({ + name: SECRETS_RESOLVE_REQUEST_METHOD, + permission: 'workspace', + params: SecretsResolveRequestParamsSchema, + handler: async (params, ctx): Promise => { + requirePersonCaller(ctx) + return deps.store().resolve(params.requestId, params.outcome) + } + }) + ] +} + +export const SECRET_REQUEST_METHODS = createSecretRequestMethods() diff --git a/src/main/runtime/secrets/secret-request-store.test.ts b/src/main/runtime/secrets/secret-request-store.test.ts new file mode 100644 index 00000000000..5842aa45746 --- /dev/null +++ b/src/main/runtime/secrets/secret-request-store.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, it } from 'vitest' +import { SECRET_REQUEST_ERRORS } from '../../../shared/secret-request-contract' +import { + phoneSecretRequestEvent, + SecretRequestError, + SecretRequestStore, + type SecretRequestInput, + type SecretRequestStoreEvent +} from './secret-request-store' + +const MIN = 60_000 + +function makeStore() { + const clock = { now: 1_000_000 } + let seq = 0 + const store = new SecretRequestStore( + () => clock.now, + () => `sr_test${String(++seq).padStart(4, '0')}` + ) + const events: SecretRequestStoreEvent[] = [] + store.subscribe((event) => events.push(event)) + return { store, clock, events } +} + +function input(name: string, extra: Partial = {}): SecretRequestInput { + return { + name, + reason: 'Run the integration tests', + agent: 'claude', + worktreeId: 'wt-1', + terminalHandle: 'term-1', + sessionEnvNames: new Set(), + ...extra + } +} + +function errorCode(fn: () => unknown): string | undefined { + try { + fn() + } catch (error) { + return error instanceof SecretRequestError ? error.code : undefined + } + return undefined +} + +describe('SecretRequestStore', () => { + it('queues a request, announces it and defaults the scope to personal', () => { + const { store, events } = makeStore() + expect(store.request(input('STRIPE_KEY', { scope: undefined }))).toEqual({ + requestId: 'sr_test0001', + status: 'pending' + }) + expect(events).toEqual([ + { + type: 'secrets.requested', + requestId: 'sr_test0001', + name: 'STRIPE_KEY', + reason: 'Run the integration tests', + scope: 'personal', + agent: 'claude', + worktreeId: 'wt-1', + terminalHandle: 'term-1', + requestedAt: 1_000_000, + expiresAt: 1_000_000 + 15 * MIN + } + ]) + expect(store.status('sr_test0001')).toMatchObject({ status: 'pending', name: 'STRIPE_KEY' }) + }) + + it('answers already-set without queueing when the session env has the name', () => { + const { store, events } = makeStore() + expect( + store.request(input('SENTRY_DSN', { sessionEnvNames: new Set(['SENTRY_DSN']) })) + ).toEqual({ requestId: null, status: 'already-set' }) + expect(events).toEqual([]) + expect(store.pendingEvents()).toEqual([]) + }) + + it.each([ + ['lower_case', SECRET_REQUEST_ERRORS.invalidName], + ['1STARTS_WITH_DIGIT', SECRET_REQUEST_ERRORS.invalidName], + ['A'.repeat(129), SECRET_REQUEST_ERRORS.invalidName], + ['CLAUDE_CODE_OAUTH_TOKEN', SECRET_REQUEST_ERRORS.subscriptionTokenRefused], + ['PATH', SECRET_REQUEST_ERRORS.reservedName], + ['GITHUB_TOKEN', SECRET_REQUEST_ERRORS.reservedName], + ['ORCA_ANYTHING', SECRET_REQUEST_ERRORS.reservedName], + ['LD_PRELOAD', SECRET_REQUEST_ERRORS.reservedName], + ['GIT_CONFIG_GLOBAL', SECRET_REQUEST_ERRORS.reservedName], + ['ANTHROPIC_API_KEY', SECRET_REQUEST_ERRORS.agentCredential], + ['AWS_BEARER_TOKEN_BEDROCK', SECRET_REQUEST_ERRORS.agentCredential], + ['OPENAI_BASE_URL', SECRET_REQUEST_ERRORS.agentCredential] + ])('refuses %s with %s', (name, code) => { + const { store, events } = makeStore() + expect(errorCode(() => store.request(input(name)))).toBe(code) + expect(events).toEqual([]) + }) + + it('still allows names that are not agent credentials (AI_GATEWAY_API_KEY, general AWS_*)', () => { + const { store } = makeStore() + expect(store.request(input('AI_GATEWAY_API_KEY')).status).toBe('pending') + expect(store.request(input('AWS_SECRET_ACCESS_KEY')).status).toBe('pending') + }) + + it('dedupes the same name while pending, without a second card', () => { + const { store, events } = makeStore() + const first = store.request(input('DB_URL')) + const again = store.request(input('DB_URL', { reason: 'different words' })) + expect(again).toEqual(first) + expect(events).toHaveLength(1) + }) + + it('allows at most 3 pending requests', () => { + const { store } = makeStore() + for (const name of ['A1', 'A2', 'A3']) { + store.request(input(name)) + } + expect(errorCode(() => store.request(input('A4')))).toBe(SECRET_REQUEST_ERRORS.tooManyPending) + // Answering one frees a slot. + store.resolve('sr_test0001', 'declined') + expect(store.request(input('A4')).status).toBe('pending') + }) + + it('allows at most 10 requests per hour, counting answered ones', () => { + const { store, clock } = makeStore() + for (let i = 0; i < 10; i += 1) { + const { requestId } = store.request(input(`N${i}`)) + if (!requestId) { + throw new Error('expected a queued request') + } + store.resolve(requestId, 'provided') + clock.now += MIN + } + expect(errorCode(() => store.request(input('N10')))).toBe(SECRET_REQUEST_ERRORS.rateLimited) + // The first falls out of the hour window. + clock.now = 1_000_000 + 60 * MIN + expect(store.request(input('N10')).status).toBe('pending') + }) + + it('expires pending requests after 15 minutes and stops replaying them', () => { + const { store, clock } = makeStore() + store.request(input('TOKEN')) + clock.now += 15 * MIN - 1 + expect(store.pendingEvents()).toHaveLength(1) + clock.now += 1 + expect(store.status('sr_test0001').status).toBe('expired') + expect(store.pendingEvents()).toEqual([]) + // An expired request frees its name and slot. + expect(store.request(input('TOKEN')).requestId).toBe('sr_test0002') + }) + + it('touch extends to now + 15 minutes, capped at 60 minutes after the request', () => { + const { store, clock } = makeStore() + store.request(input('TOKEN')) + clock.now += 10 * MIN + expect(store.touch('sr_test0001')).toEqual({ expiresAt: clock.now + 15 * MIN }) + for (let i = 0; i < 4; i += 1) { + clock.now += 10 * MIN + store.touch('sr_test0001') + } + // 60 minutes after the request, however often it was touched. + expect(store.status('sr_test0001').expiresAt).toBe(1_000_000 + 60 * MIN) + clock.now = 1_000_000 + 60 * MIN + expect(store.status('sr_test0001').status).toBe('expired') + expect(errorCode(() => store.touch('sr_test0001'))).toBe(SECRET_REQUEST_ERRORS.notPending) + }) + + it('resolves once; a request that expired mid-save reports expired', () => { + const { store, clock, events } = makeStore() + store.request(input('A')) + store.request(input('B')) + expect(store.resolve('sr_test0001', 'provided')).toEqual({ outcome: 'provided' }) + expect(store.resolve('sr_test0001', 'declined')).toEqual({ outcome: 'provided' }) + expect(store.status('sr_test0001').status).toBe('provided') + clock.now += 16 * MIN + expect(store.resolve('sr_test0002', 'provided')).toEqual({ outcome: 'expired' }) + expect(events.filter((e) => e.type === 'secrets.requestSettled')).toEqual([ + { type: 'secrets.requestSettled', requestId: 'sr_test0001', status: 'provided' } + ]) + }) + + it('reports unknown ids, and forgets old ones', () => { + const { store, clock } = makeStore() + expect(errorCode(() => store.status('sr_missing00'))).toBe(SECRET_REQUEST_ERRORS.notFound) + store.request(input('A')) + clock.now += 2 * 60 * MIN + expect(errorCode(() => store.status('sr_test0001'))).toBe(SECRET_REQUEST_ERRORS.notFound) + }) + + it('gives phones status only: no reason or terminal handle', () => { + const { store, events } = makeStore() + store.request(input('A')) + const event = events[0] + const phone = phoneSecretRequestEvent(event) + expect(phone).not.toHaveProperty('reason') + expect(phone).not.toHaveProperty('terminalHandle') + expect(phone).toMatchObject({ name: 'A', agent: 'claude', requestId: event.requestId }) + }) +}) diff --git a/src/main/runtime/secrets/secret-request-store.ts b/src/main/runtime/secrets/secret-request-store.ts new file mode 100644 index 00000000000..086fa90244e --- /dev/null +++ b/src/main/runtime/secrets/secret-request-store.ts @@ -0,0 +1,223 @@ +import { randomBytes } from 'node:crypto' +import { + SECRET_REQUEST_ERRORS, + SECRET_REQUEST_MAX_LIFETIME_MS, + SECRET_REQUEST_MAX_PENDING, + SECRET_REQUEST_MAX_PER_HOUR, + SECRET_REQUEST_TTL_MS, + SECRETS_REQUEST_SETTLED_EVENT, + SECRETS_REQUESTED_EVENT, + type SecretRequestedEvent, + type SecretRequestScope, + type SecretRequestSettledEvent, + type SecretRequestStatus, + type SecretsRequestResult, + type SecretsRequestStatusResult, + type SecretsResolveRequestResult, + type SecretsTouchRequestResult +} from '../../../shared/secret-request-contract' +import { secretRequestNameRefusal } from '../../../shared/secret-request-names' + +const HOUR_MS = 60 * 60_000 + +export class SecretRequestError extends Error { + constructor(readonly code: string) { + super(code) + this.name = 'SecretRequestError' + } +} + +type SecretRequestRecord = { + requestId: string + name: string + reason: string + scope: SecretRequestScope + agent: string | null + worktreeId: string | null + terminalHandle: string | null + requestedAt: number + expiresAt: number + outcome: 'provided' | 'declined' | null +} + +export type SecretRequestInput = { + name: string + reason: string + scope?: SecretRequestScope + /** Derived by the caller from the terminal's agent session, never from request params. */ + agent: string | null + worktreeId: string | null + terminalHandle: string | null + /** Names currently in the session env. */ + sessionEnvNames: ReadonlySet +} + +export type SecretRequestStoreEvent = SecretRequestedEvent | SecretRequestSettledEvent + +/** In-memory only (never on disk): one orcad serves one cloud workspace, so limits and dedupe are + * per store. Records outlive their request by an hour so `--wait` can read the outcome. */ +export class SecretRequestStore { + private readonly records = new Map() + private readonly listeners = new Set<(event: SecretRequestStoreEvent) => void>() + + constructor( + private readonly now: () => number = Date.now, + private readonly newId: () => string = () => `sr_${randomBytes(12).toString('base64url')}` + ) {} + + request(input: SecretRequestInput): SecretsRequestResult { + const refusal = secretRequestNameRefusal(input.name) + if (refusal) { + throw new SecretRequestError(refusal) + } + if (input.sessionEnvNames.has(input.name)) { + return { requestId: null, status: 'already-set' } + } + const now = this.now() + this.prune(now) + const pending = [...this.records.values()].filter((r) => this.statusOf(r, now) === 'pending') + const same = pending.find((r) => r.name === input.name) + if (same) { + return { requestId: same.requestId, status: 'pending' } + } + if (pending.length >= SECRET_REQUEST_MAX_PENDING) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.tooManyPending) + } + const lastHour = [...this.records.values()].filter((r) => now - r.requestedAt < HOUR_MS) + if (lastHour.length >= SECRET_REQUEST_MAX_PER_HOUR) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.rateLimited) + } + const record: SecretRequestRecord = { + requestId: this.newId(), + name: input.name, + reason: input.reason, + scope: input.scope ?? 'personal', + agent: input.agent, + worktreeId: input.worktreeId, + terminalHandle: input.terminalHandle, + requestedAt: now, + expiresAt: now + SECRET_REQUEST_TTL_MS, + outcome: null + } + this.records.set(record.requestId, record) + this.emit(toRequestedEvent(record)) + return { requestId: record.requestId, status: 'pending' } + } + + status(requestId: string): SecretsRequestStatusResult { + const record = this.require(requestId) + return { + requestId, + name: record.name, + status: this.statusOf(record, this.now()), + expiresAt: record.expiresAt + } + } + + /** D3: the card is in use, so keep the agent waiting: now + 15 min, capped at 60 min after the request. */ + touch(requestId: string): SecretsTouchRequestResult { + const record = this.require(requestId) + const now = this.now() + if (this.statusOf(record, now) !== 'pending') { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.notPending) + } + record.expiresAt = Math.min( + now + SECRET_REQUEST_TTL_MS, + record.requestedAt + SECRET_REQUEST_MAX_LIFETIME_MS + ) + return { expiresAt: record.expiresAt } + } + + /** First outcome wins. A request that expired mid-save reports `expired`; the saved value stands. */ + resolve(requestId: string, outcome: 'provided' | 'declined'): SecretsResolveRequestResult { + const record = this.require(requestId) + const status = this.statusOf(record, this.now()) + if (status !== 'pending') { + return { outcome: status } + } + record.outcome = outcome + this.emit({ type: SECRETS_REQUEST_SETTLED_EVENT, requestId, status: outcome }) + return { outcome } + } + + /** Requests still waiting, for replay to a client that attaches later. */ + pendingEvents(): SecretRequestedEvent[] { + const now = this.now() + return [...this.records.values()] + .filter((r) => this.statusOf(r, now) === 'pending') + .map(toRequestedEvent) + } + + subscribe(listener: (event: SecretRequestStoreEvent) => void): () => void { + this.listeners.add(listener) + return () => { + this.listeners.delete(listener) + } + } + + private statusOf(record: SecretRequestRecord, now: number): SecretRequestStatus { + if (record.outcome) { + return record.outcome + } + return now >= record.expiresAt ? 'expired' : 'pending' + } + + private require(requestId: string): SecretRequestRecord { + this.prune(this.now()) + const record = this.records.get(requestId) + if (!record) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.notFound) + } + return record + } + + private prune(now: number): void { + for (const [id, record] of this.records) { + if (now - record.requestedAt >= SECRET_REQUEST_MAX_LIFETIME_MS + HOUR_MS) { + this.records.delete(id) + } + } + } + + private emit(event: SecretRequestStoreEvent): void { + for (const listener of this.listeners) { + try { + listener(event) + } catch { + // One broken subscriber must not keep the others from seeing the request. + } + } + } +} + +function toRequestedEvent(record: SecretRequestRecord): SecretRequestedEvent { + return { + type: SECRETS_REQUESTED_EVENT, + requestId: record.requestId, + name: record.name, + reason: record.reason, + scope: record.scope, + agent: record.agent, + worktreeId: record.worktreeId, + ...(record.terminalHandle ? { terminalHandle: record.terminalHandle } : {}), + requestedAt: record.requestedAt, + expiresAt: record.expiresAt + } +} + +/** Phones show status only: no agent-written text. */ +export function phoneSecretRequestEvent(event: SecretRequestStoreEvent): SecretRequestStoreEvent { + if (event.type !== SECRETS_REQUESTED_EVENT) { + return event + } + const { reason: _reason, terminalHandle: _terminalHandle, ...status } = event + return status +} + +let sharedStore: SecretRequestStore | null = null + +/** The process's store: orcad's requests live as long as orcad. */ +export function getSecretRequestStore(): SecretRequestStore { + sharedStore ??= new SecretRequestStore() + return sharedStore +} diff --git a/src/main/runtime/secrets/session-env-names.test.ts b/src/main/runtime/secrets/session-env-names.test.ts new file mode 100644 index 00000000000..1557ada56e4 --- /dev/null +++ b/src/main/runtime/secrets/session-env-names.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { readSessionEnvNames } from './session-env-names' + +describe('readSessionEnvNames', () => { + it('reads names (never values) from the session env file', async () => { + const paths: string[] = [] + const names = await readSessionEnvNames({ + uid: 1000, + read: async (path) => { + paths.push(path) + return 'STRIPE_KEY=c2VjcmV0\nDB_URL=\nnot a line\nlower=eA==\n' + }, + env: { FROM_PROCESS: '1' } + }) + expect(paths).toEqual(['/dev/shm/orca-env-1000/session.env']) + expect([...names]).toEqual(['STRIPE_KEY', 'DB_URL']) + }) + + it("falls back to the process env when there's no session env file", async () => { + const names = await readSessionEnvNames({ + uid: 1000, + read: async () => { + throw Object.assign(new Error('missing'), { code: 'ENOENT' }) + }, + env: { FROM_PROCESS: '1' } + }) + expect([...names]).toEqual(['FROM_PROCESS']) + }) +}) diff --git a/src/main/runtime/secrets/session-env-names.ts b/src/main/runtime/secrets/session-env-names.ts new file mode 100644 index 00000000000..25b2770597d --- /dev/null +++ b/src/main/runtime/secrets/session-env-names.ts @@ -0,0 +1,33 @@ +import { readFile } from 'node:fs/promises' + +/** Where /opt/orca/bin/orca-sandbox-env keeps the cloud session env (tmpfs; `NAME=` lines). */ +export function sessionEnvFilePath(uid: number): string { + return `/dev/shm/orca-env-${uid}/session.env` +} + +/** Names only, never values. Falls back to this process's env where there is no session env file. */ +export async function readSessionEnvNames( + options: { + uid?: number + read?: (path: string) => Promise + env?: NodeJS.ProcessEnv + } = {} +): Promise> { + const uid = options.uid ?? process.getuid?.() + const read = options.read ?? ((path: string) => readFile(path, 'utf8')) + if (uid !== undefined) { + try { + const text = await read(sessionEnvFilePath(uid)) + return new Set( + text + .split('\n') + .filter((line) => line.includes('=')) + .map((line) => line.slice(0, line.indexOf('='))) + .filter((name) => /^[A-Z_][A-Z0-9_]*$/.test(name)) + ) + } catch { + // No session env file (not a cloud VM, or not written yet): use the process env. + } + } + return new Set(Object.keys(options.env ?? process.env)) +} diff --git a/src/main/startup/cli-command-names.ts b/src/main/startup/cli-command-names.ts index 13bd049c0bc..38dfd5329d7 100644 --- a/src/main/startup/cli-command-names.ts +++ b/src/main/startup/cli-command-names.ts @@ -66,6 +66,7 @@ export const CLI_COMMAND_NAMES = [ 'scroll', 'scrollintoview', 'search', + 'secret', 'select', 'select-all', 'sender', diff --git a/src/shared/agent-credentials/agent-credential-names.ts b/src/shared/agent-credentials/agent-credential-names.ts new file mode 100644 index 00000000000..3af10fe3b6e --- /dev/null +++ b/src/shared/agent-credentials/agent-credential-names.ts @@ -0,0 +1,18 @@ +// Per-agent credential names (single source of truth; agent-sources contract §1). The Worker mirrors +// this list verbatim in cloud/apps/sandbox-control/src/agent-credential-names.ts. +export type CredentialAgent = 'claude' | 'codex' +export const AGENT_CREDENTIAL_NAMES: Record = { + claude: [ + 'ANTHROPIC_API_KEY', + 'ANTHROPIC_AUTH_TOKEN', + 'ANTHROPIC_BASE_URL', + 'ANTHROPIC_MODEL', + 'ANTHROPIC_SMALL_FAST_MODEL', + 'CLAUDE_CODE_USE_BEDROCK', + 'CLAUDE_CODE_USE_VERTEX', + 'AWS_BEARER_TOKEN_BEDROCK', + 'ANTHROPIC_VERTEX_PROJECT_ID', + 'CLOUD_ML_REGION' + ], + codex: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL'] +} diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index 28b524adbe2..c2ecacbccc1 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -779,6 +779,11 @@ import { WorktreeTeardownMissingTerminalsParams } from './worktree-params' import { WorktreeAdoptProvisionedRoot } from './worktree-provisioned-root-params' +import { + SecretsRequestIdParamsSchema, + SecretsRequestParamsSchema, + SecretsResolveRequestParamsSchema +} from '../secret-request-contract' import { RepoIconDataUrlsParams } from '../sidebar-list/repo-icon-data-urls-contract' import { SidebarInputsReadParams } from '../sidebar-list/sidebar-inputs-feed-contract' import { SkillBundleInstallRequestSchema } from '../skill-bundle-install-contract' @@ -1523,6 +1528,10 @@ export const RPC_PARAMS_BY_METHOD = { 'runtime.clientEvents.subscribe': ClientEventsSubscribeParams, 'runtime.clientEvents.unsubscribe': ClientEventsUnsubscribeParams, 'runtimeEnvironment.wakeRecipeVm': RecipeVmWakeParams, + 'secrets.request': SecretsRequestParamsSchema, + 'secrets.requestStatus': SecretsRequestIdParamsSchema, + 'secrets.resolveRequest': SecretsResolveRequestParamsSchema, + 'secrets.touchRequest': SecretsRequestIdParamsSchema, 'session.readTerminalScrollback': SessionReadTerminalScrollbackParams, 'session.tabs.activate': ActivateTab, 'session.tabs.close': CloseTab, diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index 65cda9b9c1c..f543e8b2a72 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -12,6 +12,7 @@ import type { RuntimeNavigationTarget } from './runtime-navigation' import type { WorktreeSortOrderUpdate } from './worktree/sort-order-update' import type { SidebarInputsChangedEvent } from './sidebar-list/sidebar-inputs-feed-contract' import type { BrowserClientHostRequestEvent } from './browser/client-hosting/browser-client-host-request-protocol' +import type { SecretRequestedEvent, SecretRequestSettledEvent } from './secret-request-contract' export type RuntimeClientEvent = | { @@ -94,6 +95,9 @@ export type RuntimeClientEventStreamMessage = | RuntimeClientEvent // Addressed to this subscriber only, never broadcast. | BrowserClientHostRequestEvent + // Agent secret requests; replayed on attach while pending. Phones get no reason text. + | SecretRequestedEvent + | SecretRequestSettledEvent | { type: 'end' } export type RuntimeActivateWorktreeEvent = Extract diff --git a/src/shared/secret-request-contract.ts b/src/shared/secret-request-contract.ts new file mode 100644 index 00000000000..c2a1a28bd07 --- /dev/null +++ b/src/shared/secret-request-contract.ts @@ -0,0 +1,103 @@ +import { z } from 'zod' + +/** Agent-initiated secret requests (agent-sources contract §3). The value never travels through orcad + * or the agent: the desktop saves it to the control plane, which refreshes the session env. */ +export const SECRETS_REQUEST_METHOD = 'secrets.request' +export const SECRETS_REQUEST_STATUS_METHOD = 'secrets.requestStatus' +export const SECRETS_TOUCH_REQUEST_METHOD = 'secrets.touchRequest' +export const SECRETS_RESOLVE_REQUEST_METHOD = 'secrets.resolveRequest' + +/** Client event types (runtime.clientEvents.subscribe). */ +export const SECRETS_REQUESTED_EVENT = 'secrets.requested' +export const SECRETS_REQUEST_SETTLED_EVENT = 'secrets.requestSettled' + +export const SECRET_REQUEST_REASON_MAX = 200 +export const SECRET_REQUEST_TTL_MS = 15 * 60_000 +/** touchRequest extends to now + TTL, never past this long after the request. */ +export const SECRET_REQUEST_MAX_LIFETIME_MS = 60 * 60_000 +export const SECRET_REQUEST_MAX_PENDING = 3 +export const SECRET_REQUEST_MAX_PER_HOUR = 10 + +export const SecretRequestScopeSchema = z.enum(['personal', 'repo']) +export type SecretRequestScope = z.infer + +const RequestId = z.string().regex(/^sr_[A-Za-z0-9_-]{8,64}$/) + +export const SecretsRequestParamsSchema = z + .object({ + // Shape only; the name rules (reserved names, agent credentials) are checked by the handler so the + // agent gets a specific error code back. + name: z.string().min(1).max(128), + reason: z.string().trim().min(1).max(SECRET_REQUEST_REASON_MAX), + /** A hint only: the card always preselects Personal (D2). */ + scope: SecretRequestScopeSchema.optional(), + worktreeId: z.string().min(1).max(512).optional(), + terminalHandle: z.string().min(1).max(512).optional() + }) + .strict() +export type SecretsRequestParams = z.infer + +export const SecretsRequestIdParamsSchema = z.object({ requestId: RequestId }).strict() + +export const SecretsResolveRequestParamsSchema = z + .object({ requestId: RequestId, outcome: z.enum(['provided', 'declined']) }) + .strict() + +export type SecretRequestStatus = 'pending' | 'provided' | 'declined' | 'expired' + +export type SecretsRequestResult = + | { requestId: string; status: 'pending' } + /** The name is already in the session env; nothing was queued. */ + | { requestId: null; status: 'already-set' } + +export type SecretsRequestStatusResult = { + requestId: string + name: string + status: SecretRequestStatus + expiresAt: number +} + +export type SecretsTouchRequestResult = { expiresAt: number } + +export type SecretsResolveRequestResult = { outcome: 'provided' | 'declined' | 'expired' } + +/** Sent to connected clients when a request is made, and replayed on attach until it expires. */ +export type SecretRequestedEvent = { + type: typeof SECRETS_REQUESTED_EVENT + requestId: string + name: string + /** Untrusted agent text: show quoted and muted, never linkified. Omitted for phones (status only). */ + reason?: string + scope: SecretRequestScope + /** From the calling terminal's agent session, never from the caller; null when unknown. */ + agent: string | null + worktreeId: string | null + terminalHandle?: string + requestedAt: number + expiresAt: number +} + +/** A request was provided or declined, so other clients can drop their card. */ +export type SecretRequestSettledEvent = { + type: typeof SECRETS_REQUEST_SETTLED_EVENT + requestId: string + status: Exclude +} + +/** Error codes (RPC error message) the CLI and desktop map to guidance. */ +export const SECRET_REQUEST_ERRORS = { + invalidName: 'invalid_name', + reservedName: 'reserved_name', + subscriptionTokenRefused: 'subscription_token_refused', + agentCredential: 'use_sign_in_or_cloud_secrets', + tooManyPending: 'too_many_pending_requests', + rateLimited: 'secret_request_rate_limited', + notFound: 'secret_request_not_found', + notPending: 'secret_request_not_pending', + forbidden: 'secret_request_forbidden' +} as const + +/** D4: printed by the CLI once a request is provided. */ +export function secretReloadHint(name: string): string { + return `${name} is set for new shells in this workspace. To use it in this shell: eval "$(orca-env)" (fish: orca-env --fish | source).` +} diff --git a/src/shared/secret-request-names.test.ts b/src/shared/secret-request-names.test.ts new file mode 100644 index 00000000000..01198ddc6cf --- /dev/null +++ b/src/shared/secret-request-names.test.ts @@ -0,0 +1,36 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { + secretRequestNameRefusal, + WORKER_RESERVED_SECRET_NAMES, + WORKER_RESERVED_SECRET_PREFIXES +} from './secret-request-names' + +const WORKER_SECRETS = fileURLToPath( + new URL('../../cloud/apps/sandbox-control/src/secrets.ts', import.meta.url) +) + +function quotedStrings(text: string): string[] { + return [...text.matchAll(/'([A-Z0-9_]+)'/g)].map((match) => match[1]) +} + +describe('secret request names match the control plane', () => { + const source = readFileSync(WORKER_SECRETS, 'utf8') + + it('uses the Worker reserved names and prefixes', () => { + const names = source.match(/const RESERVED_NAMES[^=]*= new Set\(\[([\s\S]*?)\]\)/)?.[1] + const prefixes = source.match(/const RESERVED_PREFIXES = \[([^\]]*)\]/)?.[1] + expect(names, 'RESERVED_NAMES not found in the Worker').toBeTruthy() + expect(prefixes, 'RESERVED_PREFIXES not found in the Worker').toBeTruthy() + expect(new Set(quotedStrings(names ?? ''))).toEqual(WORKER_RESERVED_SECRET_NAMES) + expect(quotedStrings(prefixes ?? '')).toEqual([...WORKER_RESERVED_SECRET_PREFIXES]) + }) + + it('uses the Worker name pattern and length', () => { + expect(source).toContain('const NAME = /^[A-Z_][A-Z0-9_]*$/') + expect(source).toContain('const MAX_NAME_LENGTH = 128') + expect(secretRequestNameRefusal('A'.repeat(128))).toBeNull() + expect(secretRequestNameRefusal('_PRIVATE_1')).toBeNull() + }) +}) diff --git a/src/shared/secret-request-names.ts b/src/shared/secret-request-names.ts new file mode 100644 index 00000000000..bde801b87e6 --- /dev/null +++ b/src/shared/secret-request-names.ts @@ -0,0 +1,86 @@ +import { AGENT_CREDENTIAL_NAMES } from './agent-credentials/agent-credential-names' +import { SECRET_REQUEST_ERRORS } from './secret-request-contract' + +// The control plane's secret-name rules (cloud/apps/sandbox-control/src/secrets.ts checkName), so a +// request the Worker would refuse is refused before anyone is asked. secret-request-names.test.ts +// diffs these lists against the Worker source. +const NAME = /^[A-Z_][A-Z0-9_]*$/ +const MAX_NAME_LENGTH = 128 + +export const WORKER_RESERVED_SECRET_NAMES: ReadonlySet = new Set([ + 'PATH', + 'HOME', + 'USER', + 'LOGNAME', + 'SHELL', + 'PWD', + 'OLDPWD', + 'LANG', + 'TERM', + 'TMPDIR', + 'IFS', + 'ENV', + 'BASH_ENV', + 'PS4', + 'PROMPT_COMMAND', + 'SHELLOPTS', + 'BASHOPTS', + 'NODE_OPTIONS', + 'NODE_PATH', + 'NODE_EXTRA_CA_CERTS', + 'NODE_TLS_REJECT_UNAUTHORIZED', + 'SSL_CERT_FILE', + 'SSL_CERT_DIR', + 'CURL_CA_BUNDLE', + 'REQUESTS_CA_BUNDLE', + 'HTTP_PROXY', + 'HTTPS_PROXY', + 'ALL_PROXY', + 'NO_PROXY', + 'PYTHONPATH', + 'PYTHONSTARTUP', + 'PERL5OPT', + 'RUBYOPT', + 'JAVA_TOOL_OPTIONS', + 'GIT_SSH', + 'GIT_SSH_COMMAND', + 'GIT_ASKPASS', + 'GIT_EXEC_PATH', + 'GIT_PROXY_COMMAND', + 'SSH_AUTH_SOCK', + 'GH_TOKEN', + 'GITHUB_TOKEN', + 'CLAUDE_CODE_OAUTH_TOKEN' +]) + +export const WORKER_RESERVED_SECRET_PREFIXES: readonly string[] = [ + 'LD_', + 'DYLD_', + 'ORCA_', + 'VERCEL_', + 'BASH_FUNC_', + 'GIT_CONFIG' +] + +const AGENT_CREDENTIALS: ReadonlySet = new Set(Object.values(AGENT_CREDENTIAL_NAMES).flat()) + +/** Null when an agent may request this name; otherwise the error code to return. */ +export function secretRequestNameRefusal(name: string): string | null { + if (name.length > MAX_NAME_LENGTH || !NAME.test(name)) { + return SECRET_REQUEST_ERRORS.invalidName + } + if (name === 'CLAUDE_CODE_OAUTH_TOKEN') { + return SECRET_REQUEST_ERRORS.subscriptionTokenRefused + } + if ( + WORKER_RESERVED_SECRET_NAMES.has(name) || + WORKER_RESERVED_SECRET_PREFIXES.some((prefix) => name.startsWith(prefix)) + ) { + return SECRET_REQUEST_ERRORS.reservedName + } + // Agent keys come from the person's sign-in or Cloud secrets, never from an agent's request. + if (AGENT_CREDENTIALS.has(name)) { + return SECRET_REQUEST_ERRORS.agentCredential + } + return null +} From e9561c3c500cd333dbb49d5617c906e60fe588aa Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 02:55:34 -0800 Subject: [PATCH 29/46] fix(run-actions): persisted runs load at startup (TDZ), relaunch after a rollover waits for the new host to answer Found live on an Orca Cloud rollover (m4air): the persisted-run reader referenced a const declared below the module-level read, so every restart started with no runs and nothing relaunched. The relaunch also read orca.yaml before the replacement host served RPCs; it now retries with a bound. --- .../src/lib/run-actions/run-action-config.ts | 23 ++++++++ .../lib/run-actions/run-action-controller.ts | 3 +- .../lib/run-actions/run-actions-store.test.ts | 52 +++++++++++++++++++ .../src/lib/run-actions/run-actions-store.ts | 4 +- 4 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/lib/run-actions/run-actions-store.test.ts diff --git a/src/renderer/src/lib/run-actions/run-action-config.ts b/src/renderer/src/lib/run-actions/run-action-config.ts index 9d37f8aab13..4f852591e32 100644 --- a/src/renderer/src/lib/run-actions/run-action-config.ts +++ b/src/renderer/src/lib/run-actions/run-action-config.ts @@ -121,3 +121,26 @@ export function pickPrimaryRunAction( : undefined return liveAction ?? pickDefaultRunAction(actions) } + +const RELAUNCH_RETRY_DELAYS_MS = [0, 3_000, 6_000, 12_000, 24_000, 48_000] +const RELAUNCH_ATTEMPT_TIMEOUT_MS = 10_000 + +/** A host that just restarted may not serve repo reads yet; give it a little while to answer. */ +export async function loadRunActionsOnceHostAnswers( + worktreeId: string +): Promise { + for (const delayMs of RELAUNCH_RETRY_DELAYS_MS) { + if (delayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, delayMs)) + } + // A read queued behind a reconnecting host can hang; bound each attempt and try again. + const config = await Promise.race([ + loadWorktreeRunActions(worktreeId, { background: true }), + new Promise((resolve) => setTimeout(() => resolve(null), RELAUNCH_ATTEMPT_TIMEOUT_MS)) + ]) + if (config && config.actions.length > 0) { + return config + } + } + return null +} diff --git a/src/renderer/src/lib/run-actions/run-action-controller.ts b/src/renderer/src/lib/run-actions/run-action-controller.ts index 9e4154a5407..2d515fe0acb 100644 --- a/src/renderer/src/lib/run-actions/run-action-controller.ts +++ b/src/renderer/src/lib/run-actions/run-action-controller.ts @@ -15,6 +15,7 @@ import { type RunActionRun } from './run-actions-store' import { + loadRunActionsOnceHostAnswers, loadWorktreeRunActions, resolveRunActionTarget, type RunActionTarget, @@ -299,7 +300,7 @@ export async function relaunchInterruptedRunActions(worktreeId: string): Promise if (byAction.size === 0) { return 0 } - const config = await loadWorktreeRunActions(worktreeId) + const config = await loadRunActionsOnceHostAnswers(worktreeId) let started = 0 for (const run of byAction.values()) { const action = config?.actions.find((candidate) => candidate.id === run.actionId) diff --git a/src/renderer/src/lib/run-actions/run-actions-store.test.ts b/src/renderer/src/lib/run-actions/run-actions-store.test.ts new file mode 100644 index 00000000000..934704549e8 --- /dev/null +++ b/src/renderer/src/lib/run-actions/run-actions-store.test.ts @@ -0,0 +1,52 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const RUN = { + worktreeId: 'repo::/w', + repoId: 'repo', + actionId: 'web', + actionName: 'Web', + tabId: 'tab-1', + status: 'running', + exitCode: null, + startedAt: 1 +} + +afterEach(() => { + vi.unstubAllGlobals() + vi.resetModules() +}) + +function stubStorage(initial: Record): Map { + const data = new Map(Object.entries(initial)) + vi.stubGlobal('localStorage', { + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => void data.set(key, value) + }) + return data +} + +describe('run-actions store persistence', () => { + it('loads runs persisted by an earlier window at module load', async () => { + stubStorage({ 'orca.runActions.v1': JSON.stringify({ 'repo::/w': { web: RUN } }) }) + const store = await import('./run-actions-store') + expect(store.getRunActionRun('repo::/w', 'web')).toEqual(RUN) + }) + + it('drops malformed persisted entries', async () => { + stubStorage({ + 'orca.runActions.v1': JSON.stringify({ + 'repo::/w': { web: { ...RUN, status: 'weird' }, ok: { ...RUN, actionId: 'ok' } } + }) + }) + const store = await import('./run-actions-store') + expect(store.listRunActionRuns().map((run) => run.actionId)).toEqual(['ok']) + }) + + it('writes every change back', async () => { + const data = stubStorage({}) + const store = await import('./run-actions-store') + store.setRunActionRun({ ...RUN, status: 'running' }) + store.patchRunActionRun('repo::/w', 'web', { status: 'stopped' }) + expect(JSON.parse(data.get('orca.runActions.v1')!)['repo::/w'].web.status).toBe('stopped') + }) +}) diff --git a/src/renderer/src/lib/run-actions/run-actions-store.ts b/src/renderer/src/lib/run-actions/run-actions-store.ts index efc60bcd67f..363fb0310d3 100644 --- a/src/renderer/src/lib/run-actions/run-actions-store.ts +++ b/src/renderer/src/lib/run-actions/run-actions-store.ts @@ -19,6 +19,8 @@ export type RunActionRun = { type RunsByWorktree = Record> const STORAGE_KEY = 'orca.runActions.v1' +// Declared before `runs`: reading persisted runs at module load needs it (no temporal dead zone). +const STATUSES: readonly RunActionStatus[] = ['running', 'stopping', 'stopped', 'exited', 'failed'] let runs: RunsByWorktree = readPersisted() const listeners = new Set<() => void>() @@ -33,8 +35,6 @@ function readPersisted(): RunsByWorktree { } } -const STATUSES: readonly RunActionStatus[] = ['running', 'stopping', 'stopped', 'exited', 'failed'] - function readRun(value: unknown): RunActionRun | null { if (typeof value !== 'object' || value === null) { return null From 4ececa2c61352d05581882be5ea724b024085125 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:00:43 -0800 Subject: [PATCH 30/46] fix: keep the runtime call site to its original size; one import per module --- src/main/hosted-sandbox/cloud-desktop-keys.test.ts | 9 ++------- src/main/hosted-sandbox/cloud-desktop-keys.ts | 9 ++++----- .../runtime-environment-connectivity-handlers.ts | 8 ++------ 3 files changed, 8 insertions(+), 18 deletions(-) diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts index 0703593478c..956653b8bb2 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts @@ -5,6 +5,7 @@ const environments = new Map = {} const launchCalls: unknown[][] = [] +vi.mock('electron', () => ({ app: { getPath: () => '/u' } })) vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ listEphemeralVmRuntimes: () => runtimes })) @@ -90,13 +91,7 @@ describe('withHostAgentApiKeyEnv', () => { const { withHostAgentApiKeyEnv } = await import('./cloud-desktop-keys') const readStatus = vi.fn() expect( - await withHostAgentApiKeyEnv( - '/u', - 'env-cloud', - 'terminal.createAgentSession', - params, - readStatus - ) + await withHostAgentApiKeyEnv('env-cloud', 'terminal.createAgentSession', params, readStatus) ).toBe(params) expect(launchCalls).toEqual([]) expect(readStatus).not.toHaveBeenCalled() diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.ts b/src/main/hosted-sandbox/cloud-desktop-keys.ts index b5217dad2eb..30dcb1d8430 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.ts @@ -2,17 +2,17 @@ // host those keys ride each agent launch as plain env. An Orca Cloud VM must never hold a model key, // so they are not sent there at all: the user saves a key as a personal Cloud secret instead (one key // per click), and the VM then gets a placeholder the egress proxy swaps. +import { app } from 'electron' import { resolveAgentApiKeyLaunchEnv, withAgentApiKeyLaunchEnv } from '../agent-api-keys/agent-api-key-launch-env' +import { withAgentApiKeyRuntimeEnv } from '../agent-api-keys/agent-api-key-runtime-call' import { isCloudSshAlias } from '../cloud-ssh/cloud-ssh-config' import { getSshTargetRegistryStore } from '../ssh/targets/ssh-target-registry' -import { getConnectionExecutionHostId } from '../../shared/execution-host' -import { withAgentApiKeyRuntimeEnv } from '../agent-api-keys/agent-api-key-runtime-call' import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { toRuntimeExecutionHostId } from '../../shared/execution-host' +import { getConnectionExecutionHostId, toRuntimeExecutionHostId } from '../../shared/execution-host' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' /** Orca Cloud sandboxes answer on Vercel Sandbox routes. */ @@ -73,13 +73,12 @@ export async function desktopKeyValueForCloud( * (the VM then only sees egress placeholders). */ export async function withHostAgentApiKeyEnv( - userDataPath: string, environmentId: string, method: string, params: unknown, readStatus: Parameters[3] ): Promise { - if (isOrcaCloudRuntimeEnvironment(userDataPath, environmentId)) { + if (isOrcaCloudRuntimeEnvironment(app.getPath('userData'), environmentId)) { return params } return withAgentApiKeyRuntimeEnv(environmentId, method, params, readStatus) diff --git a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts index 5c4fd3e64cb..a9836bc6f4e 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts @@ -287,12 +287,8 @@ function registerPassiveCallHandler( getUserDataPath(), environment.id, args.method, - await withHostAgentApiKeyEnv( - getUserDataPath(), - environment.id, - args.method, - accounts.params, - () => callRuntimeEnvironment(getUserDataPath(), environment.id, 'status.get', undefined) + await withHostAgentApiKeyEnv(environment.id, args.method, accounts.params, () => + callRuntimeEnvironment(getUserDataPath(), environment.id, 'status.get', undefined) ), args.timeoutMs, args.expectedEnvironmentPairingRevision, From 797504f58236db1fda0056805fcc5ce7aa0f840f Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:02:30 -0800 Subject: [PATCH 31/46] chore(run-actions): read worktree records through the catalog selector --- src/renderer/src/lib/run-actions/run-action-config.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/lib/run-actions/run-action-config.ts b/src/renderer/src/lib/run-actions/run-action-config.ts index 4f852591e32..be7d6b2ad80 100644 --- a/src/renderer/src/lib/run-actions/run-action-config.ts +++ b/src/renderer/src/lib/run-actions/run-action-config.ts @@ -1,6 +1,7 @@ import { useAppStore } from '@/store' import { checkRuntimeHooks } from '@/runtime/repo-hooks/runtime-hooks-client' import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' +import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import type { AppState } from '@/store/types' import type { OrcaHooks, OrcaRunAction } from '../../../../shared/orca-yaml-hook-types' import { @@ -37,7 +38,7 @@ export function resolveRunActionTarget( // The active-host hint can disagree for remote workspaces; fall back to the catalog row itself. const worktree = findWorktreeById(state, worktreeId) ?? - Object.values(state.worktreesByRepo ?? {}) + Object.values(selectWorktreesByRepo(state) ?? {}) .flat() .find((candidate) => candidate.id === worktreeId) if (!worktree) { From 7734019354c3b646d9ebd2cb25894d113e7c9e7e Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:04:17 -0800 Subject: [PATCH 32/46] =?UTF-8?q?fix(w3):=20DS-29=20follow-up=20=E2=80=94?= =?UTF-8?q?=20port=20row=20inline=20actions=20trimmed,=20distinct=20Copy?= =?UTF-8?q?=20details=20icon=20(#215)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(w3): port row keeps only Open in browser, Share… and More inline; Copy details gets its own icon (DS-29 follow-up) * chore(w3): drop the unreferenced inline copy-button label from every locale --- .../right-sidebar/local-port-row.tsx | 79 +++---------------- .../right-sidebar/local-port-section.tsx | 2 - .../runtime-port-forward-status.fixture.tsx | 1 - .../runtime-port-forward-status.tsx | 38 +-------- .../use-runtime-port-row-forwarding.tsx | 10 --- src/renderer/src/i18n/locales/de.json | 1 - src/renderer/src/i18n/locales/en.json | 1 - src/renderer/src/i18n/locales/es.json | 1 - src/renderer/src/i18n/locales/fr.json | 1 - src/renderer/src/i18n/locales/ja.json | 1 - src/renderer/src/i18n/locales/ko.json | 1 - src/renderer/src/i18n/locales/pt.json | 1 - src/renderer/src/i18n/locales/ru.json | 1 - src/renderer/src/i18n/locales/tr.json | 1 - src/renderer/src/i18n/locales/zh-Hant.json | 1 - src/renderer/src/i18n/locales/zh.json | 1 - 16 files changed, 12 insertions(+), 129 deletions(-) diff --git a/src/renderer/src/components/right-sidebar/local-port-row.tsx b/src/renderer/src/components/right-sidebar/local-port-row.tsx index dc83f2e85b3..fc4d0efcd0d 100644 --- a/src/renderer/src/components/right-sidebar/local-port-row.tsx +++ b/src/renderer/src/components/right-sidebar/local-port-row.tsx @@ -1,5 +1,14 @@ import React, { useCallback, useRef } from 'react' -import { Box, Copy, Ellipsis, ExternalLink, Info, Server, Trash2 } from 'lucide-react' +import { + Box, + ClipboardList, + Copy, + Ellipsis, + ExternalLink, + Info, + Server, + Trash2 +} from 'lucide-react' import { getPortOpenBrowserTooltipLabel } from '@/lib/workspace-ports/workspace-port-actions' import { addressForPort } from '@/lib/workspace-ports/workspace-port-urls' import { Button } from '@/components/ui/button' @@ -28,7 +37,6 @@ export function LocalPortRow({ onOpenInBrowser, forwardStatus, forwardMenuItems, - forwardActions, shareAction, copyAddress }: { @@ -40,8 +48,6 @@ export function LocalPortRow({ /** A remote host's port: where it is forwarded on this computer, or how to forward it. */ forwardStatus?: React.ReactNode forwardMenuItems?: React.ReactNode - /** Hover actions for the forward (Stop Forwarding), next to Open/Copy. */ - forwardActions?: React.ReactNode /** Orca Cloud: a "Share…" hover button after Open (the same action as the menu's Share…). */ shareAction?: React.ReactNode /** Overrides the copied address, e.g. with the forwarded localhost one. */ @@ -60,16 +66,6 @@ export function LocalPortRow({ [onOpenInBrowser, port] ) - const handleCopyButtonClick = useCallback( - (event: React.MouseEvent) => { - handleCopy() - if (event.detail > 0) { - event.currentTarget.blur() - } - }, - [handleCopy] - ) - const handleOpenBrowserButtonClick = useCallback( (event: React.MouseEvent) => { // Keyboard clicks have detail=0; only pointer clicks carry the system-browser modifier intent. @@ -81,16 +77,6 @@ export function LocalPortRow({ [handleOpenBrowser] ) - const handleStopButtonClick = useCallback( - (event: React.MouseEvent) => { - onStop(port) - if (event.detail > 0) { - event.currentTarget.blur() - } - }, - [onStop, port] - ) - // The row menu is a context menu; this opens it under the button so keyboard and trackpad users reach Share… and the rest. const handleMoreActionsClick = useCallback((event: React.MouseEvent) => { const rect = event.currentTarget.getBoundingClientRect() @@ -173,7 +159,6 @@ export function LocalPortRow({
    - {forwardActions} {onOpenInBrowser && ( @@ -194,48 +179,6 @@ export function LocalPortRow({ )} {shareAction} - - - - - - {t('auto.components.right.sidebar.PortsPanel.1004af16ab', 'Copy {{value0}}', { - value0: address - })} - - - {canStopProcess && ( - - - - - - {stopProcessLabel} - - - )} - - - {t('auto.components.right.sidebar.RuntimePortForward.stopForwarding', 'Stop forwarding')} - - - ) -} diff --git a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx index d957681c442..b452a1b1a54 100644 --- a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx +++ b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx @@ -21,7 +21,6 @@ import type { WorkspacePort } from '../../../../shared/workspace-ports' import type { PortRowForwarding } from './local-port-section' import { RuntimePortForwardStatus, - RuntimePortForwardStopButton, type RuntimePortForwardRowState } from './runtime-port-forward-status' @@ -140,15 +139,6 @@ export function useRuntimePortRowForwarding( } /> ), - actions: (port) => { - const existing = forwardFor(port) - return existing ? ( - void closeRuntimePortForward(existing)} - /> - ) : null - }, menuItems: (port) => { const existing = forwardFor(port) const forwardItems = existing ? ( diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index d44ad3ef561..04bb5b48436 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -13577,7 +13577,6 @@ "c7e920aa7c": "Als {{value0}} angekündigt", "e740075063": "Entfernen", "b3548e59f4": "Bearbeiten", - "fe2730d050": "{{value0}} kopieren", "75aeea592f": "{{value0}} im Browser öffnen", "de349d4560": "Öffnet {{value0}}", "907eb53ed2": "Port weiterleiten", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 5e974e3b17e..609c5e98ac7 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -14815,7 +14815,6 @@ "c7e920aa7c": "advertised as {{value0}}", "e740075063": "Remove", "b3548e59f4": "Edit", - "fe2730d050": "Copy {{value0}}", "75aeea592f": "Open {{value0}} in Browser", "de349d4560": "opens {{value0}}", "907eb53ed2": "Forward a Port", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index ea40d7898b0..f0232680c67 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -13236,7 +13236,6 @@ "c7e920aa7c": "anunciado como {{value0}}", "e740075063": "Eliminar", "b3548e59f4": "Editar", - "fe2730d050": "Copiar {{value0}}", "75aeea592f": "Abrir {{value0}} en el navegador", "de349d4560": "abre {{value0}}", "907eb53ed2": "Reenviar un puerto", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index d3bc9765917..00b5cb19999 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -13479,7 +13479,6 @@ "c7e920aa7c": "annoncé comme {{value0}}", "e740075063": "Supprimer", "b3548e59f4": "Édition", - "fe2730d050": "Copier {{value0}}", "75aeea592f": "Ouvrir {{value0}} dans le navigateur", "de349d4560": "ouvre {{value0}}", "907eb53ed2": "Transférer un port", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index f54f01172a3..e7cfdc7ea9b 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -12930,7 +12930,6 @@ "c7e920aa7c": "{{value0}} として公開", "e740075063": "削除", "b3548e59f4": "編集", - "fe2730d050": "{{value0}}をコピー", "75aeea592f": "ブラウザで{{value0}}を開く", "de349d4560": "{{value0}} を開く", "907eb53ed2": "ポートを転送する", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 11ab1bea587..f41bd68ff62 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -12930,7 +12930,6 @@ "c7e920aa7c": "{{value0}}(으)로 공개", "e740075063": "제거", "b3548e59f4": "편집", - "fe2730d050": "{{value0}} 복사", "75aeea592f": "브라우저에서 {{value0}} 열기", "de349d4560": "{{value0}} 열기", "907eb53ed2": "포트 전달", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 461b4f20b0c..b8364cb5e7c 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -10506,7 +10506,6 @@ "c7e920aa7c": "anunciado como {{value0}}", "e740075063": "Remover", "b3548e59f4": "Editar", - "fe2730d050": "Copiar {{value0}}", "75aeea592f": "Abrir {{value0}} no Navegador", "de349d4560": "abre {{value0}}", "907eb53ed2": "Encaminhar uma Porta", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 602152d89bc..de039cda2d3 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -13941,7 +13941,6 @@ "c7e920aa7c": "объявлен как {{value0}}", "e740075063": "Удалить", "b3548e59f4": "Редактировать", - "fe2730d050": "Копировать {{value0}}", "75aeea592f": "Открыть {{value0}} в браузере", "de349d4560": "открывает {{value0}}", "907eb53ed2": "Пробросить порт", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 47b65c71412..c576548e567 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -13561,7 +13561,6 @@ "c7e920aa7c": "{{value0}} olarak duyuruldu", "e740075063": "Kaldır", "b3548e59f4": "Düzenle", - "fe2730d050": "{{value0}} Kopyala", "75aeea592f": "{{value0}} öğesini Tarayıcıda Aç", "de349d4560": "{{value0}} açar", "907eb53ed2": "Bir Port Yönlendir", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index d7ffd980735..f818b59e4a1 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -13397,7 +13397,6 @@ "c7e920aa7c": "公開為 {{value0}}", "e740075063": "移除", "b3548e59f4": "編輯", - "fe2730d050": "複製 {{value0}}", "75aeea592f": "在瀏覽器中開啟 {{value0}}", "de349d4560": "開啟 {{value0}}", "907eb53ed2": "轉送連接埠", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 6e666420865..890f7e6c503 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -12930,7 +12930,6 @@ "c7e920aa7c": "公开为 {{value0}}", "e740075063": "移除", "b3548e59f4": "编辑", - "fe2730d050": "复制 {{value0}}", "75aeea592f": "在浏览器中打开 {{value0}}", "de349d4560": "打开 {{value0}}", "907eb53ed2": "转发端口", From d3bf567b19c45b6d9710a95751a406c1c1bdc41b Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:05:42 -0800 Subject: [PATCH 33/46] fix: keep the launch path free of Electron (user data path set at startup) --- src/main/cloud-secrets/cloud-secrets-ipc.ts | 6 +++++- src/main/hosted-sandbox/cloud-desktop-keys.test.ts | 5 +++-- src/main/hosted-sandbox/cloud-desktop-keys.ts | 14 ++++++++++++-- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/cloud-secrets/cloud-secrets-ipc.ts b/src/main/cloud-secrets/cloud-secrets-ipc.ts index 436b2c21250..502a3502990 100644 --- a/src/main/cloud-secrets/cloud-secrets-ipc.ts +++ b/src/main/cloud-secrets/cloud-secrets-ipc.ts @@ -20,7 +20,10 @@ import { cloudSecretSwapped, cloudSecretValueError } from '../../shared/cloud-secrets/cloud-secret-rules' -import { desktopKeyValueForCloud } from '../hosted-sandbox/cloud-desktop-keys' +import { + desktopKeyValueForCloud, + setCloudDesktopKeysUserDataPath +} from '../hosted-sandbox/cloud-desktop-keys' import { cloudSecretsFailureCode, createCloudSecretsClient, @@ -97,6 +100,7 @@ function sandboxIdFor(userDataPath: string, runtimeEnvironmentId: string): strin } export function registerCloudSecretsHandlers(userDataPath: string): void { + setCloudDesktopKeysUserDataPath(userDataPath) // Packaged integration builds read no shell env; their control-plane URL is baked in. const config = getHostedSandboxConfig( userDataPath, diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts index 956653b8bb2..39de8220bcd 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts @@ -5,7 +5,6 @@ const environments = new Map = {} const launchCalls: unknown[][] = [] -vi.mock('electron', () => ({ app: { getPath: () => '/u' } })) vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ listEphemeralVmRuntimes: () => runtimes })) @@ -88,7 +87,9 @@ describe('withHostAgentApiKeyEnv', () => { runtimes.push({ runtimeEnvironmentId: 'env-cloud', recipe: { provider: 'orca-cloud' } }) launchEnv = { GEMINI_API_KEY: 'AIzaSy-real' } const params = { agent: 'gemini', kind: 'explicit' } - const { withHostAgentApiKeyEnv } = await import('./cloud-desktop-keys') + const { setCloudDesktopKeysUserDataPath, withHostAgentApiKeyEnv } = + await import('./cloud-desktop-keys') + setCloudDesktopKeysUserDataPath('/u') const readStatus = vi.fn() expect( await withHostAgentApiKeyEnv('env-cloud', 'terminal.createAgentSession', params, readStatus) diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.ts b/src/main/hosted-sandbox/cloud-desktop-keys.ts index 30dcb1d8430..f036d072020 100644 --- a/src/main/hosted-sandbox/cloud-desktop-keys.ts +++ b/src/main/hosted-sandbox/cloud-desktop-keys.ts @@ -2,7 +2,6 @@ // host those keys ride each agent launch as plain env. An Orca Cloud VM must never hold a model key, // so they are not sent there at all: the user saves a key as a personal Cloud secret instead (one key // per click), and the VM then gets a placeholder the egress proxy swaps. -import { app } from 'electron' import { resolveAgentApiKeyLaunchEnv, withAgentApiKeyLaunchEnv @@ -15,6 +14,13 @@ import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runti import { getConnectionExecutionHostId, toRuntimeExecutionHostId } from '../../shared/execution-host' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +// Set once the desktop starts (registerCloudSecretsHandlers); this module stays free of Electron +// because launch assembly that the headless runtime also loads imports it. +let desktopUserDataPath: string | null = null +export function setCloudDesktopKeysUserDataPath(path: string): void { + desktopUserDataPath = path +} + /** Orca Cloud sandboxes answer on Vercel Sandbox routes. */ const ORCA_CLOUD_ENDPOINT_HOST = /\.vercel\.run$/i @@ -78,7 +84,11 @@ export async function withHostAgentApiKeyEnv( params: unknown, readStatus: Parameters[3] ): Promise { - if (isOrcaCloudRuntimeEnvironment(app.getPath('userData'), environmentId)) { + // Without the desktop's records nothing can be ruled out, so no keys go anywhere. + if ( + desktopUserDataPath === null || + isOrcaCloudRuntimeEnvironment(desktopUserDataPath, environmentId) + ) { return params } return withAgentApiKeyRuntimeEnv(environmentId, method, params, readStatus) From be26e2f8328d29ffdc99455b5ae6a5297ceaf26e Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:09:39 -0800 Subject: [PATCH 34/46] =?UTF-8?q?copy(w8):=20DS-04=20phone=20status=20read?= =?UTF-8?q?s=20"N=20sandbox=20hours=20so=20far.=20Uses=20sandbox=20hours?= =?UTF-8?q?=20while=20running."=20/=20"=E2=80=A6Uses=20no=20sandbox=20hour?= =?UTF-8?q?s=20while=20asleep."=20(no=20dollars)=20(#217)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mobile/src/cloud/CloudStatusCard.tsx | 8 ++++---- mobile/src/i18n/en-runtime-required.json | 8 ++++---- mobile/src/i18n/locales/en.json | 8 ++++---- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/mobile/src/cloud/CloudStatusCard.tsx b/mobile/src/cloud/CloudStatusCard.tsx index bcd3adbc34d..4917bd9db42 100644 --- a/mobile/src/cloud/CloudStatusCard.tsx +++ b/mobile/src/cloud/CloudStatusCard.tsx @@ -27,21 +27,21 @@ function spendLine( if (!awake) { return t( 'cloud.usage.asleep', - '{{hours}} sandbox hours so far · no sandbox hours while asleep', + '{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.', { count: value, hours: label, - defaultValue_one: '{{hours}} sandbox hour so far · no sandbox hours while asleep' + defaultValue_one: '{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.' } ) } return t( 'cloud.usage.running', - '{{hours}} sandbox hours so far · uses sandbox hours while running', + '{{hours}} sandbox hours so far. Uses sandbox hours while running.', { count: value, hours: label, - defaultValue_one: '{{hours}} sandbox hour so far · uses sandbox hours while running' + defaultValue_one: '{{hours}} sandbox hour so far. Uses sandbox hours while running.' } ) } diff --git a/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index f68d8368a8b..154fcb60230 100644 --- a/mobile/src/i18n/en-runtime-required.json +++ b/mobile/src/i18n/en-runtime-required.json @@ -150,10 +150,10 @@ } }, "usage": { - "asleep_one": "{{hours}} sandbox hour so far · no sandbox hours while asleep", - "asleep_other": "{{hours}} sandbox hours so far · no sandbox hours while asleep", - "running_one": "{{hours}} sandbox hour so far · uses sandbox hours while running", - "running_other": "{{hours}} sandbox hours so far · uses sandbox hours while running" + "asleep_one": "{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.", + "asleep_other": "{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.", + "running_one": "{{hours}} sandbox hour so far. Uses sandbox hours while running.", + "running_other": "{{hours}} sandbox hours so far. Uses sandbox hours while running." } }, "components": { diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 46a10e3f498..a9454bde967 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -5196,10 +5196,10 @@ } }, "usage": { - "asleep_one": "{{hours}} sandbox hour so far · no sandbox hours while asleep", - "asleep_other": "{{hours}} sandbox hours so far · no sandbox hours while asleep", - "running_one": "{{hours}} sandbox hour so far · uses sandbox hours while running", - "running_other": "{{hours}} sandbox hours so far · uses sandbox hours while running" + "asleep_one": "{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.", + "asleep_other": "{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.", + "running_one": "{{hours}} sandbox hour so far. Uses sandbox hours while running.", + "running_other": "{{hours}} sandbox hours so far. Uses sandbox hours while running." } } } From 86ccf4eb29f46d47c7f4dec368d1e45227b8ab01 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:10:34 -0800 Subject: [PATCH 35/46] fix(cloud): read snapshot lists chats from orcad's session store (the local socket can't stream subscribeStatus) Live on dev the first capture sealed zero sessions: agentSession.subscribeStatus needs a streaming transport and the unix socket refuses it, and worktree.ps lists only agents live right now. The collector now reads orcad's own session records (agent-session-journal.db, read-only): provider, name and last turn, open tabs first; live worktree.ps rows override status; history still comes from agentSession.history, with the stored last turn as fallback. --- .../image/vm-scripts.generated.ts | 2 +- .../image/vm/orca-read-snapshot.cjs | 107 ++++++++++++++++-- .../test/read-snapshots.test.ts | 45 ++++++-- 3 files changed, 130 insertions(+), 24 deletions(-) diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 94149c6455d..043863d2a95 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -3,7 +3,7 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0","opencode-ai@1.19.5","@google/gemini-cli@0.67.0","@github/copilot@1.0.108"],"cursorAgent":{"version":"2026.11.05-86047df","sha256":"170b77786cbf4c93064d64fff12b71a178b968730561c64afc2e8e752535442e"},"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" -export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline }) {\n const timeLeft = () => deadline - Date.now()\n const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })])\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : []\n // Newest activity first; chats with nothing in them still list (agent + status).\n const picked = summaries\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n const { messages, hasOlder } = messagesOf(history)\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: str(s.agent, 40),\n title: str(s.conversationName, 200) || str(s.latestPrompt, 200),\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: str(s.turnOutcome, 40),\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline }))\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at)\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of listSessions()) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs index b12c08577e5..a039671a4e9 100644 --- a/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs +++ b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs @@ -201,11 +201,76 @@ function prOf(linked) { } const STATUSES = new Set(['working', 'attention', 'idle']) +const PANE_PREFIX = 'structured-agent-session-' + +/** + * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name + * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and + * worktree.ps lists only agents that are live right now, so this is the complete list. + */ +function storedSessions(dataDir) { + let db + try { + const { DatabaseSync } = require('node:sqlite') + db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true }) + const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id)) + const out = [] + for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) { + let record + try { + record = JSON.parse(row.record_json) + } catch { + continue + } + const last = isObj(record.lastTurn) ? record.lastTurn : {} + out.push({ + sessionId: row.session_id, + agent: str(record.provider, 40), + title: str(record.conversationName, 200) || str(last.prompt, 200), + status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown', + turnOutcome: str(last.outcome, 40), + updatedAt: num(record.updatedAt), + open: open.has(row.session_id), + lastPrompt: str(last.prompt, LIMITS.messageChars), + lastReply: str(last.reply, LIMITS.messageChars), + lastAt: num(last.at) + }) + } + return out + } catch { + return [] + } finally { + try { + db && db.close() + } catch {} + } +} + +/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */ +function liveAgents(worktrees) { + const out = new Map() + for (const w of worktrees) { + for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) { + const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : '' + if (!tab.startsWith(PANE_PREFIX)) { + continue + } + const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state + out.set(tab.slice(PANE_PREFIX.length), { + agent: str(a.agentType, 40), + title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200), + status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle', + updatedAt: num(a.updatedAt) + }) + } + } + return out +} /** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */ -async function gather(call, { workspaceId, snapshotId, reason, now, deadline }) { +async function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) { const timeLeft = () => deadline - Date.now() - const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })]) + const ps = await call('worktree.ps', { limit: 20 }) const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : [] const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}` @@ -213,22 +278,38 @@ async function gather(call, { workspaceId, snapshotId, reason, now, deadline }) call('git.status', { worktree: selector, includeLineStats: true }), call('git.history', { worktree: selector, limit: LIMITS.commits }) ]) - const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : [] - // Newest activity first; chats with nothing in them still list (agent + status). - const picked = summaries + const live = liveAgents(worktrees) + const byId = new Map() + for (const s of listSessions()) { + byId.set(s.sessionId, s) + } + for (const [sessionId, a] of live) { + byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) }) + } + // Open chats first, then newest activity. + const picked = [...byId.values()] .filter((s) => typeof s.sessionId === 'string') - .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0)) + .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0)) .slice(0, LIMITS.sessions) const sessions = [] for (const s of picked) { const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null - const { messages, hasOlder } = messagesOf(history) + let { messages, hasOlder } = messagesOf(history) + if (messages.length === 0) { + // No readable history (or out of time): the stored last turn still says what happened. + const at = s.lastAt || s.updatedAt || 0 + messages = [ + ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []), + ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : []) + ] + hasOlder = hasOlder || messages.length > 0 + } sessions.push({ sessionId: s.sessionId.slice(0, 200), - agent: str(s.agent, 40), - title: str(s.conversationName, 200) || str(s.latestPrompt, 200), + agent: s.agent || null, + title: s.title || null, status: STATUSES.has(s.status) ? s.status : 'unknown', - turnOutcome: str(s.turnOutcome, 40), + turnOutcome: s.turnOutcome || null, updatedAt: num(s.updatedAt), messages: messages.slice(-LIMITS.messagesPerSession), truncated: hasOlder || messages.length > LIMITS.messagesPerSession @@ -308,14 +389,16 @@ async function main() { } const deadline = started + TOTAL_BUDGET_MS const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now()))) - const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline })) + const payload = fitToBudget( + await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) }) + ) const out = seal(payload, recipients, workspaceId, snapshotId) // Timing only: counts and sizes would describe the plaintext to the control plane's logs. out.stats = { collectMs: Date.now() - started } process.stdout.write(`${JSON.stringify(out)}\n`) } -module.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc } +module.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents } if (require.main === module) { // A fixed message: an error text could carry workspace content into the control plane's logs. diff --git a/cloud/apps/sandbox-control/test/read-snapshots.test.ts b/cloud/apps/sandbox-control/test/read-snapshots.test.ts index a5887f9d5a6..81eaff2e970 100644 --- a/cloud/apps/sandbox-control/test/read-snapshots.test.ts +++ b/cloud/apps/sandbox-control/test/read-snapshots.test.ts @@ -1,4 +1,8 @@ +import { mkdtempSync } from 'node:fs' import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' import { SignJWT, exportJWK, generateKeyPair } from 'jose' import { describe, expect, it, vi } from 'vitest' import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from '../../../../src/main/cloud-workspaces/sealed-grant-node' @@ -13,25 +17,20 @@ const vm = require('../image/vm/orca-read-snapshot.cjs') as { seal: (payload: unknown, recipients: unknown[], workspaceId: string, snapshotId: string) => Record gather: (call: (method: string, params: unknown) => Promise, opts: Record) => Promise> fitToBudget: (payload: T, maxBytes?: number) => T + storedSessions: (dataDir: string) => Record[] } const SECRET_LINE = 'the deploy key is in 1password, not in the repo' -function fakeOrcad(method: string): unknown { +function fakeOrcad(method: string, params?: unknown): unknown { switch (method) { - case 'agentSession.subscribeStatus': - return { - type: 'snapshot', - sessions: [ - { sessionId: 'chat-1', agent: 'claude', status: 'idle', conversationName: 'Fix login', turnOutcome: 'completed', updatedAt: 2 }, - { sessionId: 'chat-2', agent: 'codex', status: 'working', conversationName: 'Add tests', updatedAt: 1 } - ] - } case 'worktree.ps': return { worktrees: [ { path: '/vercel/sandbox/project', + // Live right now: its status wins over the stored one. + agents: [{ paneKey: 'structured-agent-session-chat-2:leaf-1', agentType: 'codex', state: 'working', conversationName: 'Add tests', updatedAt: 1 }], linkedPR: { number: 42, title: 'Fix login', state: 'open', url: 'https://github.com/acme/app/pull/42', checksStatus: 'success', checksSummary: '3/3 passed' } } ] @@ -41,6 +40,10 @@ function fakeOrcad(method: string): unknown { case 'git.history': return { items: [{ id: 'abc1234', subject: 'Fix the login redirect', author: 'Alice', timestamp: 1 }] } case 'agentSession.history': + // chat-2 has no readable history yet: its stored last turn stands in. + if ((params as { sessionId?: string })?.sessionId === 'chat-2') { + return null + } return { page: { hasOlder: false, @@ -60,12 +63,17 @@ function fakeOrcad(method: string): unknown { async function runVmSealer(params: RunCommandParams): Promise { const env = params.env ?? {} const payload = vm.fitToBudget( - await vm.gather(async (method) => fakeOrcad(method), { + await vm.gather(async (method, params) => fakeOrcad(method, params), { workspaceId: env.ORCA_READ_WORKSPACE_ID, snapshotId: env.ORCA_READ_SNAPSHOT_ID, reason: env.ORCA_READ_REASON, now: 1_800_000_000_000, - deadline: Date.now() + 10_000 + deadline: Date.now() + 10_000, + // What orcad's session store holds (agent-session-journal.db on the VM). + listSessions: () => [ + { sessionId: 'chat-1', agent: 'claude', title: 'Fix login', status: 'idle', turnOutcome: 'success', updatedAt: 2, open: true }, + { sessionId: 'chat-2', agent: 'codex', title: 'Add tests', status: 'idle', updatedAt: 1, open: true, lastPrompt: 'Add tests', lastReply: null, lastAt: 1 } + ] }) ) const out = vm.seal(payload, JSON.parse(env.ORCA_READ_RECIPIENTS ?? '[]'), env.ORCA_READ_WORKSPACE_ID!, env.ORCA_READ_SNAPSHOT_ID!) @@ -297,4 +305,19 @@ describe('read snapshots of sleeping workspaces (E2EE)', () => { const out = vm.seal({ v: 1 }, [{ keyId: 'rk_bad', publicKeyB64: 'x' }, { keyId: 'rk_000000000000000000000000', publicKeyB64: generateGrantRecipientKey().publicKeyB64 }], 'sbx_0', 'rsn_0') as { recipients: unknown[] } expect(out.recipients).toHaveLength(1) }) + + it('lists chats from orcad’s session store (read-only), open tabs and last turns included', () => { + const dir = mkdtempSync(join(tmpdir(), 'orcad-')) + const db = new DatabaseSync(join(dir, 'agent-session-journal.db')) + db.exec('CREATE TABLE agent_session_records (session_id TEXT PRIMARY KEY, record_json TEXT NOT NULL); CREATE TABLE agent_session_tabs (tab_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, position INTEGER NOT NULL)') + const record = { provider: 'claude', conversationName: 'Gap5 live check', updatedAt: 5, lastTurn: { state: 'settled', outcome: 'success', prompt: 'What is this repo?', reply: 'Hello World!', at: 4 } } + db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run('claude_1', JSON.stringify(record)) + db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run('broken', '{not json') + db.prepare('INSERT INTO agent_session_tabs VALUES (?, ?, 0)').run('structured-agent-session-claude_1', 'claude_1') + db.close() + expect(vm.storedSessions(dir)).toEqual([ + expect.objectContaining({ sessionId: 'claude_1', agent: 'claude', title: 'Gap5 live check', status: 'idle', turnOutcome: 'success', open: true, lastPrompt: 'What is this repo?', lastReply: 'Hello World!' }) + ]) + expect(vm.storedSessions(join(dir, 'missing'))).toEqual([]) + }) }) From 233ddf8111dee89a34a207b337d7d369e4493041 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:12:32 -0800 Subject: [PATCH 36/46] fix(ports): never pin every workspace on a host to the host's ORCA_PORT #216 let a launcher-set ORCA_PORT (the VM launcher sets 3000) override the per-workspace block, so two worktrees on one cloud VM would both get 3000. Each workspace always gets its own registry block again; a regression test covers a host env with ORCA_PORT=3000. --- docs/site/content/docs/model/orca-yaml.mdx | 2 +- src/main/ipc/pty/spawn-pane-env-ports.test.ts | 35 +++++++++++++++++++ src/main/ipc/pty/spawn-pane-env.ts | 6 ++-- .../workspace-hooks/setup-hook-env-vars.ts | 4 +-- .../workspace-port-block-registry.test.ts | 21 +---------- src/shared/workspace-port-block.ts | 20 ----------- 6 files changed, 42 insertions(+), 46 deletions(-) create mode 100644 src/main/ipc/pty/spawn-pane-env-ports.test.ts diff --git a/docs/site/content/docs/model/orca-yaml.mdx b/docs/site/content/docs/model/orca-yaml.mdx index fac76241fc4..49bf4c2ca5a 100644 --- a/docs/site/content/docs/model/orca-yaml.mdx +++ b/docs/site/content/docs/model/orca-yaml.mdx @@ -133,7 +133,7 @@ scripts: - `autoRunAfterSetup` starts the action once the Setup terminal's script succeeds. - Shared `orca.yaml` actions go through the same approval prompt as setup scripts. Actions imported into local settings are treated as your own. -Every terminal in a worktree gets a stable block of 10 ports: `ORCA_PORT` through `ORCA_PORT+9` (`ORCA_PORT_COUNT` is `10`). Two worktrees on the same host never share a block, so the same dev server can run in each without port collisions. `CONDUCTOR_PORT` is set to the same value, so imported Conductor scripts work unchanged. A host that runs a single workspace can pin the block by starting Orca with `ORCA_PORT` (and optionally `ORCA_PORT_COUNT`) set. Ports a run opens appear in the Run menu and the **Ports** panel. +Every terminal in a worktree gets a stable block of 10 ports: `ORCA_PORT` through `ORCA_PORT+9` (`ORCA_PORT_COUNT` is `10`). Two worktrees on the same host never share a block, so the same dev server can run in each without port collisions. `CONDUCTOR_PORT` is set to the same value, so imported Conductor scripts work unchanged. Ports a run opens appear in the Run menu and the **Ports** panel. ### Terminal defaults and issue commands diff --git a/src/main/ipc/pty/spawn-pane-env-ports.test.ts b/src/main/ipc/pty/spawn-pane-env-ports.test.ts new file mode 100644 index 00000000000..16225d1e7c6 --- /dev/null +++ b/src/main/ipc/pty/spawn-pane-env-ports.test.ts @@ -0,0 +1,35 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../workspace-ports/workspace-port-block-registry', () => ({ + getWorkspacePortBlockForWorktreeId: async (worktreeId: string) => + worktreeId.endsWith('/a') ? { base: 21000, count: 10 } : { base: 21010, count: 10 } +})) + +const { stampWorkspacePortEnv, stampPtySpawnPaneEnv } = await import('./spawn-pane-env') + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('workspace port env', () => { + it('gives each workspace its own block even when the host process has ORCA_PORT (VM launcher)', async () => { + vi.stubEnv('ORCA_PORT', '3000') + const a: Record = { ORCA_PORT: '3000', CONDUCTOR_PORT: '3000' } + const b: Record = { ORCA_PORT: '3000', CONDUCTOR_PORT: '3000' } + await stampWorkspacePortEnv(a, 'repo::/w/a') + await stampWorkspacePortEnv(b, 'repo::/w/b') + expect(a).toEqual({ ORCA_PORT: '21000', ORCA_PORT_COUNT: '10', CONDUCTOR_PORT: '21000' }) + expect(b).toEqual({ ORCA_PORT: '21010', ORCA_PORT_COUNT: '10', CONDUCTOR_PORT: '21010' }) + }) + + it('scrubs an inherited block from a spawn that names no pane', () => { + const env: Record = { + ORCA_PORT: '3000', + ORCA_PORT_COUNT: '10', + CONDUCTOR_PORT: '3000' + } + stampPtySpawnPaneEnv(env, { pane: null, jcodeRuntimeDir: undefined }) + expect(env.ORCA_PORT).toBeUndefined() + expect(env.CONDUCTOR_PORT).toBeUndefined() + }) +}) diff --git a/src/main/ipc/pty/spawn-pane-env.ts b/src/main/ipc/pty/spawn-pane-env.ts index 6e435d5707e..93b3896fda2 100644 --- a/src/main/ipc/pty/spawn-pane-env.ts +++ b/src/main/ipc/pty/spawn-pane-env.ts @@ -8,7 +8,6 @@ import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/ import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-tab-id' import { buildWorkspacePortEnv, - hostPinnedPortBlock, WORKSPACE_PORT_ENV_KEYS } from '../../../shared/workspace-port-block' import { getWorkspacePortBlockForWorktreeId } from '../../workspace-ports/workspace-port-block-registry' @@ -96,8 +95,9 @@ export async function stampWorkspacePortEnv( return } try { - const block = - hostPinnedPortBlock(process.env) ?? (await getWorkspacePortBlockForWorktreeId(worktreeId)) + // Always the workspace's own block: a host env's ORCA_PORT (a VM launcher sets one) would make + // every workspace on that host share it. + const block = await getWorkspacePortBlockForWorktreeId(worktreeId) if (block) { Object.assign(env, buildWorkspacePortEnv(block)) } diff --git a/src/main/workspace-hooks/setup-hook-env-vars.ts b/src/main/workspace-hooks/setup-hook-env-vars.ts index 1b6d7762ec7..94590520ad0 100644 --- a/src/main/workspace-hooks/setup-hook-env-vars.ts +++ b/src/main/workspace-hooks/setup-hook-env-vars.ts @@ -1,7 +1,7 @@ import { getRuntimePathBasename } from '../../shared/cross-platform-path' import { TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV } from '../../shared/shell/launch/terminal-git-credential-guard' import type { Repo } from '../../shared/repo-types' -import { buildWorkspacePortEnv, hostPinnedPortBlock } from '../../shared/workspace-port-block' +import { buildWorkspacePortEnv } from '../../shared/workspace-port-block' import { peekWorkspacePortBlock } from '../workspace-ports/workspace-port-block-registry' // Path-valued keys only, so WSL and posix-shell launches translate them; names are not paths. @@ -33,7 +33,7 @@ export function getSetupEnvVars( function getWorkspacePortEnv(worktreePath: string): Record { try { // Setup terminals get the block from their own spawn; this covers hook processes run directly. - const block = hostPinnedPortBlock(process.env) ?? peekWorkspacePortBlock(worktreePath) + const block = peekWorkspacePortBlock(worktreePath) return block ? buildWorkspacePortEnv(block) : {} } catch { return {} diff --git a/src/main/workspace-ports/workspace-port-block-registry.test.ts b/src/main/workspace-ports/workspace-port-block-registry.test.ts index c422fe296c4..973187f1601 100644 --- a/src/main/workspace-ports/workspace-port-block-registry.test.ts +++ b/src/main/workspace-ports/workspace-port-block-registry.test.ts @@ -6,8 +6,7 @@ import { WORKSPACE_PORT_BLOCK_SIZE, WORKSPACE_PORT_RANGE_END, WORKSPACE_PORT_RANGE_START, - buildWorkspacePortEnv, - hostPinnedPortBlock + buildWorkspacePortEnv } from '../../shared/workspace-port-block' import { WorkspacePortBlockRegistry } from './workspace-port-block-registry' @@ -125,21 +124,3 @@ describe('peekBlock', () => { expect(new Set(blocks.map((block) => block.base)).size).toBe(20) }) }) - -describe('hostPinnedPortBlock', () => { - it('honors a launcher-pinned ORCA_PORT on a one-workspace host', () => { - expect(hostPinnedPortBlock({ ORCA_PORT: '3000' })).toEqual({ base: 3000, count: 10 }) - expect(hostPinnedPortBlock({ ORCA_PORT: '3000', ORCA_PORT_COUNT: '5' })).toEqual({ - base: 3000, - count: 5 - }) - }) - - it('ignores a block inherited from a parent Orca pane, and bad values', () => { - expect(hostPinnedPortBlock({ ORCA_PORT: '28570', ORCA_WORKTREE_ID: 'r::/w' })).toBeNull() - expect(hostPinnedPortBlock({ ORCA_PORT: '28570', ORCA_PANE_KEY: 't:l' })).toBeNull() - expect(hostPinnedPortBlock({ ORCA_PORT: 'abc' })).toBeNull() - expect(hostPinnedPortBlock({ ORCA_PORT: '80' })).toBeNull() - expect(hostPinnedPortBlock({})).toBeNull() - }) -}) diff --git a/src/shared/workspace-port-block.ts b/src/shared/workspace-port-block.ts index 26a6a4be34e..761370ec365 100644 --- a/src/shared/workspace-port-block.ts +++ b/src/shared/workspace-port-block.ts @@ -24,23 +24,3 @@ export function buildWorkspacePortEnv(block: WorkspacePortBlock): Record= block.base && port < block.base + block.count } - -/** - * A host that runs exactly one workspace (a VM launcher, say) may pin the block by starting Orca - * with ORCA_PORT set. A copy inherited from a parent Orca pane (it also carries pane identity) - * names that pane's workspace and doesn't count. - */ -export function hostPinnedPortBlock(env: NodeJS.ProcessEnv): WorkspacePortBlock | null { - if (env.ORCA_PANE_KEY || env.ORCA_WORKTREE_ID) { - return null - } - const base = Number(env.ORCA_PORT) - if (!Number.isInteger(base) || base < 1024 || base > 65535 - WORKSPACE_PORT_BLOCK_SIZE) { - return null - } - const count = Number(env.ORCA_PORT_COUNT) - return { - base, - count: Number.isInteger(count) && count > 0 && count <= 100 ? count : WORKSPACE_PORT_BLOCK_SIZE - } -} From 97764fe30559bbf6a084b98c7dd246deb53893ae Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:13:14 -0800 Subject: [PATCH 37/46] fix(cloud): DS-35 sign-in copy, one unauthorized sentence, team busy row and chip contrast - Orca account pane: signed-out and reconnect-required lines name Orca Cloud. - Every unauthorized failure (lifecycle toast, cloud workspace errors, share links, cloud secrets) now says "Sign in to Orca again to continue." with a "Sign in" action. - Team page busy row keeps full contrast: spinner + aria-busy, no opacity dimming. - destructive-chip text uses a new --destructive-text token (light: 85% mix with foreground) so it clears AA on its tint. - TeamDialogHost quietRefresh depends on the stable refresh callbacks. --- src/renderer/src/assets/main.css | 4 + .../src/assets/theme-token-contrast.test.ts | 24 ++++++ .../billing/team/TeamDialogHost.tsx | 9 ++- .../billing/team/TeamMemberList.test.tsx | 46 +++++++++++ .../billing/team/TeamMemberList.tsx | 7 +- .../CloudWorkspacesStates.tsx | 5 +- .../cloud-workspace-errors.ts | 14 ++-- .../orca-cloud/cloud-workspace-actions.ts | 10 ++- .../cloud-share/share-link-status.ts | 6 +- .../cloud-share/share-port-dialog.tsx | 3 +- .../cloud-share/shared-links-list.tsx | 3 +- .../cloud-share/use-share-port-action.tsx | 9 +-- .../orca/OrcaAccountSettingsPane.fixture.tsx | 33 ++++++++ .../accounts/orca/OrcaAccountSettingsPane.tsx | 4 +- .../cloud-secrets/CloudSecretList.tsx | 13 +++- .../cloud-secrets/cloud-secrets-copy.ts | 3 +- .../src/components/ui/button.fixture.tsx | 12 ++- src/renderer/src/components/ui/button.tsx | 2 +- .../src/i18n/en-runtime-required.json | 12 +-- src/renderer/src/i18n/locales/en.json | 15 ++-- .../orca-cloud/orca-sign-in-again-action.ts | 10 +++ .../lib/orca-cloud/orca-sign-in-again.test.ts | 76 +++++++++++++++++++ .../src/lib/orca-cloud/orca-sign-in-again.ts | 12 +++ 23 files changed, 272 insertions(+), 60 deletions(-) create mode 100644 src/renderer/src/components/billing/team/TeamMemberList.test.tsx create mode 100644 src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx create mode 100644 src/renderer/src/lib/orca-cloud/orca-sign-in-again-action.ts create mode 100644 src/renderer/src/lib/orca-cloud/orca-sign-in-again.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/orca-sign-in-again.ts diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 782d1d11619..7b625d60f2d 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -92,6 +92,7 @@ --color-accent-foreground: var(--accent-foreground); --color-destructive: var(--destructive); --color-destructive-foreground: var(--destructive-foreground); + --color-destructive-text: var(--destructive-text); --color-border: var(--border); --color-input: var(--input); --color-ring: var(--ring); @@ -452,6 +453,8 @@ color-scheme: light; --destructive: #e40014; --destructive-foreground: #fff; + /* Why: raw red on its own 10% tint is ~4.1:1; small red text on a tint needs the darker mix. */ + --destructive-text: color-mix(in srgb, var(--destructive) 85%, var(--foreground)); --status-success: #147638; --status-success-background: color-mix(in srgb, var(--status-success) 10%, transparent); --status-success-border: color-mix(in srgb, var(--status-success) 25%, transparent); @@ -490,6 +493,7 @@ --destructive: #ff6568; /* Dark --destructive is a light red, so its label needs dark ink to clear AA. */ --destructive-foreground: #450a0a; + --destructive-text: var(--destructive); --status-success: #86efac; --status-success-background: color-mix(in srgb, var(--status-success) 10%, transparent); --status-success-border: color-mix(in srgb, var(--status-success) 25%, transparent); diff --git a/src/renderer/src/assets/theme-token-contrast.test.ts b/src/renderer/src/assets/theme-token-contrast.test.ts index 71538f350dc..3336b9e6c4b 100644 --- a/src/renderer/src/assets/theme-token-contrast.test.ts +++ b/src/renderer/src/assets/theme-token-contrast.test.ts @@ -63,3 +63,27 @@ describe.each([':root', '.dark'] as const)('built-in %s token pairs', (selector) expect(contrastRatio(token('--status-success'), surface)).toBeGreaterThanOrEqual(4.5) }) }) + +const destructiveTextMix = Number( + css.match( + /--destructive-text: color-mix\(in srgb, var\(--destructive\) (\d+)%, var\(--foreground\)\)/ + )?.[1] +) + +// The destructive chip paints its text on bg-destructive/10 (and /15 on hover) over the page. +describe.each([0.1, 0.15])('destructive chip text on a %s tint', (amount) => { + it('meets WCAG AA in the light theme', () => { + const light = themeTokens(':root') + const destructive = light.get('--destructive')! + const text = tint(destructive, destructiveTextMix / 100, light.get('--foreground')!) + const surface = tint(destructive, amount, light.get('--background')!) + expect(contrastRatio(text, surface)).toBeGreaterThanOrEqual(4.5) + }) + + it('meets WCAG AA in the dark theme', () => { + const dark = themeTokens('.dark') + const destructive = dark.get('--destructive')! + const surface = tint(destructive, amount, dark.get('--background')!) + expect(contrastRatio(destructive, surface)).toBeGreaterThanOrEqual(4.5) + }) +}) diff --git a/src/renderer/src/components/billing/team/TeamDialogHost.tsx b/src/renderer/src/components/billing/team/TeamDialogHost.tsx index dbce53b536d..d074ed1f666 100644 --- a/src/renderer/src/components/billing/team/TeamDialogHost.tsx +++ b/src/renderer/src/components/billing/team/TeamDialogHost.tsx @@ -35,10 +35,13 @@ function TeamPageBody({ arrival }: { arrival: ReturnType(null) const [now] = useState(() => Date.now()) + const refreshRoster = roster.refresh + const refreshBilling = billing.refresh + // Both refreshes are stable callbacks; depending on the hook results would rebuild this each render. const quietRefresh = useCallback(() => { - roster.refresh() - billing.refresh() - }, [roster, billing]) + refreshRoster() + refreshBilling() + }, [refreshRoster, refreshBilling]) const actions = useTeamActions({ orgId: orgId ?? '', onChanged: quietRefresh }) const rosterResult = diff --git a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx new file mode 100644 index 00000000000..57411710e07 --- /dev/null +++ b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx @@ -0,0 +1,46 @@ +// @vitest-environment happy-dom +import { cleanup, render } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles' +import { TeamMemberList } from './TeamMemberList' +import { teamRows } from './team-roster-rows' + +afterEach(cleanup) + +const roster: OrcaOrgMembersRoster = { + viewerRole: 'owner', + canManageMembers: true, + members: [ + { userId: 'u-neil', email: 'neil@acme.dev', displayName: 'Neil Parker', role: 'owner' }, + { userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', role: 'member' } + ], + pendingInvites: [] +} + +const noop = (): void => {} + +it('marks a busy row with aria-busy and a spinner, without dimming it', () => { + const { container } = render( + + ) + const busy = container.querySelector('[data-team-row="member:u-grace"]')! + const idle = container.querySelector('[data-team-row="member:u-neil"]')! + expect(busy.getAttribute('aria-busy')).toBe('true') + expect(idle.hasAttribute('aria-busy')).toBe(false) + // Dimming dropped the email under AA; the row keeps full opacity. + expect(busy.className).not.toMatch(/opacity-/) + expect(busy.querySelector('.animate-spin')).not.toBeNull() + expect(idle.querySelector('.animate-spin')).toBeNull() +}) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index 4670e261dfa..b731209e6aa 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -18,7 +18,6 @@ import { } from '@/components/ui/select' import { LoadingSpinner } from '@/components/LoadingSpinner' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles' import { PersonAvatar } from './TeamAvatar' import { invitedAsCopy, memberStatusLabel, roleDescription } from './team-copy' @@ -226,10 +225,8 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element { key={row.key} data-team-row={row.key} aria-busy={state.busy || undefined} - className={cn( - 'group/row flex min-h-12 flex-col justify-center bg-card px-3 py-2 transition-colors animate-in fade-in-0 duration-200 motion-reduce:animate-none', - state.busy && 'opacity-70' - )} + // Busy rows keep full contrast; the spinner and aria-busy say a change is pending. + className="group/row flex min-h-12 flex-col justify-center bg-card px-3 py-2 transition-colors animate-in fade-in-0 duration-200 motion-reduce:animate-none" >
    diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx index 6b03dee082e..1207e9efff1 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx @@ -12,6 +12,7 @@ import { InlineError } from '@/components/ui/inline-error' import { Input } from '@/components/ui/input' import { Skeleton } from '@/components/ui/skeleton' import { useTranslate } from '@/i18n/use-translate' +import { signInAgainActionLabel } from '@/lib/orca-cloud/orca-sign-in-again' import { describeInlineError } from './cloud-workspace-errors' /** The list failed to load. An expired session offers Sign in; anything else offers Retry. */ @@ -35,9 +36,7 @@ export function ErrorState({ className="m-1" title={describeInlineError(error, reason, t)} retryLabel={ - signIn - ? t('auto.components.cloudWorkspaces.signIn', 'Sign in') - : t('auto.components.cloudWorkspaces.retry', 'Retry') + signIn ? signInAgainActionLabel(t) : t('auto.components.cloudWorkspaces.retry', 'Retry') } retrying={retrying} onRetry={signIn ? onSignIn : onRetry} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts index 71e03df197d..ae25f9ac3d3 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-errors.ts @@ -1,6 +1,7 @@ // Copy for control-plane error codes from the team workspace registry. import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' +import { signInAgainMessage } from '@/lib/orca-cloud/orca-sign-in-again' import { getLastBillingStatus } from '@/components/billing/billing-summary-store' import { sandboxLimitFromBilling } from '@/components/worktree-creation/vm-build-failure-copy' import { classifyEntitlementDenial } from '../../../../shared/orca-billing' @@ -70,10 +71,7 @@ export function describeError( ) } if (error === 'unauthorized') { - return t( - 'auto.components.cloudWorkspaces.errorUnauthorized', - 'Your Orca Cloud session expired. Sign in again.' - ) + return signInAgainMessage(t) } return t( 'auto.components.cloudWorkspaces.errorUnknown', @@ -83,7 +81,8 @@ export function describeError( /** * The same messages for an inline error that already carries the action button (Retry or Sign - * in), so the body does not repeat "Try again." or "Sign in again.". + * in), so the body does not repeat "Try again.". An expired session keeps the one shared + * sign-in sentence so every surface says the same thing. */ export function describeInlineError( error: string, @@ -91,10 +90,7 @@ export function describeInlineError( t: Translate = translate ): string { if (error === 'unauthorized') { - return t( - 'auto.components.cloudWorkspaces.errorUnauthorizedInline', - 'Your Orca Cloud session expired.' - ) + return signInAgainMessage(t) } if (error === 'timeout' || error === 'unavailable' || error === 'provider_unavailable') { return t( diff --git a/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts b/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts index 9a8f783550f..64985a247c6 100644 --- a/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts +++ b/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts @@ -6,6 +6,8 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { runSleepWorktree } from '@/components/sidebar/workspace-actions/sleep/sleep-worktree-flow' import { openPlansPage } from '@/components/billing/plans/plans-page-store' +import { signInAgainMessage } from '@/lib/orca-cloud/orca-sign-in-again' +import { signInAgainToastAction } from '@/lib/orca-cloud/orca-sign-in-again-action' import type { ConfirmationDialogContextValue } from '@/components/confirmation-dialog-context' import { activateWorktreeFromSidebar } from '@/lib/workspace/activation/sidebar-worktree-activation' import { @@ -37,6 +39,10 @@ function failureToast(title: string, result: CloudWorkspaceResult): void { }) return } + if (result.code === 'unauthorized') { + toast.error(title, { description: signInAgainMessage(), action: signInAgainToastAction() }) + return + } toast.error(title, { description: result.code === 'unavailable' @@ -44,9 +50,7 @@ function failureToast(title: string, result: CloudWorkspaceResult): void { 'orcaCloudWorkspace.error.unavailable', 'Orca Cloud isn’t reachable right now. Try again in a moment.' ) - : result.code === 'unauthorized' - ? translate('orcaCloudWorkspace.error.signIn', 'Sign in to Orca again, then try again.') - : translate('orcaCloudWorkspace.error.generic', 'Something went wrong. Try again.') + : translate('orcaCloudWorkspace.error.generic', 'Something went wrong. Try again.') }) } diff --git a/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts b/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts index e7ba5f2fb51..fe319e47751 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts +++ b/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import { getIntlLocale, translate } from '@/i18n/i18n' import { formatUiNarrowDuration, formatUiNarrowRelativeTime } from '@/i18n/relative-time-format' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { signInAgainMessage } from '@/lib/orca-cloud/orca-sign-in-again' import type { CloudShareFailureCode } from '../../../../../shared/hosted-sandbox/hosted-sandbox-share-wire' export function shareErrorMessage(code: CloudShareFailureCode): string { @@ -17,10 +18,7 @@ export function shareErrorMessage(code: CloudShareFailureCode): string { 'That link is no longer active.' ) case 'unauthorized': - return translate( - 'auto.components.right.sidebar.CloudShare.errorUnauthorized', - 'Sign in to Orca again, then try again.' - ) + return signInAgainMessage() case 'invalid_request': return translate( 'auto.components.right.sidebar.CloudShare.errorInvalid', diff --git a/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx b/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx index 0a7a38a8aa5..236c99d7598 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx @@ -11,6 +11,7 @@ import { } from '@/components/ui/dialog' import { InlineError } from '@/components/ui/inline-error' import { OrcaSignInButton } from '@/components/OrcaSignInProgress' +import { signInAgainActionLabel } from '@/lib/orca-cloud/orca-sign-in-again' import { SettingsSegmentedControl } from '@/components/settings/form-controls/SettingsSegmentedControl' import { Switch } from '@/components/ui/switch' import { useTranslate } from '@/i18n/use-translate' @@ -297,7 +298,7 @@ export function SharePortDialog({ )} {error?.signedOut && ( - {t('auto.components.right.sidebar.CloudShare.signIn', 'Sign in to Orca')} + {signInAgainActionLabel(t)} )} {alreadyShared.length > 0 && ( diff --git a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx index 611b9193640..8b8a7c78055 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx @@ -4,6 +4,7 @@ import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' import { OrcaSignInButton } from '@/components/OrcaSignInProgress' +import { signInAgainActionLabel } from '@/lib/orca-cloud/orca-sign-in-again' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import type { ShareLink } from '../../../../../shared/hosted-sandbox/hosted-sandbox-share-wire' @@ -151,7 +152,7 @@ export function SharedLinksList({ {status === 'error' && needsSignIn && (
    - {t('auto.components.right.sidebar.CloudShare.signIn', 'Sign in to Orca')} + {signInAgainActionLabel(t)}
    )} diff --git a/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx b/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx index b9b94722911..75b76ac39f4 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx @@ -11,13 +11,13 @@ import { useCloudShares, type CloudSharesController } from '@/lib/cloud-shares/cloud-shares-store' -import { useAppStore } from '@/store' import { SHARE_RESERVED_PORTS, type CloudShareFailureCode, type ShareLink } from '../../../../../shared/hosted-sandbox/hosted-sandbox-share-wire' import { shareErrorMessage } from './share-link-status' +import { signInAgainToastAction } from '@/lib/orca-cloud/orca-sign-in-again-action' import { SharePortDialog } from './share-port-dialog' const MENU_ITEM_CLASS = @@ -30,12 +30,7 @@ function signInAction(code: CloudShareFailureCode): { if (code !== 'unauthorized') { return {} } - return { - action: { - label: translate('auto.components.right.sidebar.CloudShare.signIn', 'Sign in to Orca'), - onClick: () => void useAppStore.getState().connectCurrentOrcaProfile() - } - } + return { action: signInAgainToastAction() } } export type SharePortAction = { diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx new file mode 100644 index 00000000000..3c5a6bc38fe --- /dev/null +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx @@ -0,0 +1,33 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import type { OrcaProfileAuthStatus } from '../../../../../../shared/orca-profiles' +import { OrcaAccountSettingsPane } from './OrcaAccountSettingsPane' + +const width = 760 + +function pane(status: OrcaProfileAuthStatus) { + return defineFixture({ + width, + store: { orcaProfileAuthStatus: status }, + // The pane re-reads auth status on mount; answer with the same state so the frame holds it. + setup: () => { + Object.assign(window.api.orcaProfiles, { authStatus: () => Promise.resolve(status) }) + }, + render: () => + }) +} + +/** Signed out: the status line names Orca Cloud, Artifacts and Orca Relay. */ +export const signedOut = pane({ + activeProfileId: 'default', + configured: true, + state: 'local', + persistence: 'none' +}) + +/** The session expired: the status line says so and points back at Orca Cloud. */ +export const reconnectRequired = pane({ + activeProfileId: 'default', + configured: true, + state: 'reconnect-required', + persistence: 'encrypted' +}) diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx index 2f52d8e2a91..6666979d8e1 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx @@ -28,7 +28,7 @@ function accountStatusCopy( if (state === 'reconnect-required') { return t( 'auto.components.settings.orcaAccount.reconnectRequired', - 'Your session expired. Sign in again to use cloud features.' + 'Your session expired. Sign in again to use Orca Cloud.' ) } if (state === 'unconfigured') { @@ -40,7 +40,7 @@ function accountStatusCopy( if (state === 'local') { return t( 'auto.components.settings.orcaAccount.signedOut', - 'Sign in to extend Orca with cloud features, including Artifacts and Orca Relay.' + 'Sign in to use Orca Cloud, Artifacts and Orca Relay.' ) } return t('auto.components.settings.orcaAccount.checking', 'Checking account status…') diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx index 3ce9c10baad..21dafe32bc3 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx @@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from 'react' import { Check, ClipboardPaste, KeyRound, Plus } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' import { formatUiRelativeTime } from '@/i18n/relative-time-format' +import { signInAgainActionLabel } from '@/lib/orca-cloud/orca-sign-in-again' +import { useAppStore } from '@/store/index' import type { CloudSecretView, CloudSecretsErrorCode @@ -262,15 +264,20 @@ export function CloudSecretList({ } if (model.list.status === 'failed') { + const signIn = model.list.error === 'unauthorized' return ( void useAppStore.getState().connectCurrentOrcaProfile().then(model.reload) + : model.reload + } /> ) } diff --git a/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts b/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts index d3da00c6023..ee1690290fd 100644 --- a/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts +++ b/src/renderer/src/components/settings/cloud-secrets/cloud-secrets-copy.ts @@ -1,4 +1,5 @@ import type { Translate } from '@/i18n/use-translate' +import { signInAgainMessage } from '@/lib/orca-cloud/orca-sign-in-again' import type { CloudSecretScope, CloudSecretsErrorCode @@ -67,7 +68,7 @@ export function cloudSecretsErrorCopy( 'This scope already holds 100 secrets. Delete one first.' ) case 'unauthorized': - return t('cloudSecrets.error.unauthorized', 'Sign in to Orca again to manage cloud secrets.') + return signInAgainMessage(t) case 'not_configured': return t('cloudSecrets.error.notConfigured', 'Orca Cloud is not available in this build.') case 'unavailable': diff --git a/src/renderer/src/components/ui/button.fixture.tsx b/src/renderer/src/components/ui/button.fixture.tsx index 299ab022515..d100fd62fb0 100644 --- a/src/renderer/src/components/ui/button.fixture.tsx +++ b/src/renderer/src/components/ui/button.fixture.tsx @@ -2,7 +2,15 @@ import { GitBranch, Plus, Trash2 } from 'lucide-react' import { defineFixture } from '../../component-fixtures/component-fixture' import { Button } from './button' -const VARIANTS = ['default', 'secondary', 'outline', 'ghost', 'destructive', 'link'] as const +const VARIANTS = [ + 'default', + 'secondary', + 'outline', + 'ghost', + 'destructive', + 'destructive-chip', + 'link' +] as const const SIZES = ['xs', 'sm', 'default', 'lg'] as const export const variants = defineFixture({ @@ -11,7 +19,7 @@ export const variants = defineFixture({
    {VARIANTS.map((variant) => (
    - {variant} + {variant} + ) +} + +/** + * An expired Orca session. It is a soft state (nothing failed or was lost), so it renders as a + * neutral status, not an alert, with the shared sentence and a Sign in action. + */ +export function SignInAgainNotice({ + onSignIn, + className +}: { + onSignIn: () => void + className?: string +}): React.JSX.Element { + const t = useTranslate() + return ( + } + /> + ) +} diff --git a/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx b/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx index 236c99d7598..98ee124cf67 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useId, useRef, useState } from 'react' -import { Loader2 } from 'lucide-react' +import { Loader2, LogIn } from 'lucide-react' import { Button } from '@/components/ui/button' import { Dialog, @@ -287,7 +287,19 @@ export function SharePortDialog({ aria-describedby={`${formId}-wake-hint`} />
    - {error && ( + {error?.signedOut ? ( + // An expired session is a soft state, not a failure: neutral, with Sign in. + + + {signInAgainActionLabel(t)} + + } + /> + ) : error ? ( - )} - {error?.signedOut && ( - - {signInAgainActionLabel(t)} - - )} + ) : null} {alreadyShared.length > 0 && (

    diff --git a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx index 8b8a7c78055..ad4280af1a7 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx @@ -1,5 +1,5 @@ import React, { useId, useRef, useState } from 'react' -import { ChevronRight, Share2 } from 'lucide-react' +import { ChevronRight, LogIn, Share2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' @@ -152,6 +152,7 @@ export function SharedLinksList({ {status === 'error' && needsSignIn && (

    + {signInAgainActionLabel(t)}
    diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx index 21dafe32bc3..1ded5d704db 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react' import { Check, ClipboardPaste, KeyRound, Plus } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' import { formatUiRelativeTime } from '@/i18n/relative-time-format' -import { signInAgainActionLabel } from '@/lib/orca-cloud/orca-sign-in-again' +import { SignInAgainNotice } from '@/components/orca-cloud/SignInAgainButton' import { useAppStore } from '@/store/index' import type { CloudSecretView, @@ -264,20 +264,20 @@ export function CloudSecretList({ } if (model.list.status === 'failed') { - const signIn = model.list.error === 'unauthorized' + if (model.list.error === 'unauthorized') { + const signIn = (): void => + void useAppStore.getState().connectCurrentOrcaProfile().then(model.reload) + return + } return ( void useAppStore.getState().connectCurrentOrcaProfile().then(model.reload) - : model.reload - } + retryLabel={t('cloudSecrets.list.retry', 'Try again')} + onRetry={model.reload} /> ) } From 9b56250956ee7b5e1f22994dca77d2057e030e91 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:21:22 -0800 Subject: [PATCH 40/46] =?UTF-8?q?feat(cloud):=20agent=20Source=20per=20per?= =?UTF-8?q?son=20(GET/PUT=20/v1/agent-sources,=20offer=20answers,=20owner?= =?UTF-8?q?=20block)=20=E2=80=94=20'Your=20sign-in'=20keeps=20that=20agent?= =?UTF-8?q?'s=20credentials=20out=20of=20the=20sandbox=20session=20live;?= =?UTF-8?q?=20shared=20credential-names=20module=20+=20Worker=20mirror=20(?= =?UTF-8?q?migration=200041)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migrations/0041_agent_sources.sql | 13 ++ .../src/agent-credential-names.ts | 20 ++ .../apps/sandbox-control/src/agent-sources.ts | 183 ++++++++++++++++++ cloud/apps/sandbox-control/src/index.ts | 70 +++++++ cloud/apps/sandbox-control/src/lifecycle.ts | 3 + cloud/apps/sandbox-control/src/session-env.ts | 12 +- .../test/agent-sources.test.ts | 138 +++++++++++++ .../agent-credential-names.ts | 18 ++ 8 files changed, 454 insertions(+), 3 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0041_agent_sources.sql create mode 100644 cloud/apps/sandbox-control/src/agent-credential-names.ts create mode 100644 cloud/apps/sandbox-control/src/agent-sources.ts create mode 100644 cloud/apps/sandbox-control/test/agent-sources.test.ts create mode 100644 src/shared/agent-credentials/agent-credential-names.ts diff --git a/cloud/apps/sandbox-control/migrations/0041_agent_sources.sql b/cloud/apps/sandbox-control/migrations/0041_agent_sources.sql new file mode 100644 index 00000000000..7ac41691c4b --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0041_agent_sources.sql @@ -0,0 +1,13 @@ +-- Per-person agent Source (agent-sources contract §2): "Your sign-in" or "API key", as a default +-- (scope 'default'), a per-workspace override (scope = sandbox id), or the one-time sign-in offer answer +-- (scope 'offer', source 'accepted'|'declined'). Rows for a sandbox go with it. +CREATE TABLE agent_sources ( + user_id TEXT NOT NULL, + account_id TEXT NOT NULL, + scope TEXT NOT NULL, + agent TEXT NOT NULL CHECK (agent IN ('claude', 'codex')), + source TEXT NOT NULL CHECK (source IN ('sign-in', 'key', 'accepted', 'declined')), + updated_at INTEGER NOT NULL, + PRIMARY KEY (user_id, scope, agent) +); +CREATE INDEX agent_sources_scope ON agent_sources (scope); diff --git a/cloud/apps/sandbox-control/src/agent-credential-names.ts b/cloud/apps/sandbox-control/src/agent-credential-names.ts new file mode 100644 index 00000000000..84d14a32e10 --- /dev/null +++ b/cloud/apps/sandbox-control/src/agent-credential-names.ts @@ -0,0 +1,20 @@ +// Worker mirror of src/shared/agent-credentials/agent-credential-names.ts (agent-sources contract §1); +// test/agent-credential-names.test.ts fails if the two lists drift. +export type CredentialAgent = 'claude' | 'codex' +export const AGENT_CREDENTIAL_NAMES: Record = { + claude: [ + 'ANTHROPIC_API_KEY', + 'ANTHROPIC_AUTH_TOKEN', + 'ANTHROPIC_BASE_URL', + 'ANTHROPIC_MODEL', + 'ANTHROPIC_SMALL_FAST_MODEL', + 'CLAUDE_CODE_USE_BEDROCK', + 'CLAUDE_CODE_USE_VERTEX', + 'AWS_BEARER_TOKEN_BEDROCK', + 'ANTHROPIC_VERTEX_PROJECT_ID', + 'CLOUD_ML_REGION' + ], + codex: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL'] +} + +export const CREDENTIAL_AGENTS: readonly CredentialAgent[] = ['claude', 'codex'] diff --git a/cloud/apps/sandbox-control/src/agent-sources.ts b/cloud/apps/sandbox-control/src/agent-sources.ts new file mode 100644 index 00000000000..312b66bf722 --- /dev/null +++ b/cloud/apps/sandbox-control/src/agent-sources.ts @@ -0,0 +1,183 @@ +// Agent Source per person (agent-sources contract §2): "Your sign-in" or "API key", per agent, as a +// default plus an optional per-workspace override, and the one-time "Use my sign-in" offer answer (D8). +// GET /v1/agent-sources[?workspaceId=] +// PUT /v1/agent-sources {agent, source: 'sign-in'|'key'|null, workspaceId?} +// PUT /v1/agent-sources/offer {agent, answer: 'accepted'|'declined'} +// A sandbox applies its OWNER's effective source: with 'sign-in', that agent's credential names are left +// out of the session env (and so out of egress routes, the allowlist and gateway derivation), letting +// the agent's own login inside the sandbox win. Variables are never touched. +import { z } from 'zod' +import { AGENT_CREDENTIAL_NAMES, CREDENTIAL_AGENTS, type CredentialAgent } from './agent-credential-names' +import type { SandboxCaller } from './auth' +import { memberNamesFor } from './member-names' +import { effectiveSecrets } from './secrets' +import { getSandbox, type SandboxRow } from './store' + +export type AgentSource = 'sign-in' | 'key' +type OfferAnswer = 'unanswered' | 'accepted' | 'declined' +const DEFAULT_SCOPE = 'default' +const OFFER_SCOPE = 'offer' + +type SourceRow = { scope: string; agent: CredentialAgent; source: string } + +const AgentSchema = z.enum(['claude', 'codex']) +export const PutSourceSchema = z + .object({ + agent: AgentSchema, + source: z.enum(['sign-in', 'key']).nullable(), + workspaceId: z.string().min(1).max(128).optional() + }) + .strict() +export const PutOfferSchema = z.object({ agent: AgentSchema, answer: z.enum(['accepted', 'declined']) }).strict() + +export class AgentSourceError extends Error { + constructor( + readonly status: 400 | 403 | 404, + readonly code: string, + readonly reason?: string + ) { + super(reason ? `${code}:${reason}` : code) + } +} + +async function rowsFor(db: D1Database, userId: string, scopes: string[]): Promise { + const { results } = await db + .prepare(`SELECT scope, agent, source FROM agent_sources WHERE user_id = ? AND scope IN (${scopes.map(() => '?').join(', ')})`) + .bind(userId, ...scopes) + .all() + return results +} + +function byAgent(rows: SourceRow[], scope: string): Record { + const out = { claude: null, codex: null } as Record + for (const row of rows) { + if (row.scope === scope && (row.source === 'sign-in' || row.source === 'key')) { + out[row.agent] = row.source + } + } + return out +} + +/** Agents whose owner chose "Your sign-in" for this sandbox (override first, then default). */ +export async function signInAgentsFor(db: D1Database, row: Pick): Promise> { + const rows = await rowsFor(db, row.user_id, [row.id, DEFAULT_SCOPE]) + const workspace = byAgent(rows, row.id) + const defaults = byAgent(rows, DEFAULT_SCOPE) + return new Set(CREDENTIAL_AGENTS.filter((agent) => (workspace[agent] ?? defaults[agent]) === 'sign-in')) +} + +/** Drops the credential names of agents on "Your sign-in" (after preset derivation, so derived ones go too). */ +export function withoutSignInCredentials>(env: T, signIn: ReadonlySet): T { + if (signIn.size === 0) { + return env + } + const next: Record = { ...env } + for (const agent of signIn) { + for (const name of AGENT_CREDENTIAL_NAMES[agent]) { + delete next[name] + } + } + return next as T +} + +/** Some agent key the caller's sessions would get covers this agent (the gateway key covers both). */ +function coveredByKey(names: ReadonlySet): Record { + const gateway = names.has('AI_GATEWAY_API_KEY') + return { + claude: gateway || ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'AWS_BEARER_TOKEN_BEDROCK', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX'].some((n) => names.has(n)), + codex: gateway || names.has('OPENAI_API_KEY') + } +} + +async function ownedWorkspace(db: D1Database, caller: SandboxCaller, workspaceId: string): Promise { + const row = await getSandbox(db, workspaceId) + if (!row || row.account_id !== caller.accountId || row.status === 'destroyed') { + throw new AgentSourceError(404, 'not_found') + } + return row +} + +export async function agentSourcesView(db: D1Database, caller: SandboxCaller, workspaceId: string | null) { + const row = workspaceId ? await ownedWorkspace(db, caller, workspaceId) : null + // The sandbox applies its owner's choice (shared sandboxes, v1): show the owner's, not the caller's. + const subject = row ? row.user_id : caller.userId + const rows = await rowsFor(db, subject, [DEFAULT_SCOPE, OFFER_SCOPE, ...(row ? [row.id] : [])]) + const defaults = byAgent(rows, DEFAULT_SCOPE) + const workspace = row ? byAgent(rows, row.id) : null + const effective = await effectiveSecrets(db, caller, row?.repo_url ?? null) + const covered = coveredByKey(new Set(effective.map((secret) => secret.name))) + const offerRows = rows.filter((r) => r.scope === OFFER_SCOPE) + const signInOffer = Object.fromEntries( + CREDENTIAL_AGENTS.map((agent) => [ + agent, + (offerRows.find((r) => r.agent === agent)?.source as OfferAnswer | undefined) ?? 'unanswered' + ]) + ) as Record + const resolved = Object.fromEntries( + CREDENTIAL_AGENTS.map((agent) => { + const chosen = workspace?.[agent] ?? null + if (chosen) { + return [agent, { source: chosen, origin: 'workspace' }] + } + if (defaults[agent]) { + return [agent, { source: defaults[agent], origin: 'default' }] + } + return [agent, { source: covered[agent] ? 'key' : null, origin: 'implicit' }] + }) + ) + let owner: { userId: string; displayName: string | null; isCaller: boolean } | null = null + if (row) { + const names = await memberNamesFor(db, caller.accountId, [row.user_id]) + owner = { userId: row.user_id, displayName: names.get(row.user_id) ?? null, isCaller: row.user_id === caller.userId } + } + return { defaults, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner } +} + +async function upsert(db: D1Database, caller: SandboxCaller, scope: string, agent: CredentialAgent, source: string | null, now: number) { + if (source === null) { + await db.prepare('DELETE FROM agent_sources WHERE user_id = ? AND scope = ? AND agent = ?').bind(caller.userId, scope, agent).run() + return + } + await db + .prepare( + `INSERT INTO agent_sources (user_id, account_id, scope, agent, source, updated_at) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (user_id, scope, agent) DO UPDATE SET source = excluded.source, account_id = excluded.account_id, updated_at = excluded.updated_at` + ) + .bind(caller.userId, caller.accountId, scope, agent, source, now) + .run() +} + +/** Returns the sandbox whose session env must refresh (a running one whose owner's source changed), if any. */ +export async function putAgentSource(db: D1Database, caller: SandboxCaller, body: z.infer, now: number) { + let row: SandboxRow | null = null + if (body.workspaceId) { + row = await ownedWorkspace(db, caller, body.workspaceId) + if (row.user_id !== caller.userId) { + throw new AgentSourceError(403, 'forbidden', 'owner_only') + } + } + // D9: accepted while the sandbox is still starting; its first boot reads the row. + await upsert(db, caller, row ? row.id : DEFAULT_SCOPE, body.agent, body.source, now) + return row +} + +export async function putOfferAnswer(db: D1Database, caller: SandboxCaller, body: z.infer, now: number) { + await upsert(db, caller, OFFER_SCOPE, body.agent, body.answer, now) +} + +/** Running sandboxes of this person that a default change affects (no workspace override for that agent). */ +export async function runningSandboxesForDefault(db: D1Database, userId: string, agent: CredentialAgent): Promise { + const { results } = await db + .prepare( + `SELECT s.* FROM sandboxes s WHERE s.user_id = ? AND s.status = 'running' + AND NOT EXISTS (SELECT 1 FROM agent_sources a WHERE a.user_id = s.user_id AND a.scope = s.id AND a.agent = ?) + LIMIT 200` + ) + .bind(userId, agent) + .all() + return results +} + +export async function deleteAgentSourcesForSandbox(db: D1Database, sandboxId: string): Promise { + await db.prepare('DELETE FROM agent_sources WHERE scope = ?').bind(sandboxId).run() +} diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 7bed38b9c95..569d71d39b5 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -93,6 +93,15 @@ import { reconcile } from './reconcile' import { egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress' import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets' import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh' +import { + AgentSourceError, + PutOfferSchema, + PutSourceSchema, + agentSourcesView, + putAgentSource, + putOfferAnswer, + runningSandboxesForDefault +} from './agent-sources' import { EgressHostsSchema, egressUserHosts, normalizeUserHosts, setEgressUserHosts } from './egress-hosts' import { cachedProviderEnv } from './session-env' import { credentialTargets, type CredentialTarget } from './provider-env' @@ -1071,6 +1080,16 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) } return response } + if (url.pathname === '/v1/agent-sources' || url.pathname === '/v1/agent-sources/offer') { + const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)()) + if (!caller) { + return fail('unauthorized', 401) + } + if (caller.deviceSessionId) { + return fail('forbidden', 403, 'device_session') + } + return await agentSourcesRoute(request, url, env, deps, caller) + } if (isEnvironmentRoute(url.pathname)) { const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)()) if (!caller) { @@ -1663,3 +1682,54 @@ export class EnvironmentBuildRunner implements DurableObject { await this.state.storage.setAlarm(Date.now() + next) } } + +async function agentSourcesRoute(request: Request, url: URL, env: Env, deps: Deps, caller: SandboxCaller): Promise { + const db = env.SANDBOX_DB + const now = (deps.now ?? Date.now)() + // Labels for the owner block on teammates' views; a failure here must never fail the request. + await rememberCallerName(db, caller, now).catch(() => undefined) + const noStore = (body: unknown) => Response.json(body, { headers: { 'cache-control': 'no-store' } }) + try { + if (request.method === 'GET' && url.pathname === '/v1/agent-sources') { + return noStore(await agentSourcesView(db, caller, url.searchParams.get('workspaceId'))) + } + if (request.method === 'PUT' && url.pathname === '/v1/agent-sources/offer') { + const body = PutOfferSchema.safeParse(await readJson(request)) + if (!body.success) { + return fail('invalid_request', 400) + } + await putOfferAnswer(db, caller, body.data, now) + return noStore(await agentSourcesView(db, caller, null)) + } + if (request.method === 'PUT' && url.pathname === '/v1/agent-sources') { + const body = PutSourceSchema.safeParse(await readJson(request)) + if (!body.success) { + return fail('invalid_request', 400) + } + const row = await putAgentSource(db, caller, body.data, now) + // A running sandbox picks the change up in new shells within seconds (same path as a secret edit). + const targets = row ? (row.status === 'running' ? [row] : []) : await runningSandboxesForDefault(db, caller.userId, body.data.agent) + if (targets.length > 0) { + const work = lifecycleDeps(env, deps).then(async (life) => { + if (life) { + for (const target of targets) { + await refreshSandboxEnv(life, target).catch(() => false) + } + } + }) + if (deps.waitUntil) { + deps.waitUntil(work.catch(() => undefined)) + } else { + await work + } + } + return noStore(await agentSourcesView(db, caller, body.data.workspaceId ?? null)) + } + return fail('not_found', 404) + } catch (error) { + if (error instanceof AgentSourceError) { + return fail(error.code, error.status, error.reason) + } + throw error + } +} diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 098a683bb3b..53307250b1e 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -1,5 +1,6 @@ // Sandbox lifecycle: one persistent provider sandbox per Orca workspace, with an Orca-owned lease, // a forced stop before the provider's 24h cap, usage metering and write-ahead rows. +import { deleteAgentSourcesForSandbox } from './agent-sources' import type { EntitlementClient, MachineSize } from './entitlements' import { parseGitHubRepo, type GitHubAppMinter } from './github-app' import { @@ -833,6 +834,8 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom await deps.db.prepare('DELETE FROM sandbox_archives WHERE sandbox_id = ?').bind(row.id).run() // So does its sealed read snapshot. await deleteReadSnapshot(deps.db, row.id) + // And its per-workspace agent Source overrides. + await deleteAgentSourcesForSandbox(deps.db, row.id) const destroyed = await claim(deps, destroying, { status: 'destroyed', ...NO_SESSION, diff --git a/cloud/apps/sandbox-control/src/session-env.ts b/cloud/apps/sandbox-control/src/session-env.ts index 52e3446f882..f0aaca727a9 100644 --- a/cloud/apps/sandbox-control/src/session-env.ts +++ b/cloud/apps/sandbox-control/src/session-env.ts @@ -2,6 +2,7 @@ // presets filled in, and with egress placeholders on, model keys swapped for placeholders. The same // answer drives the egress allowlist and the proxy's credential routes, at boot and on refresh. import type { LifecycleDeps } from './lifecycle' +import { signInAgentsFor, withoutSignInCredentials } from './agent-sources' import { deriveProviderEnv, deriveProviderScopes, providerHosts } from './provider-env' import { applySecretPlaceholders, encodeEgressSecretHosts } from './secret-egress' import { resolveSandboxSecrets } from './secrets' @@ -26,8 +27,11 @@ export async function resolvedProviderEnv( keyring: Keyring, row: Pick ): Promise { - const { env: stored, scopes } = await resolveSandboxSecrets(db, keyring, row) - const env = deriveProviderEnv(stored) + const [{ env: stored, scopes }, signIn] = await Promise.all([ + resolveSandboxSecrets(db, keyring, row), + signInAgentsFor(db, row) + ]) + const env = withoutSignInCredentials(deriveProviderEnv(stored), signIn) return { env, scopes: deriveProviderScopes(stored, env, scopes) } } @@ -70,7 +74,9 @@ export async function sessionSecretEnv( return EMPTY } const { env: stored, scopes: storedScopes, skipped } = await resolveSandboxSecrets(deps.db, deps.secrets.keyring, row) - const env = deriveProviderEnv(stored) + // Agents on "Your sign-in" (owner's choice): their credentials never reach this session. + const signIn = await signInAgentsFor(deps.db, row) + const env = withoutSignInCredentials(deriveProviderEnv(stored), signIn) const scopes = deriveProviderScopes(stored, env, storedScopes) const egressAllowHosts = providerHosts(env).join(',') || null // Counts only. diff --git a/cloud/apps/sandbox-control/test/agent-sources.test.ts b/cloud/apps/sandbox-control/test/agent-sources.test.ts new file mode 100644 index 00000000000..390738d0dd7 --- /dev/null +++ b/cloud/apps/sandbox-control/test/agent-sources.test.ts @@ -0,0 +1,138 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { AGENT_CREDENTIAL_NAMES } from '../src/agent-credential-names' +import { ENV_COMMAND, START_COMMAND } from '../src/sandbox-vm-commands' +import { createHarness } from './harness' + +const KEK = Buffer.alloc(32, 7).toString('base64') +const PROXY_URL = 'https://sandbox.test/v1/egress/proxy' +const TEAM_KEY = 'sk-ant-api03-TEAM-fake-0000-aaaa' +const GATEWAY_KEY = 'vck_fake-gateway-key-0000-aaaa-bbbb' + +let logs: string[] = [] +beforeEach(() => { + logs = [] + for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) { + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + logs.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ')) + }) + } +}) +afterEach(() => { + for (const value of [TEAM_KEY, GATEWAY_KEY]) { + expect(logs.join('\n')).not.toContain(value) + } + vi.restoreAllMocks() +}) + +function decode(encoded: string | undefined): Record { + return Object.fromEntries( + (encoded ?? '') + .split('\n') + .filter(Boolean) + .map((line) => { + const at = line.indexOf('=') + return [line.slice(0, at), Buffer.from(line.slice(at + 1), 'base64').toString('utf8')] + }) + ) +} + +async function setup(overrides: Record = {}) { + const h = await createHarness({ SECRETS_KEK: KEK, ...overrides }) + const as = (sub: string, org?: string, role?: string, name?: string) => + h.token(sub, org, 'sandbox', { ...(role ? { orgRole: role } : {}), ...(name ? { name } : {}) }) + const put = (scope: string, name: string, value: string, bearer: string) => + h.call('PUT', `/v1/secrets/${scope}/${name}`, { body: { value }, bearer }) + const lastEnv = (command: string) => decode(h.vercel.commands.filter((c) => c.command === command).at(-1)?.env.ORCA_SECRET_ENV) + return { h, as, put, lastEnv } +} + +describe('per-agent credential names', () => { + it('the Worker mirror matches the shared module verbatim', () => { + const shared = readFileSync(fileURLToPath(new URL('../../../../src/shared/agent-credentials/agent-credential-names.ts', import.meta.url).href), 'utf8') + for (const [agent, names] of Object.entries(AGENT_CREDENTIAL_NAMES)) { + const block = new RegExp(`${agent}: \\[([^\\]]*)\\]`).exec(shared)?.[1] ?? '' + expect(block.match(/'[A-Z0-9_]+'/g)?.map((n) => n.slice(1, -1))).toEqual([...names]) + } + }) +}) + +describe('/v1/agent-sources', () => { + it('implicit default follows key coverage, explicit choices win, and the offer is per person', async () => { + const { h, as, put } = await setup() + const ada = await as('ada', 'acme', 'admin') + const mia = await as('mia', 'acme', 'member') + let view = await h.call('GET', '/v1/agent-sources', { bearer: mia }) + expect(view.body.effective).toEqual({ claude: { source: null, origin: 'implicit' }, codex: { source: null, origin: 'implicit' } }) + expect(view.body.signInOffer).toEqual({ claude: 'unanswered', codex: 'unanswered' }) + await put('org', 'ANTHROPIC_API_KEY', TEAM_KEY, ada) + view = await h.call('GET', '/v1/agent-sources', { bearer: mia }) + expect(view.body.coveredByKey).toEqual({ claude: true, codex: false }) + expect(view.body.effective.claude).toEqual({ source: 'key', origin: 'implicit' }) + view = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in' } }) + expect(view.body.effective.claude).toEqual({ source: 'sign-in', origin: 'default' }) + view = await h.call('PUT', '/v1/agent-sources/offer', { bearer: mia, body: { agent: 'claude', answer: 'declined' } }) + expect(view.body.signInOffer.claude).toBe('declined') + // Ada's answers are hers alone. + expect((await h.call('GET', '/v1/agent-sources', { bearer: ada })).body.signInOffer.claude).toBe('unanswered') + expect((await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'gemini', source: 'key' } })).status).toBe(400) + }) + + it('"Your sign-in" keeps that agent\'s credentials (incl. gateway-derived) out of the session, live, and only that agent\'s', async () => { + const { h, as, put, lastEnv } = await setup({ SECRETS_EGRESS_PLACEHOLDERS: 'on', EGRESS_PROXY_URL: PROXY_URL }) + const ada = await as('ada', 'acme', 'admin') + const mia = await as('mia', 'acme', 'member', 'Mia Chen') + await put('org', 'AI_GATEWAY_API_KEY', GATEWAY_KEY, ada) + await put('personal', 'APP_MODE', 'dev', mia) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const id: string = created.body.sandbox.id + expect(Object.keys(lastEnv(START_COMMAND))).toEqual(expect.arrayContaining(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'OPENAI_API_KEY'])) + const view = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in', workspaceId: id } }) + expect(view.body.effective.claude).toEqual({ source: 'sign-in', origin: 'workspace' }) + expect(view.body.owner).toEqual({ userId: 'mia', displayName: 'Mia Chen', isCaller: true }) + const env = lastEnv(ENV_COMMAND) + for (const name of AGENT_CREDENTIAL_NAMES.claude) { + expect(env[name]).toBeUndefined() + } + expect(env.OPENAI_API_KEY).toMatch(/^orca-ph-openai-api-key-/) + expect(env.APP_MODE).toBe('dev') + const row = await h.env.SANDBOX_DB.prepare('SELECT egress_secret_hosts FROM sandboxes WHERE id = ?').bind(id).first<{ egress_secret_hosts: string }>() + expect(row!.egress_secret_hosts).not.toContain('ANTHROPIC') + // Back to the key: it returns in new shells. + await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: null, workspaceId: id } }) + expect(lastEnv(ENV_COMMAND).ANTHROPIC_AUTH_TOKEN).toMatch(/^orca-ph-anthropic-auth-token-/) + }) + + it('a default applies to running sandboxes without an override; only the owner sets a workspace source', async () => { + const { h, as, put, lastEnv } = await setup() + const ada = await as('ada', 'acme', 'admin', 'Ada Lovelace') + const mia = await as('mia', 'acme', 'member') + await put('org', 'OPENAI_API_KEY', 'sk-proj-team-fake-1234-zzzz', ada) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ada', machineSize: 'standard' }, bearer: ada }) + const id: string = created.body.sandbox.id + await h.call('PUT', '/v1/agent-sources', { bearer: ada, body: { agent: 'codex', source: 'sign-in' } }) + expect(lastEnv(ENV_COMMAND).OPENAI_API_KEY).toBeUndefined() + const forbidden = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'codex', source: 'key', workspaceId: id } }) + expect(forbidden.status).toBe(403) + expect(forbidden.body.reason).toBe('owner_only') + const teammate = await h.call('GET', `/v1/agent-sources?workspaceId=${id}`, { bearer: mia }) + expect(teammate.body.owner).toEqual({ userId: 'ada', displayName: 'Ada Lovelace', isCaller: false }) + expect(teammate.body.effective.codex).toEqual({ source: 'sign-in', origin: 'default' }) + expect((await h.call('GET', `/v1/agent-sources?workspaceId=${id}`, { bearer: await as('zed', 'other', 'admin') })).status).toBe(404) + }) + + it('a workspace source set while the sandbox is still starting applies at its first boot (D9)', async () => { + const { h, as, put, lastEnv } = await setup() + const mia = await as('mia') + await put('personal', 'ANTHROPIC_API_KEY', TEAM_KEY, mia) + const id = 'sbx_creating_fake' + await h.env.SANDBOX_DB.prepare( + `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, machine_size, region, generation, created_at, updated_at) + VALUES (?, 'user:mia', 'mia', 'ws-c', 'vercel', 'orca-test-x', 'creating', 'standard', 'iad1', 0, 1, 1)` + ).bind(id).run() + const put1 = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in', workspaceId: id } }) + expect(put1.status).toBe(200) + expect(put1.body.effective.claude.source).toBe('sign-in') + }) +}) diff --git a/src/shared/agent-credentials/agent-credential-names.ts b/src/shared/agent-credentials/agent-credential-names.ts new file mode 100644 index 00000000000..3af10fe3b6e --- /dev/null +++ b/src/shared/agent-credentials/agent-credential-names.ts @@ -0,0 +1,18 @@ +// Per-agent credential names (single source of truth; agent-sources contract §1). The Worker mirrors +// this list verbatim in cloud/apps/sandbox-control/src/agent-credential-names.ts. +export type CredentialAgent = 'claude' | 'codex' +export const AGENT_CREDENTIAL_NAMES: Record = { + claude: [ + 'ANTHROPIC_API_KEY', + 'ANTHROPIC_AUTH_TOKEN', + 'ANTHROPIC_BASE_URL', + 'ANTHROPIC_MODEL', + 'ANTHROPIC_SMALL_FAST_MODEL', + 'CLAUDE_CODE_USE_BEDROCK', + 'CLAUDE_CODE_USE_VERTEX', + 'AWS_BEARER_TOKEN_BEDROCK', + 'ANTHROPIC_VERTEX_PROJECT_ID', + 'CLOUD_ML_REGION' + ], + codex: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL'] +} From 43aa595ee7a9523f7a51ac5ba6c3b5a3bcede6ef Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:33:45 -0800 Subject: [PATCH 41/46] feat(sandbox-control): internal per-session CPU tracking and fair-use report (U22) Customers keep flat sandbox hours. Each stopped session's activeCpuDurationMs (from Vercel's stop response or GET session) is stored in a new session_cpu table (migration 0042), idempotent per session. Recording is best-effort and never blocks suspend, stop or usage reporting; a 5-minute cron sweep retries recent sessions still missing CPU. Operator-only GET /v1/internal/fair-use reports per-account 30-day utilisation sum(active_cpu_ms)/sum(wall_ms*vcpus) with fairUseFlag above 60%. Nothing reaches usage_outbox, billing or clients. --- .../migrations/0042_session_cpu.sql | 20 ++ cloud/apps/sandbox-control/src/index.ts | 6 + cloud/apps/sandbox-control/src/lifecycle.ts | 13 +- cloud/apps/sandbox-control/src/operator.ts | 12 ++ .../sandbox-control/src/sandbox-provider.ts | 16 +- cloud/apps/sandbox-control/src/session-cpu.ts | 175 +++++++++++++++ .../sandbox-control/src/vercel-sandbox-api.ts | 36 +++- .../apps/sandbox-control/test/fake-vercel.ts | 20 +- .../sandbox-control/test/session-cpu.test.ts | 201 ++++++++++++++++++ 9 files changed, 492 insertions(+), 7 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0042_session_cpu.sql create mode 100644 cloud/apps/sandbox-control/src/session-cpu.ts create mode 100644 cloud/apps/sandbox-control/test/session-cpu.test.ts diff --git a/cloud/apps/sandbox-control/migrations/0042_session_cpu.sql b/cloud/apps/sandbox-control/migrations/0042_session_cpu.sql new file mode 100644 index 00000000000..ffb834b73c9 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0042_session_cpu.sql @@ -0,0 +1,20 @@ +-- U22: each session's measured CPU, for internal fair-use review only. Customers keep flat +-- sandbox hours: nothing here feeds usage_outbox, billing or any customer-facing route. +-- One row per provider session (idempotent); active_cpu_ms stays NULL until Vercel reports it +-- after the VM stops, and a cron sweep retries the ones still missing. Additive. +CREATE TABLE session_cpu ( + session_id TEXT PRIMARY KEY, + sandbox_id TEXT NOT NULL, + account_id TEXT NOT NULL, + user_id TEXT, + vcpus INTEGER NOT NULL, + memory_mb INTEGER, + active_cpu_ms INTEGER, + wall_ms INTEGER NOT NULL, + started_at INTEGER, + ended_at INTEGER NOT NULL, + fetched_at INTEGER, + attempts INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX session_cpu_account_ended ON session_cpu (account_id, ended_at); +CREATE INDEX session_cpu_pending ON session_cpu (ended_at) WHERE active_cpu_ms IS NULL; diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 569d71d39b5..7a565027349 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -165,6 +165,7 @@ import { workspaceViews } from './workspaces' import { rememberCallerName } from './member-names' +import { sweepSessionCpu } from './session-cpu' import type { SandboxCaller } from './auth' const MAX_JSON_BYTES = 16 * 1024 @@ -1601,6 +1602,11 @@ export default { // Counts only; no ids, tokens or pairing material. const summary = await reconcile(life) console.log(JSON.stringify({ event: 'reconcile', ...summary })) + // Internal fair-use review (U22): retry sessions whose CPU the stop couldn't read yet. + const cpu = await sweepSessionCpu(life.db, life.provider, life.now()) + if (cpu.checked > 0) { + console.log(JSON.stringify({ event: 'session_cpu_sweep', ...cpu })) + } const retried = await retryPendingMessages(life).catch(() => -1) if (retried !== 0) { console.log(JSON.stringify({ event: 'message_retry', retried })) diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 53307250b1e..1ca025f0b61 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -43,6 +43,7 @@ import { type SandboxRow, type SessionFields } from './store' +import { recordSessionEnd } from './session-cpu' import { flushUsage, queueUsage } from './usage' import { SANDBOX_VCPUS } from './machine-size' import { isRegionalFailure } from './regions' @@ -674,15 +675,21 @@ export async function stopForSuspend( if (stopped.snapshotId) { await recordSnapshots(deps.db, row.id, [stopped.snapshotId], deps.now()) } + await queueUsage(deps.db, row, deps.now()) + // Internal CPU review (U22): never throws, never touches the meter. + await recordSessionEnd(deps.db, row, deps.now(), stopped.usage, deps.now()) + } else { + await queueUsage(deps.db, row, deps.now()) } - await queueUsage(deps.db, row, deps.now()) await deps.hooks?.afterStop?.(row).catch(() => undefined) return claim(deps, row, { status: 'suspended', ...NO_SESSION }) } /** The provider ended the session on its own (lease lapsed): bill up to when it stopped. */ export async function markProviderStopped(deps: LifecycleDeps, row: SandboxRow): Promise { - await queueUsage(deps.db, row, Math.min(deps.now(), row.lease_expires_at ?? deps.now())) + const endedAt = Math.min(deps.now(), row.lease_expires_at ?? deps.now()) + await queueUsage(deps.db, row, endedAt) + await recordSessionEnd(deps.db, row, endedAt, null, deps.now()) await deps.hooks?.afterStop?.(row).catch(() => undefined) return claim(deps, row, { status: 'suspended', ...NO_SESSION }) } @@ -809,6 +816,8 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom } let destroying = row.status === 'destroying' ? row : await claim(deps, row, { status: 'destroying' }) const settled = await queueUsage(deps.db, destroying, deps.now()) + // A live session ends with the delete (no-op once suspended: the row has no session then). + await recordSessionEnd(deps.db, destroying, deps.now(), null, deps.now()) if (settled !== destroying.usage_settled_at) { destroying = await claim(deps, destroying, { usage_settled_at: settled }) } diff --git a/cloud/apps/sandbox-control/src/operator.ts b/cloud/apps/sandbox-control/src/operator.ts index 1dfe2de47a7..a709679b12a 100644 --- a/cloud/apps/sandbox-control/src/operator.ts +++ b/cloud/apps/sandbox-control/src/operator.ts @@ -7,6 +7,8 @@ // DELETE /v1/internal/github/bindings {installationId, accountId?} // POST /v1/internal/members/role-changed {accountId, userId, role} re-cap their keys and MCP grants (auth calls this) // POST /v1/internal/members/removed {accountId, userId} revoke a departed member's keys, phones and workspace grants, disable their routines (auth calls this) +// GET /v1/internal/fair-use?days=30 per-account CPU utilisation + fair-use flag (U22; internal only, never billed) +// POST /v1/internal/session-cpu/sweep fetch CPU for recently stopped sessions now (the cron does this every 5 min) import { z } from 'zod' import { audit } from './api/audit' import { syncMemberRole } from './api/member-role-sync' @@ -18,6 +20,7 @@ import { guardrails, type LifecycleDeps } from './lifecycle' import { drainAll, housekeeping } from './retention' import { memberChangeTime, recordMemberChange } from './member-changes' import { removeMember } from './member-removal' +import { fairUseReport, FAIR_USE_WINDOW_DAYS, sweepSessionCpu } from './session-cpu' import { listByStatus } from './store' const KillSwitchBody = z.object({ enabled: z.boolean(), drain: z.boolean().optional() }).strict() @@ -141,6 +144,15 @@ export async function handleOperator( const removal = await removeMember(life, body.data.accountId, body.data.userId, now, body.data.changedAt) return Response.json({ revoked: removal.keysRevoked, ...removal }) } + case 'GET /v1/internal/fair-use': { + const days = Number(new URL(request.url).searchParams.get('days') ?? FAIR_USE_WINDOW_DAYS) + if (!Number.isInteger(days) || days < 1 || days > 90) { + return Response.json({ error: 'invalid_request' }, { status: 400 }) + } + return Response.json(await fairUseReport(life.db, now, days), { headers: { 'cache-control': 'no-store' } }) + } + case 'POST /v1/internal/session-cpu/sweep': + return Response.json({ sweep: await sweepSessionCpu(life.db, life.provider, now) }) default: return null } diff --git a/cloud/apps/sandbox-control/src/sandbox-provider.ts b/cloud/apps/sandbox-control/src/sandbox-provider.ts index 8d31727ab3a..9f9852141d6 100644 --- a/cloud/apps/sandbox-control/src/sandbox-provider.ts +++ b/cloud/apps/sandbox-control/src/sandbox-provider.ts @@ -27,6 +27,18 @@ export type ProviderSession = { timeoutMs: number } +/** A session's measured usage (internal fair-use review only; never metered or sent to billing). */ +export type ProviderSessionUsage = { + sessionId: string + status: ProviderSessionStatus + /** Vercel reports this only once the VM has stopped. */ + activeCpuMs: number | null + durationMs: number | null + vcpus: number | null + memoryMb: number | null + stoppedAt: number | null +} + export type ProviderRoute = { port: number; url: string } export type ProviderSandboxState = { @@ -87,7 +99,9 @@ export type SandboxProviderApi = { createSandbox(params: CreateSandboxParams): Promise /** `resume: true` boots a stopped persistent sandbox from its latest snapshot. Null when absent. */ getSandbox(name: string, options: { resume: boolean }): Promise - stopSession(sessionId: string): Promise<{ snapshotId: string | null }> + stopSession(sessionId: string): Promise<{ snapshotId: string | null; usage?: ProviderSessionUsage | null }> + /** A session's usage, stopped or not. Null when the provider no longer knows it. Optional: CPU review is best-effort. */ + getSessionUsage?(sessionId: string): Promise extendTimeout(sessionId: string, durationMs: number): Promise updateNetworkPolicy(sessionId: string, policy: NetworkPolicy): Promise /** Sets the full exposed-port list on the sandbox (live on a running session); returns its routes. */ diff --git a/cloud/apps/sandbox-control/src/session-cpu.ts b/cloud/apps/sandbox-control/src/session-cpu.ts new file mode 100644 index 00000000000..4bae566095f --- /dev/null +++ b/cloud/apps/sandbox-control/src/session-cpu.ts @@ -0,0 +1,175 @@ +// U22: internal-only CPU tracking. Customers keep flat sandbox hours; this records each session's +// measured active CPU (Vercel reports it after the VM stops) so operators can spot fair-use outliers. +// Never touches usage_outbox, billing or a customer route, and never blocks a stop: every entry +// point swallows its own failures, and the cron sweep fills in what the stop couldn't read. +import { SANDBOX_VCPUS } from './machine-size' +import type { ProviderSessionUsage, SandboxProviderApi } from './sandbox-provider' +import type { SandboxRow } from './store' + +export const FAIR_USE_WINDOW_DAYS = 30 +/** Average active CPU over vCPU-time above this flags an account for review. */ +export const FAIR_USE_THRESHOLD = 0.6 +/** Sessions older than this without CPU are given up on (the provider may have forgotten them). */ +const SWEEP_WINDOW_MS = 7 * 24 * 60 * 60_000 +const SWEEP_MAX_ATTEMPTS = 12 +const SWEEP_BATCH = 25 + +/** + * Records a session that just ended; idempotent per session id. `usage` is whatever the stop + * answered (often no CPU yet). Never throws. + */ +export async function recordSessionEnd( + db: D1Database, + row: SandboxRow, + endedAt: number, + usage: ProviderSessionUsage | null | undefined, + now: number +): Promise { + try { + if (!row.session_id) { + return + } + const vcpus = positive(usage?.vcpus) ?? SANDBOX_VCPUS + const startedAt = row.session_started_at + const wallMs = positive(usage?.durationMs) ?? (startedAt !== null ? Math.max(0, endedAt - startedAt) : 0) + await db + .prepare( + `INSERT OR IGNORE INTO session_cpu + (session_id, sandbox_id, account_id, user_id, vcpus, memory_mb, wall_ms, started_at, ended_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .bind(row.session_id, row.id, row.account_id, row.user_id ?? null, vcpus, positive(usage?.memoryMb), wallMs, startedAt, endedAt) + .run() + if (usage) { + await applyUsage(db, row.session_id, usage, now) + } + } catch { + // Internal review data only: a D1 or shape problem must never fail the stop. + } +} + +/** Fills CPU on a pending row; first answer wins (re-fetching never rewrites a recorded value). */ +async function applyUsage(db: D1Database, sessionId: string, usage: ProviderSessionUsage, now: number): Promise { + if (usage.activeCpuMs === null || !Number.isFinite(usage.activeCpuMs) || usage.activeCpuMs < 0) { + return false + } + const result = await db + .prepare( + `UPDATE session_cpu SET active_cpu_ms = ?, fetched_at = ?, + wall_ms = COALESCE(?, wall_ms), vcpus = COALESCE(?, vcpus), memory_mb = COALESCE(?, memory_mb) + WHERE session_id = ? AND active_cpu_ms IS NULL` + ) + .bind( + Math.round(usage.activeCpuMs), + now, + positive(usage.durationMs), + positive(usage.vcpus), + positive(usage.memoryMb), + sessionId + ) + .run() + return (result.meta?.changes ?? 0) > 0 +} + +export type SessionCpuSweep = { checked: number; recorded: number; failed: number } + +/** Cron: asks the provider again for recent sessions still missing CPU. Never throws. */ +export async function sweepSessionCpu( + db: D1Database, + provider: Pick, + now: number +): Promise { + const summary: SessionCpuSweep = { checked: 0, recorded: 0, failed: 0 } + if (!provider.getSessionUsage) { + return summary + } + let pending: { session_id: string }[] + try { + pending = ( + await db + .prepare( + `SELECT session_id FROM session_cpu + WHERE active_cpu_ms IS NULL AND ended_at >= ? AND attempts < ? + ORDER BY ended_at DESC LIMIT ?` + ) + .bind(now - SWEEP_WINDOW_MS, SWEEP_MAX_ATTEMPTS, SWEEP_BATCH) + .all<{ session_id: string }>() + ).results + } catch { + return summary + } + for (const { session_id } of pending) { + summary.checked++ + try { + const usage = await provider.getSessionUsage(session_id) + if (usage && (await applyUsage(db, session_id, usage, now))) { + summary.recorded++ + continue + } + } catch { + summary.failed++ + } + await db + .prepare('UPDATE session_cpu SET attempts = attempts + 1 WHERE session_id = ?') + .bind(session_id) + .run() + .catch(() => undefined) + } + return summary +} + +export type FairUseAccount = { + accountId: string + sessions: number + activeCpuMs: number + vcpuMs: number + /** sum(active_cpu_ms) / sum(wall_ms × vcpus), 0..1 (null when there is no measured time). */ + cpuUtilization: number | null + fairUseFlag: boolean +} + +export type FairUseReport = { + windowDays: number + since: number + threshold: number + /** Ended sessions in the window still waiting for the provider's CPU figure (excluded from the math). */ + pendingSessions: number + accounts: FairUseAccount[] +} + +/** Operator-only. Per account over the window; highest utilisation first. */ +export async function fairUseReport(db: D1Database, now: number, windowDays = FAIR_USE_WINDOW_DAYS): Promise { + const since = now - windowDays * 24 * 60 * 60_000 + const { results } = await db + .prepare( + `SELECT account_id, COUNT(*) AS sessions, SUM(active_cpu_ms) AS active_cpu_ms, SUM(wall_ms * vcpus) AS vcpu_ms + FROM session_cpu WHERE ended_at >= ? AND active_cpu_ms IS NOT NULL + GROUP BY account_id` + ) + .bind(since) + .all<{ account_id: string; sessions: number; active_cpu_ms: number; vcpu_ms: number }>() + const pending = await db + .prepare('SELECT COUNT(*) AS n FROM session_cpu WHERE ended_at >= ? AND active_cpu_ms IS NULL') + .bind(since) + .first<{ n: number }>() + const accounts = results + .map((row): FairUseAccount => { + const vcpuMs = Number(row.vcpu_ms) || 0 + const activeCpuMs = Number(row.active_cpu_ms) || 0 + const ratio = vcpuMs > 0 ? activeCpuMs / vcpuMs : null + return { + accountId: row.account_id, + sessions: Number(row.sessions), + activeCpuMs, + vcpuMs, + cpuUtilization: ratio === null ? null : Math.round(ratio * 10_000) / 10_000, + fairUseFlag: ratio !== null && ratio > FAIR_USE_THRESHOLD + } + }) + .sort((a, b) => (b.cpuUtilization ?? -1) - (a.cpuUtilization ?? -1)) + return { windowDays, since, threshold: FAIR_USE_THRESHOLD, pendingSessions: Number(pending?.n ?? 0), accounts } +} + +function positive(value: number | null | undefined): number | null { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : null +} diff --git a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts index e8715bcac9b..088c66da934 100644 --- a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts +++ b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts @@ -8,6 +8,7 @@ import { type CommandResult, type ProviderSandboxState, type ProviderSession, + type ProviderSessionUsage, type SandboxProviderApi } from './sandbox-provider' @@ -26,7 +27,13 @@ const Session = z.looseObject({ id: z.string(), status: Status, startedAt: z.number().optional(), - timeout: z.number() + timeout: z.number(), + // Usage fields (SDK 3.9.1). activeCpuDurationMs only appears once the VM has stopped. + vcpus: z.number().optional(), + memory: z.number().optional(), + duration: z.number().optional(), + stoppedAt: z.number().optional(), + activeCpuDurationMs: z.number().optional() }) const Sandbox = z.looseObject({ name: z.string(), @@ -104,6 +111,15 @@ export function createVercelSandboxApi( startedAt: session.startedAt ?? null, timeoutMs: session.timeout }) + const toUsage = (session: z.infer): ProviderSessionUsage => ({ + sessionId: session.id, + status: session.status, + activeCpuMs: session.activeCpuDurationMs ?? null, + durationMs: session.duration ?? null, + vcpus: session.vcpus ?? null, + memoryMb: session.memory ?? null, + stoppedAt: session.stoppedAt ?? null + }) const toState = (body: z.infer): ProviderSandboxState => ({ sandbox: { name: body.sandbox.name, @@ -163,8 +179,22 @@ export function createVercelSandboxApi( async stopSession(sessionId) { const response = await request('POST', `/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}/stop`) - const body = await json(z.looseObject({ snapshot: Snapshot.optional() }), response) - return { snapshotId: body.snapshot?.id ?? null } + const body = await json(z.looseObject({ snapshot: Snapshot.optional(), session: z.unknown().optional() }), response) + // Usage is internal-only and best-effort: a session shape we can't read never fails the stop. + const session = Session.safeParse(body.session) + return { snapshotId: body.snapshot?.id ?? null, usage: session.success ? toUsage(session.data) : null } + }, + + async getSessionUsage(sessionId) { + try { + const response = await request('GET', `/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}`) + return toUsage((await json(z.looseObject({ session: Session }), response)).session) + } catch (error) { + if (error instanceof ProviderError && error.status === 404) { + return null + } + throw error + } }, async extendTimeout(sessionId, durationMs) { diff --git a/cloud/apps/sandbox-control/test/fake-vercel.ts b/cloud/apps/sandbox-control/test/fake-vercel.ts index abf4af00964..0162e3ed33f 100644 --- a/cloud/apps/sandbox-control/test/fake-vercel.ts +++ b/cloud/apps/sandbox-control/test/fake-vercel.ts @@ -83,6 +83,10 @@ export type FakeVercel = SandboxProviderApi & GoldenImageProviderApi & { snapshotExpirations: Map /** Simulates the provider ending a session at its timeout. */ expire(name: string): void + /** activeCpuDurationMs per session, as GET session reports it once stopped (stop answers without it). */ + sessionCpu: Map + /** GET session fails (provider outage) when set. */ + failSessionUsage: boolean } export function createFakeVercel(now: () => number): FakeVercel { @@ -122,6 +126,8 @@ export function createFakeVercel(now: () => number): FakeVercel { const buildCommands = new Map() const fake: FakeVercel = { + sessionCpu: new Map(), + failSessionUsage: false, boxes, snapshots, commands, @@ -222,7 +228,19 @@ export function createFakeVercel(now: () => number): FakeVercel { }, async stopSession(sessionId) { const box = bySession(sessionId) - return { snapshotId: box.status === 'running' ? stop(box) : null } + const startedAt = box.startedAt + const snapshotId = box.status === 'running' ? stop(box) : null + return { + snapshotId, + usage: { sessionId, status: 'stopped', activeCpuMs: null, durationMs: now() - startedAt, vcpus: box.params.vcpus, memoryMb: box.params.vcpus * 2048, stoppedAt: now() } + } + }, + async getSessionUsage(sessionId) { + if (fake.failSessionUsage) { + throw new ProviderError(503, null) + } + const cpu = fake.sessionCpu.get(sessionId) + return cpu === undefined ? null : { sessionId, status: 'stopped', activeCpuMs: cpu, durationMs: null, vcpus: null, memoryMb: null, stoppedAt: null } }, async extendTimeout(sessionId, durationMs) { const box = bySession(sessionId) diff --git a/cloud/apps/sandbox-control/test/session-cpu.test.ts b/cloud/apps/sandbox-control/test/session-cpu.test.ts new file mode 100644 index 00000000000..9288d5dfaaf --- /dev/null +++ b/cloud/apps/sandbox-control/test/session-cpu.test.ts @@ -0,0 +1,201 @@ +// U22: internal-only per-session CPU, fair-use report, and its operator gate. +import { describe, expect, it } from 'vitest' +import { FAIR_USE_THRESHOLD, fairUseReport, recordSessionEnd, sweepSessionCpu } from '../src/session-cpu' +import type { SandboxRow } from '../src/store' +import { createVercelSandboxApi } from '../src/vercel-sandbox-api' +import { createFakeD1 } from './d1-fake' +import { createHarness } from './harness' + +const OPERATOR = 'o'.repeat(40) +const MIN = 60_000 +const create = { workspaceId: 'ws-1', machineSize: 'standard' } + +async function operator(h: Awaited>, method: string, path: string) { + const response = await h.send( + new Request(`https://sandbox.test${path}`, { method, headers: { authorization: `Bearer ${OPERATOR}` } }) + ) + return { status: response.status, body: (await response.json()) as any } +} + +function client(answer: (url: URL, method: string) => Response) { + return createVercelSandboxApi({ + token: 'vercel_test_token', + teamId: 'team_orca', + projectId: 'prj_orca', + fetch: async (input, init) => answer(new URL(String(input)), init?.method ?? 'GET') + }) +} + +const stoppedSession = { + id: 'sess_1', + status: 'stopped', + startedAt: 1000, + timeout: 1_800_000, + memory: 16384, + vcpus: 8, + region: 'iad1', + duration: 600_000, + stoppedAt: 601_000, + activeCpuDurationMs: 123_456 +} + +describe('Vercel session usage mapping', () => { + it('maps activeCpuDurationMs, duration, vcpus and memory from GET session', async () => { + let seen: URL | null = null + const api = client((url) => ((seen = url), Response.json({ session: stoppedSession, routes: [] }))) + expect(await api.getSessionUsage!('sess_1')).toEqual({ + sessionId: 'sess_1', + status: 'stopped', + activeCpuMs: 123_456, + durationMs: 600_000, + vcpus: 8, + memoryMb: 16384, + stoppedAt: 601_000 + }) + expect(seen!.pathname).toBe('/api/v2/sandboxes/sessions/sess_1') + }) + + it('a running session has no CPU yet; a forgotten one is null', async () => { + const running = client(() => Response.json({ session: { id: 's', status: 'running', timeout: 1, vcpus: 8 } })) + expect(await running.getSessionUsage!('s')).toMatchObject({ activeCpuMs: null, vcpus: 8, durationMs: null }) + const gone = client(() => Response.json({ error: { code: 'not_found' } }, { status: 404 })) + expect(await gone.getSessionUsage!('s')).toBeNull() + }) + + it('reads usage off the stop response, and an unreadable session never fails the stop', async () => { + const withSession = client(() => Response.json({ session: stoppedSession, snapshot: { id: 'snap_1', status: 'created', sourceSessionId: 'sess_1' } })) + expect(await withSession.stopSession('sess_1')).toMatchObject({ snapshotId: 'snap_1', usage: { activeCpuMs: 123_456 } }) + const odd = client(() => Response.json({ session: { id: 7 }, snapshot: { id: 'snap_1', status: 'created', sourceSessionId: 'sess_1' } })) + expect(await odd.stopSession('sess_1')).toEqual({ snapshotId: 'snap_1', usage: null }) + }) +}) + +function row(overrides: Partial = {}): SandboxRow { + return { + id: 'sbx_1', + account_id: 'user:alice', + user_id: 'alice', + session_id: 'sess_1', + session_started_at: 1_000, + ...overrides + } as SandboxRow +} + +describe('session CPU storage', () => { + it('is idempotent per session and the first recorded CPU wins', async () => { + const { db, raw } = createFakeD1() + await recordSessionEnd(db, row(), 61_000, null, 61_000) + await recordSessionEnd(db, row(), 99_000, null, 99_000) + const usage = { sessionId: 'sess_1', status: 'stopped' as const, activeCpuMs: 30_000, durationMs: 60_000, vcpus: 8, memoryMb: 16384, stoppedAt: 61_000 } + await recordSessionEnd(db, row(), 99_000, usage, 100_000) + await recordSessionEnd(db, row(), 99_000, { ...usage, activeCpuMs: 1 }, 200_000) + const rows = raw.prepare('SELECT * FROM session_cpu').all() as any[] + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ session_id: 'sess_1', sandbox_id: 'sbx_1', account_id: 'user:alice', user_id: 'alice', ended_at: 61_000, active_cpu_ms: 30_000, wall_ms: 60_000, vcpus: 8, memory_mb: 16384, fetched_at: 100_000 }) + }) + + it('never throws, even when D1 does', async () => { + const broken = { prepare: () => { throw new Error('d1 down') } } as unknown as D1Database + await expect(recordSessionEnd(broken, row(), 1, null, 1)).resolves.toBeUndefined() + expect(await sweepSessionCpu(broken, { getSessionUsage: async () => null }, 1)).toEqual({ checked: 0, recorded: 0, failed: 0 }) + }) +}) + +describe('session CPU through the lifecycle', () => { + it('suspend records the session (wall time, vCPUs) without touching the meter; the sweep fills CPU later', async () => { + const h = await createHarness({ OPERATOR_TOKEN: OPERATOR }) + const { body } = await h.call('POST', '/v1/sandboxes', { body: create }) + const sessionId = [...h.vercel.boxes.values()][0]!.sessionId + h.advance(10 * MIN) + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200) + + const [recorded] = h.raw.prepare('SELECT * FROM session_cpu').all() as any[] + expect(recorded).toMatchObject({ session_id: sessionId, sandbox_id: body.sandbox.id, account_id: 'user:alice', vcpus: 8, wall_ms: 10 * MIN, active_cpu_ms: null }) + // Billing sees exactly the flat-hours segment, with no CPU anywhere in it. + expect(h.billing.usage).toHaveLength(1) + expect(Object.keys(h.billing.usage[0]!).sort()).toEqual(['accountId', 'endedAt', 'machineSize', 'sandboxId', 'startedAt', 'usageId', 'userId']) + + h.vercel.sessionCpu.set(sessionId, 4 * 8 * MIN) + expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body).toEqual({ sweep: { checked: 1, recorded: 1, failed: 0 } }) + expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body.sweep.checked).toBe(0) + const report = await operator(h, 'GET', '/v1/internal/fair-use') + expect(report.body.accounts).toEqual([ + { accountId: 'user:alice', sessions: 1, activeCpuMs: 32 * MIN, vcpuMs: 80 * MIN, cpuUtilization: 0.4, fairUseFlag: false } + ]) + }) + + it('a failing CPU fetch never blocks suspend or usage reporting; the sweep backs off', async () => { + const h = await createHarness({ OPERATOR_TOKEN: OPERATOR }) + const { body } = await h.call('POST', '/v1/sandboxes', { body: create }) + h.vercel.failSessionUsage = true + // Even a D1 table missing entirely must not fail the stop. + h.raw.exec('ALTER TABLE session_cpu RENAME TO session_cpu_hidden') + h.advance(5 * MIN) + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200) + expect(h.billing.usage).toHaveLength(1) + h.raw.exec('ALTER TABLE session_cpu_hidden RENAME TO session_cpu') + + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/resume`)).status).toBe(200) + h.advance(5 * MIN) + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200) + expect(h.billing.usage).toHaveLength(2) + expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body.sweep).toEqual({ checked: 1, recorded: 0, failed: 1 }) + expect((h.raw.prepare('SELECT attempts FROM session_cpu').get() as any).attempts).toBe(1) + }) + + it('a session the provider ended on its own is recorded too', async () => { + const h = await createHarness() + const { body } = await h.call('POST', '/v1/sandboxes', { body: create }) + const box = [...h.vercel.boxes.values()][0]! + h.advance(31 * MIN) + h.vercel.expire(box.params.name) + await h.reconcile() + expect(h.raw.prepare('SELECT sandbox_id, wall_ms FROM session_cpu').all()).toEqual([{ sandbox_id: body.sandbox.id, wall_ms: 30 * MIN }]) + }) +}) + +describe('fair-use report', () => { + async function seed(db: D1Database, account: string, session: string, wallMs: number, vcpus: number, cpuMs: number | null, endedAt: number) { + await recordSessionEnd(db, row({ id: `sbx_${session}`, account_id: account, session_id: session, session_started_at: endedAt - wallMs }), endedAt, null, endedAt) + if (cpuMs !== null) { + await recordSessionEnd(db, row({ session_id: session }), endedAt, { sessionId: session, status: 'stopped', activeCpuMs: cpuMs, durationMs: wallMs, vcpus, memoryMb: null, stoppedAt: endedAt }, endedAt) + } + } + + it('averages active CPU over wall × vCPUs per account and flags only above 60%', async () => { + const { db } = createFakeD1() + const now = 100 * 24 * 60 * MIN + const hour = 60 * MIN + await seed(db, 'org:heavy', 'h1', hour, 8, 6 * hour, now - hour) // 75% + await seed(db, 'org:heavy', 'h2', hour, 8, 4 * hour, now - 2 * hour) // 50% → combined 62.5% + await seed(db, 'org:edge', 'e1', hour, 8, 4.8 * hour, now - hour) // exactly 60%: not over + await seed(db, 'user:light', 'l1', 2 * hour, 4, 0.8 * hour, now - hour) // 10% + await seed(db, 'user:light', 'old', hour, 8, 8 * hour, now - 31 * 24 * hour) // outside the window + await seed(db, 'user:light', 'pending', hour, 8, null, now - hour) // no CPU yet: excluded + const report = await fairUseReport(db, now) + expect(report).toMatchObject({ windowDays: 30, threshold: FAIR_USE_THRESHOLD, pendingSessions: 1 }) + expect(report.accounts.map((a) => [a.accountId, a.sessions, a.cpuUtilization, a.fairUseFlag])).toEqual([ + ['org:heavy', 2, 0.625, true], + ['org:edge', 1, 0.6, false], + ['user:light', 1, 0.1, false] + ]) + expect(report.accounts[0]).toMatchObject({ activeCpuMs: 10 * hour, vcpuMs: 16 * hour }) + }) +}) + +describe('fair-use auth gate', () => { + it('refuses customer tokens, wrong tokens and an unset operator token; accepts the operator', async () => { + const h = await createHarness({ OPERATOR_TOKEN: OPERATOR }) + expect((await h.call('GET', '/v1/internal/fair-use')).status).toBe(404) + expect((await h.call('GET', '/v1/internal/fair-use', { bearer: 'x'.repeat(40) })).status).toBe(404) + expect((await h.call('POST', '/v1/internal/session-cpu/sweep')).status).toBe(404) + expect((await operator(h, 'GET', '/v1/internal/fair-use')).body).toMatchObject({ windowDays: 30, accounts: [] }) + expect((await operator(h, 'GET', '/v1/internal/fair-use?days=0')).status).toBe(400) + + const closed = await createHarness() + const response = await closed.send( + new Request('https://sandbox.test/v1/internal/fair-use', { headers: { authorization: `Bearer ${OPERATOR}` } }) + ) + expect(response.status).toBe(404) + }) +}) From f8e362259a02422c60f5cf59109ff6ec5250507b Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:34:04 -0800 Subject: [PATCH 42/46] fix(cloud): harden agent secret requests (review of #214) - Agent and worktree come from the terminal orcad verifies from launch evidence (verifiedCallerTerminalHandle, shared with turn-sender); the terminalHandle param is gone and a worktree hint is kept only when the host knows it. - secrets.* are accepted, and their events sent, only on cloud orcad (ORCA_IS_CLOUD=1 + ORCA_SANDBOX_ID); already-set never reads orcad's env. - touchRequest emits secrets.requestUpdated; natural expiry emits secrets.requestSettled {status: expired}. - orca-env skips the control plane's reserved names and prefixes, with a test that reads them from secrets.ts. - reason drops bidi controls and turns C0/C1 controls into spaces. --- .../image/vm-scripts.generated.ts | 2 +- cloud/apps/sandbox-control/image/vm/orca-env | 14 +++- .../sandbox-control/test/orca-env.test.ts | 15 +++- src/cli/handlers/secret.test.ts | 6 +- src/cli/handlers/secret.ts | 10 +-- .../orchestration-compatibility-envelope.ts | 7 ++ .../orchestration-request-evidence.test.ts | 37 +++++++++ src/main/runtime/orca-runtime.ts | 5 ++ .../client-events-secret-requests.test.ts | 37 ++++++++- .../methods/client-events/client-events.ts | 10 ++- .../rpc/methods/orchestration/turn-sender.ts | 20 ++++- .../methods/secrets/secret-requests.test.ts | 76 ++++++++++++------- .../rpc/methods/secrets/secret-requests.ts | 60 ++++++++++----- .../secrets/secret-request-store.test.ts | 55 +++++++++++++- .../runtime/secrets/secret-request-store.ts | 54 ++++++++++++- .../runtime/secrets/session-env-names.test.ts | 21 +++-- src/main/runtime/secrets/session-env-names.ts | 43 ++++++----- src/shared/runtime-client-events.ts | 7 +- src/shared/secret-request-contract.ts | 35 +++++++-- 19 files changed, 410 insertions(+), 104 deletions(-) diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 95d3c12bf5a..258c1eac2f2 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -3,7 +3,7 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0","opencode-ai@1.19.5","@google/gemini-cli@0.67.0","@github/copilot@1.0.108"],"cursorAgent":{"version":"2026.11.05-86047df","sha256":"170b77786cbf4c93064d64fff12b71a178b968730561c64afc2e8e752535442e"},"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers\n # shells that were already open).\n sudo install -d -m 0755 /etc/zsh\n sudo touch /etc/zsh/zshenv\n grep -q zz-orca-session-env /etc/zsh/zshenv ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" -export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\nskip_name() {\n case \"$1\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) return 0 ;; esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline }) {\n const timeLeft = () => deadline - Date.now()\n const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })])\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : []\n // Newest activity first; chats with nothing in them still list (agent + status).\n const picked = summaries\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n const { messages, hasOlder } = messagesOf(history)\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: str(s.agent, 40),\n title: str(s.conversationName, 200) || str(s.latestPrompt, 200),\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: str(s.turnOutcome, 40),\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline }))\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN | CLAUDE_CODE_OAUTH_TOKEN) return 0 ;;\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline }) {\n const timeLeft = () => deadline - Date.now()\n const [statusFeed, ps] = await Promise.all([call('agentSession.subscribeStatus', null), call('worktree.ps', { limit: 20 })])\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const summaries = isObj(statusFeed) && Array.isArray(statusFeed.sessions) ? statusFeed.sessions.filter(isObj) : []\n // Newest activity first; chats with nothing in them still list (agent + status).\n const picked = summaries\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n const { messages, hasOlder } = messagesOf(history)\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: str(s.agent, 40),\n title: str(s.conversationName, 200) || str(s.latestPrompt, 200),\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: str(s.turnOutcome, 40),\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline }))\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-env b/cloud/apps/sandbox-control/image/vm/orca-env index 75ccbdc16a4..32f08c4c013 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-env +++ b/cloud/apps/sandbox-control/image/vm/orca-env @@ -36,8 +36,20 @@ quote() { fi } +# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test +# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes. skip_name() { - case "$1" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) return 0 ;; esac + case "$1" in + '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;; + LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;; + PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \ + BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \ + NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \ + CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \ + PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \ + GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \ + GH_TOKEN | GITHUB_TOKEN | CLAUDE_CODE_OAUTH_TOKEN) return 0 ;; + esac return 1 } diff --git a/cloud/apps/sandbox-control/test/orca-env.test.ts b/cloud/apps/sandbox-control/test/orca-env.test.ts index 04bdaec37af..74f5e3d5f48 100644 --- a/cloud/apps/sandbox-control/test/orca-env.test.ts +++ b/cloud/apps/sandbox-control/test/orca-env.test.ts @@ -2,7 +2,7 @@ // env file. Values must survive quoting exactly (quotes, newlines, $, backslashes) in POSIX shells // and fish, and names that were removed must be unset. import { spawnSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -116,6 +116,19 @@ describe('orca-env', () => { expect(out).toBe("export GOOD='x'\nexport ORCA_SESSION_ENV_NAMES='GOOD'\n") }) + it("never sets or unsets the control plane's reserved names and prefixes (kept in sync with secrets.ts)", () => { + const source = readFileSync(fileURLToPath(new URL('../src/secrets.ts', import.meta.url).href), 'utf8') + const quoted = (text: string | undefined): string[] => [...(text ?? '').matchAll(/'([A-Z0-9_]+)'/g)].map((m) => m[1]) + const names = quoted(source.match(/const RESERVED_NAMES[^=]*= new Set\(\[([\s\S]*?)\]\)/)?.[1]) + const prefixes = quoted(source.match(/const RESERVED_PREFIXES = \[([^\]]*)\]/)?.[1]) + expect(names.length).toBeGreaterThan(30) + expect(prefixes.length).toBeGreaterThan(3) + const blocked = [...names, ...prefixes.map((prefix) => `${prefix}X`)] + writeSessionEnv({ GOOD: 'x', ...Object.fromEntries(blocked.map((name) => [name, 'evil'])) }) + const out = orcaEnv([], blocked.join(' ')) + expect(out).toBe("export GOOD='x'\nexport ORCA_SESSION_ENV_NAMES='GOOD'\n") + }) + it('prints nothing before the session env exists and never writes a file', () => { const result = spawnSync('bash', [ORCA_ENV], { encoding: 'utf8', diff --git a/src/cli/handlers/secret.test.ts b/src/cli/handlers/secret.test.ts index c41851a576b..e7196f317df 100644 --- a/src/cli/handlers/secret.test.ts +++ b/src/cli/handlers/secret.test.ts @@ -41,12 +41,11 @@ const base: SecretRequestCliInput = { reason: 'Run the checkout tests', waitSec: null, json: false, - terminalHandle: 'term-1', worktreeId: 'wt-1' } describe('orca secret request', () => { - it('sends the terminal handle so orcad can name the agent, and never an agent name', async () => { + it('names no terminal or agent: orcad derives them from verified launch evidence', async () => { const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } }) await runSecretRequest({ ...base, scope: 'repo' }, h.deps) expect(h.calls[0]).toEqual({ @@ -55,8 +54,7 @@ describe('orca secret request', () => { name: 'STRIPE_KEY', reason: 'Run the checkout tests', scope: 'repo', - worktreeId: 'wt-1', - terminalHandle: 'term-1' + worktreeId: 'wt-1' } }) }) diff --git a/src/cli/handlers/secret.ts b/src/cli/handlers/secret.ts index 2b13825fd80..ba89eb2e672 100644 --- a/src/cli/handlers/secret.ts +++ b/src/cli/handlers/secret.ts @@ -33,7 +33,6 @@ export type SecretRequestCliInput = { scope?: SecretRequestScope waitSec: number | null json: boolean - terminalHandle?: string worktreeId?: string } @@ -46,8 +45,8 @@ export async function runSecretRequest( name: input.name, reason: input.reason, ...(input.scope ? { scope: input.scope } : {}), - ...(input.worktreeId ? { worktreeId: input.worktreeId } : {}), - ...(input.terminalHandle ? { terminalHandle: input.terminalHandle } : {}) + // The calling terminal (and so the agent) travels as launch evidence that orcad verifies. + ...(input.worktreeId ? { worktreeId: input.worktreeId } : {}) } let created: SecretsRequestResult try { @@ -136,7 +135,9 @@ const ERROR_MESSAGES: Record string> = { [SECRET_REQUEST_ERRORS.tooManyPending]: () => 'This workspace already has 3 secret requests waiting. Wait for one to be answered.', [SECRET_REQUEST_ERRORS.rateLimited]: () => - 'This workspace asked for 10 secrets in the last hour. Try again later.' + 'This workspace asked for 10 secrets in the last hour. Try again later.', + [SECRET_REQUEST_ERRORS.unavailable]: () => + 'Secret requests work only inside an Orca Cloud workspace.' } function explainRequestError(error: unknown, name: string): unknown { @@ -185,7 +186,6 @@ export const SECRET_HANDLERS: Record = { scope: parseScope(getOptionalStringFlag(flags, 'scope')), waitSec: parseSecretRequestWait(flags.get('wait')), json, - terminalHandle: process.env.ORCA_TERMINAL_HANDLE || undefined, worktreeId: process.env.ORCA_WORKTREE_ID || undefined }, { diff --git a/src/cli/runtime/orchestration-compatibility-envelope.ts b/src/cli/runtime/orchestration-compatibility-envelope.ts index be78e8dee2f..84fbd908309 100644 --- a/src/cli/runtime/orchestration-compatibility-envelope.ts +++ b/src/cli/runtime/orchestration-compatibility-envelope.ts @@ -28,6 +28,8 @@ export function createAgentLaunchCallerEvidence( } const AGENT_LAUNCH_METHODS: ReadonlySet = new Set(['agent.launch', 'agent.launchReplay']) +/** Methods where orcad names the calling terminal (and its agent) from the shell's launch evidence. */ +const TERMINAL_CALLER_METHODS: ReadonlySet = new Set(['secrets.request']) /** The caller evidence one request carries, read from this process's environment once. */ export class OrchestrationRequestEvidence { @@ -58,6 +60,11 @@ export class OrchestrationRequestEvidence { compatibilityInvocationId: request.requestId ?? base.compatibilityInvocationId } } + if (TERMINAL_CALLER_METHODS.has(method)) { + // Terminal evidence only: it identifies a caller on this host, never on a remote server. + const shell = this.remoteRead.orchestrationCompatibilityEvidence + return request.remote || !shell ? {} : { orchestrationCompatibilityEvidence: shell } + } return AGENT_LAUNCH_METHODS.has(method) && !request.remote && this.agentLaunchCaller ? { orchestrationCompatibilityEvidence: this.agentLaunchCaller } : {} diff --git a/src/cli/runtime/orchestration-request-evidence.test.ts b/src/cli/runtime/orchestration-request-evidence.test.ts index aceef390bc2..9d5d3407068 100644 --- a/src/cli/runtime/orchestration-request-evidence.test.ts +++ b/src/cli/runtime/orchestration-request-evidence.test.ts @@ -26,3 +26,40 @@ describe('caller evidence on requests to another server', () => { ).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' }) }) }) + +describe('terminal evidence on secret requests', () => { + const SHELL = { + ...CHAT, + ORCA_TERMINAL_HANDLE: 'term_1', + ORCA_PANE_KEY: 'tab:leaf', + ORCA_AGENT_LAUNCH_TOKEN: 'tok' + } + + it('sends the shell evidence (never the chat id) to this host so orcad can verify the caller', () => { + const evidence = new OrchestrationRequestEvidence(SHELL) + expect( + evidence.envelopeFor('secrets.request', { + remote: false, + mutation: false, + requestId: undefined + }) + ).toEqual({ + orchestrationCompatibilityEvidence: { + terminalHandle: 'term_1', + paneKey: 'tab:leaf', + launchToken: 'tok' + } + }) + }) + + it('sends nothing to another server', () => { + const evidence = new OrchestrationRequestEvidence(SHELL) + expect( + evidence.envelopeFor('secrets.request', { + remote: true, + mutation: false, + requestId: undefined + }) + ).toEqual({}) + }) +}) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 933d167a211..67066396178 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -327,6 +327,11 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { } } + /** Whether this host knows a worktree by id (a caller's hint is kept only when it does). */ + async isKnownWorktree(worktreeId: string): Promise { + return (await this.getResolvedWorktreeMap()).has(worktreeId) + } + /** Return the already-open record store without waiting. */ openedAgentSessionRecordStore(): AgentSessionRecordStore | null { return peekOpenedAgentSessionRecordStore() diff --git a/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts b/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts index 147109b0da2..6823510f6c5 100644 --- a/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts +++ b/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts @@ -1,4 +1,4 @@ -import { expect, it } from 'vitest' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../../../orca-runtime' import { getSecretRequestStore } from '../../../secrets/secret-request-store' import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../../core' @@ -24,6 +24,15 @@ function makeRuntime(): { runtime: OrcaRuntimeService; cleanups: (() => void)[] return { runtime: fake as unknown as OrcaRuntimeService, cleanups } } +beforeEach(() => { + vi.stubEnv('ORCA_IS_CLOUD', '1') + vi.stubEnv('ORCA_SANDBOX_ID', 'sbx_test') +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + const secretEvents = (events: unknown[]): Record[] => events.filter( (event): event is Record => @@ -34,6 +43,32 @@ const secretEvents = (events: unknown[]): Record[] => event.type.startsWith('secrets.') ) +it('sends no secret requests from a desktop runtime', async () => { + vi.stubEnv('ORCA_IS_CLOUD', '') + if (!subscribeMethod) { + throw new Error('runtime.clientEvents.subscribe is not a streaming method') + } + getSecretRequestStore().request({ + name: 'LOCAL_ONLY', + reason: 'r', + agent: null, + worktreeId: null, + terminalHandle: null, + sessionEnvNames: new Set() + }) + const { runtime, cleanups } = makeRuntime() + const seen: unknown[] = [] + const done = subscribeMethod.handler( + {}, + { runtime, connectionId: 'conn-0', clientKind: 'runtime' }, + (event) => seen.push(event) + ) + expect(secretEvents(seen)).toEqual([]) + cleanups.forEach((cleanup) => cleanup()) + await done + getSecretRequestStore().resolve(getSecretRequestStore().pendingEvents()[0].requestId, 'declined') +}) + it('registers the secrets.* methods', () => { const names = methods.map((method) => method.name) for (const name of [ diff --git a/src/main/runtime/rpc/methods/client-events/client-events.ts b/src/main/runtime/rpc/methods/client-events/client-events.ts index 1f06c6f28fc..ed23408c727 100644 --- a/src/main/runtime/rpc/methods/client-events/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events/client-events.ts @@ -21,6 +21,7 @@ import { phoneSecretRequestEvent, type SecretRequestStoreEvent } from '../../../secrets/secret-request-store' +import { isCloudWorkspaceOrcad } from '../../../secrets/session-env-names' let clientEventSubscriptionSeq = 0 @@ -68,8 +69,9 @@ export const CLIENT_EVENT_METHODS = [ // Agent secret requests (secrets.requested): phones get status only. const emitSecretRequest = (event: SecretRequestStoreEvent): void => emit(clientKind === 'mobile' ? phoneSecretRequestEvent(event) : event) - const secretRequests = getSecretRequestStore() - const unsubscribeSecretRequests = secretRequests.subscribe(emitSecretRequest) + // Only a cloud workspace's orcad takes secret requests. + const secretRequests = isCloudWorkspaceOrcad() ? getSecretRequestStore() : null + const unsubscribeSecretRequests = secretRequests?.subscribe(emitSecretRequest) const seq = ++clientEventSubscriptionSeq const subscriptionId = `runtime-client-events-${connectionId ?? 'inproc'}-${seq}` @@ -79,7 +81,7 @@ export const CLIENT_EVENT_METHODS = [ unsubscribe() unregisterHostVolunteer?.() unsubscribeTelemetry?.() - unsubscribeSecretRequests() + unsubscribeSecretRequests?.() emit({ type: 'end' }) resolve() }, @@ -88,7 +90,7 @@ export const CLIENT_EVENT_METHODS = [ // Listen before snapshotting to close the subscribe race and replay sleep state missed during disconnect. // Requests made while no client was attached wait here until they expire. - for (const event of secretRequests.pendingEvents()) { + for (const event of secretRequests?.pendingEvents() ?? []) { emitSecretRequest(event) } for (const event of runtime.getTerminalSleepClientEventSnapshot?.() ?? []) { diff --git a/src/main/runtime/rpc/methods/orchestration/turn-sender.ts b/src/main/runtime/rpc/methods/orchestration/turn-sender.ts index 696926a4499..891582cf604 100644 --- a/src/main/runtime/rpc/methods/orchestration/turn-sender.ts +++ b/src/main/runtime/rpc/methods/orchestration/turn-sender.ts @@ -24,6 +24,21 @@ function plainTerminalHandle(ctx: RpcContext): string | null { return terminal && !terminal.launchTokenHash && terminal.paneKey === paneKey ? handle : null } +/** + * The terminal an agent's own CLI call came from, as orcad attests it: a token-launched terminal + * proves its launch token, a plain one must match handle and pane key. Never read from params. + */ +export function verifiedCallerTerminalHandle(ctx: RpcContext): string | null { + // Agents reach orcad through the local CLI only; paired devices are people, not agents. + if (ctx.caller?.kind !== 'local-cli') { + return null + } + const authority = ctx.runtime.verifyOrchestrationCompatibilityCaller( + ctx.orchestrationCompatibilityEvidence + ) + return authority?.terminalHandle ?? plainTerminalHandle(ctx) +} + /** * Who drove me? For an agent's own tools: the caller is the terminal or structured session orcad * attests from its launch evidence, so one agent can never read (or claim) another agent's sender. @@ -40,10 +55,7 @@ function turnSender(ctx: RpcContext): TurnSenderResult { sender: drivingDeviceFor(agentSessionSenderKey(sessionId)) } } - const authority = ctx.runtime.verifyOrchestrationCompatibilityCaller( - ctx.orchestrationCompatibilityEvidence - ) - const handle = authority?.terminalHandle ?? plainTerminalHandle(ctx) + const handle = verifiedCallerTerminalHandle(ctx) if (!handle) { return { caller: null, sender: null } } diff --git a/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts b/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts index 1bdcbc8ca64..fa06681e83d 100644 --- a/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts +++ b/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts @@ -5,22 +5,31 @@ import type { RpcContext, RpcMethod } from '../../core' import { eraseRpcMethods } from '../../core' import { createSecretRequestMethods } from './secret-requests' -function setup(sessionEnv: string[] = []) { +/** `verified` stands in for the terminal orcad attests from launch evidence. */ +function setup( + options: { sessionEnv?: string[]; enabled?: boolean; verified?: string | null } = {} +) { let seq = 0 const store = new SecretRequestStore(Date.now, () => `sr_rpc${String(++seq).padStart(5, '0')}`) const methods = new Map( eraseRpcMethods( createSecretRequestMethods({ store: () => store, - sessionEnvNames: async () => new Set(sessionEnv) + sessionEnvNames: async () => new Set(options.sessionEnv ?? []), + enabled: () => options.enabled ?? true, + callerTerminal: (ctx) => + ctx.caller?.kind === 'local-cli' ? (options.verified ?? null) : null }) ).map((method) => [method.name, method]) ) const terminals: Record = { 'term-codex': { agent: 'codex', worktreeId: 'wt-real' } } - const fake = { getTerminalHandleAgent: (handle: string) => terminals[handle] ?? null } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handlers read only getTerminalHandleAgent. + const fake = { + getTerminalHandleAgent: (handle: string) => terminals[handle] ?? null, + isKnownWorktree: async (id: string) => id === 'wt-known' + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handlers read only these members. const runtime = fake as unknown as OrcaRuntimeService const call = async (name: string, params: unknown, ctx: Partial = {}) => { const method = methods.get(name) @@ -39,17 +48,12 @@ const desktop: Partial = { caller: { kind: 'paired-device', deviceId const agentCli: Partial = { caller: { kind: 'local-cli' } } describe('secrets.* RPC', () => { - it('derives the agent and worktree from the calling terminal, not from params', async () => { - const { call, events } = setup() + it('derives the agent and worktree from the verified calling terminal', async () => { + const { call, events } = setup({ verified: 'term-codex' }) await expect( call( 'secrets.request', - { - name: 'STRIPE_KEY', - reason: 'tests', - terminalHandle: 'term-codex', - worktreeId: 'wt-hint' - }, + { name: 'STRIPE_KEY', reason: 'tests', worktreeId: 'wt-known' }, agentCli ) ).resolves.toEqual({ requestId: 'sr_rpc00001', status: 'pending' }) @@ -60,22 +64,36 @@ describe('secrets.* RPC', () => { }) }) - it('leaves the agent unknown for an unrecognized terminal and refuses a caller-named agent', async () => { - const { call, events } = setup() - await call( - 'secrets.request', - { name: 'A', reason: 'r', terminalHandle: 'forged', worktreeId: 'wt-hint' }, - agentCli - ) - expect(events[0]).toMatchObject({ agent: null, worktreeId: 'wt-hint' }) + it('takes no terminal or agent from params', async () => { + const { call } = setup() + for (const extra of [{ terminalHandle: 'term-codex' }, { agent: 'claude' }]) { + await expect( + call('secrets.request', { name: 'A', reason: 'r', ...extra }, agentCli) + ).rejects.toThrow() + } + }) + + it('without a verified terminal: agent unknown, worktree hint kept only if this host knows it', async () => { + const { call, events } = setup({ verified: null }) + await call('secrets.request', { name: 'A', reason: 'r', worktreeId: 'wt-known' }, agentCli) + await call('secrets.request', { name: 'B', reason: 'r', worktreeId: 'wt-made-up' }, agentCli) + expect(events[0]).toMatchObject({ agent: null, worktreeId: 'wt-known' }) expect(events[0]).not.toHaveProperty('terminalHandle') + expect(events[1]).toMatchObject({ agent: null, worktreeId: null }) + }) + + it('refuses every method outside a cloud workspace orcad', async () => { + const { call } = setup({ enabled: false }) + await expect(call('secrets.request', { name: 'A', reason: 'r' })).rejects.toThrow( + 'secret_requests_unavailable' + ) await expect( - call('secrets.request', { name: 'B', reason: 'r', agent: 'claude' }, agentCli) - ).rejects.toThrow() + call('secrets.requestStatus', { requestId: 'sr_rpc00001' }, desktop) + ).rejects.toThrow('secret_requests_unavailable') }) it('answers already-set from the session env and refuses agent credentials', async () => { - const { call } = setup(['SENTRY_DSN']) + const { call } = setup({ sessionEnv: ['SENTRY_DSN'] }) await expect(call('secrets.request', { name: 'SENTRY_DSN', reason: 'r' })).resolves.toEqual({ requestId: null, status: 'already-set' @@ -85,9 +103,15 @@ describe('secrets.* RPC', () => { ).rejects.toThrow('use_sign_in_or_cloud_secrets') }) - it('rejects a reason over 200 characters', async () => { - const { call } = setup() - await expect(call('secrets.request', { name: 'A', reason: 'x'.repeat(201) })).rejects.toThrow() + it('strips control and bidi characters from the reason, and caps it at 200 characters', async () => { + const { call, events } = setup() + await call('secrets.request', { + name: 'A', + reason: 'Run‮ the\ntests\u0007 ⁦now⁩\u001b[31m' + }) + expect(events[0]).toMatchObject({ reason: 'Run the tests now [31m' }) + await expect(call('secrets.request', { name: 'B', reason: 'x'.repeat(201) })).rejects.toThrow() + await expect(call('secrets.request', { name: 'C', reason: '‮\n\u0000' })).rejects.toThrow() }) it('lets a person, never the agent CLI, touch and resolve; anyone reads status', async () => { diff --git a/src/main/runtime/rpc/methods/secrets/secret-requests.ts b/src/main/runtime/rpc/methods/secrets/secret-requests.ts index d489f188fbd..3d52f1afd64 100644 --- a/src/main/runtime/rpc/methods/secrets/secret-requests.ts +++ b/src/main/runtime/rpc/methods/secrets/secret-requests.ts @@ -17,31 +17,42 @@ import { SecretRequestError, type SecretRequestStore } from '../../../secrets/secret-request-store' -import { readSessionEnvNames } from '../../../secrets/session-env-names' +import { isCloudWorkspaceOrcad, readSessionEnvNames } from '../../../secrets/session-env-names' import { defineMethod, type RpcContext } from '../../core' import { isAgentRpcCaller } from '../../rpc-caller-identity' +import { verifiedCallerTerminalHandle } from '../orchestration/turn-sender' export type SecretRequestDeps = { store: () => SecretRequestStore sessionEnvNames: () => Promise> + /** Only a cloud workspace's orcad takes requests; a desktop's local runtime refuses them. */ + enabled: () => boolean + /** The terminal the call came from, as orcad verifies it. */ + callerTerminal: (ctx: RpcContext) => string | null } const defaultDeps: SecretRequestDeps = { store: getSecretRequestStore, - sessionEnvNames: () => readSessionEnvNames() + sessionEnvNames: () => readSessionEnvNames(), + enabled: () => isCloudWorkspaceOrcad(), + callerTerminal: verifiedCallerTerminalHandle } -type TerminalAgentLookup = Pick +type CallerRuntime = Pick -/** The agent comes from the calling terminal's own session record; the caller can't name one. */ -export function callerTerminalIdentity( - runtime: TerminalAgentLookup, - terminalHandle: string | undefined -): { agent: string | null; worktreeId: string | null } | null { - if (!terminalHandle) { - return null +/** Agent and worktree from the verified calling terminal; a worktree hint only if this host knows it. */ +export async function resolveSecretRequestCaller( + runtime: CallerRuntime, + terminalHandle: string | null, + worktreeHint: string | undefined +): Promise<{ agent: string | null; worktreeId: string | null; terminalHandle: string | null }> { + const terminal = terminalHandle ? runtime.getTerminalHandleAgent(terminalHandle) : null + if (terminal) { + return { agent: terminal.agent, worktreeId: terminal.worktreeId, terminalHandle } } - return runtime.getTerminalHandleAgent(terminalHandle) + const worktreeId = + worktreeHint && (await runtime.isKnownWorktree(worktreeHint)) ? worktreeHint : null + return { agent: null, worktreeId, terminalHandle: null } } /** Only a person's client (desktop or paired device) answers a request, never the agent's own CLI. */ @@ -52,21 +63,30 @@ function requirePersonCaller(ctx: Pick): void { } export function createSecretRequestMethods(deps: SecretRequestDeps = defaultDeps) { + // Registered everywhere so the RPC catalog is one shape; accepted only on cloud orcad. + const store = (): SecretRequestStore => { + if (!deps.enabled()) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.unavailable) + } + return deps.store() + } return [ defineMethod({ name: SECRETS_REQUEST_METHOD, permission: 'workspace', params: SecretsRequestParamsSchema, handler: async (params, ctx): Promise => { - const identity = callerTerminalIdentity(ctx.runtime, params.terminalHandle) - return deps.store().request({ + const requests = store() + const caller = await resolveSecretRequestCaller( + ctx.runtime, + deps.callerTerminal(ctx), + params.worktreeId + ) + return requests.request({ name: params.name, reason: params.reason, scope: params.scope, - agent: identity?.agent ?? null, - // A resolved terminal names its own worktree; otherwise take the hint. - worktreeId: identity?.worktreeId ?? params.worktreeId ?? null, - terminalHandle: identity ? (params.terminalHandle ?? null) : null, + ...caller, sessionEnvNames: await deps.sessionEnvNames() }) } @@ -76,7 +96,7 @@ export function createSecretRequestMethods(deps: SecretRequestDeps = defaultDeps permission: 'workspace', params: SecretsRequestIdParamsSchema, handler: async (params): Promise => - deps.store().status(params.requestId) + store().status(params.requestId) }), defineMethod({ name: SECRETS_TOUCH_REQUEST_METHOD, @@ -84,7 +104,7 @@ export function createSecretRequestMethods(deps: SecretRequestDeps = defaultDeps params: SecretsRequestIdParamsSchema, handler: async (params, ctx): Promise => { requirePersonCaller(ctx) - return deps.store().touch(params.requestId) + return store().touch(params.requestId) } }), defineMethod({ @@ -93,7 +113,7 @@ export function createSecretRequestMethods(deps: SecretRequestDeps = defaultDeps params: SecretsResolveRequestParamsSchema, handler: async (params, ctx): Promise => { requirePersonCaller(ctx) - return deps.store().resolve(params.requestId, params.outcome) + return store().resolve(params.requestId, params.outcome) } }) ] diff --git a/src/main/runtime/secrets/secret-request-store.test.ts b/src/main/runtime/secrets/secret-request-store.test.ts index 5842aa45746..e38a832e32f 100644 --- a/src/main/runtime/secrets/secret-request-store.test.ts +++ b/src/main/runtime/secrets/secret-request-store.test.ts @@ -13,13 +13,33 @@ const MIN = 60_000 function makeStore() { const clock = { now: 1_000_000 } let seq = 0 + const timers: { at: number; run: () => void; cancelled: boolean }[] = [] const store = new SecretRequestStore( () => clock.now, - () => `sr_test${String(++seq).padStart(4, '0')}` + () => `sr_test${String(++seq).padStart(4, '0')}`, + (run, ms) => { + const timer = { at: clock.now + ms, run, cancelled: false } + timers.push(timer) + return { cancel: () => (timer.cancelled = true) } + } ) const events: SecretRequestStoreEvent[] = [] store.subscribe((event) => events.push(event)) - return { store, clock, events } + /** Moves the clock and fires due timers. */ + const advance = (ms: number): void => { + clock.now += ms + for (const timer of timers.splice(0)) { + if (timer.cancelled) { + continue + } + if (timer.at <= clock.now) { + timer.run() + } else { + timers.push(timer) + } + } + } + return { store, clock, events, advance } } function input(name: string, extra: Partial = {}): SecretRequestInput { @@ -195,4 +215,35 @@ describe('SecretRequestStore', () => { expect(phone).not.toHaveProperty('terminalHandle') expect(phone).toMatchObject({ name: 'A', agent: 'claude', requestId: event.requestId }) }) + + it('announces a touch, and a natural expiry (at the touched time), to every client', () => { + const { store, events, advance } = makeStore() + store.request(input('TOKEN')) + advance(10 * MIN) + store.touch('sr_test0001') + expect(events.at(-1)).toEqual({ + type: 'secrets.requestUpdated', + requestId: 'sr_test0001', + expiresAt: 1_000_000 + 25 * MIN + }) + // The original 15-minute expiry no longer fires. + advance(6 * MIN) + expect(events.filter((e) => e.type === 'secrets.requestSettled')).toEqual([]) + advance(9 * MIN) + expect(events.at(-1)).toEqual({ + type: 'secrets.requestSettled', + requestId: 'sr_test0001', + status: 'expired' + }) + }) + + it('announces no expiry for an answered request', () => { + const { store, events, advance } = makeStore() + store.request(input('TOKEN')) + store.resolve('sr_test0001', 'provided') + advance(20 * MIN) + expect(events.filter((e) => e.type === 'secrets.requestSettled')).toEqual([ + { type: 'secrets.requestSettled', requestId: 'sr_test0001', status: 'provided' } + ]) + }) }) diff --git a/src/main/runtime/secrets/secret-request-store.ts b/src/main/runtime/secrets/secret-request-store.ts index 086fa90244e..4201e9af520 100644 --- a/src/main/runtime/secrets/secret-request-store.ts +++ b/src/main/runtime/secrets/secret-request-store.ts @@ -6,10 +6,12 @@ import { SECRET_REQUEST_MAX_PER_HOUR, SECRET_REQUEST_TTL_MS, SECRETS_REQUEST_SETTLED_EVENT, + SECRETS_REQUEST_UPDATED_EVENT, SECRETS_REQUESTED_EVENT, type SecretRequestedEvent, type SecretRequestScope, type SecretRequestSettledEvent, + type SecretRequestUpdatedEvent, type SecretRequestStatus, type SecretsRequestResult, type SecretsRequestStatusResult, @@ -52,17 +54,32 @@ export type SecretRequestInput = { sessionEnvNames: ReadonlySet } -export type SecretRequestStoreEvent = SecretRequestedEvent | SecretRequestSettledEvent +export type SecretRequestStoreEvent = + | SecretRequestedEvent + | SecretRequestUpdatedEvent + | SecretRequestSettledEvent + +/** Schedules `run` after `ms`; the result cancels it. */ +export type SecretRequestTimer = (run: () => void, ms: number) => { cancel: () => void } + +const realTimer: SecretRequestTimer = (run, ms) => { + const handle = setTimeout(run, ms) + // A pending request must never keep orcad alive. + handle.unref?.() + return { cancel: () => clearTimeout(handle) } +} /** In-memory only (never on disk): one orcad serves one cloud workspace, so limits and dedupe are * per store. Records outlive their request by an hour so `--wait` can read the outcome. */ export class SecretRequestStore { private readonly records = new Map() private readonly listeners = new Set<(event: SecretRequestStoreEvent) => void>() + private readonly expiryTimers = new Map void }>() constructor( private readonly now: () => number = Date.now, - private readonly newId: () => string = () => `sr_${randomBytes(12).toString('base64url')}` + private readonly newId: () => string = () => `sr_${randomBytes(12).toString('base64url')}`, + private readonly timer: SecretRequestTimer = realTimer ) {} request(input: SecretRequestInput): SecretsRequestResult { @@ -100,6 +117,7 @@ export class SecretRequestStore { outcome: null } this.records.set(record.requestId, record) + this.scheduleExpiry(record) this.emit(toRequestedEvent(record)) return { requestId: record.requestId, status: 'pending' } } @@ -125,6 +143,8 @@ export class SecretRequestStore { now + SECRET_REQUEST_TTL_MS, record.requestedAt + SECRET_REQUEST_MAX_LIFETIME_MS ) + this.scheduleExpiry(record) + this.emit({ type: SECRETS_REQUEST_UPDATED_EVENT, requestId, expiresAt: record.expiresAt }) return { expiresAt: record.expiresAt } } @@ -136,6 +156,7 @@ export class SecretRequestStore { return { outcome: status } } record.outcome = outcome + this.clearExpiry(requestId) this.emit({ type: SECRETS_REQUEST_SETTLED_EVENT, requestId, status: outcome }) return { outcome } } @@ -155,6 +176,35 @@ export class SecretRequestStore { } } + /** Natural expiry is announced too, so every client drops the card at the same moment. */ + private scheduleExpiry(record: SecretRequestRecord): void { + this.clearExpiry(record.requestId) + const handle = this.timer( + () => { + this.expiryTimers.delete(record.requestId) + const now = this.now() + if (record.outcome || now < record.expiresAt) { + if (!record.outcome) { + this.scheduleExpiry(record) + } + return + } + this.emit({ + type: SECRETS_REQUEST_SETTLED_EVENT, + requestId: record.requestId, + status: 'expired' + }) + }, + Math.max(0, record.expiresAt - this.now()) + ) + this.expiryTimers.set(record.requestId, handle) + } + + private clearExpiry(requestId: string): void { + this.expiryTimers.get(requestId)?.cancel() + this.expiryTimers.delete(requestId) + } + private statusOf(record: SecretRequestRecord, now: number): SecretRequestStatus { if (record.outcome) { return record.outcome diff --git a/src/main/runtime/secrets/session-env-names.test.ts b/src/main/runtime/secrets/session-env-names.test.ts index 1557ada56e4..c07cbea7ceb 100644 --- a/src/main/runtime/secrets/session-env-names.test.ts +++ b/src/main/runtime/secrets/session-env-names.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { readSessionEnvNames } from './session-env-names' +import { isCloudWorkspaceOrcad, readSessionEnvNames } from './session-env-names' describe('readSessionEnvNames', () => { it('reads names (never values) from the session env file', async () => { @@ -9,21 +9,28 @@ describe('readSessionEnvNames', () => { read: async (path) => { paths.push(path) return 'STRIPE_KEY=c2VjcmV0\nDB_URL=\nnot a line\nlower=eA==\n' - }, - env: { FROM_PROCESS: '1' } + } }) expect(paths).toEqual(['/dev/shm/orca-env-1000/session.env']) expect([...names]).toEqual(['STRIPE_KEY', 'DB_URL']) }) - it("falls back to the process env when there's no session env file", async () => { + it("is empty when there's no session env file, never orcad's own env", async () => { const names = await readSessionEnvNames({ uid: 1000, read: async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }) - }, - env: { FROM_PROCESS: '1' } + } }) - expect([...names]).toEqual(['FROM_PROCESS']) + expect([...names]).toEqual([]) + }) +}) + +describe('isCloudWorkspaceOrcad', () => { + it('needs both the cloud flag and a sandbox id', () => { + expect(isCloudWorkspaceOrcad({ ORCA_IS_CLOUD: '1', ORCA_SANDBOX_ID: 'sbx_1' })).toBe(true) + expect(isCloudWorkspaceOrcad({ ORCA_IS_CLOUD: '1' })).toBe(false) + expect(isCloudWorkspaceOrcad({ ORCA_SANDBOX_ID: 'sbx_1' })).toBe(false) + expect(isCloudWorkspaceOrcad({})).toBe(false) }) }) diff --git a/src/main/runtime/secrets/session-env-names.ts b/src/main/runtime/secrets/session-env-names.ts index 25b2770597d..63eef164ff7 100644 --- a/src/main/runtime/secrets/session-env-names.ts +++ b/src/main/runtime/secrets/session-env-names.ts @@ -5,29 +5,32 @@ export function sessionEnvFilePath(uid: number): string { return `/dev/shm/orca-env-${uid}/session.env` } -/** Names only, never values. Falls back to this process's env where there is no session env file. */ +/** Names only, never values. No file yet means the session env holds nothing; orcad's own process + * env is never consulted, so nothing about the host leaks through `already-set`. */ export async function readSessionEnvNames( - options: { - uid?: number - read?: (path: string) => Promise - env?: NodeJS.ProcessEnv - } = {} + options: { uid?: number; read?: (path: string) => Promise } = {} ): Promise> { const uid = options.uid ?? process.getuid?.() const read = options.read ?? ((path: string) => readFile(path, 'utf8')) - if (uid !== undefined) { - try { - const text = await read(sessionEnvFilePath(uid)) - return new Set( - text - .split('\n') - .filter((line) => line.includes('=')) - .map((line) => line.slice(0, line.indexOf('='))) - .filter((name) => /^[A-Z_][A-Z0-9_]*$/.test(name)) - ) - } catch { - // No session env file (not a cloud VM, or not written yet): use the process env. - } + if (uid === undefined) { + return new Set() } - return new Set(Object.keys(options.env ?? process.env)) + let text: string + try { + text = await read(sessionEnvFilePath(uid)) + } catch { + return new Set() + } + return new Set( + text + .split('\n') + .filter((line) => line.includes('=')) + .map((line) => line.slice(0, line.indexOf('='))) + .filter((name) => /^[A-Z_][A-Z0-9_]*$/.test(name)) + ) +} + +/** Secret requests exist only on a cloud workspace's orcad (orca-sandbox-start sets these). */ +export function isCloudWorkspaceOrcad(env: NodeJS.ProcessEnv = process.env): boolean { + return env.ORCA_IS_CLOUD === '1' && Boolean(env.ORCA_SANDBOX_ID?.trim()) } diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index f543e8b2a72..12b7e672bdd 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -12,7 +12,11 @@ import type { RuntimeNavigationTarget } from './runtime-navigation' import type { WorktreeSortOrderUpdate } from './worktree/sort-order-update' import type { SidebarInputsChangedEvent } from './sidebar-list/sidebar-inputs-feed-contract' import type { BrowserClientHostRequestEvent } from './browser/client-hosting/browser-client-host-request-protocol' -import type { SecretRequestedEvent, SecretRequestSettledEvent } from './secret-request-contract' +import type { + SecretRequestedEvent, + SecretRequestSettledEvent, + SecretRequestUpdatedEvent +} from './secret-request-contract' export type RuntimeClientEvent = | { @@ -97,6 +101,7 @@ export type RuntimeClientEventStreamMessage = | BrowserClientHostRequestEvent // Agent secret requests; replayed on attach while pending. Phones get no reason text. | SecretRequestedEvent + | SecretRequestUpdatedEvent | SecretRequestSettledEvent | { type: 'end' } diff --git a/src/shared/secret-request-contract.ts b/src/shared/secret-request-contract.ts index c2a1a28bd07..8f026882fd2 100644 --- a/src/shared/secret-request-contract.ts +++ b/src/shared/secret-request-contract.ts @@ -9,6 +9,7 @@ export const SECRETS_RESOLVE_REQUEST_METHOD = 'secrets.resolveRequest' /** Client event types (runtime.clientEvents.subscribe). */ export const SECRETS_REQUESTED_EVENT = 'secrets.requested' +export const SECRETS_REQUEST_UPDATED_EVENT = 'secrets.requestUpdated' export const SECRETS_REQUEST_SETTLED_EVENT = 'secrets.requestSettled' export const SECRET_REQUEST_REASON_MAX = 200 @@ -23,16 +24,31 @@ export type SecretRequestScope = z.infer const RequestId = z.string().regex(/^sr_[A-Za-z0-9_-]{8,64}$/) +// C0/C1 controls (newlines, escapes) become spaces; bidi overrides and isolates are dropped, so the +// agent's text can't reorder or restyle what the person reads. +// oxlint-disable-next-line no-control-regex -- SAFETY: matching control characters is the point. +const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/g +const BIDI_CHARS = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g + +export function sanitizeSecretRequestReason(reason: string): string { + return reason.replace(BIDI_CHARS, '').replace(CONTROL_CHARS, ' ').replace(/ {2,}/g, ' ').trim() +} + export const SecretsRequestParamsSchema = z .object({ // Shape only; the name rules (reserved names, agent credentials) are checked by the handler so the // agent gets a specific error code back. name: z.string().min(1).max(128), - reason: z.string().trim().min(1).max(SECRET_REQUEST_REASON_MAX), + reason: z + .string() + .max(SECRET_REQUEST_REASON_MAX * 4) + .transform(sanitizeSecretRequestReason) + .pipe(z.string().min(1).max(SECRET_REQUEST_REASON_MAX)), /** A hint only: the card always preselects Personal (D2). */ scope: SecretRequestScopeSchema.optional(), - worktreeId: z.string().min(1).max(512).optional(), - terminalHandle: z.string().min(1).max(512).optional() + /** A hint, kept only when this orcad knows the worktree. The agent and its terminal come from the + * caller identity orcad verifies (launch evidence), never from params. */ + worktreeId: z.string().min(1).max(512).optional() }) .strict() export type SecretsRequestParams = z.infer @@ -77,7 +93,14 @@ export type SecretRequestedEvent = { expiresAt: number } -/** A request was provided or declined, so other clients can drop their card. */ +/** touchRequest moved the expiry, so every client keeps the card as long. */ +export type SecretRequestUpdatedEvent = { + type: typeof SECRETS_REQUEST_UPDATED_EVENT + requestId: string + expiresAt: number +} + +/** A request was provided, declined or expired, so other clients can drop their card. */ export type SecretRequestSettledEvent = { type: typeof SECRETS_REQUEST_SETTLED_EVENT requestId: string @@ -94,7 +117,9 @@ export const SECRET_REQUEST_ERRORS = { rateLimited: 'secret_request_rate_limited', notFound: 'secret_request_not_found', notPending: 'secret_request_not_pending', - forbidden: 'secret_request_forbidden' + forbidden: 'secret_request_forbidden', + /** Only a cloud workspace's orcad takes secret requests. */ + unavailable: 'secret_requests_unavailable' } as const /** D4: printed by the CLI once a request is provided. */ From d76cb62c570e269b4b1b7da0a12a71a91cd7cd91 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:34:07 -0800 Subject: [PATCH 43/46] fix(sandbox-control): keep preview URLs on for the dev Worker (preview aliases 404ed) (#224) --- cloud/apps/sandbox-control/wrangler.dev.jsonc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cloud/apps/sandbox-control/wrangler.dev.jsonc b/cloud/apps/sandbox-control/wrangler.dev.jsonc index f6d711e61e1..5ed1f29ddd6 100644 --- a/cloud/apps/sandbox-control/wrangler.dev.jsonc +++ b/cloud/apps/sandbox-control/wrangler.dev.jsonc @@ -11,6 +11,8 @@ "main": "src/index.ts", "compatibility_date": "2026-11-01", "workers_dev": true, + // Preview aliases (wrangler versions upload --preview-alias) must stay reachable for pre-merge VM tests. + "preview_urls": true, "d1_databases": [ { "binding": "SANDBOX_DB", From cfb0b56118cc9d5b8d530bee2b526f69f0f01e3c Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:36:20 -0800 Subject: [PATCH 44/46] fix(cloud): archive confirm starts focus on Cancel --- .../cloud-workspaces/CloudWorkspaceConfirmDialog.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx index 14f760692d2..ed37b4ff7ec 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx @@ -111,6 +111,8 @@ export function CloudWorkspaceConfirmDialog({ name: memberName(directory, pending.ownerUserId, selfId, t) }) const losesManagement = pending.kind === 'owner' && w.ownerUserId === selfId && !canAdmin + // Destructive for someone else (their agents stop, or you lose access): focus starts on Cancel. + const focusCancel = losesManagement || pending.kind === 'archive' return ( !next && onCancel()}> @@ -142,10 +144,10 @@ export function CloudWorkspaceConfirmDialog({ {/* Giving away your own access starts on Cancel, so Enter cannot do it by accident. */} - - + + <> + {body}{' '} {t( 'auto.components.billing.paymentAskAdmin', 'Ask an owner or admin to update the payment method.' )} -

    - )} -
    -
    + + ) + } + action={ + entitlement.canManageBilling ? ( + + ) : undefined + } + /> ) } diff --git a/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx b/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx index c07c627551b..930dab3c37f 100644 --- a/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx +++ b/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx @@ -126,3 +126,77 @@ export const suspendedAdmin = defineFixture({ /> ) }) + +/** First open of Settings › Orca account: the section holds its shape while billing answers. */ +export const loading = defineFixture({ + width: 600, + render: () => +}) + +/** Billing's 75% level: the early warning under the bar (still the neutral tone below 90%). */ +export const usageWarning75 = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +/** Billing's 90% level: the bar turns to the warning tone; one hour left reads singular. */ +export const usageWarning90 = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +/** An admin types a cap above billing's maximum: the field says what the maximum is. */ +export const capTooHigh = defineFixture({ + width: 600, + render: () => ( + + ), + interact: async (frame) => { + const input = frame.querySelector('input[inputmode="numeric"]') + if (!input) { + return + } + input.focus() + // React listens for native input events. + const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set + setValue?.call(input, '6000') + input.dispatchEvent(new Event('input', { bubbles: true })) + await new Promise((resolve) => setTimeout(resolve, 100)) + } +}) diff --git a/src/renderer/src/components/billing/PlanBillingSection.tsx b/src/renderer/src/components/billing/PlanBillingSection.tsx index 47cc1fc4c1d..d76cba535d8 100644 --- a/src/renderer/src/components/billing/PlanBillingSection.tsx +++ b/src/renderer/src/components/billing/PlanBillingSection.tsx @@ -3,6 +3,7 @@ import { SettingsGroupHeader } from '@/components/settings/section-layout/Settin import { CreditCard, ExternalLink, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' +import { Skeleton } from '@/components/ui/skeleton' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { formatCents } from './plans/plans-pricing' import { cn } from '@/lib/utils' @@ -18,11 +19,17 @@ import { OverageControls, UsageSummary } from './PlanBillingUsage' import { denyReasonCopy, openFailureCopy, overageFailureCopy } from './plan-billing-copy' import { PlanStatusBadge } from './PlanStatusBadge' import { useOrcaBillingStatus } from './use-orca-billing-status' -import { invalidateOrcaCloudBilling } from '../new-workspace/orca-cloud-billing-cache' +import { useAppStore } from '@/store/index' +import { BILLING_CAPABILITY } from './register-plan-billing-menu-item' export function PlanBillingSection(): React.JSX.Element | null { const t = useTranslate() + const locale = useIntlLocale() const { loading, result, refresh } = useOrcaBillingStatus(true) + // Only billing-flagged accounts get a skeleton; others hear "unconfigured" and show nothing. + const billingFlagged = useAppStore( + (state) => state.orcaProfileAuthStatus?.capabilities?.flags[BILLING_CAPABILITY] === true + ) const [busy, setBusy] = useState(false) const [notice, setNotice] = useState(null) const [userRefreshing, setUserRefreshing] = useState(false) @@ -61,11 +68,12 @@ export function PlanBillingSection(): React.JSX.Element | null { })) setBusy(false) if (outcome.status === 'ok') { + // One shared store: this re-read also updates the Run-on picker's Orca Cloud row. refresh() - // The Run-on picker's Orca Cloud row reads a shared copy; overage/cap just changed it. - invalidateOrcaCloudBilling() } else { - const failure = overageFailureCopy(outcome, t) + const maxCap = + result?.status === 'ok' ? (result.entitlement.offers?.team.maxSpendCapCents ?? null) : null + const failure = overageFailureCopy(outcome, t, maxCap, locale) setNotice(failure ? { kind: 'error', text: failure } : null) setOverageFailures((count) => count + 1) } @@ -74,7 +82,7 @@ export function PlanBillingSection(): React.JSX.Element | null { return ( + } if (!result || result.status === 'unconfigured' || result.status === 'signed-out') { // The pane above already handles sign-in; billing stays out of builds without a service. return null @@ -268,3 +279,36 @@ export function PlanBillingView({
    ) } + +/** Same rows as a loaded plan (header, plan line, usage, overage card) so nothing jumps in. */ +function PlanBillingSkeleton(): React.JSX.Element { + const t = useTranslate() + return ( +
    + +
    + + + +
    +
    +
    + + +
    + + +
    + + +
    + ) +} diff --git a/src/renderer/src/components/billing/PlanBillingUsage.tsx b/src/renderer/src/components/billing/PlanBillingUsage.tsx index b56af82d4cd..662c5e94884 100644 --- a/src/renderer/src/components/billing/PlanBillingUsage.tsx +++ b/src/renderer/src/components/billing/PlanBillingUsage.tsx @@ -11,7 +11,14 @@ import type { OrcaBillingOverageArgs } from '../../../../shared/orca-billing' import { formatHours, includedUsagePercent } from './plan-billing-format' +import { + includedUsageTone, + sandboxHoursLeftLine, + sandboxHoursOverLine, + usageWarningLine +} from './plan-billing-usage-copy' import { formatCents, formatRateCents } from './plans/plans-pricing' +import { capTooHighCopy } from './plan-billing-copy' import { ORCA_BILLING_OVERAGE_SECTION_ID } from '../new-workspace/orca-cloud-run-target-access' /** "Resets and renews Dec 2" when both land the same day (monthly); separate parts otherwise. */ @@ -55,6 +62,8 @@ export function UsageSummary({ const locale = useIntlLocale() const date = (ms: number): string => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(ms) + const overLine = sandboxHoursOverLine(entitlement, t) + const warning = usageWarningLine(entitlement, t) return (
    @@ -68,51 +77,15 @@ export function UsageSummary({ } )} - - {t('auto.components.billing.sandboxHoursLeft', '{{value0}} sandbox hours left', { - value0: formatHours(entitlement.remainingIncludedSeconds) - })} - + {sandboxHoursLeftLine(entitlement, t)}
    = 100 && !entitlement.overage.optedIn - ? 'warning' - : 'default' - } + tone={includedUsageTone(entitlement)} aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')} /> - {entitlement.overageSeconds === 0 && - entitlement.usedSeconds > entitlement.includedSeconds && - entitlement.includedSeconds > 0 ? ( -

    - {t('auto.components.billing.sandboxHoursOver', '{{count}} sandbox hours over', { - count: Math.round((entitlement.usedSeconds - entitlement.includedSeconds) / 360) / 10, - defaultValue_one: '{{count}} sandbox hour over' - })} -

    - ) : null} - {entitlement.overageSeconds > 0 ? ( -

    - {t('auto.components.billing.overageHoursOnly', '{{value0}} overage hours this month', { - value0: formatHours(entitlement.overageSeconds) - })} -

    - ) : null} - {entitlement.usageWarningPercent !== null && entitlement.usageWarningPercent < 100 ? ( -

    - {entitlement.usageWarningPercent >= 100 - ? t('auto.components.billing.warn100b', 'All of this month’s sandbox hours are used.') - : t( - 'auto.components.billing.warnPercent2', - 'You’ve used {{value0}}% of this month’s sandbox hours.', - { - value0: String(entitlement.usageWarningPercent) - } - )} -

    - ) : null} + {overLine ?

    {overLine}

    : null} + {warning ?

    {warning}

    : null}

    {resetLine(entitlement, date, t)}

    ) @@ -158,7 +131,10 @@ export function OverageControls({ } const optedIn = optimisticOn ?? overage.optedIn const parsedCap = Number(capDollars) - const capValid = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0 + const maxCapCents = entitlement.offers?.team.maxSpendCapCents ?? null + const capWhole = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0 + const capTooHigh = capWhole && maxCapCents !== null && parsedCap * 100 > maxCapCents + const capValid = capWhole && !capTooHigh const changed = capValid && capDollars.trim() !== savedDollars const paymentFailed = entitlement.payment.pastDueSince !== null const description = t( @@ -279,13 +255,17 @@ export function OverageControls({ {t('auto.components.billing.capLabel2', 'Monthly spend cap')}
    -
    - +
    + $ {capValid ? null : (

    - {t('auto.components.billing.capInvalid', 'Enter a whole dollar amount.')} + {capTooHigh && maxCapCents !== null + ? capTooHighCopy(maxCapCents, locale, t) + : t('auto.components.billing.capInvalid', 'Enter a whole dollar amount.')}

    )}
    diff --git a/src/renderer/src/components/billing/billing-summary-store.test.ts b/src/renderer/src/components/billing/billing-summary-store.test.ts new file mode 100644 index 00000000000..38de96b89e8 --- /dev/null +++ b/src/renderer/src/components/billing/billing-summary-store.test.ts @@ -0,0 +1,121 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' +import { + getBillingState, + getBillingSummary, + getLastBillingStatus, + mergeBillingResult, + recordBillingStatus, + refreshBillingStatus, + resetBillingSummary, + watchBillingStatus +} from './billing-summary-store' +import { sampleTeam } from './plan-billing-fixtures' + +const teamA: OrcaBillingStatusResult = { status: 'ok', entitlement: { ...sampleTeam } } +const teamB: OrcaBillingStatusResult = { + status: 'ok', + entitlement: { ...sampleTeam, plan: null, planLabel: null, status: 'none' } +} +const offline: OrcaBillingStatusResult = { status: 'failed', error: 'offline' } + +let pending: ((result: OrcaBillingStatusResult) => void)[] = [] + +beforeEach(() => { + pending = [] + resetBillingSummary() + vi.stubGlobal('api', { + orcaProfiles: { + billingStatus: vi.fn( + () => new Promise((resolve) => pending.push(resolve)) + ) + } + }) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +async function answer(index: number, result: OrcaBillingStatusResult): Promise { + pending[index](result) + await Promise.resolve() + await Promise.resolve() +} + +describe('mergeBillingResult', () => { + it('keeps a good answer through a failure and replaces it otherwise', () => { + expect(mergeBillingResult(teamA, offline)).toBe(teamA) + expect(mergeBillingResult(null, offline)).toBe(offline) + expect(mergeBillingResult(teamA, teamB)).toBe(teamB) + expect(mergeBillingResult(teamA, { status: 'signed-out' })).toEqual({ status: 'signed-out' }) + }) +}) + +describe('billing store', () => { + it('keeps the last good result when a re-read fails', async () => { + const read = refreshBillingStatus() + await answer(0, teamA) + await read + expect(getBillingState()).toMatchObject({ result: teamA, loading: false }) + + const reread = refreshBillingStatus() + expect(getBillingState()).toMatchObject({ result: teamA, loading: true }) + await answer(1, offline) + await reread + expect(getBillingState()).toMatchObject({ result: teamA, loading: false }) + expect(getLastBillingStatus()).toBe(teamA) + expect(getBillingSummary()).toMatchObject({ subscribed: true, planLabel: 'Team' }) + }) + + it('re-reads after a kept failure instead of trusting it as fresh', async () => { + recordBillingStatus(teamA) + recordBillingStatus(offline) + void refreshBillingStatus({ maxAgeMs: 60_000 }) + expect(pending).toHaveLength(1) + }) + + it('joins a running read and only supersedes it when asked', async () => { + void refreshBillingStatus() + void refreshBillingStatus() + expect(pending).toHaveLength(1) + void refreshBillingStatus({ supersede: true }) + expect(pending).toHaveLength(2) + // The older read answers last; the newer one already wrote. + await answer(1, teamB) + await answer(0, teamA) + expect(getBillingState().result).toBe(teamB) + }) + + it('drops an answer that started before a team switch', async () => { + const read = refreshBillingStatus() + resetBillingSummary() + await answer(0, teamA) + await read + expect(getBillingState()).toMatchObject({ result: null, loading: false }) + expect(getLastBillingStatus()).toBeNull() + expect(getBillingSummary().subscribed).toBeNull() + }) + + it("never keeps the previous team's plan through the new team's failed read", async () => { + recordBillingStatus(teamA) + resetBillingSummary() + void refreshBillingStatus() + await answer(0, offline) + expect(getBillingState().result).toEqual(offline) + expect(getLastBillingStatus()).toBeNull() + }) + + it('reads the new team at once when a view is watching through the switch', async () => { + const release = watchBillingStatus() + void refreshBillingStatus() + resetBillingSummary() + expect(pending).toHaveLength(2) + expect(getBillingState()).toMatchObject({ result: null, loading: true }) + await answer(0, teamA) + await answer(1, teamB) + expect(getBillingState().result).toBe(teamB) + release() + }) +}) diff --git a/src/renderer/src/components/billing/billing-summary-store.ts b/src/renderer/src/components/billing/billing-summary-store.ts index b7115772237..5ffba23b560 100644 --- a/src/renderer/src/components/billing/billing-summary-store.ts +++ b/src/renderer/src/components/billing/billing-summary-store.ts @@ -1,6 +1,10 @@ -// What the always-visible upgrade entry points need to know: does this account have a plan? -// Read when the account (or org) changes and refreshed by any billing view that loads status. +// The one billing-status cache. Settings, the plans and Team pages, the build sheet, the Run-on +// picker and the account menu all read it, so they always agree and a read by one serves the others. +// It keeps the last good answer: a failed read (offline for a moment when the window regains focus) +// never replaces it. Answers are scoped to the account and team that asked for them. import { useSyncExternalStore } from 'react' +import { useAppStore } from '@/store' +import { getOrcaAccountKey } from '@/hooks/use-orca-account-key' import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' import { isActivePlan } from './team/team-seat-math' @@ -12,49 +16,85 @@ export type BillingSummary = { planLabel: string | null } -let summary: BillingSummary = { subscribed: null, canManageBilling: false, planLabel: null } +export type BillingStoreState = { + /** Last answer for the current account and team; 'failed' only when nothing good was read yet. */ + result: OrcaBillingStatusResult | null + /** A read for the current account is running. */ + loading: boolean + /** When `result` was last confirmed by the service; 0 when stale or never. */ + fetchedAt: number +} + +const EMPTY: BillingStoreState = { result: null, loading: false, fetchedAt: 0 } +const SUMMARY_MIN_REFRESH_MS = 60_000 + +let state: BillingStoreState = EMPTY +/** Account the current `result` belongs to. */ +let stateAccount: string | null = null +/** Bumped on every account/team switch; answers that started before it are dropped. */ +let generation = 0 +/** Only the newest read may write; an older one that answers late is dropped. */ +let latestRead = 0 +let inFlight: { generation: number; account: string; promise: Promise } | null = null +/** Mounted views that want billing kept current (re-read after a switch drops a read). */ +let watchers = 0 const listeners = new Set<() => void>() -let lastReadAt = 0 -let inFlight: Promise | null = null -const MIN_REFRESH_MS = 60_000 -let lastStatus: OrcaBillingStatusResult | null = null +function currentAccount(): string { + return getOrcaAccountKey(useAppStore.getState().orcaProfileAuthStatus) +} -/** The latest successful status for the current account, to seed views that open later. */ -export function getLastBillingStatus(): OrcaBillingStatusResult | null { - return lastStatus +function setState(next: BillingStoreState): void { + if ( + next.result === state.result && + next.loading === state.loading && + next.fetchedAt === state.fetchedAt + ) { + return + } + state = next + for (const listener of listeners) { + listener() + } +} + +function readBillingStatus(): Promise { + return window.api.orcaProfiles + .billingStatus() + .catch((error: unknown): OrcaBillingStatusResult => ({ + status: 'failed', + error: error instanceof Error ? error.message : String(error) + })) +} + +/** + * Merges an answer into the cache: a failure keeps the last good result for the same account + * (a brief offline moment must not blank the section); anything else replaces it. + */ +export function mergeBillingResult( + previous: OrcaBillingStatusResult | null, + next: OrcaBillingStatusResult +): OrcaBillingStatusResult { + return next.status === 'failed' && previous?.status === 'ok' ? previous : next } export function recordBillingStatus(result: OrcaBillingStatusResult): void { - if (result.status === 'ok') { - lastStatus = result - } else if (result.status !== 'failed') { - lastStatus = null - } - const next: BillingSummary = - result.status === 'ok' - ? { - subscribed: isActivePlan(result.entitlement), - canManageBilling: result.entitlement.canManageBilling, - planLabel: isActivePlan(result.entitlement) ? result.entitlement.planLabel : null - } - : result.status === 'failed' - ? summary - : { subscribed: null, canManageBilling: false, planLabel: null } - if ( - next.subscribed !== summary.subscribed || - next.canManageBilling !== summary.canManageBilling || - next.planLabel !== summary.planLabel - ) { - summary = next - for (const listener of listeners) { - listener() - } - } + const account = currentAccount() + const previous = stateAccount === account ? state.result : null + const merged = mergeBillingResult(previous, result) + stateAccount = account + setState({ + result: merged, + loading: inFlight !== null, + // A result kept through a failure counts as stale, so the next look reads again. + fetchedAt: merged === result ? Date.now() : 0 + }) } -/** Bumped on every account/org switch; answers from an older account are ignored. */ -let generation = 0 +/** The latest good status for the current account, to seed views that open later. */ +export function getLastBillingStatus(): OrcaBillingStatusResult | null { + return stateAccount === currentAccount() && state.result?.status === 'ok' ? state.result : null +} export function getBillingGeneration(): number { return generation @@ -70,47 +110,153 @@ export function recordBillingStatusIfCurrent( } } -/** Forget the previous account's plan at once (sign-out, account or org switch). */ +/** Forget the previous account's plan at once (sign-out, account or team switch). */ export function resetBillingSummary(): void { generation++ + latestRead++ inFlight = null - lastReadAt = 0 - recordBillingStatus({ status: 'signed-out' }) -} - -/** Re-reads billing status at most once a minute unless `force` (account or org switched). */ -export function refreshBillingSummary(force = false): Promise { - if (!force && (inFlight || Date.now() - lastReadAt < MIN_REFRESH_MS)) { - return inFlight ?? Promise.resolve() + stateAccount = null + setState(EMPTY) + if (watchers > 0) { + // Views still on screen read the new account's billing at once. + void refreshBillingStatus() } - const requestGeneration = generation - lastReadAt = Date.now() - const request = window.api.orcaProfiles - .billingStatus() - .then((result) => { - if (requestGeneration === generation) { - recordBillingStatus(result) - } - }) - .catch(() => undefined) - .finally(() => { - if (inFlight === request) { - inFlight = null - } - }) - inFlight = request - return request } -export function getBillingSummary(): BillingSummary { - return summary +/** Marks the cached answer stale (billing changed elsewhere) so the next read doesn't trust it. */ +export function markBillingStale(): void { + setState({ ...state, fetchedAt: 0 }) } -export function subscribeBillingSummary(listener: () => void): () => void { +export function hasBillingWatchers(): boolean { + return watchers > 0 +} + +/** A mounted view that wants billing current; returns its release. */ +export function watchBillingStatus(): () => void { + watchers++ + let released = false + return () => { + if (!released) { + released = true + watchers-- + } + } +} + +/** The running read for the current account, if any (callers wait on it). */ +export function getBillingReadInFlight(): Promise | null { + return inFlight?.promise ?? null +} + +/** + * Reads billing status. Joins a running read for the same account unless `supersede` (billing just + * changed in-app, so a read that started earlier may be stale). With `maxAgeMs`, a cached answer + * younger than that is trusted and nothing is read. + */ +export function refreshBillingStatus({ + supersede = false, + maxAgeMs = 0 +}: { supersede?: boolean; maxAgeMs?: number } = {}): Promise { + const account = currentAccount() + if ( + !supersede && + inFlight && + inFlight.generation === generation && + inFlight.account === account + ) { + return inFlight.promise + } + if ( + maxAgeMs > 0 && + stateAccount === account && + state.result && + Date.now() - state.fetchedAt < maxAgeMs + ) { + return Promise.resolve() + } + if (stateAccount !== account) { + // Another account's answer must not stay on screen while this one's loads. + stateAccount = account + setState(EMPTY) + } + const startedGeneration = generation + const mine = ++latestRead + const promise = readBillingStatus().then((result): Promise | void => { + if (mine !== latestRead) { + // Superseded by a newer read or a reset; that one writes. + return + } + inFlight = null + if (startedGeneration !== generation || account !== currentAccount()) { + // The account or team changed mid-read: the answer is for the old one. Read again for + // whoever is still looking. + if (watchers > 0) { + return refreshBillingStatus() + } + setState({ ...state, loading: false }) + return + } + recordBillingStatus(result) + }) + inFlight = { generation: startedGeneration, account, promise } + setState({ ...state, loading: true }) + return promise +} + +/** Re-reads billing status at most once a minute unless `force` (account or team switched). */ +export function refreshBillingSummary(force = false): Promise { + return refreshBillingStatus(force ? {} : { maxAgeMs: SUMMARY_MIN_REFRESH_MS }) +} + +export function getBillingState(): BillingStoreState { + return state +} + +export function subscribeBillingState(listener: () => void): () => void { listeners.add(listener) return () => listeners.delete(listener) } +export function useBillingState(): BillingStoreState { + return useSyncExternalStore(subscribeBillingState, getBillingState) +} + +const UNKNOWN_SUMMARY: BillingSummary = { + subscribed: null, + canManageBilling: false, + planLabel: null +} +let summaryFor: OrcaBillingStatusResult | null = null +let summary: BillingSummary = UNKNOWN_SUMMARY + +export function getBillingSummary(): BillingSummary { + const result = state.result + if (result === summaryFor) { + return summary + } + summaryFor = result + const next: BillingSummary = + result?.status === 'ok' + ? { + subscribed: isActivePlan(result.entitlement), + canManageBilling: result.entitlement.canManageBilling, + planLabel: isActivePlan(result.entitlement) ? result.entitlement.planLabel : null + } + : UNKNOWN_SUMMARY + // Keep the same object when nothing visible changed, so subscribers don't re-render. + if ( + next.subscribed !== summary.subscribed || + next.canManageBilling !== summary.canManageBilling || + next.planLabel !== summary.planLabel + ) { + summary = next + } + return summary +} + +export const subscribeBillingSummary = subscribeBillingState + export function useBillingSummary(): BillingSummary { - return useSyncExternalStore(subscribeBillingSummary, getBillingSummary) + return useSyncExternalStore(subscribeBillingState, getBillingSummary) } diff --git a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx index 955e69bda54..7b2922b2552 100644 --- a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx +++ b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx @@ -38,53 +38,55 @@ function OrderSummary({ const renewsLabel = new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(renews) const seatCount = new Intl.NumberFormat(locale).format(seats) return ( -
    -
    -
    - {interval === 'year' - ? t('auto.components.billing.checkout.planAnnual', '{{value0}} · Annual', { - value0: team.label - }) - : t('auto.components.billing.checkout.planMonthly', '{{value0}} · Monthly', { - value0: team.label - })} -
    -
    - {perSeat === null - ? null - : interval === 'year' - ? t( - 'auto.components.billing.checkout.lineItemYearly', - '{{seats}} × {{price}} per seat, billed yearly', - { - count: seats, - seats: seatCount, - price: formatCents(perSeat, locale), - defaultValue_one: '{{seats}} × {{price}} per seat, billed yearly' - } - ) - : t( - 'auto.components.billing.checkout.lineItemMonthly', - '{{seats}} × {{price}} per seat per month', - { - count: seats, - seats: seatCount, - price: formatCents(perSeat, locale), - defaultValue_one: '{{seats}} × {{price}} per seat per month' - } - )} -
    -
    -
    -
    - {phase.kind === 'paid' - ? t('auto.components.billing.checkout.paidRow', 'Paid') - : t('auto.components.billing.checkout.dueToday', 'Due today')} -
    -
    - {total === null ? '—' : formatCents(total, locale)} -
    -
    +
    +
    +
    +
    + {interval === 'year' + ? t('auto.components.billing.checkout.planAnnual', '{{value0}} · Annual', { + value0: team.label + }) + : t('auto.components.billing.checkout.planMonthly', '{{value0}} · Monthly', { + value0: team.label + })} +
    +
    + {perSeat === null + ? null + : interval === 'year' + ? t( + 'auto.components.billing.checkout.lineItemYearly', + '{{seats}} × {{price}} per seat, billed yearly', + { + count: seats, + seats: seatCount, + price: formatCents(perSeat, locale), + defaultValue_one: '{{seats}} × {{price}} per seat, billed yearly' + } + ) + : t( + 'auto.components.billing.checkout.lineItemMonthly', + '{{seats}} × {{price}} per seat per month', + { + count: seats, + seats: seatCount, + price: formatCents(perSeat, locale), + defaultValue_one: '{{seats}} × {{price}} per seat per month' + } + )} +
    +
    +
    +
    + {phase.kind === 'paid' + ? t('auto.components.billing.checkout.paidRow', 'Paid') + : t('auto.components.billing.checkout.dueToday', 'Due today')} +
    +
    + {total === null ? '—' : formatCents(total, locale)} +
    +
    +

    {t( 'auto.components.billing.checkout.renewsNote', @@ -92,7 +94,7 @@ function OrderSummary({ { value0: renewsLabel } )}

    -
    +
    ) } @@ -101,7 +103,7 @@ function StatusIcon({ phase }: { phase: CheckoutPanelProps['phase'] }): React.JS return ( diff --git a/src/renderer/src/components/billing/plan-billing-copy.ts b/src/renderer/src/components/billing/plan-billing-copy.ts index a584182fd4a..8563da88b66 100644 --- a/src/renderer/src/components/billing/plan-billing-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-copy.ts @@ -5,6 +5,7 @@ import type { OrcaBillingOpenResult, OrcaBillingOverageResult } from '../../../../shared/orca-billing' +import { formatCents } from './plans/plans-pricing' export function denyReasonCopy( reason: OrcaBillingDenyReason, @@ -113,12 +114,27 @@ export function openFailureCopy(result: OrcaBillingOpenResult, t: Translate): st } } -export function overageFailureCopy(result: OrcaBillingOverageResult, t: Translate): string | null { +/** "The spend cap can be at most $5,000." */ +export function capTooHighCopy(maxCents: number, locale: string, t: Translate): string { + return t('auto.components.billing.capAtMost', 'The spend cap can be at most {{max}}.', { + max: formatCents(maxCents, locale) + }) +} + +export function overageFailureCopy( + result: OrcaBillingOverageResult, + t: Translate, + /** The service's highest allowed cap; null from older services that don't send it. */ + maxCapCents: number | null = null, + locale = 'en-US' +): string | null { switch (result.status) { case 'ok': return null case 'cap-too-high': - return t('auto.components.billing.capTooHigh', 'That spend cap is above the allowed maximum.') + return maxCapCents === null + ? t('auto.components.billing.capTooHigh', 'That spend cap is above the allowed maximum.') + : capTooHighCopy(maxCapCents, locale, t) case 'no-subscription': return t('auto.components.billing.overageNoPlan', 'Overage needs an active plan.') case 'forbidden': diff --git a/src/renderer/src/components/billing/plan-billing-fixtures.ts b/src/renderer/src/components/billing/plan-billing-fixtures.ts index 1dc2a62e47b..696ede6ee78 100644 --- a/src/renderer/src/components/billing/plan-billing-fixtures.ts +++ b/src/renderer/src/components/billing/plan-billing-fixtures.ts @@ -16,7 +16,8 @@ export const sampleOffers: OrcaBillingOffers = { concurrentSandboxesPerSeat: 3, idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, overageCentsPerHour: 100, - defaultSpendCapCents: 2500 + defaultSpendCapCents: 2500, + maxSpendCapCents: 500_000 }, enterprise: { label: 'Enterprise', diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts new file mode 100644 index 00000000000..f1b5292ecee --- /dev/null +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest' +import { translate } from '@/i18n/i18n' +import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' +import { sampleTeam } from './plan-billing-fixtures' +import { + accountMenuUsageLines, + includedUsageTone, + sandboxHoursCount, + sandboxHoursLeftLine, + sandboxHoursOverLine, + usageWarningLine +} from './plan-billing-usage-copy' + +const HOUR = 3600 +const t = translate +const team = (patch: Partial): OrcaBillingEntitlement => ({ + ...sampleTeam, + ...patch +}) + +describe('sandbox hours copy', () => { + it('counts hours to one decimal', () => { + expect(sandboxHoursCount(78.5 * HOUR)).toBe(78.5) + expect(sandboxHoursCount(HOUR + 1)).toBe(1) + expect(sandboxHoursCount(-5)).toBe(0) + }) + + it('pluralizes the hours left', () => { + expect(sandboxHoursLeftLine(team({ remainingIncludedSeconds: 78.5 * HOUR }), t)).toBe( + '78.5 sandbox hours left' + ) + expect(sandboxHoursLeftLine(team({ remainingIncludedSeconds: HOUR }), t)).toBe( + '1 sandbox hour left' + ) + expect(sandboxHoursLeftLine(team({ remainingIncludedSeconds: 0 }), t)).toBe( + '0 sandbox hours left' + ) + }) + + it('says how far over the included amount the team is, billed or not', () => { + expect(sandboxHoursOverLine(team({}), t)).toBeNull() + expect( + sandboxHoursOverLine(team({ usedSeconds: 123 * HOUR, overageSeconds: 3 * HOUR }), t) + ).toBe('3 sandbox hours over the included amount this month') + expect(sandboxHoursOverLine(team({ usedSeconds: 121 * HOUR, overageSeconds: 0 }), t)).toBe( + '1 sandbox hour over the included amount this month' + ) + }) + + it('warns at the level billing reports until the hours run out', () => { + expect(usageWarningLine(team({ usageWarningPercent: null }), t)).toBeNull() + expect(usageWarningLine(team({ usageWarningPercent: 75 }), t)).toBe( + 'Your team has used 75% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usageWarningPercent: 90 }), t)).toBe( + 'Your team has used 90% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usageWarningPercent: 80 }), t)).toBe( + 'Your team has used 80% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usageWarningPercent: 100 }), t)).toBeNull() + }) + + it('turns the hours bar to the warning tone at 90%', () => { + expect(includedUsageTone(team({ usedSeconds: 107 * HOUR }))).toBe('default') + expect(includedUsageTone(team({ usedSeconds: 108 * HOUR }))).toBe('warning') + expect(includedUsageTone(team({ usedSeconds: 200 * HOUR }))).toBe('warning') + }) + + it('gives the account menu hours and the usage warning only on a plan', () => { + expect( + accountMenuUsageLines( + { + status: 'ok', + entitlement: team({ remainingIncludedSeconds: 20 * HOUR, usageWarningPercent: 90 }) + }, + t + ) + ).toEqual({ + hoursLeft: '20 sandbox hours left', + warning: 'Your team has used 90% of this month’s sandbox hours.' + }) + expect( + accountMenuUsageLines( + { status: 'ok', entitlement: team({ plan: null, planLabel: null, status: 'none' }) }, + t + ) + ).toBeNull() + expect(accountMenuUsageLines({ status: 'failed', error: 'offline' }, t)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.ts new file mode 100644 index 00000000000..a4c45fcbbec --- /dev/null +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.ts @@ -0,0 +1,86 @@ +// Sandbox-hours lines shared by Plan & billing, the plans page and the account menu, so every +// surface counts, pluralizes and warns the same way. +import type { Translate } from '@/i18n/use-translate' +import type { + OrcaBillingEntitlement, + OrcaBillingStatusResult +} from '../../../../shared/orca-billing' +import { includedUsagePercent } from './plan-billing-format' +import { isActivePlan } from './team/team-seat-math' + +/** The included-hours bar turns to the warning tone from this share of the month's hours. */ +export const INCLUDED_HOURS_WARNING_PERCENT = 90 + +/** Hours as a plural count: one decimal, whole numbers without it (41.5, 78, 1). */ +export function sandboxHoursCount(seconds: number): number { + return Math.round(Math.max(0, seconds) / 360) / 10 +} + +export function includedUsageTone(entitlement: OrcaBillingEntitlement): 'default' | 'warning' { + return includedUsagePercent(entitlement) >= INCLUDED_HOURS_WARNING_PERCENT ? 'warning' : 'default' +} + +/** "78.5 sandbox hours left" / "1 sandbox hour left". */ +export function sandboxHoursLeftLine(entitlement: OrcaBillingEntitlement, t: Translate): string { + return t('auto.components.billing.sandboxHoursLeftCount', '{{count}} sandbox hours left', { + count: sandboxHoursCount(entitlement.remainingIncludedSeconds), + defaultValue_one: '{{count}} sandbox hour left' + }) +} + +/** Hours past the included amount this month (billed as overage or not), or 0. */ +export function hoursOverIncludedSeconds(entitlement: OrcaBillingEntitlement): number { + if (entitlement.includedSeconds <= 0) { + return entitlement.overageSeconds + } + return Math.max(entitlement.overageSeconds, entitlement.usedSeconds - entitlement.includedSeconds) +} + +/** "3 sandbox hours over the included amount this month", or null when within it. */ +export function sandboxHoursOverLine( + entitlement: OrcaBillingEntitlement, + t: Translate +): string | null { + const count = sandboxHoursCount(hoursOverIncludedSeconds(entitlement)) + if (count <= 0) { + return null + } + return t( + 'auto.components.billing.sandboxHoursOverIncluded', + '{{count}} sandbox hours over the included amount this month', + { + count, + defaultValue_one: '{{count}} sandbox hour over the included amount this month' + } + ) +} + +/** + * The early warning at whichever level billing reports (75%, 90%) until the hours run out; at 100% + * the bar, the hours-left line and the out-of-hours states say it instead. + */ +export function usageWarningLine(entitlement: OrcaBillingEntitlement, t: Translate): string | null { + const percent = entitlement.usageWarningPercent + if (percent === null || percent >= 100) { + return null + } + return t( + 'auto.components.billing.teamUsedPercent', + 'Your team has used {{percent}}% of this month’s sandbox hours.', + { percent: String(percent) } + ) +} + +/** The account menu's plan lines: hours left, and the early warning once the team reaches it. */ +export function accountMenuUsageLines( + result: OrcaBillingStatusResult | null, + t: Translate +): { hoursLeft: string; warning: string | null } | null { + if (result?.status !== 'ok' || !isActivePlan(result.entitlement)) { + return null + } + return { + hoursLeft: sandboxHoursLeftLine(result.entitlement, t), + warning: usageWarningLine(result.entitlement, t) + } +} diff --git a/src/renderer/src/components/billing/plans/PlansDialogContent.tsx b/src/renderer/src/components/billing/plans/PlansDialogContent.tsx index 16e304cc02c..fca2a5f2531 100644 --- a/src/renderer/src/components/billing/plans/PlansDialogContent.tsx +++ b/src/renderer/src/components/billing/plans/PlansDialogContent.tsx @@ -30,10 +30,12 @@ export function PlansDialogContent( : 'top-[6vh] max-h-[88vh] translate-y-0 sm:max-w-4xl [@media(max-height:800px)]:top-4 [@media(max-height:800px)]:max-h-[calc(100vh-2rem)]' } onOpenAutoFocus={(event) => { - // The dialog itself first; PlansView moves focus to the primary action once plans load. + // The heading, not the first button: Enter on "Continue" would start a monthly Checkout, + // and Tab from here reaches the interval toggle before the plan cards. event.preventDefault() if (event.currentTarget instanceof HTMLElement) { - event.currentTarget.focus() + const heading = event.currentTarget.querySelector('[data-plans-heading]') + ;(heading ?? event.currentTarget).focus() } }} > @@ -41,7 +43,7 @@ export function PlansDialogContent(

    {t('auto.components.billing.plans.eyebrow', 'Orca Cloud')}

    - + {checkout ? checkoutState === 'paid' ? t('auto.components.billing.checkout.titlePaid', 'Welcome to Orca Cloud') diff --git a/src/renderer/src/components/billing/plans/PlansView.fixture.tsx b/src/renderer/src/components/billing/plans/PlansView.fixture.tsx index 627ee89ebd9..c496a5b2947 100644 --- a/src/renderer/src/components/billing/plans/PlansView.fixture.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.fixture.tsx @@ -105,3 +105,23 @@ export const loadFailed = defineFixture({ width, render: () => }) + +/** Billing's 90% level on the plans page: the strip warns under the bar. */ +export const currentPlanUsageWarning = defineFixture({ + width, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/billing/plans/PlansView.tsx b/src/renderer/src/components/billing/plans/PlansView.tsx index dee2a120e06..65c1e3fb12d 100644 --- a/src/renderer/src/components/billing/plans/PlansView.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.tsx @@ -15,6 +15,12 @@ import { PlanStatusBadge } from '../PlanStatusBadge' import type { PlanBillingNotice } from '../PlanBillingSection' import { seatCountLabel } from '../team/team-copy' import { formatHours, includedUsagePercent } from '../plan-billing-format' +import { + includedUsageTone, + sandboxHoursCount, + sandboxHoursLeftLine, + usageWarningLine +} from '../plan-billing-usage-copy' import { EnterprisePlanCard } from './EnterprisePlanCard' import { PlansIntervalToggle } from './PlansIntervalToggle' import { TeamPlanCard, type TeamPlanCardMode } from './TeamPlanCard' @@ -56,8 +62,8 @@ function ValueProps(): React.JSX.Element { icon: Zap, title: t('auto.components.billing.plans.vpWakeTitle', 'Wake in seconds'), body: t( - 'auto.components.billing.plans.vpWakeBody2', - 'Idle sandboxes sleep to save hours and wake with your files as you left them.' + 'auto.components.billing.plans.vpWakeBody3', + 'Idle sandboxes sleep to save sandbox hours and wake with your files as you left them.' ) }, { @@ -96,6 +102,7 @@ function CurrentPlanStrip({ const resets = entitlement.usageWindow ? new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(entitlement.usageWindow.end) : null + const warning = usageWarningLine(entitlement, t) return (
    @@ -113,7 +120,7 @@ function CurrentPlanStrip({
    = 100 ? 'warning' : 'default'} + tone={includedUsageTone(entitlement)} aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')} />
    @@ -130,16 +137,18 @@ function CurrentPlanStrip({ {resets ? t( - 'auto.components.billing.plans.leftResets', - '{{value0}} hours left · resets {{value1}}', + 'auto.components.billing.plans.sandboxHoursLeftResets', + '{{count}} sandbox hours left · resets {{date}}', { - value0: formatHours(entitlement.remainingIncludedSeconds), - value1: resets + count: sandboxHoursCount(entitlement.remainingIncludedSeconds), + date: resets, + defaultValue_one: '{{count}} sandbox hour left · resets {{date}}' } ) - : null} + : sandboxHoursLeftLine(entitlement, t)}
    + {warning ?

    {warning}

    : null}
    ) } @@ -226,15 +235,16 @@ export function PlansView(props: PlansViewProps): React.JSX.Element { const seats = clampSeats(props.seats, ORCA_BILLING_MAX_SEATS) const result = props.result const ready = result?.status === 'ok' - // Once plans load (or after "Back to plans"), land on this state's primary action, but only if - // focus is still on the dialog or nowhere; never steal it from something the user picked. + // Once plans load (or after "Back to plans"), land on the dialog heading, never on a buy button + // (Enter would start Checkout): Tab then reaches the interval toggle before the cards. Only when + // focus is on the dialog or nowhere; never steal it from something the user picked. useEffect(() => { const active = document.activeElement if ( ready && (!active || active === document.body || active.getAttribute('role') === 'dialog') ) { - document.querySelector('[role="dialog"] [data-plans-primary]')?.focus() + document.querySelector('[role="dialog"] [data-plans-heading]')?.focus() } }, [ready]) diff --git a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx index 34e4e84771c..b4cd0843ff7 100644 --- a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx +++ b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx @@ -155,7 +155,6 @@ export function TeamPlanCard({ className="w-full" aria-disabled={busy || undefined} onClick={busy ? undefined : onCheckout} - data-plans-primary="" > {busy ? : null} {busy @@ -192,7 +191,6 @@ export function TeamPlanCard({ className="w-full" aria-disabled={busy || undefined} onClick={busy ? undefined : onManage} - data-plans-primary="" > {t('auto.components.billing.manageBilling', 'Manage billing')} diff --git a/src/renderer/src/components/billing/use-orca-billing-status.test.tsx b/src/renderer/src/components/billing/use-orca-billing-status.test.tsx index c9ac1d5ae41..5bb5464963c 100644 --- a/src/renderer/src/components/billing/use-orca-billing-status.test.tsx +++ b/src/renderer/src/components/billing/use-orca-billing-status.test.tsx @@ -3,9 +3,7 @@ import { act, cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' -let accountKey = 'user-1:team-a' -vi.mock('@/hooks/use-orca-account-key', () => ({ useOrcaAccountKey: () => accountKey })) - +import { useAppStore } from '@/store' import { getLastBillingStatus, resetBillingSummary } from './billing-summary-store' import { sampleTeam } from './plan-billing-fixtures' import { useOrcaBillingStatus } from './use-orca-billing-status' @@ -19,8 +17,27 @@ const teamB: OrcaBillingStatusResult = { type Pending = { resolve: (result: OrcaBillingStatusResult) => void } let pending: Pending[] = [] +/** Signs in as `user-1` acting for `orgId`, as the auth status would after a team pick. */ +function setAccount(orgId: string): void { + useAppStore.setState({ + orcaProfileAuthStatus: { + activeProfileId: 'local-default', + configured: true, + state: 'connected', + persistence: 'encrypted', + cloud: { + cloudProfileId: 'cloud-1', + userId: 'user-1', + email: 'ada@example.com', + linkedAt: 0, + activeOrgId: orgId + } + } + }) +} + beforeEach(() => { - accountKey = 'user-1:team-a' + setAccount('team-a') pending = [] resetBillingSummary() vi.stubGlobal('api', { @@ -43,8 +60,8 @@ afterEach(() => { /** What the auth subscriber does on a team switch: bump the generation, then re-render. */ function switchTeam(rerender: () => void, next: string): void { act(() => { + setAccount(next) resetBillingSummary() - accountKey = next rerender() }) } @@ -55,7 +72,7 @@ describe('useOrcaBillingStatus on a team switch', () => { await act(async () => pending[0].resolve(teamA)) expect(result.current.result).toEqual(teamA) - switchTeam(rerender, 'user-1:team-b') + switchTeam(rerender, 'team-b') expect(result.current).toMatchObject({ loading: true, result: null }) expect(pending).toHaveLength(2) @@ -68,7 +85,7 @@ describe('useOrcaBillingStatus on a team switch', () => { const { result, rerender } = renderHook(() => useOrcaBillingStatus(true)) expect(pending).toHaveLength(1) - switchTeam(rerender, 'user-1:team-b') + switchTeam(rerender, 'team-b') await act(async () => pending[0].resolve(teamA)) expect(result.current).toMatchObject({ loading: true, result: null }) expect(getLastBillingStatus()).toBeNull() @@ -90,3 +107,24 @@ describe('useOrcaBillingStatus on a team switch', () => { expect(result.current).toMatchObject({ loading: false, result: teamB }) }) }) + +describe('useOrcaBillingStatus on a failed re-read', () => { + it('keeps the last good plan when a focus re-read fails', async () => { + const { result } = renderHook(() => useOrcaBillingStatus(true)) + await act(async () => pending[0].resolve(teamA)) + + act(() => { + window.dispatchEvent(new Event('focus')) + }) + expect(pending).toHaveLength(2) + await act(async () => pending[1].resolve({ status: 'failed', error: 'offline' })) + + expect(result.current).toMatchObject({ loading: false, result: teamA }) + }) + + it('shows the failure when nothing was read yet', async () => { + const { result } = renderHook(() => useOrcaBillingStatus(true)) + await act(async () => pending[0].resolve({ status: 'failed', error: 'offline' })) + expect(result.current.result).toEqual({ status: 'failed', error: 'offline' }) + }) +}) diff --git a/src/renderer/src/components/billing/use-orca-billing-status.ts b/src/renderer/src/components/billing/use-orca-billing-status.ts index c3421c097ae..1c85b9baf1d 100644 --- a/src/renderer/src/components/billing/use-orca-billing-status.ts +++ b/src/renderer/src/components/billing/use-orca-billing-status.ts @@ -1,80 +1,49 @@ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useEffect } from 'react' import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' -import { - getBillingGeneration, - getLastBillingStatus, - recordBillingStatusIfCurrent -} from './billing-summary-store' +import { refreshBillingStatus, useBillingState, watchBillingStatus } from './billing-summary-store' type BillingStatusState = { + /** True until the first answer for this account arrives, and while a read runs. */ loading: boolean result: OrcaBillingStatusResult | null } -function readBillingStatus(): Promise { - return window.api.orcaProfiles - .billingStatus() - .catch((error: unknown): OrcaBillingStatusResult => ({ - status: 'failed', - error: error instanceof Error ? error.message : String(error) - })) -} - /** - * Reads the billing status while `enabled`, again on `refresh()`, and whenever the window regains - * focus (the user comes back from Checkout or the Portal in their browser). A team or account - * switch drops the previous team's status and reads the new one; an answer that started before - * the switch is never shown or recorded. + * The shared billing status while `enabled`: read on mount, again on `refresh()`, and whenever the + * window regains focus (the user comes back from Checkout or the Portal in their browser). A failed + * re-read keeps the last good answer. A team or account switch drops the previous team's status and + * reads the new one; an answer that started before the switch is never shown or recorded. */ export function useOrcaBillingStatus( enabled: boolean ): BillingStatusState & { refresh: () => void } { - const [state, setState] = useState(() => ({ - loading: enabled, - result: enabled ? getLastBillingStatus() : null - })) - const [reloadKey, setReloadKey] = useState(0) - const refresh = useCallback(() => setReloadKey((key) => key + 1), []) + const snapshot = useBillingState() const accountKey = useOrcaAccountKey() - const loadedAccount = useRef(accountKey) + // Billing just changed in-app (or the user asked): a read that started earlier may be stale. + const refresh = useCallback(() => void refreshBillingStatus({ supersede: true }), []) useEffect(() => { if (!enabled) { return } - let disposed = false - let latest = 0 - const switched = loadedAccount.current !== accountKey - loadedAccount.current = accountKey - const load = (): void => { - const request = ++latest - const startedGeneration = getBillingGeneration() - // The previous team's plan must not stay on screen while the new team's loads. - setState((previous) => - switched && request === 1 ? { loading: true, result: null } : { ...previous, loading: true } - ) - void readBillingStatus().then((result) => { - // A newer request, or unmounting, supersedes this one. - if (disposed || request !== latest) { - return - } - // The account or team changed while this was in flight: the answer is for the old one. - if (getBillingGeneration() !== startedGeneration) { - load() - return - } - recordBillingStatusIfCurrent(startedGeneration, result) - setState({ loading: false, result }) - }) - } + const release = watchBillingStatus() + const load = (): void => void refreshBillingStatus() load() window.addEventListener('focus', load) return () => { - disposed = true + release() window.removeEventListener('focus', load) } - }, [enabled, reloadKey, accountKey]) + }, [enabled, accountKey]) - return { ...state, refresh } + if (!enabled) { + return { loading: false, result: null, refresh } + } + return { + // No answer yet means one is on its way (the read starts after the first paint). + loading: snapshot.loading || snapshot.result === null, + result: snapshot.result, + refresh + } } diff --git a/src/renderer/src/components/new-workspace/orca-cloud-billing-cache.ts b/src/renderer/src/components/new-workspace/orca-cloud-billing-cache.ts index 75c64bcac9a..00ce2cbcce9 100644 --- a/src/renderer/src/components/new-workspace/orca-cloud-billing-cache.ts +++ b/src/renderer/src/components/new-workspace/orca-cloud-billing-cache.ts @@ -1,101 +1,54 @@ -import { useEffect, useMemo, useSyncExternalStore } from 'react' -import { useAppStore } from '@/store/index' -import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' +import { useEffect, useMemo } from 'react' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' +import { + getBillingReadInFlight, + getBillingState, + hasBillingWatchers, + markBillingStale, + refreshBillingStatus, + resetBillingSummary, + useBillingState, + watchBillingStatus, + type BillingStoreState +} from '@/components/billing/billing-summary-store' import { toOrcaCloudRunTargetAccess, type OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' /** - * One billing-status read shared by the Run-on picker and the selection hint. The composer prefetches - * it on mount so the Orca Cloud row rarely shows a loading state; focus refreshes it at most every - * STALE_MS (the user may come back from Checkout or the portal). The result is keyed by account and - * org, so a switch never shows the previous one's entitlement, and a newer read always wins. + * The Run-on picker's and selection hint's view of the shared billing store. The composer prefetches + * on mount so the Orca Cloud row rarely shows a loading state; focus re-reads at most every STALE_MS + * (the user may come back from Checkout or the portal). The store is scoped to the account and team, + * keeps the last good answer through a failed read, and a newer read always wins. */ const STALE_MS = 30_000 -type CacheState = { - result: OrcaBillingStatusResult | null - /** Account/org the result belongs to. */ - authKey: string | null - loading: boolean - fetchedAt: number -} - -let state: CacheState = { result: null, authKey: null, loading: false, fetchedAt: 0 } -let inFlight: { generation: number; authKey: string; promise: Promise } | null = null -let generation = 0 -const listeners = new Set<() => void>() - -function set(next: CacheState): void { - state = next - for (const listener of listeners) { - listener() - } -} - -function subscribe(listener: () => void): () => void { - listeners.add(listener) - return () => listeners.delete(listener) -} - -function currentAuthKey(): string { - const status = useAppStore.getState().orcaProfileAuthStatus - return `${status?.activeProfileId}:${status?.state}:${status?.cloud?.activeOrgId}` -} - /** - * Starts a read unless a matching one is running or the cached one is fresh for this account. + * Starts a read unless one is running or the cached answer is fresh for this account. * `force` (after an in-app billing change) always starts a new read that supersedes any running one. */ export function prefetchOrcaCloudBilling(force = false): Promise { - const authKey = currentAuthKey() - if (!force && inFlight && inFlight.authKey === authKey) { - return inFlight.promise - } - const fresh = state.authKey === authKey && Date.now() - state.fetchedAt < STALE_MS - if (!force && state.result && fresh) { - return Promise.resolve() - } - const mine = ++generation - const read = async (): Promise => { - try { - return await window.api.orcaProfiles.billingStatus() - } catch (error) { - return { status: 'failed', error: error instanceof Error ? error.message : String(error) } - } - } - const promise = read().then((result) => { - // A newer read, a reset, or an account switch supersedes this one. - if (mine !== generation) { - return - } - inFlight = null - set({ result, authKey, loading: false, fetchedAt: Date.now() }) - }) - inFlight = { generation: mine, authKey, promise } - set({ ...state, loading: true }) - return promise + return refreshBillingStatus(force ? { supersede: true } : { maxAgeMs: STALE_MS }) } /** * After billing changes in-app (overage, cap) the cached read is wrong: refetch now if anyone is - * listening. `refetchNow: false` only marks it stale, for fixes that finish elsewhere (plans, + * looking. `refetchNow: false` only marks it stale, for fixes that finish elsewhere (plans, * portal), so the next mount or focus reads again instead of trusting a 30s-fresh answer. */ export function invalidateOrcaCloudBilling({ refetchNow = true } = {}): void { - set({ ...state, fetchedAt: 0 }) - if (refetchNow && listeners.size > 0) { + markBillingStale() + if (refetchNow && hasBillingWatchers()) { void prefetchOrcaCloudBilling(true) } } -function accessFrom(snapshot: CacheState, authKey: string): OrcaCloudRunTargetAccess { - const result = snapshot.authKey === authKey ? snapshot.result : null - if (!result && snapshot.loading) { +function accessFrom(snapshot: BillingStoreState): OrcaCloudRunTargetAccess { + if (!snapshot.result && snapshot.loading) { return { state: 'loading' } } - return toOrcaCloudRunTargetAccess(result) + return toOrcaCloudRunTargetAccess(snapshot.result) } /** Resolves once billing has answered, or after `timeoutMs` with whatever is known then. */ @@ -109,37 +62,36 @@ export async function waitForOrcaCloudAccess(timeoutMs: number): Promise state) - const authKey = useAppStore((s) => { - const status = s.orcaProfileAuthStatus - return `${status?.activeProfileId}:${status?.state}:${status?.cloud?.activeOrgId}` - }) - // Re-runs on account/org change: the keyed cache then reads as empty and refetches. + const snapshot = useBillingState() + const accountKey = useOrcaAccountKey() + // Re-runs on account/team change: the store then drops the old answer and reads the new one. useEffect(() => { if (!enabled) { return } + const release = watchBillingStatus() void prefetchOrcaCloudBilling() const onFocus = (): void => void prefetchOrcaCloudBilling() window.addEventListener('focus', onFocus) - return () => window.removeEventListener('focus', onFocus) - }, [enabled, authKey]) - return useMemo(() => accessFrom(snapshot, authKey), [snapshot, authKey]) + return () => { + release() + window.removeEventListener('focus', onFocus) + } + }, [enabled, accountKey]) + return useMemo(() => accessFrom(snapshot), [snapshot]) } /** Test seam: forget the cached read and orphan any running one. */ export function resetOrcaCloudBillingCache(): void { - generation += 1 - inFlight = null - set({ result: null, authKey: null, loading: false, fetchedAt: 0 }) + resetBillingSummary() } diff --git a/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx b/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx index ee4a381618f..0e661f7425a 100644 --- a/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx +++ b/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx @@ -1,5 +1,6 @@ import { defineFixture } from '../../component-fixtures/component-fixture' import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles' +import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' import SidebarToolbar from './SidebarToolbar' import { registerPlanBillingMenuItem } from '../billing/register-plan-billing-menu-item' import { recordBillingStatus } from '../billing/billing-summary-store' @@ -45,18 +46,20 @@ const signedInWithBilling: OrcaProfileAuthStatus = { } /** Registers the billing items as main.tsx does, with a known plan state. */ -const withBilling = (subscribed: boolean) => (): void => { - const result = { - status: 'ok' as const, - entitlement: subscribed - ? sampleTeam - : { ...sampleTeam, plan: null, planLabel: null, status: 'none' } +const withBilling = + (subscribed: boolean, usage: Partial = {}) => + (): void => { + const result = { + status: 'ok' as const, + entitlement: subscribed + ? { ...sampleTeam, ...usage } + : { ...sampleTeam, plan: null, planLabel: null, status: 'none' } + } + // The registration re-reads billing when the account changes; answer like the service would. + window.api.orcaProfiles.billingStatus = async () => result + registerPlanBillingMenuItem() + recordBillingStatus(result) } - // The registration re-reads billing when the account changes; answer like the service would. - window.api.orcaProfiles.billingStatus = async () => result - registerPlanBillingMenuItem() - recordBillingStatus(result) -} const signedOut: OrcaProfileAuthStatus = { activeProfileId: 'local-default', @@ -117,6 +120,18 @@ export const signedInMenuOnTeam = footer({ interact: openAccountMenu }) +/** The team at billing's 75% level: hours left and the early warning in the header. */ +export const signedInMenuUsageWarning = footer({ + height: 360, + authStatus: signedInWithBilling, + setup: withBilling(true, { + usedSeconds: 92 * 3600, + remainingIncludedSeconds: 28 * 3600, + usageWarningPercent: 75 + }), + interact: openAccountMenu +}) + const openTeamSwitcher = async (frame: HTMLElement): Promise => { await openAccountMenu(frame) const trigger = document.querySelector('[data-account-menu-team-switcher]') diff --git a/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx b/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx index 7ad8dbc2ab7..4c15bd4dce6 100644 --- a/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx +++ b/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx @@ -16,7 +16,8 @@ import { useMountedRef } from '@/hooks/useMountedRef' import { useOptionalShortcutLabel } from '@/hooks/useShortcutLabel' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' -import { useBillingSummary } from '../../billing/billing-summary-store' +import { useBillingState } from '../../billing/billing-summary-store' +import { accountMenuUsageLines } from '../../billing/plan-billing-usage-copy' import { SidebarTeamSubmenu } from './SidebarTeamSubmenu' import { useSetupGuideProgress } from '../../setup-guide/use-setup-guide-progress' import { getAccountMenuIdentity, type AccountMenuIdentity } from './account-menu-identity' @@ -68,21 +69,8 @@ export function SidebarAccountMenu(): React.JSX.Element { const mountedRef = useMountedRef() const identity = getAccountMenuIdentity(authStatus) - const billingSummary = useBillingSummary() - const orgName = authStatus?.state === 'connected' ? authStatus.cloud?.activeOrgName : undefined - // "Acme · Team plan": which team this account acts for, and its plan once billing has answered. - const orgLine = orgName - ? billingSummary.planLabel - ? t( - 'auto.components.sidebar.SidebarAccountMenu.teamPlanLine', - '{{value0}} · {{value1}} plan', - { - value0: orgName, - value1: billingSummary.planLabel - } - ) - : orgName - : null + // The team is named once, on the switcher below; the header carries the plan's hours instead. + const usage = accountMenuUsageLines(useBillingState().result, t) const visibleItems = selectVisibleAccountMenuItems(registeredItems, authStatus) // Freeze the item list while the menu is open: a billing answer arriving mid-read must not // swap rows under the pointer (e.g. Upgrade replacing Plan & billing). @@ -196,8 +184,13 @@ export function SidebarAccountMenu(): React.JSX.Element { {identity.email} ) : null} - {orgLine ? ( - {orgLine} + {usage ? ( + + {usage.hoursLeft} + + ) : null} + {usage?.warning ? ( + {usage.warning} ) : null} ) : ( diff --git a/src/renderer/src/components/ui/dialog.tsx b/src/renderer/src/components/ui/dialog.tsx index ed2a5906b63..cb800f955c6 100644 --- a/src/renderer/src/components/ui/dialog.tsx +++ b/src/renderer/src/components/ui/dialog.tsx @@ -70,10 +70,11 @@ function DialogContentCloseButton({ variant }: { variant: 'close' | 'minimize' } variant === 'minimize' ? t('auto.components.ui.dialog.minimize', 'Minimize') : t('auto.components.ui.dialog.f26c4baeda', 'Close') + // A 24px hit area around the 16px glyph, centered where the glyph always sat (top/right 16px). const button = ( {variant === 'minimize' ? : } {label} @@ -193,7 +194,8 @@ function DialogTitle({ data-slot="dialog-title" data-size={size} className={cn( - 'text-lg leading-snug font-semibold break-words data-[size=compact]:text-sm data-[size=display]:text-2xl data-[size=display]:leading-tight data-[size=display]:tracking-tight md:data-[size=display]:text-[1.75rem]', + // outline-none: a title is never a control, but dialogs focus it (tabIndex -1) on open. + 'text-lg leading-snug font-semibold break-words outline-none data-[size=compact]:text-sm data-[size=display]:text-2xl data-[size=display]:leading-tight data-[size=display]:tracking-tight md:data-[size=display]:text-[1.75rem]', className )} {...props} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index e2f3bf70f8c..ac058397eef 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -8,6 +8,7 @@ import { useAppStore } from '@/store' import { useTranslate, type Translate } from '@/i18n/use-translate' import { resolveVmEnvironmentCheckDecision } from '@/lib/ephemeral-vm-environment-check-decision' import { openPlansPage } from '@/components/billing/plans/plans-page-store' +import { ORCA_BILLING_OVERAGE_SECTION_ID } from '@/components/new-workspace/orca-cloud-run-target-access' import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' import { toast } from 'sonner' import type { EnvironmentSetupFailureContext } from '../../../../shared/environment-setup-agent-prompt' @@ -287,7 +288,15 @@ export function VmBuildSheet({ onCreateLocally: () => onReturnToComposer({ local: true }), onOpenBilling: () => { const store = useAppStore.getState() - store.openSettingsTarget({ pane: 'orca-account', repoId: null }) + store.openSettingsTarget({ + pane: 'orca-account', + repoId: null, + // "Turn on overage" / "Raise spend cap" land on the overage card itself; the + // payment notice is at the top of the section already. + ...(failure?.kind === 'payment' + ? {} + : { sectionId: ORCA_BILLING_OVERAGE_SECTION_ID }) + }) store.openSettingsPage() }, onSignIn: signIn, diff --git a/src/renderer/src/hooks/use-orca-account-key.ts b/src/renderer/src/hooks/use-orca-account-key.ts index fcc0c894719..cf21dc3e338 100644 --- a/src/renderer/src/hooks/use-orca-account-key.ts +++ b/src/renderer/src/hooks/use-orca-account-key.ts @@ -1,12 +1,16 @@ import { useAppStore } from '@/store' +import type { OrcaProfileAuthStatus } from '../../../shared/orca-profiles' + +/** `${userId}:${activeOrgId}` for the signed-in Orca account, or 'signed-out'. */ +export function getOrcaAccountKey(status: OrcaProfileAuthStatus | null | undefined): string { + const cloud = status?.cloud + return cloud ? `${cloud.userId}:${cloud.activeOrgId ?? ''}` : 'signed-out' +} /** * `${userId}:${activeOrgId}` for the signed-in Orca account. Team-scoped views key on it so a * team switch remounts them: nothing read for the previous team survives into the new one. */ export function useOrcaAccountKey(): string { - return useAppStore((state) => { - const cloud = state.orcaProfileAuthStatus?.cloud - return cloud ? `${cloud.userId}:${cloud.activeOrgId ?? ''}` : 'signed-out' - }) + return useAppStore((state) => getOrcaAccountKey(state.orcaProfileAuthStatus)) } diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index c62981bd29f..43c799db3c9 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -212,11 +212,15 @@ "lineItemYearly_other": "{{seats}} × {{price}} per seat, billed yearly" }, "plans": { + "sandboxHoursLeftResets_one": "{{count}} sandbox hour left · resets {{date}}", + "sandboxHoursLeftResets_other": "{{count}} sandbox hours left · resets {{date}}", "seatsPerMember_one": "{{count}} seat, one per team member", "seatsPerMember_other": "{{count}} seats, one per team member" }, - "sandboxHoursOver_one": "{{count}} sandbox hour over", - "sandboxHoursOver_other": "{{count}} sandbox hours over", + "sandboxHoursLeftCount_one": "{{count}} sandbox hour left", + "sandboxHoursLeftCount_other": "{{count}} sandbox hours left", + "sandboxHoursOverIncluded_one": "{{count}} sandbox hour over the included amount this month", + "sandboxHoursOverIncluded_other": "{{count}} sandbox hours over the included amount this month", "seatsAnnual_one": "{{count}} seat · Annual", "seatsAnnual_other": "{{count}} seats · Annual", "seatsMonthly_one": "{{count}} seat · Monthly", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 5cf7cb7c955..c460efdcd89 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -7928,8 +7928,7 @@ "account": "Account", "signIn": "Sign in", "accountNamed": "Account: {{value0}}", - "accountReconnect": "Account: sign in again", - "teamPlanLine": "{{value0}} · {{value1}} plan" + "accountReconnect": "Account: sign in again" }, "CloudSshIncludeDialog": { "title": "Let {{editor}} find your cloud workspaces?", @@ -20609,7 +20608,6 @@ "subtitleSubscribed": "Usage this month, your plan, and what Enterprise adds.", "subtitle2": "Run Orca agents in hosted sandboxes that keep going when you step away.", "vpRunningBody2": "Sandboxes keep working while you are away and report back when they finish.", - "leftResets": "{{value0}} hours left · resets {{value1}}", "retry": "Try again", "featureSleep3": "Sleeps after {{value0}} minutes idle, so quiet time is free", "featureReady": "Ready in seconds, nothing to set up or host", @@ -20635,9 +20633,11 @@ "perSeatPerMonth": "per seat per month", "seatsPerMember_one": "{{count}} seat, one per team member", "seatsPerMember_other": "{{count}} seats, one per team member", - "vpWakeBody2": "Idle sandboxes sleep to save hours and wake with your files as you left them.", "totalPerMonth": "{{total}} per month", - "totalPerYear": "{{total}} per year" + "totalPerYear": "{{total}} per year", + "sandboxHoursLeftResets_one": "{{count}} sandbox hour left · resets {{date}}", + "sandboxHoursLeftResets_other": "{{count}} sandbox hours left · resets {{date}}", + "vpWakeBody3": "Idle sandboxes sleep to save sandbox hours and wake with your files as you left them." }, "capLabel2": "Monthly spend cap", "capSaved": "Saved", @@ -20700,7 +20700,6 @@ "openForbidden2": "Only an owner or admin can manage billing.", "openSignedOut2": "Sign in to Orca again to manage your team.", "overageDescription6": "Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set ({{cap}} by default).", - "overageHoursOnly": "{{value0}} overage hours this month", "overageMemberHint": "Owners and admins can change overage.", "overageOffRead": "Off", "overageOnRead": "On", @@ -20715,23 +20714,25 @@ "resetsAndRenews": "Resets and renews {{value0}}", "resetsEnds": "Hours reset {{value0}} · Plan ends {{value1}}", "resetsRenews": "Hours reset {{value0}} · Renews {{value1}}", - "sandboxHoursLeft": "{{value0}} sandbox hours left", "sandboxHoursUsedMonth": "{{value0}} of {{value1}} sandbox hours used this month", - "warn100b": "All of this month’s sandbox hours are used.", - "warnPercent2": "You’ve used {{value0}}% of this month’s sandbox hours.", "overageDescriptionOn3": "Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set.", "reasonCapMember3": "Spend cap reached. Ask an owner or admin to raise the spend cap. Your files are safe.", "reasonGraceExpired3": "Payment failed. New sandboxes can’t start and running sandboxes are asleep. Update your payment method. Your files are safe.", "reasonGraceExpiredMember2": "Payment failed. New sandboxes can’t start and running sandboxes are asleep. Ask an owner or admin to update the payment method. Your files are safe.", "reasonNoPlan2": "Orca Cloud needs a Team plan.", - "sandboxHoursOver_one": "{{count}} sandbox hour over", - "sandboxHoursOver_other": "{{count}} sandbox hours over", "sandboxHoursUsedLabel": "Sandbox hours used", "seatsAnnual_one": "{{count}} seat · Annual", "seatsAnnual_other": "{{count}} seats · Annual", "seatsMonthly_one": "{{count}} seat · Monthly", "seatsMonthly_other": "{{count}} seats · Monthly", - "upsellLine2": "Orca Cloud runs agents in sandboxes. Team is {{value0}} per seat per month." + "upsellLine2": "Orca Cloud runs agents in sandboxes. Team is {{value0}} per seat per month.", + "capAtMost": "The spend cap can be at most {{max}}.", + "loadingPlan": "Loading your plan…", + "sandboxHoursLeftCount_one": "{{count}} sandbox hour left", + "sandboxHoursLeftCount_other": "{{count}} sandbox hours left", + "sandboxHoursOverIncluded_one": "{{count}} sandbox hour over the included amount this month", + "sandboxHoursOverIncluded_other": "{{count}} sandbox hours over the included amount this month", + "teamUsedPercent": "Your team has used {{percent}}% of this month’s sandbox hours." }, "ports": { "RuntimePortAutoForwarder": { diff --git a/src/shared/orca-billing.ts b/src/shared/orca-billing.ts index 23252573f91..74f544bfd27 100644 --- a/src/shared/orca-billing.ts +++ b/src/shared/orca-billing.ts @@ -77,6 +77,8 @@ export type OrcaBillingOffers = { idleSleepMinutes: number overageCentsPerHour: number defaultSpendCapCents: number + /** Highest monthly spend cap billing accepts; null from older services. */ + maxSpendCapCents: number | null } enterprise: { label: string; priceLabel: string; contactUrl: string } } From 018f918a8ce9a4412e59a66bb500802fc80cf38d Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 03:39:16 -0800 Subject: [PATCH 46/46] fix(billing): usage warning states the actual share used, floored (DS-34 review) --- .../billing/plan-billing-usage-copy.test.ts | 13 ++++++++++ .../billing/plan-billing-usage-copy.ts | 24 +++++++++++++++---- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts index f1b5292ecee..57bf4e51b26 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts @@ -61,6 +61,19 @@ describe('sandbox hours copy', () => { expect(usageWarningLine(team({ usageWarningPercent: 100 }), t)).toBeNull() }) + it('states the actual share used, floored, not the level that triggered it', () => { + expect(usageWarningLine(team({ usedSeconds: 119 * HOUR, usageWarningPercent: 90 }), t)).toBe( + 'Your team has used 99% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usedSeconds: 92 * HOUR, usageWarningPercent: 75 }), t)).toBe( + 'Your team has used 76% of this month’s sandbox hours.' + ) + // Never "100%" while billing still reports hours left. + expect(usageWarningLine(team({ usedSeconds: 119.9 * HOUR, usageWarningPercent: 90 }), t)).toBe( + 'Your team has used 99% of this month’s sandbox hours.' + ) + }) + it('turns the hours bar to the warning tone at 90%', () => { expect(includedUsageTone(team({ usedSeconds: 107 * HOUR }))).toBe('default') expect(includedUsageTone(team({ usedSeconds: 108 * HOUR }))).toBe('warning') diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.ts index a4c45fcbbec..4b2852f860c 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.ts @@ -56,18 +56,32 @@ export function sandboxHoursOverLine( } /** - * The early warning at whichever level billing reports (75%, 90%) until the hours run out; at 100% - * the bar, the hours-left line and the out-of-hours states say it instead. + * The share of included hours actually used, floored, for the warning sentence: never below the + * level billing reported (its count may be fresher) and never 100 while hours remain. + */ +export function usedPercentForWarning(entitlement: OrcaBillingEntitlement): number { + const level = entitlement.usageWarningPercent ?? 0 + const used = + entitlement.includedSeconds > 0 + ? Math.floor((entitlement.usedSeconds / entitlement.includedSeconds) * 100) + : level + return Math.min(99, Math.max(level, used)) +} + +/** + * Shown once billing reports a warning level (75%, 90%) until the hours run out; the sentence states + * the actual share used, not the level. At 100% the bar, the hours-left line and the out-of-hours + * states say it instead. */ export function usageWarningLine(entitlement: OrcaBillingEntitlement, t: Translate): string | null { - const percent = entitlement.usageWarningPercent - if (percent === null || percent >= 100) { + const level = entitlement.usageWarningPercent + if (level === null || level >= 100) { return null } return t( 'auto.components.billing.teamUsedPercent', 'Your team has used {{percent}}% of this month’s sandbox hours.', - { percent: String(percent) } + { percent: String(usedPercentForWarning(entitlement)) } ) }