From 85f5283d98daac9f5c7ac9d5d70597540b97ada5 Mon Sep 17 00:00:00 2001 From: Neil Date: Sat, 14 Nov 2026 22:13:51 -0800 Subject: [PATCH 01/35] =?UTF-8?q?feat(settings):=20Orca=20Cloud=20agent=20?= =?UTF-8?q?sign-ins=20move=20to=20Settings=20=E2=80=BA=20Orca=20Cloud=20?= =?UTF-8?q?=E2=80=BA=20Cloud=20agent=20sign-ins?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neil: an Orca Cloud part inside Settings › Agent accounts was confusing. The Claude and ChatGPT sign-ins for cloud workspaces (set up, paste a token, renew, remove) are now their own page in the Orca Cloud group, right after Account & billing. Agent accounts keeps This computer and Hosts and one row, "Orca Cloud sign-ins live in Orca Cloud settings", that opens the new page. Every deep link moves with it: Renew in Settings, the sign-in sheet's footer, the host panel, and old links to pane 'accounts' at 'orca-cloud' / 'accounts-orca-cloud' (resolveCloudAgentSignInsTarget). Copy that sent people to "Settings → Agent accounts" for Orca Cloud now says "Settings → Cloud agent sign-ins" (new i18n keys so stale translations don't point at the old place), including sandbox-control's expired-Claude and RS-4 Codex messages. Search: the Orca Cloud keywords (subscription, chatgpt, setup-token, renew) move to the new page. Behavior is unchanged. --- .../sandbox-control/src/account-providers.ts | 2 +- .../sandbox-control/src/codex-credentials.ts | 2 +- .../test/agent-accounts.test.ts | 2 +- .../sandbox-control/test/codex-broker.test.ts | 2 +- .../CloudAgentsPanelSection.tsx | 7 +- .../open-agent-host-settings.ts | 3 +- .../cloud-agent-setup-strip-model.ts | 2 +- .../cloud-renew-in-place.ts | 6 +- .../cloud-setup-strip-actions.ts | 2 +- .../new-workspace/OrcaCloudAgentSetupRow.tsx | 14 +-- .../run-on/cloud-start-agent-step.test.ts | 2 +- .../orca-cloud/CloudAgentRowSignInTarget.tsx | 2 +- .../CloudAgentSignInsLinkRow.tsx | 26 +++++ .../CloudAgentSignInsPage.fixture.tsx | 103 ++++++++++++++++++ .../agent-accounts/OrcaCloudAccounts.tsx | 2 +- .../agent-accounts/agent-accounts-search.ts | 25 ++++- .../orca-cloud-accounts-types.ts | 2 +- .../sign-in-sheet/OrcaCloudSignInSheet.tsx | 8 +- .../settings/cloud-api/cloud-api-copy.ts | 4 +- .../cloud-api/cloud-api-format.test.ts | 2 +- .../cloud-secrets/cloud-secrets-copy.ts | 4 +- .../navigation/settings-navigation-types.ts | 1 + .../settings-capability-section-renderers.tsx | 5 +- ...rca-cloud-agent-accounts-sections.test.tsx | 38 +++++-- ...ngs-orca-cloud-agent-accounts-sections.tsx | 27 +++-- .../settings-orca-cloud-section-renderers.tsx | 26 ++++- .../settings/page/settings-page-renderer.tsx | 8 +- .../page/use-settings-page-effects.ts | 13 ++- .../cloud-agents-row/build-agents-row-copy.ts | 9 +- ...ngs-navigation-orca-cloud-sections.test.ts | 42 ++++++- ...settings-navigation-orca-cloud-sections.ts | 43 +++++++- .../src/i18n/en-runtime-required.json | 26 +++++ src/renderer/src/i18n/locales/en.json | 37 +++++-- .../lib/orca-cloud/cloud-agent-row-sign-in.ts | 2 +- .../orca-cloud-agent-accounts-model.ts | 2 +- src/shared/cloud-api/routine-run-sign-in.ts | 2 +- 36 files changed, 421 insertions(+), 82 deletions(-) create mode 100644 src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsLinkRow.tsx create mode 100644 src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsPage.fixture.tsx diff --git a/cloud/apps/sandbox-control/src/account-providers.ts b/cloud/apps/sandbox-control/src/account-providers.ts index aa110528382..a48b2751662 100644 --- a/cloud/apps/sandbox-control/src/account-providers.ts +++ b/cloud/apps/sandbox-control/src/account-providers.ts @@ -100,7 +100,7 @@ export const claudeAccount: AccountProvider = { type: 'error', error: { type: 'authentication_error', - message: 'Your Claude sign-in for Orca Cloud expired. Renew it in Orca: Settings → Agent accounts.' + message: 'Your Claude sign-in for Orca Cloud expired. Renew it in Orca: Settings → Cloud agent sign-ins.' } }) } diff --git a/cloud/apps/sandbox-control/src/codex-credentials.ts b/cloud/apps/sandbox-control/src/codex-credentials.ts index 7065a8c8793..d6a0b9eb119 100644 --- a/cloud/apps/sandbox-control/src/codex-credentials.ts +++ b/cloud/apps/sandbox-control/src/codex-credentials.ts @@ -183,7 +183,7 @@ export const codexAccount: AccountProvider = { status: 403, contentType: 'application/json', body: JSON.stringify({ - detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Agent accounts.' + detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Cloud agent sign-ins.' }) }, // CODEX-EGRESS-BLOCKED: chatgpt.com answers Cloudflare Workers' egress with a 403 "Unable to load diff --git a/cloud/apps/sandbox-control/test/agent-accounts.test.ts b/cloud/apps/sandbox-control/test/agent-accounts.test.ts index 63e9261d9f4..85c422797da 100644 --- a/cloud/apps/sandbox-control/test/agent-accounts.test.ts +++ b/cloud/apps/sandbox-control/test/agent-accounts.test.ts @@ -42,7 +42,7 @@ function decode(encoded: string | undefined): Record { function expectSignedOut(answer: { status: number; body: string }): void { expect(answer.status).toBe(401) expect(JSON.parse(answer.body)).toMatchObject({ type: 'error', error: { type: 'authentication_error' } }) - expect(JSON.parse(answer.body).error.message).toBe('Your Claude sign-in for Orca Cloud expired. Renew it in Orca: Settings → Agent accounts.') + expect(JSON.parse(answer.body).error.message).toBe('Your Claude sign-in for Orca Cloud expired. Renew it in Orca: Settings → Cloud agent sign-ins.') } async function setup(overrides: Record = {}) { diff --git a/cloud/apps/sandbox-control/test/codex-broker.test.ts b/cloud/apps/sandbox-control/test/codex-broker.test.ts index b6d925cfbf7..19479480d57 100644 --- a/cloud/apps/sandbox-control/test/codex-broker.test.ts +++ b/cloud/apps/sandbox-control/test/codex-broker.test.ts @@ -381,7 +381,7 @@ describe('Codex account in workspaces (D10, D13)', () => { // RS-4: still a 403 (a 401 would start Codex's own token refresh), now with words Codex prints. expect(refused.status).toBe(403) expect(JSON.parse(refused.body)).toEqual({ - detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Agent accounts.' + detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Cloud agent sign-ins.' }) expect(lastEnv('/opt/orca/bin/orca-sandbox-env').ORCA_CODEX_AUTH_PLACEHOLDER).toBeUndefined() }) diff --git a/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx b/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx index c64e631a22e..81e43653140 100644 --- a/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx +++ b/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx @@ -29,7 +29,7 @@ export type CloudAgentsPanelLoad = export type CloudAgentsPanelActions = { chooseSource: (agent: OrcaCloudAccountAgent, source: Exclude) => void - /** Settings › Agent accounts (S0): set up once, or renew. */ + /** Settings › Orca Cloud › Cloud agent sign-ins (S0): set up once, or renew. */ manage: () => void signIn: () => void retry: () => void @@ -63,7 +63,10 @@ function statusCopy(row: CloudAgentPanelRow, t: Translate): { line: string; deta line: t('agentHostPanel.cloud.expired', 'Your {{agent}} sign-in for Orca Cloud expired', { agent }), - detail: t('agentHostPanel.cloud.expiredDetail', 'Renew it once in Agent accounts.') + detail: t( + 'agentHostPanel.cloud.expiredDetailCloudSignIns', + 'Renew it once in Cloud agent sign-ins.' + ) } case 'sharedUnavailable': return { diff --git a/src/renderer/src/components/agent-host-panel/open-agent-host-settings.ts b/src/renderer/src/components/agent-host-panel/open-agent-host-settings.ts index b5634b5bdc2..aec0fcfdc56 100644 --- a/src/renderer/src/components/agent-host-panel/open-agent-host-settings.ts +++ b/src/renderer/src/components/agent-host-panel/open-agent-host-settings.ts @@ -7,7 +7,8 @@ import { closeAgentHostPanel } from './agent-host-panel-store' const TARGET = { accounts: { pane: 'accounts' }, - agentAccounts: { pane: 'accounts', sectionId: 'orca-cloud' }, + // Opens the sign-in sheet (below); its page is Settings › Orca Cloud › Cloud agent sign-ins. + agentAccounts: { pane: 'cloud-agent-sign-ins' }, agentApiKeys: { pane: 'agent-api-keys' }, cloudSecrets: { pane: 'cloud-secrets' }, customEnvironments: { pane: 'servers' }, diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts index d9166b3a5ca..d96fc47f8ba 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts @@ -1,5 +1,5 @@ // PC-3b: the Orca Cloud pane strip for an agent that isn't set up yet. The launch holds; "Set up -// once" runs the same one-time setup as Settings › Accounts › Orca Cloud (S0) right in the pane, +// once" runs the same one-time setup as Settings › Orca Cloud › Cloud agent sign-ins (S0) right in the pane, // and once it's saved the strip offers "Start {{agent}}". Pure: the strip renders what this returns. import type { Translate } from '@/i18n/use-translate' import { diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts index 66a8c0cdaf1..6ba53db427d 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts @@ -110,7 +110,7 @@ export function cloudRenewInPlaceActions(args: { setup: OrcaCloudAgentSetup /** The surface's own actions, used outside the renewal (Restart, a renewed strip's ×). */ surface: CloudStripActions - /** "Renew in Settings": the same renewal in Settings › Accounts › Orca Cloud. */ + /** "Renew in Settings": the same renewal in Settings › Orca Cloud › Cloud agent sign-ins. */ openSettings: () => void copyText: (text: string) => void openLink: (url: string) => void @@ -147,10 +147,10 @@ export function cloudRenewInPlaceActions(args: { } } -/** "Renew in Settings": Settings › Accounts › Orca Cloud, where the same renewal runs. */ +/** "Renew in Settings": Settings › Orca Cloud › Cloud agent sign-ins, where the same renewal runs. */ export function openOrcaCloudAccountsSettings(): void { const store = useAppStore.getState() - store.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' }) + store.openSettingsTarget({ pane: 'cloud-agent-sign-ins', repoId: null }) store.openSettingsPage() } diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts index 7325eea6371..1d3e0f03a52 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts @@ -1,5 +1,5 @@ // PC-3b: what the "not set up" strip's buttons do. Set up once runs S0's setup for the agent (the -// same flow as Settings › Accounts › Orca Cloud); Start releases the held launch. Cancel during a +// same flow as Settings › Orca Cloud › Cloud agent sign-ins); Start releases the held launch. Cancel during a // setup stops only that setup: the launch stays held on "Set up once", and a setup finished from // anywhere (here or Settings) turns the strip into "Start". Cancel with no setup running gives up // the held launch and opens a plain shell, like cancelling any held launch (RR-a). diff --git a/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx b/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx index 5c0ed699d05..df27cd4a824 100644 --- a/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx +++ b/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx @@ -1,6 +1,6 @@ // The "Set up Orca Cloud" panel's Agent row (cloud-start G). It replaces the old "Add an agent / // Later" hint: it says how the composer's agent will sign in, links to the one-time setup in -// Settings → Agent accounts, and never blocks Start or signs in per sandbox. +// Settings → Cloud agent sign-ins, and never blocks Start or signs in per sandbox. import { useEffect } from 'react' import { openOrcaCloudSignInSheet } from '@/components/settings/agent-accounts/sign-in-sheet/orca-cloud-sign-in-sheet-store' import { CircleCheck, CircleDashed, Info, TriangleAlert } from 'lucide-react' @@ -47,8 +47,8 @@ export function orcaCloudAgentRowCopy( case 'notSetUp': return { detail: t( - 'orcaCloudAgentRow.notSetUp', - '{{agent}} isn’t set up for Orca Cloud yet. Set it up once in Settings → Agent accounts.', + 'orcaCloudAgentRow.notSetUpCloudSignIns', + '{{agent}} isn’t set up for Orca Cloud yet. Set it up once in Settings → Cloud agent sign-ins.', { agent } ), action: { @@ -59,8 +59,8 @@ export function orcaCloudAgentRowCopy( case 'expired': return { detail: t( - 'orcaCloudAgentRow.expired', - 'Your {{agent}} sign-in for Orca Cloud expired. Renew it once in Settings → Agent accounts.', + 'orcaCloudAgentRow.expiredCloudSignIns', + 'Your {{agent}} sign-in for Orca Cloud expired. Renew it once in Settings → Cloud agent sign-ins.', { agent } ), action: { @@ -79,8 +79,8 @@ export function orcaCloudAgentRowCopy( case 'signedOut': return { detail: t( - 'orcaCloudAgentRow.signedOut', - '{{agent}}: set up once in Settings → Agent accounts after you sign in', + 'orcaCloudAgentRow.signedOutCloudSignIns', + '{{agent}}: set up once in Settings → Cloud agent sign-ins after you sign in', { agent } ), status: t('orcaCloudAgentRow.optional', 'Optional') diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-agent-step.test.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-agent-step.test.ts index fd9115bbed8..115f4ff7f90 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-agent-step.test.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-agent-step.test.ts @@ -20,7 +20,7 @@ describe('cloudStartAgentStep', () => { expect(step).toMatchObject({ state: 'optional', detail: - 'Claude isn’t set up for Orca Cloud yet. Set it up once in Settings → Agent accounts.', + 'Claude isn’t set up for Orca Cloud yet. Set it up once in Settings → Cloud agent sign-ins.', action: { label: 'Set up once' } }) expect(step?.blocksStart).toBeUndefined() diff --git a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx index f8cede4d274..dbf1cf33762 100644 --- a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx +++ b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx @@ -1,5 +1,5 @@ // The status (dot and text) of a cloud agent row that needs sign-in: clicking it opens -// Settings → Agent accounts, where the fix lives. The rest of the row still opens the pane. +// Orca Cloud sign-ins, where the fix lives. The rest of the row still opens the pane. import React, { useCallback } from 'react' import { cn } from '@/lib/class-names' import { AgentStateDot } from '@/components/AgentStateDot' diff --git a/src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsLinkRow.tsx b/src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsLinkRow.tsx new file mode 100644 index 00000000000..d679fcc2f41 --- /dev/null +++ b/src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsLinkRow.tsx @@ -0,0 +1,26 @@ +// Neil: Orca Cloud's sign-ins moved from Settings › Agent accounts to Settings › Orca Cloud › Cloud +// agent sign-ins. This one row stays in Agent accounts so someone who looks there isn't lost. +import type React from 'react' +import { ArrowRight, Cloud } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' + +export function CloudAgentSignInsLinkRow({ onOpen }: { onOpen: () => void }): React.JSX.Element { + const t = useTranslate() + return ( + + ) +} diff --git a/src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsPage.fixture.tsx b/src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsPage.fixture.tsx new file mode 100644 index 00000000000..a128d27988d --- /dev/null +++ b/src/renderer/src/components/settings/agent-accounts/CloudAgentSignInsPage.fixture.tsx @@ -0,0 +1,103 @@ +// The move (Neil): Orca Cloud's sign-ins as their own page in the Orca Cloud group, and the one +// row Agent accounts keeps. settings/agent-accounts/CloudAgentSignInsPage:. +import { defineFixture } from '../../../component-fixtures/component-fixture' +import type { OrcaCloudAgentAccountsLoad } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' +import type { OrcaCloudAgentsStatus } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { AgentAccountsJumpRow } from '../accounts/AgentAccountsJumpRow' +import { AgentAccountsSubsection } from '../accounts/AgentAccountsSubsection' +import { SettingsSection } from '../section-layout/SettingsSection' +import { CloudAgentSignInsLinkRow } from './CloudAgentSignInsLinkRow' +import { OrcaCloudAccountsDescription } from './OrcaCloudAccountsDescription' +import { OrcaCloudAccountsView, type OrcaCloudAccountsActions } from './OrcaCloudAccounts' + +const NOW = Date.UTC(2026, 10, 10, 18, 0, 0) +const YEAR = 365 * 24 * 60 * 60 * 1000 +const noop = (): void => {} +const ACTIONS: OrcaCloudAccountsActions = { + start: noop, + cancel: noop, + reopen: noop, + usePaste: noop, + submitSetupCode: noop, + pasteToken: async () => null, + remove: async () => null, + setSource: async () => null, + copyCode: noop, + retryLoad: noop, + signIn: noop +} +const STATUS: OrcaCloudAgentsStatus = { + credentials: { + claude: { state: 'none' }, + codex: { state: 'none' }, + providerEnabled: { claude: true, codex: true } + }, + sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } +} +const READY: OrcaCloudAgentAccountsLoad = { kind: 'ready', status: STATUS } + +/** Settings › Orca Cloud › Cloud agent sign-ins, as settings-orca-cloud-section-renderers draws it. */ +export const cloudAgentSignIns = defineFixture({ + width: 860, + render: () => ( +
+ } + forceVisible + grouped + > + + +
+ ) +}) + +/** Settings › Agent accounts in an Orca Cloud build: the link row above This computer. */ +export const agentAccountsLinkRow = defineFixture({ + width: 860, + render: () => ( +
+ + + + +
+ + +
+ ) +}) diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx index f62dd2096a4..76ea62aade9 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx @@ -1,4 +1,4 @@ -// S0 · Settings › Agent accounts › Orca Cloud (agent-accounts spec §5): the one place a Claude or +// S0 · Settings › Orca Cloud › Cloud agent sign-ins (agent-accounts spec §5): the one place a Claude or // ChatGPT account is connected to Orca Cloud, once, on this computer. Rows show states only; the // setup-token is captured in main and a pasted one goes to main once and never comes back. import type React from 'react' diff --git a/src/renderer/src/components/settings/agent-accounts/agent-accounts-search.ts b/src/renderer/src/components/settings/agent-accounts/agent-accounts-search.ts index 5b0e63b2a30..abd48ebaea2 100644 --- a/src/renderer/src/components/settings/agent-accounts/agent-accounts-search.ts +++ b/src/renderer/src/components/settings/agent-accounts/agent-accounts-search.ts @@ -2,18 +2,37 @@ import { translate } from '@/i18n/i18n' import { createLocalizedCatalog } from '@/i18n/localized-catalog' import { translateSearchKeyword } from '../search/settings-search-keywords' +/** Agent accounts in Orca Cloud builds: this computer and your hosts. Orca Cloud's own sign-ins + * are their own page in the Orca Cloud group (getCloudAgentSignInsSearchEntries). */ export const getAgentAccountsSearchEntries = createLocalizedCatalog(() => [ { title: translate('settings.agentAccounts.searchTitle', 'Agent accounts'), description: translate( - 'settings.agentAccounts.hubSearchDescription', - 'Where Claude and Codex are signed in: Orca Cloud, this computer and your hosts.' + 'settings.agentAccounts.hubSearchDescriptionHosts', + 'Where Claude and Codex are signed in on this computer and your hosts.' + ), + keywords: [ + ...translateSearchKeyword('settings.agentAccounts.search.signIn', 'sign in'), + ...translateSearchKeyword('settings.agentAccounts.search.hosts', 'hosts') + ] + } +]) + +/** Settings › Orca Cloud › Cloud agent sign-ins: Claude and ChatGPT sign-ins for cloud workspaces. */ +export const getCloudAgentSignInsSearchEntries = createLocalizedCatalog(() => [ + { + title: translate('settings.cloudAgentSignIns.searchTitle', 'Cloud agent sign-ins'), + description: translate( + 'settings.cloudAgentSignIns.searchDescription', + 'Set up Claude and Codex once for every cloud workspace: your Claude subscription or ChatGPT sign-in.' ), keywords: [ ...translateSearchKeyword('settings.agentAccounts.search.subscription', 'subscription'), ...translateSearchKeyword('settings.agentAccounts.search.signIn', 'sign in'), ...translateSearchKeyword('settings.agentAccounts.search.chatgpt', 'chatgpt'), - ...translateSearchKeyword('settings.agentAccounts.search.setupToken', 'setup-token') + ...translateSearchKeyword('settings.agentAccounts.search.setupToken', 'setup-token'), + ...translateSearchKeyword('settings.cloudAgentSignIns.search.renew', 'renew'), + ...translateSearchKeyword('settings.cloudAgentSignIns.search.agentAccounts', 'agent accounts') ] } ]) diff --git a/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts b/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts index 0bcd4c87f12..b6c13ba49f1 100644 --- a/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts +++ b/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts @@ -34,6 +34,6 @@ export type OrcaCloudAccountsViewProps = { /** Fixtures: open a row's Remove confirmation or a row-level save error. */ initialConfirmRemove?: OrcaCloudAccountAgent initialRowError?: { agent: OrcaCloudAccountAgent; error: OrcaCloudAgentsErrorCode } - /** Inside Settings → Agent accounts the page's Orca Cloud part already titles it. */ + /** Inside Settings › Orca Cloud › Cloud agent sign-ins the page already titles it. */ hideHeader?: boolean } diff --git a/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx b/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx index ebec6ee976d..0240dd48a87 100644 --- a/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx +++ b/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx @@ -16,10 +16,10 @@ import { useOrcaCloudSignInSheetOpen } from './orca-cloud-sign-in-sheet-store' -function openAllAgentAccounts(): void { +function openCloudAgentSignInsSettings(): void { closeOrcaCloudSignInSheet() const store = useAppStore.getState() - store.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' }) + store.openSettingsTarget({ pane: 'cloud-agent-sign-ins', repoId: null }) store.openSettingsPage() } @@ -55,9 +55,9 @@ export function OrcaCloudSignInSheetView({ 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 71cd4c031c6..fc96428a574 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 @@ -201,8 +201,8 @@ export function describeRoutineRunError( if (isRoutineRunAgentSignInFailure(error, summary)) { return failure( t( - 'auto.components.settings.cloudRoutines.runError.claudeNotSetUp', - 'Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Agent accounts, then run the routine again.' + 'auto.components.settings.cloudRoutines.runError.claudeNotSetUpCloudSignIns', + 'Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Cloud agent sign-ins, then run the routine again.' ) ) } 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 ea98b60d918..cd102bd0851 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 @@ -131,7 +131,7 @@ describe('run failure copy', () => { const copy = describeRoutineRunError('agent_exit_1', translate, summary) expect(copy.tone).toBe('error') expect(copy.text).toContain('Claude isn’t set up for Orca Cloud') - expect(copy.text).toContain('Settings → Agent accounts') + expect(copy.text).toContain('Settings → Cloud agent sign-ins') expect(copy.text).not.toContain('/login') // Another failure, or the same text outside an agent exit, keeps its own copy. expect(isRoutineRunAgentSignInFailure('agent_exit_1', 'tests failed')).toBe(false) 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 15a3125c3b4..2d6546707bc 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 @@ -54,8 +54,8 @@ export function cloudSecretsErrorCopy( ) case 'subscription_token_refused': return t( - 'cloudSecrets.error.subscriptionToken', - 'This is a Claude or ChatGPT subscription token, so it can’t be saved as a secret. Set up Claude once in Settings → Agent accounts instead.' + 'cloudSecrets.error.subscriptionTokenCloudSignIns', + 'This is a Claude or ChatGPT subscription token, so it can’t be saved as a secret. Set up Claude once in Settings → Cloud agent sign-ins instead.' ) case 'value_too_large': return t('cloudSecrets.error.valueTooLarge', 'Values can be up to 8 KB.') diff --git a/src/renderer/src/components/settings/navigation/settings-navigation-types.ts b/src/renderer/src/components/settings/navigation/settings-navigation-types.ts index 2c15ad538e4..570de85c12e 100644 --- a/src/renderer/src/components/settings/navigation/settings-navigation-types.ts +++ b/src/renderer/src/components/settings/navigation/settings-navigation-types.ts @@ -48,6 +48,7 @@ const SETTINGS_NAV_TARGETS = [ 'orca-account', 'cloud-billing', 'cloud-workspaces', + 'cloud-agent-sign-ins', 'cloud-secrets', 'cloud-environments', 'cloud-mcp', diff --git a/src/renderer/src/components/settings/page/settings-capability-section-renderers.tsx b/src/renderer/src/components/settings/page/settings-capability-section-renderers.tsx index 34f8a72a7f2..791eb20f2d0 100644 --- a/src/renderer/src/components/settings/page/settings-capability-section-renderers.tsx +++ b/src/renderer/src/components/settings/page/settings-capability-section-renderers.tsx @@ -64,11 +64,13 @@ export function renderAgentsSettingsSection( * Settings → Agent accounts: one page for agent sign-ins. "This computer" (or the host picked in the * scope picker) holds provider accounts, switching and usage; `additionalParts` lets a build add * more parts below it. With more than one part, a jump row under the description links to each. + * `lead` sits above the parts (Orca Cloud builds: the link to Cloud agent sign-ins). */ export function renderAccountsSettingsSection( context: SettingsRenderContext, t: Translate = translate, - additionalParts: readonly AgentAccountsPart[] = [] + additionalParts: readonly AgentAccountsPart[] = [], + lead: React.ReactNode = null ): React.JSX.Element { const { model, navigation, view } = context const isLocalScope = model.settingsHostScope.target.kind === 'local' @@ -94,6 +96,7 @@ export function renderAccountsSettingsSection( ...additionalParts.map(({ id, title }) => ({ id, title })) ]} /> + {lead} { - it('puts Orca Cloud above Hosts, after This computer (JA-04, option A1)', () => { + it('adds Hosts after This computer; Orca Cloud sign-ins are their own Orca Cloud page', () => { const parts = orcaCloudAgentAccountsParts( context({ showDesktopOnlySettings: true, orcaCloudApiAvailable: true }) ) - expect(parts.map((part) => part.id)).toEqual(['accounts-orca-cloud', 'accounts-hosts']) + expect(parts.map((part) => part.id)).toEqual(['accounts-hosts']) + }) + + it('keeps one row that opens Cloud agent sign-ins', () => { + const scrollToSection = vi.fn() + const lead = orcaCloudAgentAccountsLead( + context({ showDesktopOnlySettings: true, orcaCloudApiAvailable: true }, scrollToSection) + ) + render(<>{lead}) + fireEvent.click(screen.getByRole('button', { name: /Orca Cloud sign-ins live in/ })) + expect(scrollToSection).toHaveBeenCalledWith('cloud-agent-sign-ins') + for (const model of [ + { showDesktopOnlySettings: true, orcaCloudApiAvailable: false }, + { showDesktopOnlySettings: false, orcaCloudApiAvailable: true } + ]) { + expect(orcaCloudAgentAccountsLead(context(model))).toBeNull() + } }) it('adds nothing without an Orca Cloud control plane or outside the desktop', () => { diff --git a/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx b/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx index f63d1369808..13709e7285c 100644 --- a/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx +++ b/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx @@ -1,14 +1,14 @@ import type { AgentAccountsPart } from '../accounts/AgentAccountsSubsection' -import { OrcaCloudAccountsSection } from '../agent-accounts/OrcaCloudAccountsSection' -import { OrcaCloudAccountsDescription } from '../agent-accounts/OrcaCloudAccountsDescription' +import { CloudAgentSignInsLinkRow } from '../agent-accounts/CloudAgentSignInsLinkRow' import { AgentAccountsOverviewSection } from '../agent-accounts/overview/AgentAccountsOverviewSection' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import type { SettingsRenderContext } from './settings-render-context' -/** Settings → Agent accounts, after "This computer": Orca Cloud (S0), then Hosts (S3). The page - * titles each part and lists it in its jump row. Desktop only, and only in builds with an Orca - * Cloud control plane. */ +/** Settings → Agent accounts, after "This computer": Hosts (S3). The page titles each part and + * lists it in its jump row. Orca Cloud's own sign-ins (S0) are Settings › Orca Cloud › Cloud agent + * sign-ins; see orcaCloudAgentAccountsLead. Desktop only, and only in builds with an Orca Cloud + * control plane. */ export function orcaCloudAgentAccountsParts( context: SettingsRenderContext, t: Translate = translate @@ -18,12 +18,6 @@ export function orcaCloudAgentAccountsParts( return [] } return [ - { - id: 'accounts-orca-cloud', - title: t('orcaCloudAccounts.title', 'Orca Cloud'), - description: , - content: - }, { id: 'accounts-hosts', title: t('settings.agentAccounts.hostsTitle', 'Hosts'), @@ -35,3 +29,14 @@ export function orcaCloudAgentAccountsParts( } ] } + +/** The one row Agent accounts keeps for Orca Cloud: a link to Cloud agent sign-ins. */ +export function orcaCloudAgentAccountsLead(context: SettingsRenderContext): React.ReactNode { + const { model, actions } = context + if (!model.showDesktopOnlySettings || !model.orcaCloudApiAvailable) { + return null + } + return ( + void actions.scrollToSection('cloud-agent-sign-ins')} /> + ) +} diff --git a/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx b/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx index d1f273f9254..f1db526c6eb 100644 --- a/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx +++ b/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx @@ -6,6 +6,8 @@ import { OrcaCloudSkillsSyncPane, OrcaCloudWorkspacesPane } from '../orca-cloud/OrcaCloudSettingsPanes' +import { OrcaCloudAccountsSection } from '../agent-accounts/OrcaCloudAccountsSection' +import { OrcaCloudAccountsDescription } from '../agent-accounts/OrcaCloudAccountsDescription' import { SettingsSection } from '../section-layout/SettingsSection' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' @@ -23,7 +25,22 @@ export function renderOrcaCloudSettingsSections( return null } // Titles and descriptions come from the nav metadata so the pane and the sidebar never disagree. - const sections: { id: string; pane: React.JSX.Element; navOnly?: boolean }[] = [ + const sections: { + id: string + pane: React.JSX.Element + navOnly?: boolean + /** Replaces the nav's plain-text description on the page. */ + description?: React.ReactNode + /** The pane draws its own card. */ + grouped?: boolean + }[] = [ + // S0, moved here from Settings › Agent accounts (which keeps a link row to this page). + { + id: 'cloud-agent-sign-ins', + pane: , + description: , + grouped: true + }, // Listed in the nav for team owners and admins only; without the entry there is no page. { id: 'cloud-workspaces', pane: , navOnly: true }, { id: 'cloud-secrets', pane: }, @@ -34,7 +51,7 @@ export function renderOrcaCloudSettingsSections( ] return ( <> - {sections.map(({ id, pane, navOnly }) => { + {sections.map(({ id, pane, navOnly, description, grouped }) => { const meta = navigation.navSections.find((section) => section.id === id) if (navOnly && !meta) { return null @@ -44,9 +61,10 @@ export function renderOrcaCloudSettingsSections( key={id} id={id} title={meta?.title ?? t('settings.breadcrumb.settings', 'Settings')} - description={meta?.description ?? ''} + description={description ?? meta?.description ?? ''} searchEntries={navigation.getSectionSearchEntries(id)} - bodyClassName={BARE_BODY} + grouped={grouped} + bodyClassName={grouped ? undefined : BARE_BODY} > {view.isSectionMounted(id) ? pane : null}
diff --git a/src/renderer/src/components/settings/page/settings-page-renderer.tsx b/src/renderer/src/components/settings/page/settings-page-renderer.tsx index 78d427dfe1f..425b2239f82 100644 --- a/src/renderer/src/components/settings/page/settings-page-renderer.tsx +++ b/src/renderer/src/components/settings/page/settings-page-renderer.tsx @@ -64,7 +64,10 @@ import { import { renderProjectSettingsSections } from './settings-project-section-renderer' import { renderCloudApiSettingsSections } from './settings-cloud-api-section-renderers' import { renderOrcaCloudSettingsSections } from './settings-orca-cloud-section-renderers' -import { orcaCloudAgentAccountsParts } from './settings-orca-cloud-agent-accounts-sections' +import { + orcaCloudAgentAccountsLead, + orcaCloudAgentAccountsParts +} from './settings-orca-cloud-agent-accounts-sections' import { SettingsHostScopePicker, shouldShowSettingsHostScopePicker @@ -173,7 +176,8 @@ export function renderSettingsPage( {renderAccountsSettingsSection( context, t, - orcaCloudAgentAccountsParts(context, t) + orcaCloudAgentAccountsParts(context, t), + orcaCloudAgentAccountsLead(context) )} {renderAgentApiKeysSettingsSection(context, t)} {renderOrchestrationSettingsSection(context, t)} diff --git a/src/renderer/src/components/settings/page/use-settings-page-effects.ts b/src/renderer/src/components/settings/page/use-settings-page-effects.ts index 2e66f3c98a4..4bb61d3196e 100644 --- a/src/renderer/src/components/settings/page/use-settings-page-effects.ts +++ b/src/renderer/src/components/settings/page/use-settings-page-effects.ts @@ -16,7 +16,10 @@ import { import type { SettingsStoreModel } from './use-settings-store-model' import type { SettingsInteractionController } from './use-settings-interaction-controller' import { setSettingsActiveSection } from '../host-scope/settings-active-section' -import { resolveAccountBillingTarget } from '@/hooks/settings-navigation-orca-cloud-sections' +import { + resolveAccountBillingTarget, + resolveCloudAgentSignInsTarget +} from '@/hooks/settings-navigation-orca-cloud-sections' import { getSettingsSectionId, SHORTCUTS_ESCAPE_CONFIRM_TOAST_ID, @@ -178,9 +181,11 @@ export function useSettingsPageEffects( return } // Plan & billing is part of Account + Billing in Orca Cloud builds; old links land on that part. - const settingsNavigationTarget = resolveAccountBillingTarget( - requestedNavigationTarget, - orcaCloudApiAvailable && showDesktopOnlySettings + // Old links to Agent accounts' Orca Cloud part land on Cloud agent sign-ins. + const cloudSettingsAvailable = orcaCloudApiAvailable && showDesktopOnlySettings + const settingsNavigationTarget = resolveCloudAgentSignInsTarget( + resolveAccountBillingTarget(requestedNavigationTarget, cloudSettingsAvailable), + cloudSettingsAvailable ) const paneSectionId = getSettingsSectionId( diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts index 6de0d1699d7..69a3b7cf1ff 100644 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts @@ -72,8 +72,8 @@ function setupText( // This row has no field: the code goes in where setup has one (the pane, Settings). detail: model.setup.acceptsCode ? t( - 'vmBuildAgents.finishInBrowserPaste', - 'Finish in your browser, then paste the code in Settings → Agent accounts.' + 'vmBuildAgents.finishInBrowserPasteCloudSignIns', + 'Finish in your browser, then paste the code in Settings → Cloud agent sign-ins.' ) : t('vmBuildAgents.finishInBrowser', 'Finish in your browser') } @@ -95,7 +95,10 @@ function setupText( return { title: t('vmBuildAgents.pasteTitle', 'Paste a {{agent}} setup token', { agent }), tag, - detail: t('vmBuildAgents.pasteDetail', 'Paste it in Settings → Agent accounts.') + detail: t( + 'vmBuildAgents.pasteDetailCloudSignIns', + 'Paste it in Settings → Cloud agent sign-ins.' + ) } case 'saving': return { diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts index 4b03b8afdb1..019c64a91cf 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts @@ -8,6 +8,7 @@ import { buildOrcaCloudSettingsSections, gatherOrcaCloudSettingsGroup, resolveAccountBillingTarget, + resolveCloudAgentSignInsTarget, labelAccountBilling, hasOrcaBillingAccount, ACCOUNT_BILLING_PLAN_ANCHOR, @@ -37,6 +38,7 @@ describe('Orca Cloud settings group', () => { const sections = buildOrcaCloudSettingsSections(options({})) expect(sections.map((section) => section.id)).toEqual([ 'cloud-billing', + 'cloud-agent-sign-ins', 'cloud-secrets', 'cloud-skills', 'cloud-environments', @@ -60,7 +62,12 @@ describe('Orca Cloud settings group', () => { expect(ids({})).not.toContain('cloud-workspaces') expect(ids({ isOrcaTeamAdmin: false })).not.toContain('cloud-workspaces') const admin = ids({ isOrcaTeamAdmin: true }) - expect(admin.slice(0, 3)).toEqual(['cloud-billing', 'cloud-workspaces', 'cloud-secrets']) + expect(admin.slice(0, 4)).toEqual([ + 'cloud-billing', + 'cloud-agent-sign-ins', + 'cloud-workspaces', + 'cloud-secrets' + ]) // Team, Enterprise and the audit log are managed in the web console (Account › Team & admin). for (const patch of [{}, { isOrcaTeamAdmin: true }]) { expect(ids(patch)).not.toContain('cloud-team') @@ -152,7 +159,7 @@ describe('one Orca Cloud group (JA-16)', () => { ]) }) - it('finds members, single sign-on and the audit log on the Account page\'s Team & admin row', () => { + it("finds members, single sign-on and the audit log on the Account page's Team & admin row", () => { const account = gatherOrcaCloudSettingsGroup(all, options({})).find( (section) => section.id === 'orca-account' ) @@ -206,6 +213,37 @@ describe('one Orca Cloud group (JA-16)', () => { }) }) + it('sends old Agent accounts › Orca Cloud links to Cloud agent sign-ins', () => { + for (const sectionId of ['orca-cloud', 'accounts-orca-cloud']) { + expect(resolveCloudAgentSignInsTarget({ pane: 'accounts', sectionId }, true)).toEqual({ + pane: 'cloud-agent-sign-ins', + sectionId: undefined + }) + // Without the Orca Cloud group there is no page to send it to. + expect(resolveCloudAgentSignInsTarget({ pane: 'accounts', sectionId }, false)).toEqual({ + pane: 'accounts', + sectionId + }) + } + // This computer's and the hosts' parts stay on Agent accounts. + expect( + resolveCloudAgentSignInsTarget({ pane: 'accounts', sectionId: 'accounts-hosts' }, true) + ).toEqual({ pane: 'accounts', sectionId: 'accounts-hosts' }) + expect(resolveCloudAgentSignInsTarget({ pane: 'accounts' }, true)).toEqual({ + pane: 'accounts' + }) + }) + + it('finds Claude and ChatGPT sign-ins on Cloud agent sign-ins', () => { + const page = buildOrcaCloudSettingsSections(options({})).find( + (section) => section.id === 'cloud-agent-sign-ins' + ) + expect(page?.title).toBe('Cloud agent sign-ins') + expect(page?.searchEntries.flatMap((entry) => entry.keywords ?? [])).toEqual( + expect.arrayContaining(['subscription', 'chatgpt', 'setup-token', 'renew', 'agent accounts']) + ) + }) + it('leaves the upstream grouping alone without Orca Cloud', () => { expect(gatherOrcaCloudSettingsGroup(all, options({ isOrcaCloudApiAvailable: false }))).toEqual( all diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts index c321fa8256c..14225295d26 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts @@ -12,6 +12,7 @@ import { getOrcaCloudTeamAdminSearchEntries, getOrcaCloudWorkspacesSearchEntries } from '@/components/settings/orca-cloud/orca-cloud-settings-search' +import { getCloudAgentSignInsSearchEntries } from '@/components/settings/agent-accounts/agent-accounts-search' import { translate } from '@/i18n/i18n' import { canManageActiveTeam } from '@/lib/orca-cloud/orca-cloud-team-role' import type { Translate } from '@/i18n/use-translate' @@ -27,6 +28,7 @@ import { CreditCard, KeySquare, LockKeyhole, + LogIn, Plug, SquareTerminal, Workflow @@ -55,6 +57,20 @@ export function buildOrcaCloudSettingsSections( searchEntries: getOrcaCloudBillingSearchEntries(), group }, + // Neil: Orca Cloud's Claude and ChatGPT sign-ins are an Orca Cloud setting, not one of this + // computer's Agent accounts; that page keeps a one-line link here. Right after the account, + // since setting up an agent once is the first thing a new cloud user does. + { + id: 'cloud-agent-sign-ins', + title: t('settings.cloudAgentSignIns.title', 'Cloud agent sign-ins'), + description: t( + 'orcaCloudAccounts.helpAccountWide', + 'Set up once. Every cloud workspace uses it, including new, cloned and restarted ones.' + ), + icon: LogIn, + searchEntries: getCloudAgentSignInsSearchEntries(), + group + }, // Team owners and admins only; members and personal accounts never see the entry. Team, // billing and admin (single sign-on, audit log) are managed in the web console, reached from // the Account page's "Team & admin" row; the desktop has no page for them. @@ -173,8 +189,8 @@ export const ACCOUNT_TEAM_ADMIN_ANCHOR = 'orca-account-team-admin' /** * JA-16: in Orca Cloud builds the Orca account leads the one Orca Cloud group instead of sitting in - * Set up. Agent accounts stays in AI capabilities: it covers this computer and hosts as much as - * Orca Cloud, and its Orca Cloud part is deep-linked from every cloud entry point. + * Set up. Agent accounts stays in AI capabilities for this computer and hosts; Orca Cloud's own + * sign-ins are the group's Cloud agent sign-ins page (resolveCloudAgentSignInsTarget). * Neil: the account and Plan & billing are one page, "Account + Billing" (account on top). Billing's * search entries move onto it and land on its Plan & billing part. Searching for members, single * sign-on or the audit log lands on its "Team & admin" row, which opens the web console. @@ -275,6 +291,29 @@ export function resolveAccountBillingTarget< } } +/** Where Settings › Agent accounts used to hold Orca Cloud's sign-ins (its part's anchors). */ +const LEGACY_CLOUD_SIGN_IN_ANCHORS: readonly string[] = ['orca-cloud', 'accounts-orca-cloud'] + +/** + * Old links to Agent accounts' Orca Cloud part (pane 'accounts' at 'orca-cloud' or + * 'accounts-orca-cloud') open Cloud agent sign-ins. Only when that page exists (desktop with Orca + * Cloud); otherwise the target is unchanged. + */ +export function resolveCloudAgentSignInsTarget< + T extends { pane: SettingsNavTarget; sectionId?: string } +>(target: T, available: boolean): T { + if ( + !available || + target.pane !== 'accounts' || + !target.sectionId || + !LEGACY_CLOUD_SIGN_IN_ANCHORS.includes(target.sectionId) + ) { + return target + } + // The page is the whole target; its legacy anchor doesn't exist there. + return { ...target, pane: 'cloud-agent-sign-ins', sectionId: undefined } +} + /** True for an Orca Cloud group page (team-level, so host-free): the cloud pages and the Orca account. */ export function isOrcaCloudSettingsSectionId(id: string | null | undefined): boolean { return typeof id === 'string' && (id.startsWith('cloud-') || ORCA_CLOUD_LEAD_IDS.includes(id)) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index f084e93e7f9..9d6a97bcf29 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -18,6 +18,9 @@ } }, "agentHostPanel": { + "cloud": { + "expiredDetail": "Renew it once in Agent accounts." + }, "recipeEnvDetailNoKeys_one": "{{count}} variable, none that look like keys. The recipe decides what reaches the VM.", "recipeEnvDetailNoKeys_other": "{{count}} variables, none that look like keys. The recipe decides what reaches the VM.", "recipeEnvDetailOneKey_one": "{{count}} variable, including 1 that looks like a key ({{names}}). The recipe decides what reaches the VM.", @@ -869,6 +872,11 @@ "appsCount_other": "{{count}} apps approved with this key are disconnected too." } }, + "cloudRoutines": { + "runError": { + "claudeNotSetUp": "Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Agent accounts, then run the routine again." + } + }, "computerUseSummary": { "permissionsRequired_one": "{{value0}} permission required before agents can operate app windows.", "permissionsRequired_other": "{{value0}} permissions required before agents can operate app windows." @@ -1667,6 +1675,9 @@ } }, "cloudSecrets": { + "error": { + "subscriptionToken": "This is a Claude or ChatGPT subscription token, so it can’t be saved as a secret. Set up Claude once in Settings → Agent accounts instead." + }, "paste": { "blocked": "{{count}} need a fix and will be skipped", "blocked_one": "{{count}} needs a fix and will be skipped", @@ -2520,6 +2531,11 @@ "unhide": "Show All", "zoom": "Zoom" }, + "orcaCloudAgentRow": { + "expired": "Your {{agent}} sign-in for Orca Cloud expired. Renew it once in Settings → Agent accounts.", + "notSetUp": "{{agent}} isn’t set up for Orca Cloud yet. Set it up once in Settings → Agent accounts.", + "signedOut": "{{agent}}: set up once in Settings → Agent accounts after you sign in" + }, "orcaCloudMove": { "confirm": { "changesCount_one": "{{count}} uncommitted change, plus untracked files", @@ -2536,6 +2552,9 @@ "untracked_other": "{{count}} untracked files" } }, + "orcaCloudSignInSheet": { + "allAccounts": "All agent accounts" + }, "orcaCloudSync": { "editedHere_one": "{{count}} file changed on this computer. Edits here don’t sync back. The cloud copy replaces it when it changes.", "editedHere_other": "{{count}} files changed on this computer. Edits here don’t sync back. The cloud copy replaces them when it changes.", @@ -2659,6 +2678,9 @@ } }, "settings": { + "agentAccounts": { + "hubSearchDescription": "Where Claude and Codex are signed in: Orca Cloud, this computer and your hosts." + }, "agents": { "defaultSurfaceKeptChat_one": "{{agents}} stays as a chat, as you set.", "defaultSurfaceKeptChat_other": "{{agents}} stay as chats, as you set.", @@ -3062,6 +3084,10 @@ "updateServerUnreachable": "Couldn't reach the update server. Try again in a few minutes." } }, + "vmBuildAgents": { + "finishInBrowserPaste": "Finish in your browser, then paste the code in Settings → Agent accounts.", + "pasteDetail": "Paste it in Settings → Agent accounts." + }, "workspace": { "links": { "linkedCount_one": "{{count}} linked", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index fcb4c690561..00882039535 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1457,13 +1457,16 @@ "subscription": "subscription", "signIn": "sign in", "chatgpt": "chatgpt", - "setupToken": "setup-token" + "setupToken": "setup-token", + "hosts": "hosts" }, "pageDescription": "Sign-ins, account switching and usage for your agents.", "thisComputer": "This computer", "selectedHost": "Selected host", "hostsTitle": "Hosts", - "jumpLabel": "Parts of this page" + "jumpLabel": "Parts of this page", + "cloudSignInsMoved": "Orca Cloud sign-ins live in Orca Cloud settings", + "hubSearchDescriptionHosts": "Where Claude and Codex are signed in on this computer and your hosts." }, "accountBilling": { "account": "Account", @@ -1520,6 +1523,15 @@ }, "signInFailed": "Couldn’t sign you in to the console", "signInFailedDetail": "Your browser opened it anyway. Sign in there to continue." + }, + "cloudAgentSignIns": { + "searchTitle": "Cloud agent sign-ins", + "searchDescription": "Set up Claude and Codex once for every cloud workspace: your Claude subscription or ChatGPT sign-in.", + "search": { + "renew": "renew", + "agentAccounts": "agent accounts" + }, + "title": "Cloud agent sign-ins" } }, "menu": { @@ -9319,7 +9331,8 @@ "interrupted": "Orca Cloud restarted during the run.", "routineChanged": "The routine changed while this run was queued.", "generic": "The run failed.", - "claudeNotSetUp": "Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Agent accounts, then run the routine again." + "claudeNotSetUp": "Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Agent accounts, then run the routine again.", + "claudeNotSetUpCloudSignIns": "Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Cloud agent sign-ins, then run the routine again." }, "event": { "prOpened": "PR opened", @@ -27920,7 +27933,8 @@ "overridden": "Set again further down; the later line is used.", "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.", - "desktopKeyConflict": "Another agent’s key is saved in your Orca account under this name. Save this one to replace it." + "desktopKeyConflict": "Another agent’s key is saved in your Orca account under this name. Save this one to replace it.", + "subscriptionTokenCloudSignIns": "This is a Claude or ChatGPT subscription token, so it can’t be saved as a secret. Set up Claude once in Settings → Cloud agent sign-ins instead." }, "vm": { "badge": "Real value in sandbox", @@ -28320,7 +28334,8 @@ "signIn": "Sign in", "failed": "Couldn’t load your agent accounts.", "sharedUnavailable": "Not available in shared workspaces", - "sharedUnavailableDetail": "Personal accounts aren’t used in shared workspaces. Ask an owner or admin to add a team key." + "sharedUnavailableDetail": "Personal accounts aren’t used in shared workspaces. Ask an owner or admin to add a team key.", + "expiredDetailCloudSignIns": "Renew it once in Cloud agent sign-ins." }, "kind": { "local": "This computer", @@ -28538,7 +28553,10 @@ "error": "Couldn’t check whether {{agent}} is set up for Orca Cloud. You can still start.", "tryAgain": "Try again", "label": "Agent", - "checking": "Checking {{agent}}" + "checking": "Checking {{agent}}", + "notSetUpCloudSignIns": "{{agent}} isn’t set up for Orca Cloud yet. Set it up once in Settings → Cloud agent sign-ins.", + "expiredCloudSignIns": "Your {{agent}} sign-in for Orca Cloud expired. Renew it once in Settings → Cloud agent sign-ins.", + "signedOutCloudSignIns": "{{agent}}: set up once in Settings → Cloud agent sign-ins after you sign in" }, "orcaCloudAccounts": { "paste": { @@ -28684,7 +28702,9 @@ "groupKey": "{{agents}} with {{key}}", "notOffered": "Signs in for each cloud workspace for now", "expiredDetailRenew": "Renew once. Every cloud workspace picks it up.", - "finishInBrowserPaste": "Finish in your browser, then paste the code in Settings → Agent accounts." + "finishInBrowserPaste": "Finish in your browser, then paste the code in Settings → Agent accounts.", + "finishInBrowserPasteCloudSignIns": "Finish in your browser, then paste the code in Settings → Cloud agent sign-ins.", + "pasteDetailCloudSignIns": "Paste it in Settings → Cloud agent sign-ins." }, "agentAccountsOverview": { "action": { @@ -28926,7 +28946,8 @@ "title": "Agents in Orca Cloud", "description": "Set up Claude and Codex once. Every cloud workspace uses them, including new, cloned and restarted ones.", "footerLabel": "Related settings", - "allAccounts": "All agent accounts" + "allAccounts": "All agent accounts", + "openCloudSettings": "Open in Orca Cloud settings" }, "cloudSkillsSync": { "appliesEverywhere": "Applies to every cloud workspace", diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts index 3f2bd5b6d8c..d9e762146dd 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts @@ -84,7 +84,7 @@ export function cloudAgentRowSignInLabel(signIn: CloudAgentRowSignIn, t: Transla : t('agentSignInStrip.rowNeedsSignIn', 'Needs sign-in') } -/** Where the fix lives; the row's status opens it (Settings → Agent accounts). */ +/** Where the fix lives; the row's status opens it (Settings → Cloud agent sign-ins). */ export function cloudAgentRowSignInTooltip(signIn: CloudAgentRowSignIn, t: Translate): string { return signIn === 'expired' ? t('agentSignInStrip.rowExpiredTooltip', 'Renew for Orca Cloud') diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts index 9373ba48686..d854dcbf891 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts @@ -1,4 +1,4 @@ -// What S0 (Settings › Agent accounts › Orca Cloud) and the composer's Agent row show for each agent, +// What S0 (Settings › Orca Cloud › Cloud agent sign-ins) and the composer's Agent row show for each agent, // derived from GET /v1/agent-credentials + /v1/agent-sources and the setup running on this computer. import type { CloudEffectiveSecret } from '../../../../shared/cloud-secrets/cloud-secrets-wire' import { diff --git a/src/shared/cloud-api/routine-run-sign-in.ts b/src/shared/cloud-api/routine-run-sign-in.ts index 6373c7eb781..338476dd950 100644 --- a/src/shared/cloud-api/routine-run-sign-in.ts +++ b/src/shared/cloud-api/routine-run-sign-in.ts @@ -16,4 +16,4 @@ export function isRoutineRunAgentSignInFailure( /** The plain-English line, for surfaces without the desktop's translations (the CLI). */ export const ROUTINE_RUN_CLAUDE_NOT_SET_UP = - 'Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Agent accounts, then run the routine again.' + 'Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Cloud agent sign-ins, then run the routine again.' From 8cb1d5d2ff0b3f7b69bfa743b5d5853756f0f713 Mon Sep 17 00:00:00 2001 From: Neil Date: Sat, 14 Nov 2026 23:41:42 -0800 Subject: [PATCH 02/35] chore(i18n): drop the moved copy's old keys --- .../src/i18n/en-runtime-required.json | 26 ------------------- src/renderer/src/i18n/locales/en.json | 10 ------- 2 files changed, 36 deletions(-) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 9d6a97bcf29..f084e93e7f9 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -18,9 +18,6 @@ } }, "agentHostPanel": { - "cloud": { - "expiredDetail": "Renew it once in Agent accounts." - }, "recipeEnvDetailNoKeys_one": "{{count}} variable, none that look like keys. The recipe decides what reaches the VM.", "recipeEnvDetailNoKeys_other": "{{count}} variables, none that look like keys. The recipe decides what reaches the VM.", "recipeEnvDetailOneKey_one": "{{count}} variable, including 1 that looks like a key ({{names}}). The recipe decides what reaches the VM.", @@ -872,11 +869,6 @@ "appsCount_other": "{{count}} apps approved with this key are disconnected too." } }, - "cloudRoutines": { - "runError": { - "claudeNotSetUp": "Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Agent accounts, then run the routine again." - } - }, "computerUseSummary": { "permissionsRequired_one": "{{value0}} permission required before agents can operate app windows.", "permissionsRequired_other": "{{value0}} permissions required before agents can operate app windows." @@ -1675,9 +1667,6 @@ } }, "cloudSecrets": { - "error": { - "subscriptionToken": "This is a Claude or ChatGPT subscription token, so it can’t be saved as a secret. Set up Claude once in Settings → Agent accounts instead." - }, "paste": { "blocked": "{{count}} need a fix and will be skipped", "blocked_one": "{{count}} needs a fix and will be skipped", @@ -2531,11 +2520,6 @@ "unhide": "Show All", "zoom": "Zoom" }, - "orcaCloudAgentRow": { - "expired": "Your {{agent}} sign-in for Orca Cloud expired. Renew it once in Settings → Agent accounts.", - "notSetUp": "{{agent}} isn’t set up for Orca Cloud yet. Set it up once in Settings → Agent accounts.", - "signedOut": "{{agent}}: set up once in Settings → Agent accounts after you sign in" - }, "orcaCloudMove": { "confirm": { "changesCount_one": "{{count}} uncommitted change, plus untracked files", @@ -2552,9 +2536,6 @@ "untracked_other": "{{count}} untracked files" } }, - "orcaCloudSignInSheet": { - "allAccounts": "All agent accounts" - }, "orcaCloudSync": { "editedHere_one": "{{count}} file changed on this computer. Edits here don’t sync back. The cloud copy replaces it when it changes.", "editedHere_other": "{{count}} files changed on this computer. Edits here don’t sync back. The cloud copy replaces them when it changes.", @@ -2678,9 +2659,6 @@ } }, "settings": { - "agentAccounts": { - "hubSearchDescription": "Where Claude and Codex are signed in: Orca Cloud, this computer and your hosts." - }, "agents": { "defaultSurfaceKeptChat_one": "{{agents}} stays as a chat, as you set.", "defaultSurfaceKeptChat_other": "{{agents}} stay as chats, as you set.", @@ -3084,10 +3062,6 @@ "updateServerUnreachable": "Couldn't reach the update server. Try again in a few minutes." } }, - "vmBuildAgents": { - "finishInBrowserPaste": "Finish in your browser, then paste the code in Settings → Agent accounts.", - "pasteDetail": "Paste it in Settings → Agent accounts." - }, "workspace": { "links": { "linkedCount_one": "{{count}} linked", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 00882039535..930f3285e97 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1452,7 +1452,6 @@ }, "agentAccounts": { "searchTitle": "Agent accounts", - "hubSearchDescription": "Where Claude and Codex are signed in: Orca Cloud, this computer and your hosts.", "search": { "subscription": "subscription", "signIn": "sign in", @@ -9331,7 +9330,6 @@ "interrupted": "Orca Cloud restarted during the run.", "routineChanged": "The routine changed while this run was queued.", "generic": "The run failed.", - "claudeNotSetUp": "Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Agent accounts, then run the routine again.", "claudeNotSetUpCloudSignIns": "Claude isn’t set up for Orca Cloud, so this run couldn’t start it. Set it up once in Settings → Cloud agent sign-ins, then run the routine again." }, "event": { @@ -27918,7 +27916,6 @@ "error": { "invalidName": "Use capital letters, digits and underscores, not starting with a digit.", "reservedName": "Orca manages this variable in cloud workspaces. Pick another name.", - "subscriptionToken": "This is a Claude or ChatGPT subscription token, so it can’t be saved as a secret. Set up Claude once in Settings → Agent accounts instead.", "valueTooLarge": "Values can be up to 8 KB.", "invalidValue": "Enter a value.", "repoRequired": "Choose a repository first.", @@ -28324,7 +28321,6 @@ "notSetUp": "Not set up", "notSetUpDetail": "Set up once on this computer. Every cloud workspace uses it.", "expired": "Your {{agent}} sign-in for Orca Cloud expired", - "expiredDetail": "Renew it once in Agent accounts.", "signsInHere": "{{agent}} signs in for this workspace", "sourceLabel": "{{agent}} source in this workspace", "choose": "Choose", @@ -28543,12 +28539,9 @@ "orcaCloudAgentRow": { "fromAccount": "{{agent}} · from your Orca account", "viaKey": "{{agent}} · {{key}}", - "notSetUp": "{{agent}} isn’t set up for Orca Cloud yet. Set it up once in Settings → Agent accounts.", "setUpOnce": "Set up once", - "expired": "Your {{agent}} sign-in for Orca Cloud expired. Renew it once in Settings → Agent accounts.", "renew": "Renew", "killSwitch": "{{agent}} signs in for each cloud workspace while Orca account sign-in is paused.", - "signedOut": "{{agent}}: set up once in Settings → Agent accounts after you sign in", "optional": "Optional", "error": "Couldn’t check whether {{agent}} is set up for Orca Cloud. You can still start.", "tryAgain": "Try again", @@ -28685,7 +28678,6 @@ "preparing": "Getting {{product}} sign-in ready…", "deviceGuard": "Only continue if you started this sign-in in Orca.", "pasteTitle": "Paste a {{agent}} setup token", - "pasteDetail": "Paste it in Settings → Agent accounts.", "saving": "Saving to your Orca account…", "savingDetail": "Every cloud workspace will use it.", "signIn": "Agent sign-in", @@ -28702,7 +28694,6 @@ "groupKey": "{{agents}} with {{key}}", "notOffered": "Signs in for each cloud workspace for now", "expiredDetailRenew": "Renew once. Every cloud workspace picks it up.", - "finishInBrowserPaste": "Finish in your browser, then paste the code in Settings → Agent accounts.", "finishInBrowserPasteCloudSignIns": "Finish in your browser, then paste the code in Settings → Cloud agent sign-ins.", "pasteDetailCloudSignIns": "Paste it in Settings → Cloud agent sign-ins." }, @@ -28946,7 +28937,6 @@ "title": "Agents in Orca Cloud", "description": "Set up Claude and Codex once. Every cloud workspace uses them, including new, cloned and restarted ones.", "footerLabel": "Related settings", - "allAccounts": "All agent accounts", "openCloudSettings": "Open in Orca Cloud settings" }, "cloudSkillsSync": { From 0bb3d8ec78a3cfdd61ef078805d07e3b8e32fe30 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:08:35 -0800 Subject: [PATCH 03/35] fix(ports): agent CLIs' own listeners are never auto-forwarded or toasted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neil got "Forwarded :34719 to localhost:34719 · codex · sand23 · Open": Codex's own listener on an ephemeral port, forwarded and announced as if it were his app. Auto-forward now skips: - a listener whose process is an agent CLI (claude, codex, opencode, gemini, cursor-agent, …; by binary name, path, .exe or platform suffix), on any port; - an anonymous ephemeral port (>= 32768) with no known web protocol and no URL the workspace printed: an agent's MCP child, a language server, a debugger. Dev servers keep auto-forward: usual ports (3000, 5173, 8080, …) and any port whose URL the terminal printed. An earlier auto forward of an agent port retires once idle, as for any non-candidate. The toast says what happened in the user's terms: "Your app on port 3000 is available at localhost:3000", and "3 apps are available on this computer" for several. --- .../ports/RuntimePortAutoForwarder.tsx | 12 +-- src/renderer/src/i18n/locales/en.json | 6 +- .../runtime-port-auto-forward-plan.test.ts | 74 ++++++++++++++++++- .../runtime-port-auto-forward-plan.ts | 55 +++++++++++++- 4 files changed, 136 insertions(+), 11 deletions(-) diff --git a/src/renderer/src/components/ports/RuntimePortAutoForwarder.tsx b/src/renderer/src/components/ports/RuntimePortAutoForwarder.tsx index 84b26f0e3a0..6fcacb94779 100644 --- a/src/renderer/src/components/ports/RuntimePortAutoForwarder.tsx +++ b/src/renderer/src/components/ports/RuntimePortAutoForwarder.tsx @@ -86,8 +86,8 @@ function announce(port: WorkspacePort, forward: RuntimePortForward): void { .join(' · ') toast.success( translate( - 'auto.components.ports.RuntimePortAutoForwarder.forwarded', - 'Forwarded :{{value0}} to localhost:{{value1}}', + 'auto.components.ports.RuntimePortAutoForwarder.appAvailable', + 'Your app on port {{value0}} is available at localhost:{{value1}}', { value0: port.port, value1: forward.localPort } ), { @@ -115,9 +115,11 @@ function announce(port: WorkspacePort, forward: RuntimePortForward): void { /** Several servers at once (a monorepo `dev`) get one toast instead of a stack. */ function announceMany(environmentId: string, count: number): void { toast.success( - translate('auto.components.ports.RuntimePortAutoForwarder.many', '{{value0}} ports forwarded', { - value0: count - }), + translate( + 'auto.components.ports.RuntimePortAutoForwarder.manyAppsAvailable', + '{{value0}} apps are available on this computer', + { value0: count } + ), { id: `runtime-port-forward:${environmentId}:many`, duration: FORWARDED_TOAST_MS, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index fcb4c690561..489af4ab65e 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21212,11 +21212,11 @@ "open": "Open", "busyDescription": "\"Same port number only\" is on, so :{{value0}} was not forwarded.", "useAnother": "Use another port", - "forwarded": "Forwarded :{{value0}} to localhost:{{value1}}", "remappedInUse": "{{value0}} · {{value1}} in use on this computer", - "many": "{{value0}} ports forwarded", "busyInUse": "localhost:{{value0}} in use on this computer", - "openPortsPanel": "Open ports" + "openPortsPanel": "Open ports", + "appAvailable": "Your app on port {{value0}} is available at localhost:{{value1}}", + "manyAppsAvailable": "{{value0}} apps are available on this computer" } }, "cloudWorkspaces": { diff --git a/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts b/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts index 441c4a226c4..b5d05f17332 100644 --- a/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts +++ b/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts @@ -4,7 +4,11 @@ import { DEFAULT_RUNTIME_PORT_FORWARD_SETTINGS, type RuntimePortForward } from '../../../../shared/runtime-port-forwards' -import { planAutoForwards } from './runtime-port-auto-forward-plan' +import { + isAgentCliProcessName, + isAutoForwardCandidate, + planAutoForwards +} from './runtime-port-auto-forward-plan' const owner = { worktreeId: 'w', @@ -95,4 +99,72 @@ describe('planAutoForwards', () => { }) expect(second.close.map((forward) => forward.remotePort)).toEqual([5173]) }) + + it("never forwards an agent CLI's own listener, at any port or protocol", () => { + const agentPort = (port: number, processName: string): WorkspacePort => ({ + ...workspace(port), + processName + }) + // Neil's toast: "Forwarded :34719 to localhost:34719 · codex · sand23". + const plan = planAutoForwards({ + ...base, + ports: [ + agentPort(34719, 'codex'), + agentPort(1455, 'codex'), + agentPort(5173, '/usr/local/bin/claude'), + agentPort(4096, 'opencode'), + agentPort(8080, 'codex-linux-x64'), + agentPort(3000, 'node') + ], + forwards: [] + }) + expect(plan.open.map((port) => port.port)).toEqual([3000]) + }) + + it('skips an anonymous ephemeral port, but not one with a known web port or a printed URL', () => { + const settings = DEFAULT_RUNTIME_PORT_FORWARD_SETTINGS + const unknown = (port: number): WorkspacePort => ({ + ...workspace(port), + protocol: 'unknown', + processName: 'node' + }) + // An agent's MCP child or a language server: high port, no URL, nothing known about it. + expect(isAutoForwardCandidate(unknown(41234), settings)).toBe(false) + // The user's dev server on its usual port (protocol not inferred) still forwards. + expect(isAutoForwardCandidate(unknown(5173), settings)).toBe(true) + // A dev server on a high port that printed its URL forwards too. + expect( + isAutoForwardCandidate( + { ...unknown(41234), protocol: 'http', advertisedUrl: 'http://localhost:41234' }, + settings + ) + ).toBe(true) + }) + + it('retires an earlier auto forward of an agent port once it is idle', () => { + const plan = planAutoForwards({ + ...base, + previousMissing: new Map([[34719, 1]]), + ports: [{ ...workspace(34719), processName: 'codex' }], + forwards: [auto(34719)] + }) + expect(plan.close.map((forward) => forward.remotePort)).toEqual([34719]) + }) +}) + +describe('isAgentCliProcessName', () => { + it('names agent CLIs by binary, path, .exe or platform suffix, and nothing else', () => { + for (const name of [ + 'codex', + 'Codex', + '/opt/bin/claude', + 'C:\\bin\\codex.exe', + 'codex-x86_64' + ]) { + expect(isAgentCliProcessName(name)).toBe(true) + } + for (const name of [undefined, '', 'node', 'vite', 'next-server', 'claudette', 'python3']) { + expect(isAgentCliProcessName(name)).toBe(false) + } + }) }) diff --git a/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.ts b/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.ts index 9d6b777c274..cf6d18e503b 100644 --- a/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.ts +++ b/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.ts @@ -15,7 +15,56 @@ export type AutoForwardPlan = { missing: Map } -/** Dev servers a workspace started: attributed to a workspace, in range, and not Orca's own. */ +/** + * Agent CLIs open their own listeners (Codex's sign-in callback and app server, Claude's IDE and MCP + * bridges). Those are the agent's plumbing, not the user's app: never auto-forwarded or announced. + */ +const AGENT_CLI_PROCESS_NAMES: ReadonlySet = new Set([ + 'claude', + 'codex', + 'opencode', + 'opencode2', + 'gemini', + 'cursor-agent', + 'grok', + 'omp', + 'pi', + 'amp', + 'goose', + 'droid', + 'qwen', + 'copilot', + 'aider' +]) + +/** The start of the OS ephemeral range (Linux's default; macOS and Windows start higher, at 49152). */ +export const EPHEMERAL_PORT_START = 32_768 + +/** `codex`, `/usr/bin/codex`, `codex.exe` and `codex-linux-x64` all name Codex. */ +export function isAgentCliProcessName(processName: string | undefined): boolean { + if (!processName) { + return false + } + const base = (processName.trim().toLowerCase().split(/[\\/]/).at(-1) ?? '').replace(/\.exe$/, '') + return ( + AGENT_CLI_PROCESS_NAMES.has(base) || + [...AGENT_CLI_PROCESS_NAMES].some((name) => base.startsWith(`${name}-`)) + ) +} + +/** + * Looks like a dev server: a well-known web port, or a URL the workspace printed for it. A listener + * on an ephemeral port with neither is some process's internal socket (an agent's MCP child, a + * language server, a debugger), so it isn't forwarded on its own. + */ +function looksLikeDevServer(port: Extract): boolean { + return port.port < EPHEMERAL_PORT_START || port.protocol !== 'unknown' || !!port.advertisedUrl +} + +/** + * Dev servers a workspace started: attributed to a workspace, in range, not Orca's own, not an + * agent CLI's own listener, and not an anonymous ephemeral port. + */ export function isAutoForwardCandidate( port: WorkspacePort, settings: RuntimePortForwardSettings @@ -24,7 +73,9 @@ export function isAutoForwardCandidate( port.kind === 'workspace' && port.port >= settings.rangeStart && port.port <= settings.rangeEnd && - !RUNTIME_PORT_FORWARD_AUTO_EXCLUDED_PORTS.has(port.port) + !RUNTIME_PORT_FORWARD_AUTO_EXCLUDED_PORTS.has(port.port) && + !isAgentCliProcessName(port.processName) && + looksLikeDevServer(port) ) } From 14cf7b12dab12b4fafda687d2420e3764da2509a Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:19:20 -0800 Subject: [PATCH 04/35] fix(toasts): hovering a toast never moves it out from under the pointer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neil: the Orca Cloud GitHub App notice sank when hovered and popped back when the pointer left, in a loop, and looked cut off while it did. Sonner sizes an expanded toast to the height it measured when the toast was issued. The cloud toasts update their copy in place, so a card that grew after it showed kept its first, shorter height: on hover it shrank from the top, sank 20px out from under the pointer, collapsed and came back. - cloud-toast-stack re-issues a card under the same id when its content changes, so sonner measures it again (no re-add, no animation, same identity). - The front toast keeps its natural height when the stack expands, as it does when collapsed, so no toast can resize under the pointer however its content changed. Positions are unchanged: the card sits 16px from the right edge and clear of the status bar. Regression: fixture orca-cloud/CloudToastHover:grownAfterShowing fails before (766→786) and passes after; a unit test pins the re-issue. --- src/renderer/src/assets/main.css | 9 ++ .../orca-cloud/CloudToastHover.fixture.tsx | 97 +++++++++++++++++++ .../orca-cloud/cloud-toast-stack.test.tsx | 24 +++++ .../orca-cloud/cloud-toast-stack.tsx | 28 ++++-- .../runtime-port-auto-forward-plan.test.ts | 9 +- 5 files changed, 158 insertions(+), 9 deletions(-) create mode 100644 src/renderer/src/components/orca-cloud/CloudToastHover.fixture.tsx diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 185ebf16bec..e6d169d1d6f 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -637,6 +637,15 @@ body[data-modal-overlay-open] [data-toasts-raised] [data-sonner-toaster] { gap: 6px; } +/* Hovering the stack must never move the toast under the pointer. Sonner sizes an expanded toast to + the height it measured when the toast was issued; a toast whose content grew since then shrank + from the top on hover, sank out from under the pointer, collapsed and popped back up (a loop). + The front toast keeps its natural height in both states, as it already has when collapsed. */ +[data-sonner-toaster] + [data-sonner-toast][data-mounted='true'][data-expanded='true'][data-front='true'][data-removed='false'] { + height: auto; +} + /* Clip folded toast overflow to prevent hover/re-expansion loops; hidden would create a focus-scrollable container. */ [data-sonner-toaster] [data-sonner-toast][data-expanded='false'][data-front='false'] { overflow: clip; diff --git a/src/renderer/src/components/orca-cloud/CloudToastHover.fixture.tsx b/src/renderer/src/components/orca-cloud/CloudToastHover.fixture.tsx new file mode 100644 index 00000000000..ce5f5076bfb --- /dev/null +++ b/src/renderer/src/components/orca-cloud/CloudToastHover.fixture.tsx @@ -0,0 +1,97 @@ +// Hovering a persistent cloud toast must not move it (Neil: the GitHub App push notice sank on +// hover and popped back on leave). settings: one card alone, and one under a newer plain toast. +import { useEffect } from 'react' +import { toast } from 'sonner' +import { defineFixture } from '../../component-fixtures/component-fixture' +import { Toaster } from '../ui/sonner' +import { hideCloudToast, resetCloudToasts, showCloudToast } from './cloud-toast-stack' + +const noop = (): void => {} + +function showPushNotice(text = PUSH_TEXT): void { + showCloudToast('push:fixture', { + priority: 'action', + lines: [ + { + key: 'push', + text, + action: { label: 'Install on octocat', onClick: noop, primary: true } + } + ] + }) +} + +const PUSH_TEXT = + 'Orca Cloud can read octocat/hello-world but can’t push yet. Install the Orca GitHub App on octocat to push.' + +function Stage({ + withPlainToast = false, + grows = false +}: { + withPlainToast?: boolean + grows?: boolean +}): React.JSX.Element { + useEffect(() => { + // The notice's copy is settled after it shows (the repo resolves): the card grows in place. + showPushNotice(grows ? 'Orca Cloud can’t push yet.' : PUSH_TEXT) + const grow = grows ? window.setTimeout(() => showPushNotice(), 300) : undefined + if (withPlainToast) { + toast.success('Your app on port 3000 is available at localhost:3000', { + duration: Number.POSITIVE_INFINITY, + description: 'node · fix-login-flake' + }) + } + return () => { + window.clearTimeout(grow) + hideCloudToast('push:fixture') + resetCloudToasts() + toast.dismiss() + } + }, [withPlainToast, grows]) + return ( +
+ +
+ ) +} + +export const alone = defineFixture({ width: 1280, render: () => }) +/** Regression: a card whose copy grew after it showed stays put under the pointer when the stack + * expands on hover (it used to shrink to its first height and sink). */ +export const grownAfterShowing = defineFixture({ + width: 1280, + render: () => , + interact: async () => { + const card = (): HTMLElement | null => document.querySelector('[data-cloud-toast]') + const deadline = performance.now() + 3000 + while (!card()?.textContent?.includes('GitHub App')) { + if (performance.now() > deadline) { + throw new Error('Timed out waiting for the grown card') + } + await new Promise((resolve) => setTimeout(resolve, 50)) + } + await new Promise((resolve) => setTimeout(resolve, 500)) + const before = card()!.getBoundingClientRect() + // Sonner expands the stack on mouseenter/mousemove over its list (React derives enter from mouseover). + for (const type of ['mouseover', 'mousemove']) { + card()!.dispatchEvent(new MouseEvent(type, { bubbles: true, relatedTarget: document.body })) + } + await new Promise((resolve) => setTimeout(resolve, 500)) + if (card()!.closest('[data-sonner-toast]')?.getAttribute('data-expanded') !== 'true') { + throw new Error('The stack should expand on hover') + } + const after = card()!.getBoundingClientRect() + if (Math.abs(after.top - before.top) > 1 || Math.abs(after.bottom - before.bottom) > 1) { + throw new Error( + `The hovered card moved: ${before.top}→${after.top}, ${before.bottom}→${after.bottom}` + ) + } + if (after.right > window.innerWidth || after.bottom > window.innerHeight) { + throw new Error('The card must sit fully inside the window') + } + } +}) +export const underPlainToast = defineFixture({ + width: 1280, + render: () => +}) diff --git a/src/renderer/src/components/orca-cloud/cloud-toast-stack.test.tsx b/src/renderer/src/components/orca-cloud/cloud-toast-stack.test.tsx index 5f8533f7ce5..2c7ccd66258 100644 --- a/src/renderer/src/components/orca-cloud/cloud-toast-stack.test.tsx +++ b/src/renderer/src/components/orca-cloud/cloud-toast-stack.test.tsx @@ -166,6 +166,30 @@ describe('cloud toast stack (DS-q)', () => { expect(cloudToastInternalId(AGENT)).toBeNull() }) + it('re-issues a card whose copy changed in place, so sonner measures its new height', () => { + // Neil: the GitHub App push notice sank on hover and popped back (sonner sized it to its old, + // shorter height when the stack expanded). + showCloudToast(AGENT, agentView('Short.'), {}, 0) + const internal = cloudToastInternalId(AGENT) + sonner.custom.mockClear() + showCloudToast( + AGENT, + agentView('A longer line that wraps onto a second one in the card.'), + {}, + 1 + ) + expect(sonner.custom).toHaveBeenCalledOnce() + expect(sonner.custom.mock.calls[0]?.[1]).toMatchObject({ id: internal, className: '' }) + expect(sonner.dismiss).not.toHaveBeenCalled() + // The same view again changes nothing. + sonner.custom.mockClear() + const same = agentView('Same.') + showCloudToast(AGENT, same, {}, 2) + sonner.custom.mockClear() + showCloudToast(AGENT, same, {}, 3) + expect(sonner.custom).not.toHaveBeenCalled() + }) + describe('workspace scope (N-03)', () => { const W1 = 'w1' const inWorkspace = (id: string | null) => ({ activeView: 'terminal', activeWorktreeId: id }) diff --git a/src/renderer/src/components/orca-cloud/cloud-toast-stack.tsx b/src/renderer/src/components/orca-cloud/cloud-toast-stack.tsx index af618195af6..7116be9f9e8 100644 --- a/src/renderer/src/components/orca-cloud/cloud-toast-stack.tsx +++ b/src/renderer/src/components/orca-cloud/cloud-toast-stack.tsx @@ -64,6 +64,8 @@ type Entry = { generation: number /** Re-added: hide from assistive tech until this time (it was announced already). */ quietUntil: number + /** The class its current sonner toast was issued with, kept when the toast is re-issued. */ + sonnerClassName?: string } /** How long a re-added card stays hidden from assistive tech: longer than the live region's read. */ @@ -104,16 +106,21 @@ function desiredOrder(): string[] { /** Long enough for the re-added card to settle, after which it animates like any other toast. */ const READD_STILL_MS = 600 +function issueToSonner(logicalId: string, internalId: string, className: string): void { + toast.custom(() => , { + id: internalId, + duration: Number.POSITIVE_INFINITY, + unstyled: true, + dismissible: false, + className + }) +} + function addToSonner(logicalId: string, entry: Entry, readd: boolean): void { const internalId = entry.internalId const add = (className: string): void => { - toast.custom(() => , { - id: internalId, - duration: Number.POSITIVE_INFINITY, - unstyled: true, - dismissible: false, - className - }) + entry.sonnerClassName = className + issueToSonner(logicalId, internalId, className) } // A re-add must look like the card stayed put: no slide-in. Later stack moves animate as usual. add(readd ? 'cloud-toast-readd' : '') @@ -221,11 +228,18 @@ export function showCloudToast( const reorder = existing.view.priority !== view.priority || existing.scope?.workspaceId !== options.scope?.workspaceId + const contentChanged = existing.view !== view existing.view = view existing.onDismiss = options.onDismiss existing.scope = options.scope if (reorder) { reconcile(now) + } else if (contentChanged && sonnerOrder.includes(logicalId)) { + // Sonner measures a toast's height only when it is (re)issued, and an expanded stack sizes + // every card to that height. A card whose copy grew in place kept its old height, so hovering + // it shrank it from the top: it sank out from under the pointer, collapsed, and popped back. + // Re-issuing under the same id updates it in place and measures it again. + issueToSonner(logicalId, existing.internalId, existing.sonnerClassName ?? '') } emit() return diff --git a/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts b/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts index b5d05f17332..9fab5827ff8 100644 --- a/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts +++ b/src/renderer/src/lib/runtime-port-forwards/runtime-port-auto-forward-plan.test.ts @@ -123,8 +123,13 @@ describe('planAutoForwards', () => { it('skips an anonymous ephemeral port, but not one with a known web port or a printed URL', () => { const settings = DEFAULT_RUNTIME_PORT_FORWARD_SETTINGS - const unknown = (port: number): WorkspacePort => ({ - ...workspace(port), + const unknown = (port: number): Extract => ({ + id: `127.0.0.1:${port}`, + kind: 'workspace', + owner, + bindHost: '127.0.0.1', + connectHost: 'localhost', + port, protocol: 'unknown', processName: 'node' }) From 919b6259bbc165196941533d4cd4161154c86560 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:21:38 -0800 Subject: [PATCH 05/35] feat(cloud): CODEX-RELAY chatgpt.com egress through a Cloud Run relay chatgpt.com answers Cloudflare Workers' egress with a 403 "Unable to load site" page, so Codex via the Orca account could never get an answer through the egress proxy (#767 made that a printed error). Cloud Run's egress is answered normally (probed, then deleted). - cloud/apps/chatgpt-relay: a dependency-free Node relay. chatgpt.com only, the same Codex path pinning as the Worker (shared sandbox-control/src/codex-paths.ts), SSE streamed chunk by chunk, no WebSocket upgrades, hop and Cloud Run headers dropped, logs without headers, bodies or queries. - Cloud Run IAM authenticates the Worker: one invoker service account (run.invoker on the relay only); the Worker mints a Google ID token for the relay URL and sends it in X-Serverless-Authorization, so the swapped ChatGPT Authorization passes through untouched. - sandbox-control: CHATGPT_RELAY_URL + CHATGPT_RELAY_SERVICE_ACCOUNT route the egress proxy's chatgpt.com fetches through the relay; unset, chatgpt.com goes direct as before. A relay sign-in failure answers Codex a 503 JSON detail instead of reaching chatgpt.com. - cloud/infra/chatgpt-relay: Terraform (staging backend applied; production is a runbook step). --- cloud/apps/chatgpt-relay/Dockerfile | 10 ++ cloud/apps/chatgpt-relay/build-image.sh | 19 +++ cloud/apps/chatgpt-relay/package.json | 17 +++ cloud/apps/chatgpt-relay/src/index.ts | 8 + cloud/apps/chatgpt-relay/src/relay.ts | 144 ++++++++++++++++++ cloud/apps/chatgpt-relay/test/relay.test.ts | 116 ++++++++++++++ cloud/apps/chatgpt-relay/tsconfig.json | 21 +++ .../apps/sandbox-control/src/chatgpt-relay.ts | 94 ++++++++++++ .../sandbox-control/src/codex-credentials.ts | 29 +--- cloud/apps/sandbox-control/src/codex-paths.ts | 29 ++++ cloud/apps/sandbox-control/src/env.ts | 4 + cloud/apps/sandbox-control/src/index.ts | 23 ++- .../test/chatgpt-relay.test.ts | 85 +++++++++++ .../sandbox-control/test/codex-broker.test.ts | 29 +++- cloud/apps/sandbox-control/wrangler.dev.jsonc | 3 + cloud/infra/chatgpt-relay/.gitignore | 1 + cloud/infra/chatgpt-relay/.terraform.lock.hcl | 22 +++ cloud/infra/chatgpt-relay/README.md | 31 ++++ cloud/infra/chatgpt-relay/backend/staging.hcl | 2 + .../chatgpt-relay/environments/staging.tfvars | 3 + cloud/infra/chatgpt-relay/main.tf | 104 +++++++++++++ cloud/infra/chatgpt-relay/outputs.tf | 12 ++ cloud/infra/chatgpt-relay/variables.tf | 18 +++ cloud/infra/chatgpt-relay/versions.tf | 16 ++ cloud/pnpm-lock.yaml | 12 ++ 25 files changed, 824 insertions(+), 28 deletions(-) create mode 100644 cloud/apps/chatgpt-relay/Dockerfile create mode 100755 cloud/apps/chatgpt-relay/build-image.sh create mode 100644 cloud/apps/chatgpt-relay/package.json create mode 100644 cloud/apps/chatgpt-relay/src/index.ts create mode 100644 cloud/apps/chatgpt-relay/src/relay.ts create mode 100644 cloud/apps/chatgpt-relay/test/relay.test.ts create mode 100644 cloud/apps/chatgpt-relay/tsconfig.json create mode 100644 cloud/apps/sandbox-control/src/chatgpt-relay.ts create mode 100644 cloud/apps/sandbox-control/src/codex-paths.ts create mode 100644 cloud/apps/sandbox-control/test/chatgpt-relay.test.ts create mode 100644 cloud/infra/chatgpt-relay/.gitignore create mode 100644 cloud/infra/chatgpt-relay/.terraform.lock.hcl create mode 100644 cloud/infra/chatgpt-relay/README.md create mode 100644 cloud/infra/chatgpt-relay/backend/staging.hcl create mode 100644 cloud/infra/chatgpt-relay/environments/staging.tfvars create mode 100644 cloud/infra/chatgpt-relay/main.tf create mode 100644 cloud/infra/chatgpt-relay/outputs.tf create mode 100644 cloud/infra/chatgpt-relay/variables.tf create mode 100644 cloud/infra/chatgpt-relay/versions.tf diff --git a/cloud/apps/chatgpt-relay/Dockerfile b/cloud/apps/chatgpt-relay/Dockerfile new file mode 100644 index 00000000000..6f48e6c0ac8 --- /dev/null +++ b/cloud/apps/chatgpt-relay/Dockerfile @@ -0,0 +1,10 @@ +# Build context: cloud/apps (the relay imports sandbox-control's codex-paths.ts, the shared path pinning). +FROM node:24-slim +WORKDIR /app +COPY sandbox-control/src/codex-paths.ts sandbox-control/src/codex-paths.ts +COPY chatgpt-relay/package.json chatgpt-relay/package.json +COPY chatgpt-relay/src chatgpt-relay/src +WORKDIR /app/chatgpt-relay +ENV NODE_ENV=production +USER node +CMD ["node", "src/index.ts"] diff --git a/cloud/apps/chatgpt-relay/build-image.sh b/cloud/apps/chatgpt-relay/build-image.sh new file mode 100755 index 00000000000..48d4462a800 --- /dev/null +++ b/cloud/apps/chatgpt-relay/build-image.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Builds the relay image with Cloud Build (context: cloud/apps) and prints its digest-pinned name for +# `terraform apply -var image=...` in cloud/infra/chatgpt-relay. +# Usage: build-image.sh [region] +set -euo pipefail +project="${1:?project}" +region="${2:-us-central1}" +apps="$(cd "$(dirname "$0")/.." && pwd)" +repo="$region-docker.pkg.dev/$project/orca-chatgpt-relay/relay" +tag="$(git -C "$apps" rev-parse --short=12 HEAD)" +gcloud builds submit "$apps" --project "$project" --region "$region" --quiet \ + --config /dev/stdin <&2 +steps: + - name: gcr.io/cloud-builders/docker + args: [build, -f, chatgpt-relay/Dockerfile, -t, "$repo:$tag", .] +images: ["$repo:$tag"] +YAML +digest="$(gcloud artifacts docker images describe "$repo:$tag" --project "$project" --format='value(image_summary.digest)')" +echo "$repo@$digest" diff --git a/cloud/apps/chatgpt-relay/package.json b/cloud/apps/chatgpt-relay/package.json new file mode 100644 index 00000000000..9983d7ff35a --- /dev/null +++ b/cloud/apps/chatgpt-relay/package.json @@ -0,0 +1,17 @@ +{ + "name": "@orca-cloud/chatgpt-relay", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "start": "node src/index.ts", + "test": "vitest run", + "typecheck": "tsc -p tsconfig.json --noEmit", + "lint": "tsc -p tsconfig.json --noEmit" + }, + "devDependencies": { + "@types/node": "^24.19.2", + "typescript": "^7.0.2", + "vitest": "^5.0.5" + } +} diff --git a/cloud/apps/chatgpt-relay/src/index.ts b/cloud/apps/chatgpt-relay/src/index.ts new file mode 100644 index 00000000000..cf0871d6dd5 --- /dev/null +++ b/cloud/apps/chatgpt-relay/src/index.ts @@ -0,0 +1,8 @@ +import { createServer } from 'node:http' +import { createRelay } from './relay.ts' + +const server = createServer(createRelay()) +// Long Codex turns stream for minutes: no Node-side request or header timeout (Cloud Run caps it). +server.requestTimeout = 0 +server.headersTimeout = 0 +server.listen(Number(process.env.PORT ?? 8080), () => console.log(JSON.stringify({ event: 'relay_listening' }))) diff --git a/cloud/apps/chatgpt-relay/src/relay.ts b/cloud/apps/chatgpt-relay/src/relay.ts new file mode 100644 index 00000000000..3c41d902ed2 --- /dev/null +++ b/cloud/apps/chatgpt-relay/src/relay.ts @@ -0,0 +1,144 @@ +// CODEX-RELAY: chatgpt.com refuses Cloudflare Workers' egress, so the sandbox-control egress proxy +// sends its chatgpt.com requests here (Cloud Run, which ChatGPT answers). The Worker already chose the +// credential and pinned the path; this relay pins the path again, forwards to chatgpt.com only, and +// streams the answer back as it arrives (Codex reads Server-Sent Events). +// Cloud Run IAM authenticates the Worker (an ID token in X-Serverless-Authorization, run.invoker on +// one service account): nothing unauthenticated reaches this code. No header or body is ever logged. +import type { IncomingMessage, ServerResponse } from 'node:http' +import { Readable } from 'node:stream' +import { codexPathAllowed } from '../../sandbox-control/src/codex-paths.ts' + +export const UPSTREAM_ORIGIN = 'https://chatgpt.com' + +/** Never forwarded: hop-by-hop, Cloud Run's own auth and tracing, and proxy breadcrumbs. */ +const DROP_REQUEST = new Set([ + 'host', + 'connection', + 'keep-alive', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'content-length', + 'x-serverless-authorization', + 'forwarded', + 'traceparent', + 'tracestate', + 'x-cloud-trace-context' +]) +const DROP_REQUEST_PREFIXES = ['x-forwarded-', 'x-goog-', 'cf-'] + +/** fetch already decoded the body, so its encoding and length no longer describe what we send. */ +const DROP_RESPONSE = new Set([ + 'connection', + 'keep-alive', + 'transfer-encoding', + 'content-encoding', + 'content-length', + 'trailer', + 'upgrade' +]) + +export type RelayDeps = { + fetch?: typeof fetch + log?: (line: Record) => void + now?: () => number +} + +function refuse(res: ServerResponse, status: number, reason: string): void { + res.writeHead(status, { 'content-type': 'text/plain' }) + res.end(reason) +} + +/** The first two path segments only (e.g. /backend-api/codex): never ids or queries. */ +function pathLabel(path: string): string { + return (path.split('?')[0] ?? '').split('/').slice(0, 3).join('/') +} + +export function forwardHeaders(req: IncomingMessage): Headers { + const headers = new Headers() + for (const [name, value] of Object.entries(req.headers)) { + const key = name.toLowerCase() + if (value === undefined || DROP_REQUEST.has(key) || DROP_REQUEST_PREFIXES.some((p) => key.startsWith(p))) { + continue + } + for (const one of Array.isArray(value) ? value : [value]) { + headers.append(key, one) + } + } + return headers +} + +export function createRelay(deps: RelayDeps = {}) { + const doFetch = deps.fetch ?? fetch + const log = deps.log ?? ((line) => console.log(JSON.stringify(line))) + const now = deps.now ?? Date.now + return async function handle(req: IncomingMessage, res: ServerResponse): Promise { + const started = now() + const method = (req.method ?? 'GET').toUpperCase() + const path = req.url ?? '/' + if (path === '/health' && method === 'GET') { + res.writeHead(200, { 'content-type': 'text/plain' }) + res.end('ok') + return + } + // Codex is configured for HTTPS (supports_websockets = false); the Worker proxy can't upgrade either. + if (req.headers.upgrade) { + refuse(res, 426, 'upgrade_not_supported') + return + } + if (!path.startsWith('/') || !codexPathAllowed(method, path)) { + log({ event: 'relay_refused', reason: 'path_not_allowed', method, path: pathLabel(path) }) + refuse(res, 403, 'path_not_allowed') + return + } + const hasBody = method !== 'GET' && method !== 'HEAD' + const abort = new AbortController() + // The VM's client went away: stop reading from chatgpt.com too. + res.on('close', () => { + if (!res.writableFinished) { + abort.abort() + } + }) + let upstream: Response + try { + upstream = await doFetch(`${UPSTREAM_ORIGIN}${path}`, { + method, + headers: forwardHeaders(req), + body: hasBody ? (Readable.toWeb(req) as ReadableStream) : undefined, + // Node needs this for a streamed request body. + ...(hasBody ? { duplex: 'half' } : {}), + redirect: 'manual', + signal: abort.signal + } as RequestInit) + } catch { + log({ event: 'relay_upstream_failed', method, path: pathLabel(path), ms: now() - started }) + if (!res.headersSent) { + refuse(res, 502, 'upstream_unreachable') + } + return + } + const headers: Record = {} + upstream.headers.forEach((value, name) => { + if (!DROP_RESPONSE.has(name.toLowerCase())) { + ;(headers[name] ??= []).push(value) + } + }) + res.writeHead(upstream.status, headers) + // Each chunk is written as it arrives: SSE events reach Codex without buffering. + res.flushHeaders() + if (upstream.body) { + try { + for await (const chunk of upstream.body as unknown as AsyncIterable) { + res.write(chunk) + } + } catch { + // The client left (abort) or chatgpt.com cut the stream: end what was sent. + } + } + res.end() + log({ event: 'relay', method, path: pathLabel(path), status: upstream.status, ms: now() - started }) + } +} diff --git a/cloud/apps/chatgpt-relay/test/relay.test.ts b/cloud/apps/chatgpt-relay/test/relay.test.ts new file mode 100644 index 00000000000..3e8f2d33686 --- /dev/null +++ b/cloud/apps/chatgpt-relay/test/relay.test.ts @@ -0,0 +1,116 @@ +import { createServer, request, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { afterEach, describe, expect, it } from 'vitest' +import { createRelay } from '../src/relay.ts' + +type Seen = { url: string; headers: Headers; body: string | null } +let server: Server | null = null +afterEach(() => new Promise((done) => (server ? server.close(() => done()) : done()))) + +async function start(reply: (seen: Seen) => Response) { + const seen: Seen[] = [] + const logs: Record[] = [] + const relay = createRelay({ + log: (line) => logs.push(line), + fetch: async (input, init) => { + const body = init?.body ? await new Response(init.body as BodyInit).text() : null + const one = { url: String(input), headers: new Headers(init?.headers), body } + seen.push(one) + return reply(one) + } + }) + server = createServer((req, res) => void relay(req, res)) + await new Promise((done) => server!.listen(0, '127.0.0.1', done)) + const port = (server.address() as AddressInfo).port + const call = (method: string, path: string, headers: Record = {}, body?: string) => + new Promise<{ status: number; headers: Record; body: string; chunks: string[] }>((resolve, reject) => { + const req = request({ host: '127.0.0.1', port, method, path, headers }, (res) => { + const chunks: string[] = [] + res.setEncoding('utf8') + res.on('data', (c: string) => chunks.push(c)) + res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: chunks.join(''), chunks })) + }) + req.on('error', reject) + req.end(body) + }) + return { seen, logs, call } +} + +describe('ChatGPT relay (CODEX-RELAY)', () => { + it('forwards an allowed Codex call to chatgpt.com with its credential, minus Cloud Run auth and hop headers', async () => { + const t = await start(() => new Response('{"ok":true}', { status: 200, headers: { 'content-type': 'application/json', 'content-encoding': 'gzip' } })) + const res = await t.call( + 'POST', + '/backend-api/codex/responses', + { + authorization: 'Bearer real-token', + 'chatgpt-account-id': 'acct-1', + 'x-serverless-authorization': 'Bearer google-id-token', + 'x-forwarded-for': '1.2.3.4', + 'content-type': 'application/json' + }, + '{"input":"hi"}' + ) + expect(res.status).toBe(200) + expect(res.body).toBe('{"ok":true}') + expect(res.headers['content-encoding']).toBeUndefined() + const sent = t.seen[0]! + expect(sent.url).toBe('https://chatgpt.com/backend-api/codex/responses') + expect(sent.body).toBe('{"input":"hi"}') + expect(sent.headers.get('authorization')).toBe('Bearer real-token') + expect(sent.headers.get('chatgpt-account-id')).toBe('acct-1') + expect(sent.headers.get('x-serverless-authorization')).toBeNull() + expect(sent.headers.get('x-forwarded-for')).toBeNull() + expect(sent.headers.get('host')).toBeNull() + }) + + it('pins the same paths as the Worker: nothing else on chatgpt.com', async () => { + const t = await start(() => new Response('{}')) + expect((await t.call('GET', '/backend-api/conversations')).status).toBe(403) + expect((await t.call('POST', '/backend-api/wham/usage')).status).toBe(403) + expect((await t.call('GET', '/backend-api/codex/../conversations')).status).toBe(403) + expect((await t.call('GET', '/backend-api/wham/usage')).status).toBe(200) + expect(t.seen.map((s) => s.url)).toEqual(['https://chatgpt.com/backend-api/wham/usage']) + }) + + it('streams Server-Sent Events as they arrive, not after the upstream ends', async () => { + let push: (text: string) => void = () => {} + let close: () => void = () => {} + const stream = new ReadableStream({ + start(controller) { + push = (text) => controller.enqueue(new TextEncoder().encode(text)) + close = () => controller.close() + } + }) + const t = await start(() => new Response(stream, { status: 200, headers: { 'content-type': 'text/event-stream' } })) + const pending = t.call('POST', '/backend-api/codex/responses', { 'content-type': 'application/json' }, '{}') + // The first event is out before the second exists. + await new Promise((r) => setTimeout(r, 20)) + push('event: a\ndata: 1\n\n') + await new Promise((r) => setTimeout(r, 50)) + push('event: b\ndata: 2\n\n') + close() + const res = await pending + expect(res.headers['content-type']).toBe('text/event-stream') + expect(res.body).toBe('event: a\ndata: 1\n\nevent: b\ndata: 2\n\n') + expect(res.chunks.length).toBeGreaterThanOrEqual(2) + }) + + it('logs method, a two-segment path and the status only: never headers, bodies or queries', async () => { + const t = await start(() => new Response('secret-body')) + await t.call('GET', '/backend-api/codex/models?client_version=0.166.0', { authorization: 'Bearer real-token' }) + const text = JSON.stringify(t.logs) + expect(t.logs.at(-1)).toMatchObject({ event: 'relay', method: 'GET', path: '/backend-api/codex', status: 200 }) + for (const leak of ['real-token', 'secret-body', 'client_version']) { + expect(text).not.toContain(leak) + } + }) + + it('refuses WebSocket upgrades and answers 502 when chatgpt.com is unreachable', async () => { + const t = await start(() => { + throw new TypeError('fetch failed') + }) + expect((await t.call('GET', '/backend-api/codex/responses', { upgrade: 'websocket', connection: 'Upgrade' })).status).toBe(426) + expect((await t.call('GET', '/backend-api/wham/usage')).status).toBe(502) + }) +}) diff --git a/cloud/apps/chatgpt-relay/tsconfig.json b/cloud/apps/chatgpt-relay/tsconfig.json new file mode 100644 index 00000000000..493d8ecb3cb --- /dev/null +++ b/cloud/apps/chatgpt-relay/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "types": [ + "node" + ], + "rootDir": "..", + "lib": [ + "ES2024", + "DOM" + ] + }, + "include": [ + "src", + "test", + "../sandbox-control/src/codex-paths.ts" + ] +} diff --git a/cloud/apps/sandbox-control/src/chatgpt-relay.ts b/cloud/apps/sandbox-control/src/chatgpt-relay.ts new file mode 100644 index 00000000000..3a98ce62ee8 --- /dev/null +++ b/cloud/apps/sandbox-control/src/chatgpt-relay.ts @@ -0,0 +1,94 @@ +// CODEX-RELAY: chatgpt.com refuses Cloudflare Workers' egress (a 403 "Unable to load site" page), so +// the egress proxy sends its chatgpt.com requests through the ChatGPT relay on Cloud Run +// (cloud/apps/chatgpt-relay), which ChatGPT answers. The Worker still decides everything: which +// credential, which paths. The relay pins the paths again and only ever talks to chatgpt.com. +// Auth: Cloud Run IAM. The Worker signs in as one service account that holds only run.invoker on the +// relay, and sends a Google ID token for the relay's URL in X-Serverless-Authorization, so the +// request's own Authorization (the ChatGPT token) passes through untouched. +// CHATGPT_RELAY_URL https://.run.app (unset: chatgpt.com directly, as before) +// CHATGPT_RELAY_SERVICE_ACCOUNT (secret) service-account JSON with run.invoker on that service only +import { SignJWT, importPKCS8 } from 'jose' +import { z } from 'zod' + +const TOKEN_URL = 'https://oauth2.googleapis.com/token' +export const RELAYED_HOSTS: ReadonlySet = new Set(['chatgpt.com']) +const ServiceAccount = z.looseObject({ client_email: z.string().min(3).max(320), private_key: z.string().min(100) }) +const IdTokenResponse = z.looseObject({ id_token: z.string().min(20) }) + +export class RelayAuthError extends Error {} + +/** A Google ID token for `audience`, minted from the service account, cached until 5 minutes before expiry. */ +export function createIdTokenSource(config: { serviceAccountJson: string; audience: string; fetch?: typeof fetch; now?: () => number }) { + const doFetch = config.fetch ?? fetch + const now = config.now ?? Date.now + let cached: { value: string; expiresAt: number } | null = null + let pending: Promise | null = null + let signingKey: CryptoKey | null = null + async function mint(): Promise { + let account: z.infer + try { + account = ServiceAccount.parse(JSON.parse(config.serviceAccountJson)) + signingKey ??= await importPKCS8(account.private_key, 'RS256') + } catch { + throw new RelayAuthError('relay service account is malformed') + } + const iat = Math.floor(now() / 1000) - 30 + const assertion = await new SignJWT({ target_audience: config.audience }) + .setProtectedHeader({ alg: 'RS256', typ: 'JWT' }) + .setIssuer(account.client_email) + .setSubject(account.client_email) + .setAudience(TOKEN_URL) + .setIssuedAt(iat) + .setExpirationTime(iat + 600) + .sign(signingKey) + const response = await doFetch(TOKEN_URL, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString(), + signal: AbortSignal.timeout(10_000) + }) + const parsed = IdTokenResponse.safeParse(await response.json().catch(() => null)) + if (!response.ok || !parsed.success) { + throw new RelayAuthError(`relay id token mint failed (${response.status})`) + } + // Google ID tokens last an hour; read exp rather than assume it. + const payload = JSON.parse(atob(parsed.data.id_token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/'))) as { exp?: number } + cached = { value: parsed.data.id_token, expiresAt: (payload.exp ?? Math.floor(now() / 1000) + 3600) * 1000 } + return cached.value + } + return async (): Promise => { + if (cached && cached.expiresAt - now() > 5 * 60_000) { + return cached.value + } + pending ??= mint().finally(() => { + pending = null + }) + return pending + } +} + +/** + * The egress proxy's upstream fetch: chatgpt.com through the relay when one is configured, every other host + * (and chatgpt.com without a relay) directly. Same request, same path and query; only the origin changes. + */ +export function relayingFetch(config: { relayUrl?: string; idToken?: () => Promise; fetch?: typeof fetch }): typeof fetch { + const doFetch = config.fetch ?? fetch + const relay = config.relayUrl ? new URL(config.relayUrl) : null + return (async (input: RequestInfo | URL, init?: RequestInit) => { + const target = new URL(typeof input === 'string' || input instanceof URL ? input : input.url) + if (!relay || !config.idToken || target.protocol !== 'https:' || !RELAYED_HOSTS.has(target.hostname)) { + return doFetch(input, init) + } + let idToken: string + try { + idToken = await config.idToken() + } catch { + // In ChatGPT's error shape (a JSON detail), so Codex prints it instead of retrying a bare 5xx. + console.error(JSON.stringify({ event: 'chatgpt_relay_auth_failed' })) + return Response.json({ detail: 'Orca Cloud couldn’t reach ChatGPT just now. Try again in a minute.' }, { status: 503 }) + } + const headers = new Headers(init?.headers) + headers.set('x-serverless-authorization', `Bearer ${idToken}`) + return doFetch(`${relay.origin}${target.pathname}${target.search}`, { ...init, headers }) + }) as typeof fetch +} diff --git a/cloud/apps/sandbox-control/src/codex-credentials.ts b/cloud/apps/sandbox-control/src/codex-credentials.ts index 7065a8c8793..8624762cd18 100644 --- a/cloud/apps/sandbox-control/src/codex-credentials.ts +++ b/cloud/apps/sandbox-control/src/codex-credentials.ts @@ -11,6 +11,9 @@ // (that is what `refresh_token_reused` punishes). import { decodeJwt } from 'jose' import type { AccountProvider } from './account-providers' +import { codexPathAllowed } from './codex-paths' + +export { codexPathAllowed } import { credentialBinding, putAgentCredential, readUsableAgentCredential } from './agent-credentials' import type { Keyring } from './secrets-crypto' import type { SandboxRow } from './store' @@ -118,32 +121,6 @@ function formatCodex(credential: string): string { return `Bearer ${stored ? stored.access_token : credential}` } -/** - * The ChatGPT backend calls Codex makes with its login (seen live, Codex 0.166): the Codex API itself, its - * plugin catalog and usage. Nothing else on chatgpt.com (conversations, memories, connectors) gets the token. - */ -const CODEX_PREFIXES = ['/backend-api/codex/'] -const CODEX_EXACT_GETS = new Set([ - '/backend-api/ps/plugins/list', - '/backend-api/ps/plugins/installed', - '/backend-api/ps/plugins/suggested/codex', - '/backend-api/plugins/featured', - '/backend-api/plugins/export/curated', - '/backend-api/wham/usage' -]) - -export function codexPathAllowed(method: string, path: string): boolean { - const pathname = path.split('?')[0] ?? '' - // Plain segments only: no encoded or dot segments that could walk out of an allowed prefix. - if (!/^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+\/?$/.test(pathname) || /(^|\/)\.\.?(\/|$)/.test(pathname)) { - return false - } - if (CODEX_PREFIXES.some((prefix) => pathname.startsWith(prefix))) { - return true - } - return method.toUpperCase() === 'GET' && CODEX_EXACT_GETS.has(pathname) -} - export const codexAccount: AccountProvider = { agent: 'codex', hosts: CODEX_ACCOUNT_HOSTS, diff --git a/cloud/apps/sandbox-control/src/codex-paths.ts b/cloud/apps/sandbox-control/src/codex-paths.ts new file mode 100644 index 00000000000..60ddf0b5ace --- /dev/null +++ b/cloud/apps/sandbox-control/src/codex-paths.ts @@ -0,0 +1,29 @@ +// The chatgpt.com paths Codex's login may be used on. Shared, unchanged, by the Worker's egress proxy +// (codex-credentials.ts) and the ChatGPT relay (cloud/apps/chatgpt-relay), which pins the same paths a +// second time. Erasable TypeScript only: the relay runs this file with Node's type stripping. + +/** + * The ChatGPT backend calls Codex makes with its login (seen live, Codex 0.166): the Codex API itself, its + * plugin catalog and usage. Nothing else on chatgpt.com (conversations, memories, connectors) gets the token. + */ +const CODEX_PREFIXES = ['/backend-api/codex/'] +const CODEX_EXACT_GETS = new Set([ + '/backend-api/ps/plugins/list', + '/backend-api/ps/plugins/installed', + '/backend-api/ps/plugins/suggested/codex', + '/backend-api/plugins/featured', + '/backend-api/plugins/export/curated', + '/backend-api/wham/usage' +]) + +export function codexPathAllowed(method: string, path: string): boolean { + const pathname = path.split('?')[0] ?? '' + // Plain segments only: no encoded or dot segments that could walk out of an allowed prefix. + if (!/^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+\/?$/.test(pathname) || /(^|\/)\.\.?(\/|$)/.test(pathname)) { + return false + } + if (CODEX_PREFIXES.some((prefix) => pathname.startsWith(prefix))) { + return true + } + return method.toUpperCase() === 'GET' && CODEX_EXACT_GETS.has(pathname) +} diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 9b9960e194c..8030c89af7a 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -90,6 +90,10 @@ export type Env = { RUNTIME_REFRESH?: string /** Public URL of this Worker's /v1/egress/proxy; Vercel forwardURL rules point here. */ EGRESS_PROXY_URL?: string + /** CODEX-RELAY (src/chatgpt-relay.ts): the Cloud Run relay chatgpt.com egress goes through. Unset: direct. */ + CHATGPT_RELAY_URL?: string + /** (secret) service-account JSON holding run.invoker on CHATGPT_RELAY_URL's service only. */ + CHATGPT_RELAY_SERVICE_ACCOUNT?: string /** Shortened session deadline (ms) for staging rollover rehearsals; refused when SANDBOX_ENV=prod. */ SESSION_DEADLINE_MS?: string /** Dev-only: Authorization the egress proxy injects for api.github.com until the GitHub App minter exists. */ diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 87f6182fcc1..7b7317c60a0 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -66,6 +66,7 @@ import { tickRoutines } from './routines/runs' import { activeGoldenSnapshots, advanceGoldenImages } from './golden-images' import { sandboxRegions, seedRegion } from './regions' import { handleRuntimeBundleRoute, runtimeBundleFor, runtimeBundleUrl } from './runtime-bundles' +import { createIdTokenSource, relayingFetch } from './chatgpt-relay' import { NO_CREDENTIALS, handleEgressProxy, type CredentialBroker, type ProxiedRoute } from './egress-proxy' import { BillingUnavailableError, @@ -1317,7 +1318,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise getSandboxByProviderName(env.SANDBOX_DB, name), routesFor: egressRoutes(env, deps), - fetch: deps.egressFetch, + fetch: chatgptRelayFetch(env, deps.egressFetch), keysForIssuer: deps.egressKeysForIssuer }) } @@ -2859,3 +2860,23 @@ async function agentSourcesRoute(request: Request, url: URL, env: Env, deps: Dep throw error } } + +// CODEX-RELAY: one ID-token source per isolate and relay config (the token is cached for its hour). +let relayIdTokens: { key: string; source: () => Promise } | null = null +function chatgptRelayFetch(env: Env, egressFetch: typeof fetch | undefined): typeof fetch | undefined { + if (!env.CHATGPT_RELAY_URL || !env.CHATGPT_RELAY_SERVICE_ACCOUNT) { + return egressFetch + } + const key = `${env.CHATGPT_RELAY_URL}\n${env.CHATGPT_RELAY_SERVICE_ACCOUNT.length}` + if (relayIdTokens?.key !== key) { + relayIdTokens = { + key, + source: createIdTokenSource({ + serviceAccountJson: env.CHATGPT_RELAY_SERVICE_ACCOUNT, + audience: env.CHATGPT_RELAY_URL, + ...(egressFetch ? { fetch: egressFetch } : {}) + }) + } + } + return relayingFetch({ relayUrl: env.CHATGPT_RELAY_URL, idToken: relayIdTokens.source, ...(egressFetch ? { fetch: egressFetch } : {}) }) +} diff --git a/cloud/apps/sandbox-control/test/chatgpt-relay.test.ts b/cloud/apps/sandbox-control/test/chatgpt-relay.test.ts new file mode 100644 index 00000000000..8d75daffbdb --- /dev/null +++ b/cloud/apps/sandbox-control/test/chatgpt-relay.test.ts @@ -0,0 +1,85 @@ +import { exportPKCS8, generateKeyPair, decodeJwt } from 'jose' +import { describe, expect, it } from 'vitest' +import { createIdTokenSource, relayingFetch } from '../src/chatgpt-relay' + +const RELAY = 'https://orca-chatgpt-relay-abc.us-central1.run.app' + +function idTokenFor(exp: number): string { + const enc = (o: unknown) => Buffer.from(JSON.stringify(o)).toString('base64url') + return `${enc({ alg: 'RS256' })}.${enc({ exp, aud: RELAY })}.sig` +} + +async function serviceAccount() { + const { privateKey } = await generateKeyPair('RS256', { extractable: true }) + return JSON.stringify({ client_email: 'relay-invoker@p.iam.gserviceaccount.com', private_key: await exportPKCS8(privateKey) }) +} + +describe('relayingFetch (CODEX-RELAY)', () => { + it('sends chatgpt.com through the relay with an ID token beside, never instead of, the ChatGPT credential', async () => { + const seen: { url: string; headers: Headers }[] = [] + const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => { + seen.push({ url: String(input), headers: new Headers(init?.headers) }) + return new Response('ok') + }) as typeof fetch + const relayed = relayingFetch({ relayUrl: RELAY, idToken: async () => 'google-id', fetch: fetchImpl }) + await relayed('https://chatgpt.com/backend-api/codex/models?client_version=0.166.0', { headers: { authorization: 'Bearer chatgpt-real' } }) + await relayed('https://api.anthropic.com/v1/messages', { headers: { authorization: 'Bearer other' } }) + expect(seen[0]!.url).toBe(`${RELAY}/backend-api/codex/models?client_version=0.166.0`) + expect(seen[0]!.headers.get('authorization')).toBe('Bearer chatgpt-real') + expect(seen[0]!.headers.get('x-serverless-authorization')).toBe('Bearer google-id') + // Every other host goes direct, with no relay token. + expect(seen[1]!.url).toBe('https://api.anthropic.com/v1/messages') + expect(seen[1]!.headers.get('x-serverless-authorization')).toBeNull() + }) + + it('without a relay URL chatgpt.com goes direct, as before', async () => { + const urls: string[] = [] + const fetchImpl = (async (input: RequestInfo | URL) => (urls.push(String(input)), new Response('ok'))) as typeof fetch + await relayingFetch({ fetch: fetchImpl })('https://chatgpt.com/backend-api/wham/usage') + expect(urls).toEqual(['https://chatgpt.com/backend-api/wham/usage']) + }) + + it('a relay sign-in failure answers in ChatGPT’s error shape (Codex prints it), never reaching chatgpt.com', async () => { + let calls = 0 + const fetchImpl = (async () => (calls++, new Response('ok'))) as typeof fetch + const res = await relayingFetch({ + relayUrl: RELAY, + idToken: async () => { + throw new Error('no') + }, + fetch: fetchImpl + })('https://chatgpt.com/backend-api/codex/responses', { method: 'POST' }) + expect(res.status).toBe(503) + expect(((await res.json()) as { detail: string }).detail).toContain('ChatGPT') + expect(calls).toBe(0) + }) +}) + +describe('createIdTokenSource', () => { + it('mints with target_audience = the relay URL, and reuses the token until 5 minutes before it expires', async () => { + let now = 1_800_000_000_000 + const assertions: string[] = [] + const fetchImpl = (async (_input: RequestInfo | URL, init?: RequestInit) => { + assertions.push(new URLSearchParams(String(init?.body)).get('assertion')!) + return Response.json({ id_token: idTokenFor(Math.floor(now / 1000) + 3600) }) + }) as typeof fetch + const source = createIdTokenSource({ serviceAccountJson: await serviceAccount(), audience: RELAY, fetch: fetchImpl, now: () => now }) + const first = await source() + expect(await source()).toBe(first) + expect(assertions).toHaveLength(1) + const claims = decodeJwt(assertions[0]!) + expect(claims).toMatchObject({ target_audience: RELAY, aud: 'https://oauth2.googleapis.com/token', iss: 'relay-invoker@p.iam.gserviceaccount.com' }) + now += 56 * 60_000 + await source() + expect(assertions).toHaveLength(2) + }) + + it('a refused mint throws (the caller answers 503) and the next call tries again', async () => { + let ok = false + const fetchImpl = (async () => (ok ? Response.json({ id_token: idTokenFor(4e9) }) : new Response('{}', { status: 400 }))) as typeof fetch + const source = createIdTokenSource({ serviceAccountJson: await serviceAccount(), audience: RELAY, fetch: fetchImpl }) + await expect(source()).rejects.toThrow() + ok = true + await expect(source()).resolves.toContain('.') + }) +}) diff --git a/cloud/apps/sandbox-control/test/codex-broker.test.ts b/cloud/apps/sandbox-control/test/codex-broker.test.ts index b6d925cfbf7..819c15d9f0a 100644 --- a/cloud/apps/sandbox-control/test/codex-broker.test.ts +++ b/cloud/apps/sandbox-control/test/codex-broker.test.ts @@ -1,6 +1,6 @@ // Codex via the person's Orca account (contract D11, flag S2): the broker sandbox login, the lease refresher, // the placeholder auth.json and the chatgpt.com egress swap. Fake provider; no real OpenAI call. -import { SignJWT, createLocalJWKSet, exportJWK, generateKeyPair } from 'jose' +import { SignJWT, createLocalJWKSet, exportJWK, exportPKCS8, generateKeyPair } from 'jose' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { BROKER_AUTH_PATH, BROKER_EXIT_PATH, BROKER_START_MARKER, parseDeviceCode } from '../src/codex-broker' import { CODEX_TOKEN_URL, codexPlaceholder, refreshCodexCredential, refreshCodexLeases, setCodexTokenFetch } from '../src/codex-credentials' @@ -83,6 +83,11 @@ async function setup(overrides: Record = {}) { egressKeysForIssuer: () => createLocalJWKSet(jwks), credentials: { authorizationFor: async () => null }, egressFetch: async (input, init) => { + if (String(input) === 'https://oauth2.googleapis.com/token') { + // CODEX-RELAY: Google's ID token for the relay (only asked when a relay is configured). + const enc = (o: unknown) => Buffer.from(JSON.stringify(o)).toString('base64url') + return Response.json({ id_token: `${enc({ alg: 'RS256' })}.${enc({ exp: 4e9 })}.sig` }) + } upstream.push({ url: String(input), headers: new Headers(init?.headers) }) if (edgeBlock.on) { return new Response('Unable to load site', { @@ -491,3 +496,25 @@ describe('CODEX-EGRESS-BLOCKED: chatgpt.com refuses the proxy itself', () => { expect((await proxied(id, 'chatgpt.com', auth)).status).toBe(200) }) }) + +describe('CODEX-RELAY: chatgpt.com through the Cloud Run relay', () => { + it('sends the swapped request to the relay with a Google ID token; the path and the ChatGPT credential are unchanged', async () => { + const { privateKey } = await generateKeyPair('RS256', { extractable: true }) + const RELAY = 'https://orca-chatgpt-relay-x.us-central1.run.app' + const { h, as, signIn, proxied, upstream } = await setup({ + CHATGPT_RELAY_URL: RELAY, + CHATGPT_RELAY_SERVICE_ACCOUNT: JSON.stringify({ client_email: 'invoker@p.iam.gserviceaccount.com', private_key: await exportPKCS8(privateKey) }) + }) + const mia = await as('mia', 'acme', 'member') + await signIn(mia) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const id: string = created.body.sandbox.id + const res = await proxied(id, 'chatgpt.com', { authorization: `Bearer ${codexPlaceholder({ id })}` }, '/backend-api/codex/models?client_version=0.166.0', 'GET') + expect(res.status).toBe(200) + const sent = upstream.at(-1)! + expect(sent.url).toBe(`${RELAY}/backend-api/codex/models?client_version=0.166.0`) + expect(sent.headers.get('authorization')).toBe(`Bearer ${ACCESS}`) + expect(sent.headers.get('chatgpt-account-id')).toBe('acct-1') + expect(sent.headers.get('x-serverless-authorization')).toMatch(/^Bearer [\w-]+\.[\w-]+\.sig$/) + }) +}) diff --git a/cloud/apps/sandbox-control/wrangler.dev.jsonc b/cloud/apps/sandbox-control/wrangler.dev.jsonc index be71143f999..addae4af9c9 100644 --- a/cloud/apps/sandbox-control/wrangler.dev.jsonc +++ b/cloud/apps/sandbox-control/wrangler.dev.jsonc @@ -78,6 +78,9 @@ // person in the team" check before a workspace changes owner. Unset = hand-offs refused. "AUTH_INTERNAL_ORIGIN": "https://auth-staging.onorca.dev", "EGRESS_PROXY_URL": "https://orca-sandbox-control-dev.lovecast.workers.dev/v1/egress/proxy", + // CODEX-RELAY: chatgpt.com refuses Workers' egress; its requests go through this Cloud Run relay + // (cloud/infra/chatgpt-relay, staging). Secret CHATGPT_RELAY_SERVICE_ACCOUNT holds its invoker key. + "CHATGPT_RELAY_URL": "https://orca-chatgpt-relay-gjzz5mc7ka-uc.a.run.app", // SEC-3 phase 1: the secret store's KEK comes out of Cloud KMS (src/secrets-kms.ts); the Worker // holds only the KMS-wrapped KEK (secret SECRETS_KEK_WRAPPED, AAD orca-secrets-kek:) // and a service account that can only decrypt with this key (secret SECRETS_KMS_SERVICE_ACCOUNT). diff --git a/cloud/infra/chatgpt-relay/.gitignore b/cloud/infra/chatgpt-relay/.gitignore new file mode 100644 index 00000000000..1c99dc138aa --- /dev/null +++ b/cloud/infra/chatgpt-relay/.gitignore @@ -0,0 +1 @@ +.terraform/ diff --git a/cloud/infra/chatgpt-relay/.terraform.lock.hcl b/cloud/infra/chatgpt-relay/.terraform.lock.hcl new file mode 100644 index 00000000000..78b8795f9bc --- /dev/null +++ b/cloud/infra/chatgpt-relay/.terraform.lock.hcl @@ -0,0 +1,22 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/google" { + version = "6.50.0" + constraints = "~> 6.0" + hashes = [ + "h1:79CwMTsp3Ud1nOl5hFS5mxQHyT0fGVye7pqpU0PPlHI=", + "zh:1f3513fcfcbf7ca53d667a168c5067a4dd91a4d4cccd19743e248ff31065503c", + "zh:3da7db8fc2c51a77dd958ea8baaa05c29cd7f829bd8941c26e2ea9cb3aadc1e5", + "zh:3e09ac3f6ca8111cbb659d38c251771829f4347ab159a12db195e211c76068bb", + "zh:7bb9e41c568df15ccf1a8946037355eefb4dfb4e35e3b190808bb7c4abae547d", + "zh:81e5d78bdec7778e6d67b5c3544777505db40a826b6eb5abe9b86d4ba396866b", + "zh:8d309d020fb321525883f5c4ea864df3d5942b6087f6656d6d8b3a1377f340fc", + "zh:93e112559655ab95a523193158f4a4ac0f2bfed7eeaa712010b85ebb551d5071", + "zh:d3efe589ffd625b300cef5917c4629513f77e3a7b111c9df65075f76a46a63c7", + "zh:d4a4d672bbef756a870d8f32b35925f8ce2ef4f6bbd5b71a3cb764f1b6c85421", + "zh:e13a86bca299ba8a118e80d5f84fbdd708fe600ecdceea1a13d4919c068379fe", + "zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c", + "zh:fec30c095647b583a246c39d557704947195a1b7d41f81e369ba377d997faef6", + ] +} diff --git a/cloud/infra/chatgpt-relay/README.md b/cloud/infra/chatgpt-relay/README.md new file mode 100644 index 00000000000..f6bfb00f2cb --- /dev/null +++ b/cloud/infra/chatgpt-relay/README.md @@ -0,0 +1,31 @@ +# ChatGPT relay (CODEX-RELAY) + +chatgpt.com answers Cloudflare Workers' egress with a 403 "Unable to load site" page, so Codex via the +Orca account can't reach it through the sandbox-control egress proxy directly. The proxy sends its +chatgpt.com requests to this Cloud Run service instead (`cloud/apps/chatgpt-relay`), which: + +- forwards to `https://chatgpt.com` only, on the Codex paths in `sandbox-control/src/codex-paths.ts`; +- streams responses as they arrive (SSE), refuses WebSocket upgrades (Codex is configured for HTTPS); +- logs method, a two-segment path, status and duration: never headers, bodies or queries; +- is callable only by `orca-chatgpt-relay-invoker` (Cloud Run IAM, ID token in `X-Serverless-Authorization`). + +## Staging (serves orca-sandbox-control-dev) + +``` +terraform init -backend-config=backend/staging.hcl +terraform apply -var-file=environments/staging.tfvars # registry + accounts +IMG=$(CLOUDSDK_CORE_ACCOUNT= ../../apps/chatgpt-relay/build-image.sh onorca-cloud-staging) +terraform apply -var-file=environments/staging.tfvars -var image=$IMG # the service +``` + +Worker: `CHATGPT_RELAY_URL` (wrangler var) = the `relay_url` output; secret `CHATGPT_RELAY_SERVICE_ACCOUNT` = +a key of `invoker_service_account`, created with `gcloud iam service-accounts keys create` into a 0600 temp +file, piped into `wrangler secret put`, then deleted. Without both, chatgpt.com goes direct, as before. + +## Production (runbook, at Neil's go) + +1. Add `backend/production.hcl` (bucket `onorca-cloud-terraform-state`, prefix `terraform/chatgpt-relay`) and + `environments/production.tfvars` (`project_id = "onorca-cloud"`, `environment = "production"`). +2. The same three steps against `onorca-cloud`. +3. Set `CHATGPT_RELAY_URL` in `wrangler.prod.jsonc` and the secret on `orca-sandbox-control-prod`; deploy. +4. Check: a Codex turn via the Orca account answers; the relay's logs show `relay ... status 200`. diff --git a/cloud/infra/chatgpt-relay/backend/staging.hcl b/cloud/infra/chatgpt-relay/backend/staging.hcl new file mode 100644 index 00000000000..a202078d21a --- /dev/null +++ b/cloud/infra/chatgpt-relay/backend/staging.hcl @@ -0,0 +1,2 @@ +bucket = "onorca-cloud-staging-terraform-state" +prefix = "terraform/chatgpt-relay" diff --git a/cloud/infra/chatgpt-relay/environments/staging.tfvars b/cloud/infra/chatgpt-relay/environments/staging.tfvars new file mode 100644 index 00000000000..ebc040bb328 --- /dev/null +++ b/cloud/infra/chatgpt-relay/environments/staging.tfvars @@ -0,0 +1,3 @@ +# Serves orca-sandbox-control-dev (CHATGPT_RELAY_URL). Prod: a runbook step, not applied from here yet. +project_id = "onorca-cloud-staging" +environment = "staging" diff --git a/cloud/infra/chatgpt-relay/main.tf b/cloud/infra/chatgpt-relay/main.tf new file mode 100644 index 00000000000..d7cc3425cdf --- /dev/null +++ b/cloud/infra/chatgpt-relay/main.tf @@ -0,0 +1,104 @@ +# CODEX-RELAY: the ChatGPT relay. chatgpt.com refuses Cloudflare Workers' egress, so the sandbox-control +# Worker's egress proxy sends chatgpt.com requests through this Cloud Run service (cloud/apps/chatgpt-relay). +# It forwards to chatgpt.com only, on the Codex paths the Worker allows, and streams the answers back. +# Only the invoker service account (held by the Worker as CHATGPT_RELAY_SERVICE_ACCOUNT) may call it. +# Own root and state (backend prefix terraform/chatgpt-relay). The invoker's key is created with gcloud and +# piped straight into the Worker secret: no key material in this root or its state. + +locals { + labels = { + app = "orca-cloud" + component = "chatgpt-relay" + environment = var.environment + managed_by = "terraform" + } +} + +resource "google_project_service" "run" { + project = var.project_id + service = "run.googleapis.com" + disable_on_destroy = false +} + +resource "google_project_service" "artifactregistry" { + project = var.project_id + service = "artifactregistry.googleapis.com" + disable_on_destroy = false +} + +resource "google_artifact_registry_repository" "relay" { + project = var.project_id + location = var.region + repository_id = "orca-chatgpt-relay" + format = "DOCKER" + labels = local.labels + + depends_on = [google_project_service.artifactregistry] +} + +# The service runs as an account with no grants: it needs nothing in Google Cloud. +resource "google_service_account" "runtime" { + project = var.project_id + account_id = "orca-chatgpt-relay" + display_name = "ChatGPT relay runtime (no grants)" +} + +resource "google_service_account" "invoker" { + project = var.project_id + account_id = "orca-chatgpt-relay-invoker" + display_name = "sandbox-control Worker: run.invoker on the ChatGPT relay only" + description = "Held by the sandbox-control Worker as CHATGPT_RELAY_SERVICE_ACCOUNT. Its only grant is run.invoker on orca-chatgpt-relay." +} + +resource "google_cloud_run_v2_service" "relay" { + count = var.image == "" ? 0 : 1 + project = var.project_id + name = "orca-chatgpt-relay" + location = var.region + ingress = "INGRESS_TRAFFIC_ALL" + labels = local.labels + + deletion_protection = false + + template { + service_account = google_service_account.runtime.email + # Codex turns stream for minutes. + timeout = "3600s" + max_instance_request_concurrency = 80 + + scaling { + min_instance_count = 0 + max_instance_count = 4 + } + + containers { + image = var.image + + resources { + limits = { + cpu = "1" + memory = "512Mi" + } + # SSE streams: keep CPU while a response is still being written. + cpu_idle = false + } + + startup_probe { + http_get { + path = "/health" + } + } + } + } + + depends_on = [google_project_service.run] +} + +resource "google_cloud_run_v2_service_iam_member" "invoker" { + count = var.image == "" ? 0 : 1 + project = var.project_id + location = var.region + name = google_cloud_run_v2_service.relay[0].name + role = "roles/run.invoker" + member = "serviceAccount:${google_service_account.invoker.email}" +} diff --git a/cloud/infra/chatgpt-relay/outputs.tf b/cloud/infra/chatgpt-relay/outputs.tf new file mode 100644 index 00000000000..a9ec7f10b10 --- /dev/null +++ b/cloud/infra/chatgpt-relay/outputs.tf @@ -0,0 +1,12 @@ +output "relay_url" { + description = "CHATGPT_RELAY_URL for the sandbox-control Worker." + value = var.image == "" ? null : google_cloud_run_v2_service.relay[0].uri +} + +output "image_repository" { + value = "${var.region}-docker.pkg.dev/${var.project_id}/${google_artifact_registry_repository.relay.repository_id}" +} + +output "invoker_service_account" { + value = google_service_account.invoker.email +} diff --git a/cloud/infra/chatgpt-relay/variables.tf b/cloud/infra/chatgpt-relay/variables.tf new file mode 100644 index 00000000000..2770290dd29 --- /dev/null +++ b/cloud/infra/chatgpt-relay/variables.tf @@ -0,0 +1,18 @@ +variable "project_id" { + type = string +} + +variable "environment" { + type = string +} + +variable "region" { + type = string + default = "us-central1" +} + +variable "image" { + description = "Relay image (cloud/apps/chatgpt-relay/build-image.sh prints it). Empty: the root creates only the registry and accounts." + type = string + default = "" +} diff --git a/cloud/infra/chatgpt-relay/versions.tf b/cloud/infra/chatgpt-relay/versions.tf new file mode 100644 index 00000000000..125453f8d1d --- /dev/null +++ b/cloud/infra/chatgpt-relay/versions.tf @@ -0,0 +1,16 @@ +terraform { + required_version = ">= 1.7.0" + + required_providers { + google = { + source = "hashicorp/google" + version = "~> 6.0" + } + } + + backend "gcs" {} +} + +provider "google" { + project = var.project_id +} diff --git a/cloud/pnpm-lock.yaml b/cloud/pnpm-lock.yaml index be2f226d157..46f863ce06c 100644 --- a/cloud/pnpm-lock.yaml +++ b/cloud/pnpm-lock.yaml @@ -235,6 +235,18 @@ importers: specifier: ^4.157.0 version: 4.157.0(@cloudflare/workers-types@5.20261104.1)(@types/node@24.19.2) + apps/chatgpt-relay: + devDependencies: + '@types/node': + specifier: ^24.19.2 + version: 24.19.2 + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@24.19.2)(vite@8.3.4(@types/node@24.19.2)(esbuild@0.28.2)(tsx@4.23.15)) + apps/push: dependencies: '@hono/node-server': From 5a895dcedc9a74b3502add78e0420897acde1f86 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:25:15 -0800 Subject: [PATCH 06/35] feat(cloud): CREATE-GH-STEP GitHub access step in the create wizard Ask for Orca GitHub App access while the sandbox starts, not in a toast afterwards. Server (sandbox-control): - GET /v1/github/repo-access answers `push`: ok | not_installed | repo_not_selected | not_connected, with `configureUrl` (the installation's settings page) for repo_not_selected. A public repo that can't push now gets an install URL too. - GitHub installation lookups (repo and new owner lookup) cached in D1 (migration 0061): found 60 s, 404 15 s, dropped by installation / installation_repositories webhooks and the setup return. The owner lookup never holds the answer (3 s cap, errors read as not_installed). Desktop: - "GitHub access" row after Start sandbox, checked when the create starts (parallel, so no latency when access is fine). Missing: Install GitHub App / Add repository on GitHub / Copy request for an owner, plus Skip for now ("You can pull; pushes need access later"). Polls (2 s for 3 min, then 10 s; on focus) and auto-advances on grant. - The create holds before Open workspace only while the step asks and the sheet is on screen. - Skip remembered per repo on this device; later creates show it skipped (Set up) without holding; forgotten once the repo has access. - A grant that lands after the sandbox started calls applyCloudGitHubAccessToSandbox, a stub until gh-access's live refresh lands. --- .../0061_github_installation_cache.sql | 18 + cloud/apps/sandbox-control/src/github-app.ts | 13 + .../src/github-installation-cache.ts | 109 ++++++ .../sandbox-control/src/github-repo-access.ts | 113 +++++- .../test/github-repo-access.test.ts | 174 ++++++++- .../hosted-sandbox/hosted-account-ipc.test.ts | 57 +++ src/main/hosted-sandbox/hosted-account-ipc.ts | 28 +- .../VmBuildGitHubAccessRow.tsx | 213 +++++++++++ .../worktree-creation/VmBuildSheet.tsx | 34 +- .../VmBuildSheetGitHubAccess.fixture.tsx | 80 ++++ src/renderer/src/i18n/locales/en.json | 17 + .../cloud-create-github-access-model.ts | 77 ++++ .../cloud-create-github-access-registry.ts | 63 ++++ .../cloud-create-github-access.test.ts | 241 ++++++++++++ .../orca-cloud/cloud-create-github-access.ts | 345 ++++++++++++++++++ .../orca-cloud/cloud-create-github-apply.ts | 12 + .../orca-cloud/cloud-create-github-skip.ts | 59 +++ .../start-cloud-workspace-from-github.ts | 17 +- .../ephemeral-vm-worktree-creation.ts | 25 ++ .../hosted-sandbox/hosted-github-wire.ts | 9 +- 20 files changed, 1662 insertions(+), 42 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0061_github_installation_cache.sql create mode 100644 cloud/apps/sandbox-control/src/github-installation-cache.ts create mode 100644 src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx create mode 100644 src/renderer/src/components/worktree-creation/VmBuildSheetGitHubAccess.fixture.tsx create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-github-access-model.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-github-access-registry.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-github-apply.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-github-skip.ts diff --git a/cloud/apps/sandbox-control/migrations/0061_github_installation_cache.sql b/cloud/apps/sandbox-control/migrations/0061_github_installation_cache.sql new file mode 100644 index 00000000000..aa1305550c9 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0061_github_installation_cache.sql @@ -0,0 +1,18 @@ +-- CREATE-GH-STEP: the create wizard's "GitHub access" step asks repo-access for every create and +-- polls it every 2 s while the person installs the App. GitHub's installation lookups (app JWT, one +-- per repository and owner) are cached here for a short TTL, shared by every isolate, and dropped by +-- the installation webhooks and the setup return so a fresh install answers on the next poll. +-- No credential or token is stored: installation ids and the owner's login only. Additive. +CREATE TABLE github_installation_cache ( + -- '/' for a repository lookup, '/' for an owner lookup; lowercased. + cache_key TEXT PRIMARY KEY, + owner_key TEXT NOT NULL, + -- NULL: GitHub answered 404 (the App isn't installed there, or not on this repository). + installation_id INTEGER, + github_account_id INTEGER, + github_account_login TEXT, + github_account_type TEXT, + checked_at INTEGER NOT NULL +); +CREATE INDEX github_installation_cache_owner ON github_installation_cache (owner_key); +CREATE INDEX github_installation_cache_installation ON github_installation_cache (installation_id); diff --git a/cloud/apps/sandbox-control/src/github-app.ts b/cloud/apps/sandbox-control/src/github-app.ts index 6c13a24cbda..10e4405703c 100644 --- a/cloud/apps/sandbox-control/src/github-app.ts +++ b/cloud/apps/sandbox-control/src/github-app.ts @@ -26,6 +26,11 @@ export type GitHubAppMinter = { getInstallation(installationId: number): Promise /** The installation covering a github.com repo URL, or null. */ getRepoInstallation(repoUrl: string): Promise + /** + * The App's installation on a GitHub org or user (whatever repositories it selected), or null. + * Tells "not installed on the owner" from "installed, but this repository isn't selected". + */ + getOwnerInstallation?(owner: string): Promise /** App-JWT request to an app-level endpoint (operator: /app, /app/hook/config). */ appRequest?(method: string, path: '/app' | '/app/hook/config', body?: unknown): Promise /** @@ -262,6 +267,14 @@ export function createGitHubAppMinter(config: { return github(method, path, body) }, + async getOwnerInstallation(owner) { + if (!/^[A-Za-z0-9-]{1,39}$/.test(owner)) { + return null + } + // Orgs and users have separate lookups; an org login 404s on /users/{login}/installation. + return (await installationFor(`/orgs/${owner}/installation`)) ?? installationFor(`/users/${owner}/installation`) + }, + async getRepoInstallation(repoUrl) { const parsed = parseGitHubRepo(repoUrl) return parsed ? installationFor(`/repos/${parsed.owner}/${parsed.repo}/installation`) : null diff --git a/cloud/apps/sandbox-control/src/github-installation-cache.ts b/cloud/apps/sandbox-control/src/github-installation-cache.ts new file mode 100644 index 00000000000..71f2284c8a7 --- /dev/null +++ b/cloud/apps/sandbox-control/src/github-installation-cache.ts @@ -0,0 +1,109 @@ +// CREATE-GH-STEP: GitHub's installation lookups for repo-access, cached in D1 so every isolate shares +// them and the create wizard's 2 s poll doesn't spend an app-JWT call each time. A found installation +// is kept a minute, a 404 for 15 s. The installation webhooks and the setup return drop the owner's +// entries (forgetOwner/forgetInstallation), so an install is seen on the next poll, not after the TTL. +// Only ids and the owner's login are stored. Any D1 failure falls through to GitHub. +import type { GitHubAppMinter, GitHubInstallation } from './github-app' + +export const FOUND_TTL_MS = 60_000 +export const MISSING_TTL_MS = 15_000 + +type Row = { + installation_id: number | null + github_account_id: number | null + github_account_login: string | null + github_account_type: string | null + checked_at: number +} + +function fromRow(row: Row): GitHubInstallation | null { + if (row.installation_id === null || row.github_account_login === null) { + return null + } + return { + id: row.installation_id, + account: { + id: row.github_account_id ?? 0, + login: row.github_account_login, + type: row.github_account_type === 'User' ? 'User' : 'Organization' + } + } +} + +async function cached( + db: D1Database, + key: string, + ownerKey: string, + now: number, + lookup: () => Promise +): Promise { + const row = await db + .prepare( + 'SELECT installation_id, github_account_id, github_account_login, github_account_type, checked_at FROM github_installation_cache WHERE cache_key = ?' + ) + .bind(key) + .first() + .catch(() => null) + if (row && now - row.checked_at < (row.installation_id === null ? MISSING_TTL_MS : FOUND_TTL_MS)) { + return fromRow(row) + } + // GitHub errors propagate uncached (repo-access answers 502; the next poll asks again). + const found = await lookup() + await db + .prepare( + `INSERT INTO github_installation_cache (cache_key, owner_key, installation_id, github_account_id, github_account_login, github_account_type, checked_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (cache_key) DO UPDATE SET installation_id = excluded.installation_id, github_account_id = excluded.github_account_id, + github_account_login = excluded.github_account_login, github_account_type = excluded.github_account_type, checked_at = excluded.checked_at` + ) + .bind(key, ownerKey, found?.id ?? null, found?.account.id ?? null, found?.account.login ?? null, found?.account.type ?? null, now) + .run() + .catch(() => undefined) + return found +} + +/** GET /repos/{owner}/{repo}/installation, cached. */ +export function cachedRepoInstallation( + db: D1Database, + github: GitHubAppMinter, + parsed: { owner: string; repo: string }, + now: number +): Promise { + const owner = parsed.owner.toLowerCase() + return cached(db, `${owner}/${parsed.repo.toLowerCase()}`, owner, now, () => + github.getRepoInstallation(`https://github.com/${parsed.owner}/${parsed.repo}`) + ) +} + +/** The App's installation on the owner (org or user), cached; null when the minter can't ask. */ +export function cachedOwnerInstallation( + db: D1Database, + github: GitHubAppMinter, + owner: string, + now: number +): Promise { + const lookup = github.getOwnerInstallation + if (!lookup) { + return Promise.resolve(null) + } + const key = owner.toLowerCase() + return cached(db, `${key}/`, key, now, () => lookup.call(github, owner)) +} + +/** An install, uninstall, or repository selection change on this owner: ask GitHub next time. */ +export async function forgetOwner(db: D1Database, owner: string): Promise { + await db + .prepare('DELETE FROM github_installation_cache WHERE owner_key = ?') + .bind(owner.toLowerCase()) + .run() + .catch(() => undefined) +} + +/** Same, by installation id (a webhook whose account login is missing). */ +export async function forgetInstallation(db: D1Database, installationId: number): Promise { + await db + .prepare('DELETE FROM github_installation_cache WHERE installation_id = ?') + .bind(installationId) + .run() + .catch(() => undefined) +} diff --git a/cloud/apps/sandbox-control/src/github-repo-access.ts b/cloud/apps/sandbox-control/src/github-repo-access.ts index 850a9d43a9e..dc1b46a8295 100644 --- a/cloud/apps/sandbox-control/src/github-repo-access.ts +++ b/cloud/apps/sandbox-control/src/github-repo-access.ts @@ -6,6 +6,12 @@ // installation): true = the caller can install it on the owner (it is their own GitHub account, or // they are an active admin of the owner org); false = another user's account, or a non-admin org // membership; null = unknown (no connected GitHub user token, membership unreadable, GitHub down). +// push (CREATE-GH-STEP): can a workspace on this repo push? 'ok' = granted; 'not_installed' = the +// App isn't on the owner; 'repo_not_selected' = it is, but this repository isn't one it selected +// (configureUrl: the installation's settings page); 'not_connected' = the App reaches the repo +// but through an installation this Orca account isn't bound to. installUrl is present for every +// push reason but 'ok' and 'repo_not_selected', public repositories included. +// GitHub's installation lookups are cached in D1 (github-installation-cache.ts). // GET /v1/github/repositories[?cursor=] -> {repositories, nextCursor} (start from GitHub, D4/N12) // GET /v1/internal/github/install-url?accountId&userId&repo&session (billing's setup chain, // Bearer CONTROL_PLANE_TOKEN) -> {access, url} @@ -16,6 +22,7 @@ // its own: POST /v1/internal/cloud-setup/github {sessionId?, accountId, repo, state}. import type { GitHubAppMinter, GitHubListedRepo } from './github-app' import { parseGitHubRepo } from './github-app' +import { cachedOwnerInstallation, cachedRepoInstallation, forgetInstallation, forgetOwner } from './github-installation-cache' import { bindApprovedRequests, boundAccounts, @@ -30,6 +37,9 @@ import { export type RepoAccess = 'public' | 'granted' | 'missing' | 'requested' +/** Whether a workspace on the repository can push, and if not, what's missing (CREATE-GH-STEP). */ +export type PushAccess = 'ok' | 'not_installed' | 'repo_not_selected' | 'not_connected' + export type RepoAccessDeps = { db: D1Database github: GitHubAppMinter | undefined @@ -52,25 +62,93 @@ export async function repoAccess( accountId: string, repoUrl: string ): Promise<{ access: RepoAccess; owner: string; installationId: number | null }> { + const { access, owner, installationId } = await repoAccessWithPush(deps, accountId, repoUrl) + return { access, owner, installationId } +} + +/** repoAccess plus whether a workspace can push, and the owner installation when that's the gap. */ +export async function repoAccessWithPush( + deps: RepoAccessDeps, + accountId: string, + repoUrl: string +): Promise<{ + access: RepoAccess + owner: string + installationId: number | null + push: PushAccess + ownerInstallation?: { id: number; type: 'User' | 'Organization' } +}> { const parsed = parseGitHubRepo(repoUrl) if (!parsed) { throw new RepoAccessError('not_github') } - const installation = deps.github ? await deps.github.getRepoInstallation(repoUrl) : null + const installation = deps.github ? await cachedRepoInstallation(deps.db, deps.github, parsed, deps.now) : null if (installation && (await isInstallationBound(deps.db, installation.id, accountId))) { - return { access: 'granted', owner: parsed.owner, installationId: installation.id } + return { access: 'granted', owner: parsed.owner, installationId: installation.id, push: 'ok' } } - if (await deps.publicRepoCheck(repoUrl)) { - return { access: 'public', owner: parsed.owner, installationId: installation?.id ?? null } + const [gap, isPublic] = await Promise.all([pushGap(deps, accountId, parsed.owner, installation), deps.publicRepoCheck(repoUrl)]) + if (isPublic) { + return { access: 'public', owner: parsed.owner, installationId: installation?.id ?? null, ...gap } } if (!installation && (await openInstallRequest(deps.db, accountId, parsed.owner, deps.now))) { // Ours, and still open on GitHub (an owner who declines leaves no webhook, only an empty list). const pending = await deps.github?.pendingRequestOwners?.().catch(() => null) if (!pending || pending.has(parsed.owner.toLowerCase())) { - return { access: 'requested', owner: parsed.owner, installationId: null } + return { access: 'requested', owner: parsed.owner, installationId: null, ...gap } } } - return { access: 'missing', owner: parsed.owner, installationId: installation?.id ?? null } + return { access: 'missing', owner: parsed.owner, installationId: installation?.id ?? null, ...gap } +} + +/** + * Not granted: the App reaches the repo through someone else's binding, or it's on the owner without + * this repository, or it isn't on the owner. Only an installation bound to this account counts as + * "repo not selected" without asking GitHub; otherwise one cached owner lookup tells. + */ +async function pushGap( + deps: RepoAccessDeps, + accountId: string, + owner: string, + repoInstallation: { id: number } | null +): Promise<{ push: PushAccess; ownerInstallation?: { id: number; type: 'User' | 'Organization' } }> { + if (repoInstallation) { + return { push: 'not_connected' } + } + const bound = (await listAccountInstallations(deps.db, accountId)).find( + (row) => row.github_account_login.toLowerCase() === owner.toLowerCase() + ) + if (bound) { + return { + push: 'repo_not_selected', + ownerInstallation: { id: bound.installation_id, type: bound.github_account_type === 'User' ? 'User' : 'Organization' } + } + } + // Never holds the answer up: GitHub erroring or slow reads as "not installed", whose install page + // GitHub turns into the installation's settings when the App is already there. + const onOwner = deps.github + ? await withTimeout(cachedOwnerInstallation(deps.db, deps.github, owner, deps.now), OWNER_LOOKUP_TIMEOUT_MS).catch(() => null) + : null + if (!onOwner) { + return { push: 'not_installed' } + } + // On the owner, but bound to another Orca account (or none): binding it is the install round trip. + return (await isInstallationBound(deps.db, onOwner.id, accountId)) + ? { push: 'repo_not_selected', ownerInstallation: { id: onOwner.id, type: onOwner.account.type } } + : { push: 'not_connected' } +} + +const OWNER_LOOKUP_TIMEOUT_MS = 3_000 + +function withTimeout(work: Promise, ms: number): Promise { + let timer: ReturnType | undefined + return Promise.race([work, new Promise((resolve) => (timer = setTimeout(() => resolve(null), ms)))]).finally(() => clearTimeout(timer)) +} + +/** GitHub's page where the installation's repository selection is changed. */ +export function installationSettingsUrl(owner: string, installation: { id: number; type: 'User' | 'Organization' }): string { + return installation.type === 'User' + ? `https://github.com/settings/installations/${installation.id}` + : `https://github.com/organizations/${encodeURIComponent(owner)}/settings/installations/${installation.id}` } export class RepoAccessError extends Error { @@ -150,12 +228,17 @@ export async function repoAccessView( if (!parsed) { return { status: 400, body: { error: 'invalid_request', reason: 'not_github' } } } - const result = await repoAccess(deps, caller.accountId, repo) - const body: Record = { access: result.access, owner: parsed.owner, repo: canonicalRepoUrl(parsed) } + const result = await repoAccessWithPush(deps, caller.accountId, repo) + const body: Record = { access: result.access, owner: parsed.owner, repo: canonicalRepoUrl(parsed), push: result.push } // Only while the App isn't installed for this owner: that is when the desktop picks "Install" vs "ask an owner". const askCanInstall = result.access === 'missing' || (result.access === 'public' && result.installationId === null) + // A public repository clones anonymously but can't push: the wizard's GitHub step installs from here too. + const wantsInstall = result.access === 'missing' || (result.access === 'public' && (result.push === 'not_installed' || result.push === 'not_connected')) + if (result.push === 'repo_not_selected' && result.ownerInstallation) { + body.configureUrl = installationSettingsUrl(parsed.owner, result.ownerInstallation) + } const [install, canInstall] = await Promise.all([ - result.access === 'missing' && deps.connect + wantsInstall && deps.connect ? repoInstallUrl(deps, caller, repo, { setupSessionId: url.searchParams.get('session') ?? undefined, repoId: positiveInt(url.searchParams.get('repoId')), @@ -342,6 +425,13 @@ export async function handleInstallationEvent( if (!id || !Number.isSafeInteger(id)) { return { handled: 'ignored' } } + if (eventName === 'installation' || eventName === 'installation_repositories') { + // Any install, uninstall, suspend or selection change: repo-access asks GitHub on the next poll. + await forgetInstallation(deps.db, id) + if (installation?.account?.login) { + await forgetOwner(deps.db, installation.account.login) + } + } if (eventName === 'installation' && payload.action === 'deleted') { return { handled: 'deleted', revoked: await revokeInstallation(deps.db, id, null, deps.now) } } @@ -399,6 +489,11 @@ export async function noticeAfterReturn( } const repo = `https://github.com/${state.r}` const base = { ...(state.s ? { sessionId: state.s } : {}), accountId: state.a, repo } + // Back from GitHub's install page: its webhook may not have landed yet. + const owner = parseGitHubRepo(repo)?.owner + if (owner) { + await forgetOwner(deps.db, owner) + } if (requested) { return { ...base, state: 'pending' } } diff --git a/cloud/apps/sandbox-control/test/github-repo-access.test.ts b/cloud/apps/sandbox-control/test/github-repo-access.test.ts index d893b4fef5a..f0b31570c38 100644 --- a/cloud/apps/sandbox-control/test/github-repo-access.test.ts +++ b/cloud/apps/sandbox-control/test/github-repo-access.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest' import { createGitHubAppMinter } from '../src/github-app' import { installUrl, isInstallationBound } from '../src/github-connect' import type { SetupNotice } from '../src/github-repo-access' +import { FOUND_TTL_MS, MISSING_TTL_MS } from '../src/github-installation-cache' import { storeUserToken } from '../src/github-user-tokens' import { keyringFor } from '../src/secrets' import { createHarness } from './harness' @@ -62,10 +63,11 @@ function fakeGitHub() { if (url.pathname.startsWith('/user/memberships/orgs/') && faults.membership === 'forbidden') { return new Response(null, { status: 403 }) } - if (url.pathname.startsWith('/users/') && faults.users === 'error') { + const anonymousProfile = /^\/users\/[^/]+$/.test(url.pathname) + if (anonymousProfile && faults.users === 'error') { return new Response(null, { status: 502 }) } - if ((url.pathname.startsWith('/user/memberships/orgs/') && faults.membership === 'hang') || (url.pathname.startsWith('/users/') && faults.users === 'hang')) { + if ((url.pathname.startsWith('/user/memberships/orgs/') && faults.membership === 'hang') || (anonymousProfile && faults.users === 'hang')) { return new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(init.signal!.reason))) } if (url.pathname === '/user') { @@ -100,6 +102,14 @@ function fakeGitHub() { ? Response.json({ id: person.id, login: person.login, type: 'User' }) : new Response(null, { status: 404 }) } + const ownerInstall = /^\/(orgs|users)\/([^/]+)\/installation$/.exec(url.pathname) + if (ownerInstall) { + const login = decodeURIComponent(ownerInstall[2]!).toLowerCase() + const found = installations.find( + (i) => i.account.login.toLowerCase() === login && (ownerInstall[1] === 'orgs') === (i.account.type === 'Organization') + ) + return found ? Response.json({ id: found.id, account: found.account }) : new Response(null, { status: 404 }) + } const repoInstall = /^\/repos\/([^/]+)\/([^/]+)\/installation$/.exec(url.pathname) if (repoInstall) { const found = installations.find((i) => i.repos.includes(`${repoInstall[1]}/${repoInstall[2]}`.toLowerCase())) @@ -203,13 +213,18 @@ const stateOf = (url: string) => new URL(url).searchParams.get('state')! describe('GitHub repo access (cloud-start N2/N3, D2)', () => { it('answers missing with an install URL, public, then granted once an admin installs and binds', async () => { const { h, github, notices, trialNotices, browser } = await setup({ publicRepos: ['https://github.com/acme/site'] }) - expect((await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent('https://github.com/acme/site')}`)).body).toEqual({ + const site = await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent('https://github.com/acme/site')}`) + expect(site.body).toEqual({ access: 'public', owner: 'acme', repo: 'https://github.com/acme/site', + // Clones anonymously, but can't push until the App is on acme (CREATE-GH-STEP). + push: 'not_installed', + installUrl: expect.stringMatching(/^https:\/\/github\.com\/apps\/orca-cloud-test\/installations\/new\?state=/), // The App isn't on acme yet and alice hasn't connected GitHub: unknown. canInstall: null }) + expect(HostedGithubRepoAccessResponseSchema.parse(site.body)).toEqual(site.body) const missing = await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent(`${REPO}.git`)}&session=${SESSION}`) expect(missing.body).toMatchObject({ access: 'missing', owner: 'acme', repo: REPO }) expect(HostedGithubRepoAccessResponseSchema.parse(missing.body)).toEqual(missing.body) @@ -226,9 +241,10 @@ describe('GitHub repo access (cloud-start N2/N3, D2)', () => { expect(notices).toEqual([{ sessionId: SESSION, accountId: 'user:alice', repo: REPO, state: 'done' }]) // Billing's trial abuse keys: numeric GitHub owner and user ids of the bind. expect(trialNotices).toEqual([{ accountId: 'user:alice', githubOwnerId: 50, githubUserId: 3 }]) - expect((await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent(REPO)}`)).body).toEqual({ access: 'granted', owner: 'acme', repo: REPO }) + expect((await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent(REPO)}`)).body).toEqual({ access: 'granted', owner: 'acme', repo: REPO, push: 'ok' }) // Another Orca account is not granted by alice's binding. - expect((await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent(REPO)}`, { as: 'bob' })).body.access).toBe('missing') + const bob = await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent(REPO)}`, { as: 'bob' }) + expect(bob.body).toMatchObject({ access: 'missing', push: 'not_connected' }) expect((await h.call('GET', '/v1/github/repo-access?repo=https%3A%2F%2Fgitlab.com%2Facme%2Fweb')).status).toBe(400) }) @@ -378,6 +394,8 @@ describe('GitHub repo access (cloud-start N2/N3, D2)', () => { `INSERT INTO github_installations VALUES (900, 'org:acme-team', 50, 'acme', 'Organization', 'u1', 3, 'oauth', 0, NULL)` ) .run() + // Bound straight in the database (no webhook, no setup return): the cached 404 lasts its TTL. + h.advance(MISSING_TTL_MS) expect((await h.call('GET', path, { bearer: CONTROL_PLANE_TOKEN })).body).toEqual({ access: 'granted', url: null }) expect((await h.call('GET', path.replace(SESSION, 'bad'), { bearer: CONTROL_PLANE_TOKEN })).status).toBe(400) }) @@ -440,7 +458,9 @@ describe('repo-access canInstall (REPO-CAN-INSTALL)', () => { const access = (h: Ctx['h'], repo = REPO, as?: string) => h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent(repo)}`, as ? { as } : {}) const membershipCalls = (ctx: Ctx) => ctx.github.calls.filter((c) => c.startsWith('GET /user/memberships/orgs/')) /** canInstall's reads: owner type and membership. */ - const github = (ctx: Ctx) => ctx.github.calls.filter((c) => c.startsWith('GET /user/memberships/orgs/') || c.startsWith('GET /users/')) + // The anonymous owner read and the membership read (not the app-JWT installation lookups). + const github = (ctx: Ctx) => + ctx.github.calls.filter((c) => c.startsWith('GET /user/memberships/orgs/') || (c.startsWith('GET /users/') && !c.endsWith('/installation'))) /** Connects alice (account user:alice, user alice) as the fake GitHub user behind `code`. */ async function connect(ctx: Ctx, code: string, user: { id: number; login: string }, tokens: { accessExpiresAt?: number | null; refresh?: string | null } = {}) { @@ -541,13 +561,23 @@ describe('repo-access canInstall (REPO-CAN-INSTALL)', () => { access: 'public', owner: 'acme', repo: 'https://github.com/acme/site', + push: 'not_installed', + installUrl: expect.any(String), canInstall: false }) await connect(ctx, 'code_admin', { id: 3, login: 'admin-gh' }) expect((await access(ctx.h, 'https://github.com/acme/site')).body).toMatchObject({ access: 'public', canInstall: true }) // Installed on acme (bound to some other Orca account): the App is there, so no canInstall. ctx.github.installations.push({ id: 900, account: ACME, repos: ['acme/site'] }) - expect((await access(ctx.h, 'https://github.com/acme/site')).body).toEqual({ access: 'public', owner: 'acme', repo: 'https://github.com/acme/site' }) + ctx.h.advance(MISSING_TTL_MS) + // Pushing still needs alice's account bound to it: the install round trip binds it. + expect((await access(ctx.h, 'https://github.com/acme/site')).body).toEqual({ + access: 'public', + owner: 'acme', + repo: 'https://github.com/acme/site', + push: 'not_connected', + installUrl: expect.any(String) + }) }) it('granted and requested: absent', async () => { @@ -556,7 +586,7 @@ describe('repo-access canInstall (REPO-CAN-INSTALL)', () => { ctx.github.installations.push({ id: 900, account: ACME, repos: ['acme/web'] }) const setupPage = await ctx.browser(`https://sandbox.test/v1/github/setup?installation_id=900&setup_action=install&state=${encodeURIComponent(stateOf(missing.body.installUrl))}`) await ctx.browser(`https://sandbox.test/v1/github/callback?code=code_admin&state=${encodeURIComponent(stateOf(setupPage.location!))}`) - expect((await access(ctx.h)).body).toEqual({ access: 'granted', owner: 'acme', repo: REPO }) + expect((await access(ctx.h)).body).toEqual({ access: 'granted', owner: 'acme', repo: REPO, push: 'ok' }) // Sam (a member, connected by the request's OAuth round trip) asks an owner: requested. const other = await setup() @@ -564,7 +594,7 @@ describe('repo-access canInstall (REPO-CAN-INSTALL)', () => { const page = await other.browser(`https://sandbox.test/v1/github/setup?setup_action=request&state=${encodeURIComponent(stateOf(samMissing.body.installUrl))}`) other.github.requests.push({ account: { login: 'acme' }, requester: { id: 2 } }) await other.browser(`https://sandbox.test/v1/github/callback?code=code_sam&state=${encodeURIComponent(stateOf(page.location!))}`) - expect((await access(other.h, REPO, 'sam')).body).toEqual({ access: 'requested', owner: 'acme', repo: REPO }) + expect((await access(other.h, REPO, 'sam')).body).toEqual({ access: 'requested', owner: 'acme', repo: REPO, push: 'not_installed' }) }) it('a token near expiry is refreshed through the member-git helper before the membership read', async () => { @@ -582,3 +612,129 @@ describe('repo-access canInstall (REPO-CAN-INSTALL)', () => { expect(membershipCalls(ctx)).toEqual([]) }) }) + +describe('repo-access push reason and installation cache (CREATE-GH-STEP)', () => { + type Ctx = Awaited> + const access = (h: Ctx['h'], repo = REPO, as?: string) => h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent(repo)}`, as ? { as } : {}) + const installLookups = (ctx: Ctx) => ctx.github.calls.filter((c) => c.endsWith('/installation')) + const bindAcme = async (ctx: Ctx, repos: string[]) => { + const missing = await access(ctx.h) + ctx.github.installations.push({ id: 900, account: ACME, repos }) + const setupPage = await ctx.browser(`https://sandbox.test/v1/github/setup?installation_id=900&setup_action=install&state=${encodeURIComponent(stateOf(missing.body.installUrl))}`) + await ctx.browser(`https://sandbox.test/v1/github/callback?code=code_admin&state=${encodeURIComponent(stateOf(setupPage.location!))}`) + } + + it('installed on the owner without this repository: repo_not_selected with the installation’s settings page', async () => { + const ctx = await setup({ publicRepos: ['https://github.com/acme/site'] }) + await bindAcme(ctx, ['acme/web']) + const site = await access(ctx.h, 'https://github.com/acme/site') + expect(site.body).toEqual({ + access: 'public', + owner: 'acme', + repo: 'https://github.com/acme/site', + push: 'repo_not_selected', + configureUrl: 'https://github.com/organizations/acme/settings/installations/900', + // The admin who bound it may change the selection. + canInstall: true + }) + expect(HostedGithubRepoAccessResponseSchema.parse(site.body)).toEqual(site.body) + // A private one the installation doesn't select: still missing for cloning, same reason. + expect((await access(ctx.h, 'https://github.com/acme/api')).body).toMatchObject({ access: 'missing', push: 'repo_not_selected', installUrl: expect.any(String) }) + }) + + it('a personal account’s installation links to the user settings page', async () => { + const ctx = await setup({ publicRepos: ['https://github.com/Alice-GH/dotfiles'] }) + await connectAlice(ctx) + expect((await access(ctx.h, 'https://github.com/Alice-GH/dotfiles')).body).toMatchObject({ + push: 'repo_not_selected', + configureUrl: 'https://github.com/settings/installations/901' + }) + }) + + async function connectAlice(ctx: Ctx) { + const missing = await access(ctx.h, 'https://github.com/Alice-GH/notes') + ctx.github.installations.push({ id: 901, account: { id: 7, login: 'Alice-GH', type: 'User' }, repos: ['alice-gh/notes'] }) + const setupPage = await ctx.browser(`https://sandbox.test/v1/github/setup?installation_id=901&setup_action=install&state=${encodeURIComponent(stateOf(missing.body.installUrl))}`) + await ctx.browser(`https://sandbox.test/v1/github/callback?code=code_alice&state=${encodeURIComponent(stateOf(setupPage.location!))}`) + } + + it('an installation on the owner bound to another Orca account: not_connected, with an install page', async () => { + const ctx = await setup({ publicRepos: ['https://github.com/acme/site'] }) + await bindAcme(ctx, ['acme/web']) + expect((await access(ctx.h, 'https://github.com/acme/site', 'bob')).body).toMatchObject({ access: 'public', push: 'not_connected', installUrl: expect.any(String) }) + }) + + it('polls answer from the cache; installation webhooks drop it so the next poll sees the change', async () => { + const ctx = await setup({ publicRepos: ['https://github.com/acme/site'] }) + await bindAcme(ctx, ['acme/web']) + ctx.github.calls.length = 0 + expect((await access(ctx.h, 'https://github.com/acme/site')).body.push).toBe('repo_not_selected') + expect((await access(ctx.h, 'https://github.com/acme/site')).body.push).toBe('repo_not_selected') + // One repository lookup for both polls; the bound installation answers the owner without GitHub. + expect(installLookups(ctx)).toEqual(['GET /repos/acme/site/installation']) + + // The owner selects acme/site on GitHub: without the webhook the cached 404 would stand for its TTL. + ctx.github.installations[0]!.repos.push('acme/site') + expect((await access(ctx.h, 'https://github.com/acme/site')).body.push).toBe('repo_not_selected') + const added = await ctx.webhook('installation_repositories', { + action: 'added', + installation: { id: 900, account: ACME }, + repository_selection: 'selected', + repositories_added: [{ full_name: 'acme/site' }], + repositories_removed: [], + requester: null, + sender: { id: 3, type: 'User' } + }) + expect(added.status).toBe(202) + expect((await access(ctx.h, 'https://github.com/acme/site')).body).toMatchObject({ access: 'granted', push: 'ok' }) + + // Removed again: found installations are cached too, and dropped the same way. + ctx.github.installations[0]!.repos = ['acme/web'] + await ctx.webhook('installation_repositories', { + action: 'removed', + installation: { id: 900, account: ACME }, + repository_selection: 'selected', + repositories_added: [], + repositories_removed: [{ full_name: 'acme/site' }], + requester: null, + sender: { id: 3, type: 'User' } + }) + expect((await access(ctx.h, 'https://github.com/acme/site')).body.push).toBe('repo_not_selected') + }) + + it('a cached 404 lapses after its TTL; a found installation after a minute', async () => { + const ctx = await setup({ publicRepos: ['https://github.com/acme/site'] }) + expect((await access(ctx.h, 'https://github.com/acme/site')).body.push).toBe('not_installed') + ctx.github.installations.push({ id: 900, account: ACME, repos: ['acme/site'] }) + expect((await access(ctx.h, 'https://github.com/acme/site')).body.push).toBe('not_installed') + ctx.h.advance(MISSING_TTL_MS) + expect((await access(ctx.h, 'https://github.com/acme/site')).body.push).toBe('not_connected') + ctx.github.calls.length = 0 + ctx.h.advance(FOUND_TTL_MS - 1) + await access(ctx.h, 'https://github.com/acme/site') + expect(installLookups(ctx)).toEqual([]) + ctx.h.advance(1) + await access(ctx.h, 'https://github.com/acme/site') + expect(installLookups(ctx)).toEqual(['GET /repos/acme/site/installation']) + }) + + it('the owner lookup failing never fails the answer: not_installed', async () => { + const ctx = await setup({ publicRepos: ['https://github.com/acme/site'] }) + const failing = ctx.github.fetch + const h = await createHarness({}, { + github: createGitHubAppMinter({ + appId: '1', + privateKeyPkcs8: await exportPKCS8((await generateKeyPair('RS256', { extractable: true })).privateKey), + isBound: async () => false, + log: () => undefined, + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => + /\/(orgs|users)\/[^/]+\/installation$/.test(new URL(String(input)).pathname) ? new Response(null, { status: 502 }) : failing(input, init)) as typeof fetch + }), + githubFetch: failing, + publicRepoCheck: async () => true + }) + const answer = await h.call('GET', `/v1/github/repo-access?repo=${encodeURIComponent('https://github.com/acme/site')}`) + expect(answer.status).toBe(200) + expect(answer.body).toMatchObject({ access: 'public', push: 'not_installed' }) + }) +}) diff --git a/src/main/hosted-sandbox/hosted-account-ipc.test.ts b/src/main/hosted-sandbox/hosted-account-ipc.test.ts index c6b3f834fb6..7a3141fce45 100644 --- a/src/main/hosted-sandbox/hosted-account-ipc.test.ts +++ b/src/main/hosted-sandbox/hosted-account-ipc.test.ts @@ -131,6 +131,63 @@ it('a GitHub-only create keeps the typed name as the workspace title (NAME-DROPP }) const SESSION = 'cs_abcdefghijklmnopqrstuv' +it('CREATE-GH-STEP: a public repo that can’t push asks with ids too; settings pages pass, others drop', async () => { + const githubRepoAccess = vi.fn(async (query: { repo: string; repoId?: number }) => + query.repo.endsWith('/site') + ? { + access: 'public' as const, + owner: 'acme', + repo: query.repo, + push: 'not_installed' as const, + installUrl: query.repoId + ? 'https://github.com/apps/x/installations/new/permissions?suggested_target_id=50&repository_ids[]=7&state=s' + : 'https://github.com/apps/x/installations/new?state=s' + } + : { + access: 'public' as const, + owner: 'acme', + repo: query.repo, + push: 'repo_not_selected' as const, + configureUrl: query.repo.endsWith('/evil') + ? 'https://evil.test/settings' + : 'https://github.com/organizations/acme/settings/installations/900' + } + ) + const repoIds = vi.fn(async () => ({ repoId: 7, ownerId: 50 })) + registerHostedAccountHandlers( + { + config: async () => ({ idleSleepMinutes: 15 }), + connectGitHub: async () => ({ installUrl: REPO, authorizeUrl: REPO }), + githubRepoAccess, + githubRepositories: async () => ({ repositories: [], nextCursor: null }), + create: unusedCreate, + ...githubUser + }, + { repoIds } + ) + expect( + await handlers.get(CH.getRepoAccess)?.({}, { repoUrl: 'https://github.com/acme/site' }) + ).toMatchObject({ + ok: true, + value: { push: 'not_installed', installUrl: expect.stringContaining('repository_ids[]=7') } + }) + repoIds.mockClear() + expect( + await handlers.get(CH.getRepoAccess)?.({}, { repoUrl: 'https://github.com/acme/web' }) + ).toMatchObject({ + ok: true, + value: { configureUrl: 'https://github.com/organizations/acme/settings/installations/900' } + }) + // The installation's settings page needs no install ids. + expect(repoIds).not.toHaveBeenCalled() + const evil = await handlers.get(CH.getRepoAccess)?.( + {}, + { repoUrl: 'https://github.com/acme/evil' } + ) + expect(evil).toMatchObject({ ok: true }) + expect((evil as { value: Record }).value.configureUrl).toBeUndefined() +}) + it('asks again with the repo and owner ids when access is missing, so GitHub preselects the repo', async () => { const githubRepoAccess = vi.fn(async (query: { repoId?: number }) => ({ access: 'missing' as const, diff --git a/src/main/hosted-sandbox/hosted-account-ipc.ts b/src/main/hosted-sandbox/hosted-account-ipc.ts index 6b337c6c365..b0bc6d8b5c2 100644 --- a/src/main/hosted-sandbox/hosted-account-ipc.ts +++ b/src/main/hosted-sandbox/hosted-account-ipc.ts @@ -3,6 +3,7 @@ import { ipcMain, shell } from 'electron' import { ORCA_CLOUD_WORKSPACE_CHANNELS as CH } from '../../shared/hosted-sandbox/cloud-workspace-api' import type { HostedSandboxConfigResponse } from '../../shared/hosted-sandbox/hosted-sandbox-wire' +import type { HostedGithubRepoAccessResponse } from '../../shared/hosted-sandbox/hosted-github-wire' import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' import { failure } from './hosted-workspace-runtime' import { @@ -53,6 +54,18 @@ function repoTarget(args: RepoArgs): { repo: string; setupSessionId?: string } | return { repo: `https://github.com/${slug}`, ...(session ? { setupSessionId: session } : {}) } } +/** Links the window opens must be GitHub's own pages. */ +function githubPagesOnly(value: HostedGithubRepoAccessResponse): HostedGithubRepoAccessResponse { + const onGitHub = (url: string | undefined): boolean => + url !== undefined && new URL(url).origin === 'https://github.com' + const { installUrl, configureUrl, ...rest } = value + return { + ...rest, + ...(onGitHub(installUrl) ? { installUrl } : {}), + ...(onGitHub(configureUrl) ? { configureUrl } : {}) + } +} + export function registerHostedAccountHandlers( client: Pick< HostedSandboxControlPlaneClient, @@ -127,16 +140,15 @@ export function registerHostedAccountHandlers( } try { const answer = await client.githubRepoAccess(target) - if (answer.access !== 'missing') { - return { ok: true, value: answer } - } + // A public repository that can't push gets an install page too (CREATE-GH-STEP). + const installs = + answer.access === 'missing' || + (answer.access === 'public' && + (answer.push === 'not_installed' || answer.push === 'not_connected')) // Missing: ask again with the ids GitHub's install page needs to preselect only this repo. - const ids = await repoIds(target.repo) + const ids = installs ? await repoIds(target.repo) : null const value = ids ? await client.githubRepoAccess({ ...target, ...ids }) : answer - if (value.installUrl && new URL(value.installUrl).origin !== 'https://github.com') { - return { ok: true, value: { ...value, installUrl: undefined } } - } - return { ok: true, value } + return { ok: true, value: githubPagesOnly(value) } } catch (error) { return failure(error) } diff --git a/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx new file mode 100644 index 00000000000..a6f2c74b6f1 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx @@ -0,0 +1,213 @@ +import React from 'react' +import { CircleSlash, ExternalLink, Github } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/class-names' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { + openCloudCreateGitHubAccess, + recheckCloudCreateGitHubAccess, + reopenCloudCreateGitHubAccess, + skipCloudCreateGitHubAccess, + type CloudCreateGitHubAccess +} from '@/lib/orca-cloud/cloud-create-github-access' +import { useCloudCreateGitHubAccess } from '@/lib/orca-cloud/cloud-create-github-access-registry' +import { ownerRequestLabel, useOwnerRequestCopy } from '@/lib/orca-cloud/owner-request' +import { StepIcon } from './WorktreeSetupSteps' + +export type VmBuildGitHubAccessActions = { + open: () => void + skip: () => void + reopen: () => void + copyRequest: () => void + copied: boolean +} + +function stepState(phase: CloudCreateGitHubAccess['phase']): 'running' | 'done' | 'pending' { + switch (phase) { + case 'checking': + return 'running' + case 'ok': + case 'granted': + return 'done' + default: + return 'pending' + } +} + +function askLine(access: CloudCreateGitHubAccess, t: Translate): string { + switch (access.ask) { + case 'configure': + return t( + 'orcaCloud.createGitHubAccess.configureMeaning', + 'Orca’s GitHub app is on {{owner}}, but not for this repository. You can pull without it; pushes need it.', + { owner: access.owner } + ) + case 'request': + return t( + 'orcaCloud.createGitHubAccess.requestMeaning', + 'Only an owner of {{owner}} can install Orca’s GitHub app. You can pull without it; pushes need it.', + { owner: access.owner } + ) + case 'requested': + return t( + 'orcaCloud.createGitHubAccess.requestedMeaning', + 'An owner of {{owner}} has been asked to approve Orca’s GitHub app. This continues on its own once they do.', + { owner: access.owner } + ) + default: + return t( + 'orcaCloud.createGitHubAccess.installMeaning', + 'Install Orca’s GitHub app on {{owner}} so this workspace can push. You can pull without it.', + { owner: access.owner } + ) + } +} + +/** + * The wizard's "GitHub access" step (CREATE-GH-STEP), drawn like the steps around it: a check mark + * when the Orca GitHub App can push, otherwise what grants it, and Skip for now. + */ +export function VmBuildGitHubAccessRowView({ + access, + actions +}: { + access: CloudCreateGitHubAccess + actions: VmBuildGitHubAccessActions +}): React.JSX.Element | null { + const t = useTranslate() + const labelId = React.useId() + if (access.phase === 'hidden') { + return null + } + const needed = access.phase === 'needed' + const skipped = access.phase === 'skipped' + const repo = access.repoName + const label = needed + ? t('orcaCloud.createGitHubAccess.needed', 'Let Orca push to {{repo}}', { repo }) + : t('orcaCloud.createGitHubAccess.label', 'GitHub access') + const detail = + access.phase === 'granted' + ? t('orcaCloud.createGitHubAccess.granted', 'Orca can push to {{repo}} now.', { repo }) + : skipped + ? t( + 'orcaCloud.createGitHubAccess.skippedMeaning', + 'You can pull; pushes need access later.' + ) + : null + + return ( +
  • +
    + {skipped ? ( + + ) : needed ? ( + + ) : ( + + )} + + {label} + + {access.phase === 'checking' ? ( + + {t('orcaCloud.createGitHubAccess.checking', 'Checking…')} + + ) : null} + {skipped ? ( + <> + + {t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped')} + + {access.ask ? ( + + ) : null} + + ) : null} +
    + {detail ?

    {detail}

    : null} + {needed ? ( +
    +

    {askLine(access, t)}

    + {access.opened ? ( +

    + {t( + 'orcaCloud.createGitHubAccess.waiting', + 'Waiting for GitHub… This continues on its own once access is granted.' + )} +

    + ) : null} + {access.holding ? ( +

    + {t( + 'orcaCloud.createGitHubAccess.holding', + 'Your sandbox is ready. It opens as soon as you grant access or skip.' + )} +

    + ) : null} +
    + {access.ask === 'install' || access.ask === 'configure' ? ( + + ) : ( + + )} + +
    +
    + ) : null} +
  • + ) +} + +/** The live step for a create; nothing when the create has no GitHub step. */ +export function VmBuildGitHubAccessRow({ + creationId +}: { + creationId: string +}): React.JSX.Element | null { + const access = useCloudCreateGitHubAccess(creationId) + const request = useOwnerRequestCopy(access?.repoUrl ?? null, 'push') + const needed = access?.phase === 'needed' + // An install finished in the browser: check as soon as Orca is focused again. + React.useEffect(() => { + if (!needed) { + return + } + const onFocus = (): void => recheckCloudCreateGitHubAccess(creationId) + window.addEventListener('focus', onFocus) + return () => window.removeEventListener('focus', onFocus) + }, [creationId, needed]) + if (!access) { + return null + } + return ( + openCloudCreateGitHubAccess(creationId), + skip: () => skipCloudCreateGitHubAccess(creationId), + reopen: () => reopenCloudCreateGitHubAccess(creationId), + copyRequest: request.copy, + copied: request.copied + }} + /> + ) +} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index e79bd4181c7..281946ce64e 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -23,6 +23,7 @@ import { VmBuildFailureCard } from './VmBuildFailureCard' import { VmBuildBillingBlocker } from './VmBuildBillingBlocker' import { VmBuildAgentSignInRow } from './VmBuildAgentSignInRow' import { VmBuildSecretsRow } from '../cloud-secrets-ask/VmBuildSecretsRow' +import { VmBuildGitHubAccessRow } from './VmBuildGitHubAccessRow' import { OrcaCloudQueuedPrompt } from '@/components/orca-cloud/OrcaCloudQueuedPrompt' import { classifyVmBuildFailure, @@ -280,20 +281,25 @@ export function VmBuildSheet({ {gated ? null : (
      {steps.map((step) => ( - + + + {/* CREATE-GH-STEP: checked alongside Start sandbox, held before Open. */} + {cloud && step.id === 'provision' ? ( + + ) : null} + ))} {/* Orca Cloud: agent setup happens after create (the setup page and the workspace's sign-in strip), so the build card has no agent row. Other VMs keep the host's own. */} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheetGitHubAccess.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheetGitHubAccess.fixture.tsx new file mode 100644 index 00000000000..3ba1408d216 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildSheetGitHubAccess.fixture.tsx @@ -0,0 +1,80 @@ +// CREATE-GH-STEP: the wizard's GitHub access step in each of its states, on a GitHub-only Orca Cloud +// create (the same sheet an owned create uses). +import { defineFixture } from '../../component-fixtures/component-fixture' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import type { CloudCreateGitHubAccess } from '@/lib/orca-cloud/cloud-create-github-access' +import { setCloudCreateGitHubAccessForTest } from '@/lib/orca-cloud/cloud-create-github-access-registry' +import { githubCreateRequest } from '@/lib/orca-cloud/start-cloud-workspace-from-github' +import { sheet, stampsFor, stubBillingRole, T0 } from './vm-build-sheet-fixture-support' + +const REQUEST = githubCreateRequest({ + repoUrl: 'https://github.com/acme/web', + fullName: 'acme/web', + name: 'Fix the login redirect', + agent: 'claude', + composerRepoId: 'repo' +}) + +const STARTING = ['[orca-cloud] provisioning', '[orca-cloud] plan-clone'] +const CLONED = [ + ...STARTING, + '[orca-cloud] cloning', + '[orca-cloud] clone-progress 100 checkout', + '[orca-cloud] connecting' +] + +function build(lines: readonly string[]): PendingWorktreeCreation { + return { + creationId: 'fixture', + phase: 'provisioning-vm', + status: 'creating', + startedAt: T0, + indeterminate: false, + loaderVisible: true, + provisioningLog: lines.join('\n'), + provisioningLogStamps: stampsFor(lines.length), + phaseLog: [{ phase: 'provisioning-vm', at: T0 }], + request: REQUEST + } +} + +const BASE: CloudCreateGitHubAccess = { + repoUrl: 'https://github.com/acme/web', + repoName: 'acme/web', + owner: 'acme', + phase: 'checking', + opened: false, + remembered: false, + holding: false +} + +function fixture( + access: Partial, + lines: readonly string[] = STARTING, + now = T0 + 2_500 +) { + return defineFixture({ + width: 760, + setup: () => { + stubBillingRole(true) + setCloudCreateGitHubAccessForTest('fixture', { ...BASE, ...access }) + }, + render: () => sheet(build(lines), null, now) + }) +} + +export const checking = fixture({ phase: 'checking' }) +export const ok = fixture({ phase: 'ok' }) +export const install = fixture({ phase: 'needed', ask: 'install' }) +export const installWaiting = fixture({ phase: 'needed', ask: 'install', opened: true }) +export const installHolding = fixture( + { phase: 'needed', ask: 'install', opened: true, holding: true }, + CLONED, + T0 + 9_000 +) +export const configure = fixture({ phase: 'needed', ask: 'configure' }) +export const ownerOnly = fixture({ phase: 'needed', ask: 'request' }) +export const requested = fixture({ phase: 'needed', ask: 'requested' }) +export const granted = fixture({ phase: 'granted', ask: 'install' }, CLONED, T0 + 9_000) +export const skipped = fixture({ phase: 'skipped', ask: 'install' }) +export const skippedEarlier = fixture({ phase: 'skipped', ask: 'install', remembered: true }) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index fcb4c690561..a10884cec0f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28173,6 +28173,23 @@ "copyFailed": "Couldn’t copy it.", "copied": "Copied", "copy": "Copy request for an owner" + }, + "createGitHubAccess": { + "label": "GitHub access", + "checking": "Checking…", + "needed": "Let Orca push to {{repo}}", + "installMeaning": "Install Orca’s GitHub app on {{owner}} so this workspace can push. You can pull without it.", + "configureMeaning": "Orca’s GitHub app is on {{owner}}, but not for this repository. You can pull without it; pushes need it.", + "requestMeaning": "Only an owner of {{owner}} can install Orca’s GitHub app. You can pull without it; pushes need it.", + "requestedMeaning": "An owner of {{owner}} has been asked to approve Orca’s GitHub app. This continues on its own once they do.", + "install": "Install GitHub App", + "configure": "Add repository on GitHub", + "skip": "Skip for now", + "skippedMeaning": "You can pull; pushes need access later.", + "setUp": "Set up", + "granted": "Orca can push to {{repo}} now.", + "waiting": "Waiting for GitHub… This continues on its own once access is granted.", + "holding": "Your sandbox is ready. It opens as soon as you grant access or skip." } }, "runActions": { diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-access-model.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-access-model.ts new file mode 100644 index 00000000000..cfe1140d420 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-access-model.ts @@ -0,0 +1,77 @@ +// CREATE-GH-STEP: what the create wizard's GitHub access step shows, from the control plane's +// repo-access answer (its `push` reason) and, where it decides the button, the person's install rights. +import type { HostedGithubRepoAccessResponse } from '../../../../shared/hosted-sandbox/hosted-github-wire' +import { fetchCloudPushAccess } from './cloud-push-access' + +/** + * `install`: Install GitHub App (or connect this account to the owner's installation). + * `configure`: the App is on the owner without this repository; its settings page adds it. + * `request`: only an owner can install; copy a request for one. `requested`: already asked. + */ +export type CloudCreateGitHubAsk = 'install' | 'configure' | 'request' | 'requested' + +export type CloudCreateGitHubAccess = { + repoUrl: string + /** owner/repo */ + repoName: string + owner: string + /** + * `hidden`: no row (not on GitHub, signed out, or an older control plane that can't say). + * `ok`: the App could push from the start. `granted`: it can now, after asking. + */ + phase: 'checking' | 'ok' | 'needed' | 'granted' | 'skipped' | 'hidden' + ask?: CloudCreateGitHubAsk + configureUrl?: string + /** Install (or settings) opened in the browser; GitHub's answer is being polled for. */ + opened: boolean + /** Skipped on an earlier create of this repository: this create doesn't hold for it. */ + remembered: boolean + /** The sandbox is up and the create is waiting on this step before Open workspace. */ + holding: boolean +} + +export type CloudCreateGitHubGate = { proceed: boolean; grantedDuringCreate: boolean } + +/** owner/repo from https://github.com//. */ +export function repoNameOf(repoUrl: string): string { + return repoUrl.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '') +} + +export type CloudCreateGitHubEvaluation = + | { phase: 'ok' | 'hidden' } + | { phase: 'needed'; ask: CloudCreateGitHubAsk; configureUrl?: string } + +export async function evaluateCloudCreateGitHubAccess( + repoUrl: string, + answer: HostedGithubRepoAccessResponse | null +): Promise { + if (!answer) { + return { phase: 'hidden' } + } + if (answer.push === 'ok' || answer.access === 'granted') { + return { phase: 'ok' } + } + // An older control plane can't tell pull from push: its toast after create stays the only ask. + if (answer.push === undefined) { + return { phase: 'hidden' } + } + if (answer.access === 'requested') { + return { phase: 'needed', ask: 'requested' } + } + if (answer.canInstall === false) { + return { phase: 'needed', ask: 'request' } + } + if (answer.push === 'repo_not_selected' && (answer.configureUrl || answer.installUrl)) { + return { + phase: 'needed', + ask: 'configure', + configureUrl: answer.configureUrl ?? answer.installUrl + } + } + // Same rule as the push notice: the control plane's canInstall, else the person's gh login. + const access = await fetchCloudPushAccess(repoUrl).catch(() => 'install' as const) + return { + phase: 'needed', + ask: access === 'cantInstall' ? 'request' : access === 'requested' ? 'requested' : 'install' + } +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-access-registry.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-access-registry.ts new file mode 100644 index 00000000000..ce774bb7627 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-access-registry.ts @@ -0,0 +1,63 @@ +// CREATE-GH-STEP: the GitHub access step's per-create state, read by the build sheet's row. +import { useSyncExternalStore } from 'react' +import type { + CloudCreateGitHubAccess, + CloudCreateGitHubGate +} from './cloud-create-github-access-model' + +export type Entry = { + state: CloudCreateGitHubAccess + generation: number + neededSince: number | null + wasNeeded: boolean + timer: ReturnType | null + waiters: ((gate: CloudCreateGitHubGate) => void)[] +} + +export const entries = new Map() +const listeners = new Set<() => void>() + +export function emit(): void { + for (const listener of listeners) { + listener() + } +} + +export function getCloudCreateGitHubAccess(creationId: string): CloudCreateGitHubAccess | null { + return entries.get(creationId)?.state ?? null +} + +export function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function useCloudCreateGitHubAccess(creationId: string): CloudCreateGitHubAccess | null { + return useSyncExternalStore(subscribe, () => getCloudCreateGitHubAccess(creationId)) +} + +/** Tests and fixtures: a fixed state for a creation id. */ +export function setCloudCreateGitHubAccessForTest( + creationId: string, + state: CloudCreateGitHubAccess | null +): void { + if (!state) { + entries.delete(creationId) + emit() + return + } + const entry = entries.get(creationId) + if (entry) { + entry.state = state + } else { + entries.set(creationId, { + state, + generation: 1, + neededSince: state.phase === 'needed' ? Date.now() : null, + wasNeeded: state.phase === 'needed', + timer: null, + waiters: [] + }) + } + emit() +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts new file mode 100644 index 00000000000..dea2bbcee51 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts @@ -0,0 +1,241 @@ +// CREATE-GH-STEP: the wizard's GitHub access step. Checked with the create, held before Open only +// when access is missing, released by a grant (polled) or Skip, and a skip is remembered per repo. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => { + type Listener = (state: { pendingWorktreeCreations: Record }) => void + const store = { + state: { + pendingWorktreeCreations: { c1: {} } as Record, + activePendingCreationId: 'c1' as string | null + }, + listeners: new Set() + } + return { + store, + answers: [] as unknown[], + pushAccess: 'install' as string, + install: vi.fn(async () => true), + openUrl: vi.fn(async () => undefined), + shown: true + } +}) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => mocks.store.state, + subscribe: (listener: (state: unknown) => void) => { + mocks.store.listeners.add(listener) + return () => mocks.store.listeners.delete(listener) + } + } +})) +vi.mock('@/lib/workspace/creation/worktree-creation-surface', () => ({ + selectWorktreeCreationSurfaceShown: () => mocks.shown +})) +vi.mock('./use-orca-cloud-repo-access', () => ({ + fetchOrcaCloudRepoAccess: async () => + mocks.answers.length > 1 ? mocks.answers.shift() : mocks.answers[0], + invalidateOrcaCloudRepoAccess: () => undefined +})) +vi.mock('./cloud-push-access', () => ({ + fetchCloudPushAccess: async () => mocks.pushAccess +})) +vi.mock('./cloud-setup-notice-actions', () => ({ + openOrcaGitHubAppInstall: mocks.install +})) + +import { + beginCloudCreateGitHubAccess, + disposeCloudCreateGitHubAccess, + gateCloudCreateOnGitHubAccess, + openCloudCreateGitHubAccess, + reopenCloudCreateGitHubAccess, + skipCloudCreateGitHubAccess +} from './cloud-create-github-access' +import { getCloudCreateGitHubAccess } from './cloud-create-github-access-registry' +import { isGitHubAccessSkipped, rememberGitHubAccessSkip } from './cloud-create-github-skip' + +const REPO = 'https://github.com/acme/site' +const base = { owner: 'acme', repo: REPO } +const NOT_INSTALLED = { ...base, access: 'public', push: 'not_installed', canInstall: null } +const GRANTED = { ...base, access: 'granted', push: 'ok' } + +async function settled(): Promise { + for (let i = 0; i < 10; i++) { + await Promise.resolve() + } +} + +function removeCreation(): void { + delete mocks.store.state.pendingWorktreeCreations.c1 + for (const listener of mocks.store.listeners) { + listener(mocks.store.state) + } +} + +beforeEach(() => { + vi.useFakeTimers() + const storage = new Map() + vi.stubGlobal('localStorage', { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + removeItem: (key: string) => storage.delete(key) + }) + vi.stubGlobal('window', { api: { shell: { openUrl: mocks.openUrl } } }) + mocks.store.state.pendingWorktreeCreations = { c1: {} } + mocks.store.state.activePendingCreationId = 'c1' + mocks.answers = [] + mocks.pushAccess = 'install' + mocks.shown = true + mocks.install.mockClear() + mocks.openUrl.mockClear() +}) + +afterEach(() => { + disposeCloudCreateGitHubAccess('c1') + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +describe('the create wizard’s GitHub access step', () => { + it('access already fine: a check mark, and Open is never held', async () => { + mocks.answers = [GRANTED] + beginCloudCreateGitHubAccess('c1', REPO) + expect(getCloudCreateGitHubAccess('c1')?.phase).toBe('checking') + await settled() + expect(getCloudCreateGitHubAccess('c1')?.phase).toBe('ok') + await expect(gateCloudCreateOnGitHubAccess('c1')).resolves.toEqual({ + proceed: true, + grantedDuringCreate: false + }) + }) + + it('the gate waits for the first answer instead of passing a create that needs access', async () => { + let answer: (value: unknown) => void = () => undefined + mocks.answers = [new Promise((resolve) => (answer = resolve))] + beginCloudCreateGitHubAccess('c1', REPO) + let gate: unknown = null + void gateCloudCreateOnGitHubAccess('c1').then((value) => (gate = value)) + answer(NOT_INSTALLED) + await settled() + expect(getCloudCreateGitHubAccess('c1')).toMatchObject({ + phase: 'needed', + ask: 'install', + holding: true + }) + expect(gate).toBeNull() + }) + + it('missing: Install opens GitHub, the poll sees the grant, and Open goes on with it', async () => { + mocks.answers = [NOT_INSTALLED] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + let gate: unknown = null + void gateCloudCreateOnGitHubAccess('c1').then((value) => (gate = value)) + await settled() + openCloudCreateGitHubAccess('c1') + await settled() + expect(mocks.install).toHaveBeenCalledWith(REPO) + expect(getCloudCreateGitHubAccess('c1')?.opened).toBe(true) + mocks.answers = [GRANTED] + await vi.advanceTimersByTimeAsync(2_000) + await settled() + expect(getCloudCreateGitHubAccess('c1')).toMatchObject({ phase: 'granted', holding: false }) + expect(gate).toEqual({ proceed: true, grantedDuringCreate: true }) + }) + + it('installed on the owner without this repository: opens its settings page', async () => { + const settings = 'https://github.com/organizations/acme/settings/installations/900' + mocks.answers = [ + { ...base, access: 'public', push: 'repo_not_selected', configureUrl: settings } + ] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + expect(getCloudCreateGitHubAccess('c1')).toMatchObject({ + ask: 'configure', + configureUrl: settings + }) + openCloudCreateGitHubAccess('c1') + await settled() + expect(mocks.openUrl).toHaveBeenCalledWith(settings) + expect(mocks.install).not.toHaveBeenCalled() + }) + + it('only an owner can install: a request to copy', async () => { + mocks.answers = [{ ...NOT_INSTALLED, canInstall: false }] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + expect(getCloudCreateGitHubAccess('c1')?.ask).toBe('request') + mocks.answers = [{ ...NOT_INSTALLED }] + mocks.pushAccess = 'cantInstall' + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + expect(getCloudCreateGitHubAccess('c1')?.ask).toBe('request') + }) + + it('Skip for now: Open goes on, and the next create of the repository isn’t held', async () => { + mocks.answers = [NOT_INSTALLED] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + const gate = gateCloudCreateOnGitHubAccess('c1') + await settled() + skipCloudCreateGitHubAccess('c1') + await expect(gate).resolves.toEqual({ proceed: true, grantedDuringCreate: false }) + expect(isGitHubAccessSkipped(REPO)).toBe(true) + + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + expect(getCloudCreateGitHubAccess('c1')).toMatchObject({ phase: 'skipped', remembered: true }) + await expect(gateCloudCreateOnGitHubAccess('c1')).resolves.toMatchObject({ proceed: true }) + // Set up asks again (and polls) without holding the create. + reopenCloudCreateGitHubAccess('c1') + expect(getCloudCreateGitHubAccess('c1')?.phase).toBe('needed') + expect(isGitHubAccessSkipped(REPO)).toBe(false) + }) + + it('a remembered skip is dropped once the repository has access', async () => { + rememberGitHubAccessSkip(REPO) + mocks.answers = [GRANTED] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + expect(getCloudCreateGitHubAccess('c1')?.phase).toBe('ok') + expect(isGitHubAccessSkipped(REPO)).toBe(false) + }) + + it('a create whose sheet isn’t on screen isn’t held', async () => { + mocks.answers = [NOT_INSTALLED] + mocks.shown = false + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + await expect(gateCloudCreateOnGitHubAccess('c1')).resolves.toEqual({ + proceed: true, + grantedDuringCreate: false + }) + expect(isGitHubAccessSkipped(REPO)).toBe(false) + }) + + it('cancelled while held: the wait ends with proceed false and polling stops', async () => { + mocks.answers = [NOT_INSTALLED] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + const gate = gateCloudCreateOnGitHubAccess('c1') + await settled() + removeCreation() + await expect(gate).resolves.toEqual({ proceed: false, grantedDuringCreate: false }) + expect(getCloudCreateGitHubAccess('c1')).toBeNull() + }) + + it('no answer (signed out, offline) or an older control plane: no step', async () => { + mocks.answers = [null] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + expect(getCloudCreateGitHubAccess('c1')?.phase).toBe('hidden') + mocks.answers = [{ ...base, access: 'public' }] + beginCloudCreateGitHubAccess('c1', REPO) + await settled() + expect(getCloudCreateGitHubAccess('c1')?.phase).toBe('hidden') + beginCloudCreateGitHubAccess('c1', null) + expect(getCloudCreateGitHubAccess('c1')).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts new file mode 100644 index 00000000000..d8794784c1c --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts @@ -0,0 +1,345 @@ +// CREATE-GH-STEP: the Orca Cloud create wizard's "GitHub access" step. Checked as soon as the create +// starts, in parallel with Start sandbox, so it costs nothing when the Orca GitHub App can already +// push. When it can't, the step asks (Install GitHub App, the installation's settings, or a request +// to copy for an owner) and polls until GitHub says yes; the create holds before Open workspace +// until the step is granted or skipped, so a grant reaches the new sandbox before it opens. +// "Skip for now" is remembered per repository (cloud-create-github-skip.ts): later creates show the +// step as skipped without holding, until the repository has access. +import { + evaluateCloudCreateGitHubAccess, + repoNameOf, + type CloudCreateGitHubAccess, + type CloudCreateGitHubEvaluation, + type CloudCreateGitHubGate +} from './cloud-create-github-access-model' +import { emit, entries, subscribe } from './cloud-create-github-access-registry' +import { useAppStore } from '@/store' +import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' +import { openOrcaGitHubAppInstall } from './cloud-setup-notice-actions' +import { + forgetGitHubAccessSkip, + isGitHubAccessSkipped, + rememberGitHubAccessSkip +} from './cloud-create-github-skip' +import { + fetchOrcaCloudRepoAccess, + invalidateOrcaCloudRepoAccess +} from './use-orca-cloud-repo-access' + +const FAST_POLL_MS = 2_000 +const FAST_POLL_WINDOW_MS = 3 * 60_000 +const SLOW_POLL_MS = 10_000 +/** A create left waiting this long goes on as if skipped (not remembered). */ +const GIVE_UP_MS = 30 * 60_000 +/** The check started with the create; a gate never waits longer than this for its first answer. */ +const FIRST_ANSWER_WAIT_MS = 5_000 + +function update(creationId: string, patch: Partial): void { + const entry = entries.get(creationId) + if (!entry) { + return + } + entry.state = { ...entry.state, ...patch } + if (entry.state.phase === 'needed') { + entry.wasNeeded = true + entry.neededSince ??= Date.now() + } + emit() +} + +function settle(creationId: string, gate: CloudCreateGitHubGate): void { + const entry = entries.get(creationId) + if (!entry) { + return + } + const waiters = entry.waiters.splice(0) + for (const resolve of waiters) { + resolve(gate) + } + if (entry.state.holding) { + entry.state = { ...entry.state, holding: false } + emit() + } +} + +function creationExists(creationId: string): boolean { + return Boolean(useAppStore.getState().pendingWorktreeCreations[creationId]) +} + +let watchingCreations = false + +/** A create that leaves the store (opened, cancelled, dismissed) stops its polls and any wait. */ +function watchCreations(): void { + if (watchingCreations) { + return + } + watchingCreations = true + useAppStore.subscribe((state) => { + for (const creationId of entries.keys()) { + if (!state.pendingWorktreeCreations[creationId]) { + disposeCloudCreateGitHubAccess(creationId) + } + } + }) +} + +/** Starts the step for a create (again on Retry). `repoUrl` null: not a GitHub repository, no step. */ +export function beginCloudCreateGitHubAccess(creationId: string, repoUrl: string | null): void { + watchCreations() + const previous = entries.get(creationId) + if (previous?.timer) { + clearTimeout(previous.timer) + } + if (previous) { + settle(creationId, { proceed: false, grantedDuringCreate: false }) + } + if (!repoUrl) { + entries.delete(creationId) + emit() + return + } + const repoName = repoNameOf(repoUrl) + const entry: Entry = { + state: { + repoUrl, + repoName, + owner: repoName.split('/')[0] ?? '', + phase: 'checking', + opened: false, + remembered: false, + holding: false + }, + generation: (previous?.generation ?? 0) + 1, + neededSince: null, + wasNeeded: false, + timer: null, + waiters: [] + } + entries.set(creationId, entry) + emit() + const generation = entry.generation + void fetchOrcaCloudRepoAccess(repoUrl, { force: true }) + .then((answer) => evaluateCloudCreateGitHubAccess(repoUrl, answer)) + .catch((): CloudCreateGitHubEvaluation => ({ phase: 'hidden' })) + .then((result) => { + if (entries.get(creationId)?.generation !== generation) { + return + } + if (result.phase !== 'needed') { + if (result.phase === 'ok') { + // Access arrived since a skip: the step shows its check mark and stops asking. + forgetGitHubAccessSkip(repoUrl) + } + update(creationId, { phase: result.phase }) + settle(creationId, { proceed: true, grantedDuringCreate: false }) + return + } + if (isGitHubAccessSkipped(repoUrl)) { + update(creationId, { + phase: 'skipped', + remembered: true, + ask: result.ask, + ...(result.configureUrl ? { configureUrl: result.configureUrl } : {}) + }) + settle(creationId, { proceed: true, grantedDuringCreate: false }) + return + } + update(creationId, { + phase: 'needed', + ask: result.ask, + ...(result.configureUrl ? { configureUrl: result.configureUrl } : {}) + }) + schedulePoll(creationId) + }) +} + +function schedulePoll(creationId: string, delayMs?: number): void { + const entry = entries.get(creationId) + if (!entry || entry.state.phase !== 'needed') { + return + } + if (entry.timer) { + clearTimeout(entry.timer) + } + const elapsed = Date.now() - (entry.neededSince ?? Date.now()) + const generation = entry.generation + entry.timer = setTimeout( + () => { + entry.timer = null + void pollOnce(creationId, generation) + }, + delayMs ?? (elapsed < FAST_POLL_WINDOW_MS ? FAST_POLL_MS : SLOW_POLL_MS) + ) +} + +async function pollOnce(creationId: string, generation: number): Promise { + const entry = entries.get(creationId) + if (!entry || entry.generation !== generation || entry.state.phase !== 'needed') { + return + } + if (!creationExists(creationId)) { + disposeCloudCreateGitHubAccess(creationId) + return + } + if (entry.neededSince !== null && Date.now() - entry.neededSince > GIVE_UP_MS) { + // Nobody answered: go on as a skip for this create only; the toast after create stays. + update(creationId, { phase: 'skipped' }) + settle(creationId, { proceed: true, grantedDuringCreate: false }) + return + } + invalidateOrcaCloudRepoAccess(entry.state.repoUrl) + const answer = await fetchOrcaCloudRepoAccess(entry.state.repoUrl, { force: true }).catch( + () => null + ) + if (entries.get(creationId)?.generation !== generation || entry.state.phase !== 'needed') { + return + } + if (answer?.push === 'ok' || answer?.access === 'granted') { + markGranted(creationId) + return + } + // An owner approved part of the way (requested), or the installation now exists without this repo. + if (answer?.access === 'requested' && entry.state.ask !== 'requested') { + update(creationId, { ask: 'requested' }) + } else if (answer?.push === 'repo_not_selected' && entry.state.ask === 'install') { + update(creationId, { + ask: 'configure', + ...(answer.configureUrl ? { configureUrl: answer.configureUrl } : {}) + }) + } + schedulePoll(creationId) +} + +function markGranted(creationId: string): void { + const entry = entries.get(creationId) + if (!entry) { + return + } + forgetGitHubAccessSkip(entry.state.repoUrl) + update(creationId, { phase: 'granted', opened: false }) + settle(creationId, { proceed: true, grantedDuringCreate: entry.wasNeeded }) +} + +/** Install GitHub App / Add the repository on GitHub: opens GitHub, then keeps polling. */ +export function openCloudCreateGitHubAccess(creationId: string): void { + const entry = entries.get(creationId) + if (!entry || entry.state.phase !== 'needed') { + return + } + const { repoUrl, configureUrl, ask } = entry.state + const opened = + ask === 'configure' && configureUrl + ? window.api.shell.openUrl(configureUrl).then( + () => true, + () => openOrcaGitHubAppInstall(repoUrl) + ) + : openOrcaGitHubAppInstall(repoUrl) + void opened.then((ok) => { + if (ok && entries.get(creationId) === entry) { + update(creationId, { opened: true }) + // Back from the browser: ask now instead of at the next poll. + schedulePoll(creationId, 0) + } + }) +} + +/** Orca regained focus (an install finished in the browser): check now. */ +export function recheckCloudCreateGitHubAccess(creationId: string): void { + schedulePoll(creationId, 0) +} + +/** "Skip for now": the create goes on, and later creates of this repository don't hold for it. */ +export function skipCloudCreateGitHubAccess(creationId: string): void { + const entry = entries.get(creationId) + if (!entry || entry.state.phase !== 'needed') { + return + } + if (entry.timer) { + clearTimeout(entry.timer) + entry.timer = null + } + rememberGitHubAccessSkip(entry.state.repoUrl) + update(creationId, { phase: 'skipped', remembered: false, opened: false }) + settle(creationId, { proceed: true, grantedDuringCreate: false }) +} + +/** + * "Set up" on a skipped step: asks again (and polls). The create isn't held a second time; a grant + * that lands before Open still reaches the sandbox. + */ +export function reopenCloudCreateGitHubAccess(creationId: string): void { + const entry = entries.get(creationId) + if (!entry || entry.state.phase !== 'skipped' || !entry.state.ask) { + return + } + forgetGitHubAccessSkip(entry.state.repoUrl) + entry.neededSince = null + update(creationId, { phase: 'needed', remembered: false }) + schedulePoll(creationId) +} + +/** + * Before Open workspace: proceeds at once unless the step is asking; then waits for a grant or + * Skip. A create whose sheet isn't on screen isn't held (it goes on as a skip for this create). + * `proceed: false`: the create was cancelled or retried while waiting. + */ +export async function gateCloudCreateOnGitHubAccess( + creationId: string +): Promise { + const entry = entries.get(creationId) + if (!entry) { + return { proceed: true, grantedDuringCreate: false } + } + if (entry.state.phase === 'checking') { + // Started with the create, so normally answered long before the sandbox is up. + await new Promise((resolve) => { + const done = (): void => { + clearTimeout(timer) + unsubscribe() + resolve() + } + const timer = setTimeout(done, FIRST_ANSWER_WAIT_MS) + const unsubscribe = subscribe(() => { + if (entries.get(creationId) !== entry || entry.state.phase !== 'checking') { + done() + } + }) + }) + if (entries.get(creationId) !== entry) { + return { proceed: false, grantedDuringCreate: false } + } + } + if (entry.state.phase === 'granted') { + return { proceed: true, grantedDuringCreate: entry.wasNeeded } + } + if (entry.state.phase !== 'needed') { + return { proceed: true, grantedDuringCreate: false } + } + const state = useAppStore.getState() + if (state.activePendingCreationId !== creationId || !selectWorktreeCreationSurfaceShown(state)) { + return { proceed: true, grantedDuringCreate: false } + } + const held = new Promise((resolve) => entry.waiters.push(resolve)) + update(creationId, { holding: true }) + return held +} + +/** The create is gone (opened, cancelled, dismissed): stop polling and release any wait. */ +export function disposeCloudCreateGitHubAccess(creationId: string): void { + const entry = entries.get(creationId) + if (!entry) { + return + } + if (entry.timer) { + clearTimeout(entry.timer) + } + settle(creationId, { proceed: false, grantedDuringCreate: false }) + entries.delete(creationId) + emit() +} + +export type { + CloudCreateGitHubAccess, + CloudCreateGitHubAsk, + CloudCreateGitHubGate +} from './cloud-create-github-access-model' diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-apply.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-apply.ts new file mode 100644 index 00000000000..c7b969d11c9 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-apply.ts @@ -0,0 +1,12 @@ +// CREATE-GH-STEP: a GitHub access grant that lands while the create's sandbox is already up. The +// sandbox booted without the Orca GitHub App's repository token, so its git has neither the token +// route nor the auth header; this hands it both before the workspace opens, so no restart is needed. +// Best effort: when it can't, the workspace still opens and the push notice (Check again) remains. +export type CloudGitHubAccessTarget = { sandboxId: string } | { environmentId: string } + +export async function applyCloudGitHubAccessToSandbox( + _target: CloudGitHubAccessTarget +): Promise { + // GH-LIVE-REFRESH (gh-access) supplies the live refresh; until it lands nothing is applied here. + return false +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-skip.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-skip.ts new file mode 100644 index 00000000000..20c6c2e7ba2 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-skip.ts @@ -0,0 +1,59 @@ +// CREATE-GH-STEP: "Skip for now" on the create wizard's GitHub access step, remembered per +// repository on this device so the next create doesn't ask again. The step still shows (as +// skipped, with Set up), and the memory is dropped once the repository has access. +const STORAGE_KEY = 'orca.cloud-create.github-skip.v1' +const MAX_REPOS = 200 + +type SkipRecord = Record + +function key(repoUrl: string): string { + return repoUrl.toLowerCase().replace(/\.git$/, '') +} + +function read(): SkipRecord { + try { + const parsed: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return {} + } + return Object.fromEntries( + Object.entries(parsed).filter( + (entry): entry is [string, number] => typeof entry[1] === 'number' + ) + ) + } catch { + return {} + } +} + +function write(record: SkipRecord): void { + try { + const entries = Object.entries(record) + if (entries.length === 0) { + localStorage.removeItem(STORAGE_KEY) + return + } + // Newest first, so a long-lived device keeps the repositories it still uses. + const kept = entries.sort((a, b) => b[1] - a[1]).slice(0, MAX_REPOS) + localStorage.setItem(STORAGE_KEY, JSON.stringify(Object.fromEntries(kept))) + } catch { + // Storage unavailable or full: the step just asks again next time. + } +} + +export function isGitHubAccessSkipped(repoUrl: string): boolean { + return read()[key(repoUrl)] !== undefined +} + +export function rememberGitHubAccessSkip(repoUrl: string, now = Date.now()): void { + write({ ...read(), [key(repoUrl)]: now }) +} + +export function forgetGitHubAccessSkip(repoUrl: string): void { + const record = read() + if (record[key(repoUrl)] === undefined) { + return + } + delete record[key(repoUrl)] + write(record) +} diff --git a/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts b/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts index 08b959a8bbc..35807dd340e 100644 --- a/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts +++ b/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts @@ -19,6 +19,11 @@ import { appendProvisioningLog } from '@/lib/workspace/creation/pending-creation import { setOrcaCloudCancelRetry, trackOrcaCloudCreateStep } from '@/lib/orca-cloud-cancel-cleanup' import { CANCEL_CLEANUP_UNCONFIRMED } from '../../../../shared/hosted-sandbox/cloud-workspace-api' import { launchFirstCloudAgent } from './github-cloud-first-agent' +import { + beginCloudCreateGitHubAccess, + gateCloudCreateOnGitHubAccess +} from './cloud-create-github-access' +import { applyCloudGitHubAccessToSandbox } from './cloud-create-github-apply' import { forgetGitHubCreateKey, githubCreateIdempotencyKey, @@ -199,15 +204,25 @@ async function runGitHubCloudCreate(creationId: string): Promise { if (!request || !source) { return false } + if (!startedSandboxes.has(creationId)) { + // CREATE-GH-STEP: asked alongside Start sandbox, so it adds nothing when access is fine. + beginCloudCreateGitHubAccess(creationId, source.repoUrl) + } const sandboxId = startedSandboxes.get(creationId) ?? (await startSandbox(creationId)) if (!sandboxId) { return false } - if (!current(creationId)) { + // Held before Open workspace while the GitHub step asks for access. + const github = await gateCloudCreateOnGitHubAccess(creationId) + if (!current(creationId) || !github.proceed) { // GH-CREATE-CANCEL: cancelled after the sandbox started but before it opened. await discardSandbox(creationId, sandboxId) return false } + if (github.grantedDuringCreate) { + // Granted after the sandbox started: its git gets the token now, not after a restart. + await applyCloudGitHubAccessToSandbox({ sandboxId }) + } useAppStore.getState().updatePendingWorktreeCreation(creationId, { phase: 'creating' }) const workspace = await window.api.cloudWorkspaces.get(sandboxId).catch(() => null) const opened = workspace?.ok diff --git a/src/renderer/src/lib/workspace/creation/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/ephemeral-vm-worktree-creation.ts index 345a7af387a..6cf2488bdde 100644 --- a/src/renderer/src/lib/workspace/creation/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/ephemeral-vm-worktree-creation.ts @@ -22,6 +22,11 @@ import { } from '@/lib/workspace/creation/pending-creation-provisioning-log' import { cloudCreateIdempotencyKey } from '@/lib/orca-cloud/cloud-create-intent' import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' +import { + beginCloudCreateGitHubAccess, + gateCloudCreateOnGitHubAccess +} from '@/lib/orca-cloud/cloud-create-github-access' +import { applyCloudGitHubAccessToSandbox } from '@/lib/orca-cloud/cloud-create-github-apply' export async function prepareRequestForCreate( creationId: string, @@ -53,6 +58,13 @@ async function prepareEphemeralVmRecipeRequest( // A retry provisions a new VM; the sheet must not act on the last one. vmEnvironmentId: undefined }) + if (recipe.provider === 'orca-cloud') { + // CREATE-GH-STEP: asked alongside Start sandbox, so it adds nothing when access is fine. + beginCloudCreateGitHubAccess( + creationId, + orcaCloudGitHubRepoUrl(store.repos.find((repo) => repo.id === recipe.sourceRepoId)) + ) + } const unsubscribeProvisionEvents = window.api.ephemeralVm.onProvisionEvent?.((event) => { if (event.provisionId !== creationId || event.stream !== 'stderr') { return @@ -190,6 +202,19 @@ async function prepareEphemeralVmRecipeRequest( } return null } + if (recipe.provider === 'orca-cloud') { + // CREATE-GH-STEP: held here, before Open workspace, while the GitHub step asks for access. + const github = await gateCloudCreateOnGitHubAccess(creationId) + if (!github.proceed || !useAppStore.getState().pendingWorktreeCreations[creationId]) { + notePhase(creationId, 'failed') + await cleanupEphemeralVmRuntimeForFailedCreate(preparedRequest, creationId) + return null + } + if (github.grantedDuringCreate && preparedTarget.environmentId) { + // Granted after the sandbox started: its git gets the token now, not after a restart. + await applyCloudGitHubAccessToSandbox({ environmentId: preparedTarget.environmentId }) + } + } useAppStore.getState().updatePendingWorktreeCreation(creationId, { phase: 'fetching', request: preparedRequest diff --git a/src/shared/hosted-sandbox/hosted-github-wire.ts b/src/shared/hosted-sandbox/hosted-github-wire.ts index 9be6b002591..06b84b4a96d 100644 --- a/src/shared/hosted-sandbox/hosted-github-wire.ts +++ b/src/shared/hosted-sandbox/hosted-github-wire.ts @@ -15,8 +15,15 @@ export const HostedGithubRepoAccessResponseSchema = z.object({ // installation). true: the caller can install it on the owner (their own account, or org admin); // false: another user's account, or a non-admin org member; null: unknown (no connected GitHub // user, membership unreadable, or GitHub didn't answer). - canInstall: z.boolean().nullable().optional() + canInstall: z.boolean().nullable().optional(), + // CREATE-GH-STEP: can a workspace on this repository push? `ok`: granted. `not_installed`: the + // App isn't on the owner. `repo_not_selected`: it is, without this repository (configureUrl is + // the installation's settings page). `not_connected`: the App reaches the repository through an + // installation this Orca account isn't bound to. Absent from an older control plane. + push: z.enum(['ok', 'not_installed', 'repo_not_selected', 'not_connected']).optional(), + configureUrl: z.string().url().optional() }) +export type HostedGithubRepoAccessPush = NonNullable export type HostedGithubRepoAccessResponse = z.infer /** GET /v1/github/repositories[?cursor=]: repositories the account's GitHub installations reach. */ From e8313a82afae0482a27a2e1fb13db9704d11321b Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:25:51 -0800 Subject: [PATCH 07/35] chore(cloud): CODEX-RELAY register the relay's vitest runner --- cloud/apps/chatgpt-relay/vitest.config.ts | 7 +++++++ .../scripts/ci/unit-selection/check-test-file-runners.mjs | 6 ++++++ 2 files changed, 13 insertions(+) create mode 100644 cloud/apps/chatgpt-relay/vitest.config.ts diff --git a/cloud/apps/chatgpt-relay/vitest.config.ts b/cloud/apps/chatgpt-relay/vitest.config.ts new file mode 100644 index 00000000000..9f469145c99 --- /dev/null +++ b/cloud/apps/chatgpt-relay/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + // A string tsconfig skips the lookup, which otherwise climbs to the desktop app's tsconfig. + oxc: { tsconfig: false }, + test: { include: ['test/**/*.test.ts'] } +}) diff --git a/config/scripts/ci/unit-selection/check-test-file-runners.mjs b/config/scripts/ci/unit-selection/check-test-file-runners.mjs index b02e52ae92c..18041e1ef42 100644 --- a/config/scripts/ci/unit-selection/check-test-file-runners.mjs +++ b/config/scripts/ci/unit-selection/check-test-file-runners.mjs @@ -49,6 +49,12 @@ const NON_UNIT_TEST_RUNNERS = [ sources: [`cloud/apps/${app}/vitest.config.ts`], mirrors: ["include: ['src/**/*.test.ts']"] })), + { + name: 'cloud chatgpt-relay', + include: ['cloud/apps/chatgpt-relay/test/**/*.test.ts'], + sources: ['cloud/apps/chatgpt-relay/vitest.config.ts'], + mirrors: ["include: ['test/**/*.test.ts']"] + }, { name: 'cloud relay-edge', include: ['cloud/apps/relay-edge/test/**/*.test.ts'], From 9184ab48073153e58dea973b085ebb906a6f9997 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:26:13 -0800 Subject: [PATCH 08/35] fix: import the registry's Entry type --- src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts index d8794784c1c..c3eb3611731 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.ts @@ -12,7 +12,7 @@ import { type CloudCreateGitHubEvaluation, type CloudCreateGitHubGate } from './cloud-create-github-access-model' -import { emit, entries, subscribe } from './cloud-create-github-access-registry' +import { emit, entries, subscribe, type Entry } from './cloud-create-github-access-registry' import { useAppStore } from '@/store' import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' import { openOrcaGitHubAppInstall } from './cloud-setup-notice-actions' From 5879c3d9884087c8a025918079543d293db33fa1 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:29:35 -0800 Subject: [PATCH 09/35] fix: lint (no type assertions in tests, exhaustive switches) --- .../hosted-sandbox/hosted-account-ipc.test.ts | 2 +- .../VmBuildGitHubAccessRow.tsx | 7 +++++-- .../cloud-create-github-access.test.ts | 18 +++++++++--------- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/main/hosted-sandbox/hosted-account-ipc.test.ts b/src/main/hosted-sandbox/hosted-account-ipc.test.ts index 7a3141fce45..380c99e1dda 100644 --- a/src/main/hosted-sandbox/hosted-account-ipc.test.ts +++ b/src/main/hosted-sandbox/hosted-account-ipc.test.ts @@ -185,7 +185,7 @@ it('CREATE-GH-STEP: a public repo that can’t push asks with ids too; settings { repoUrl: 'https://github.com/acme/evil' } ) expect(evil).toMatchObject({ ok: true }) - expect((evil as { value: Record }).value.configureUrl).toBeUndefined() + expect(evil).not.toHaveProperty('value.configureUrl') }) it('asks again with the repo and owner ids when access is missing, so GitHub preselects the repo', async () => { diff --git a/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx index a6f2c74b6f1..6b9c70b7f06 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx @@ -29,7 +29,9 @@ function stepState(phase: CloudCreateGitHubAccess['phase']): 'running' | 'done' case 'ok': case 'granted': return 'done' - default: + case 'needed': + case 'skipped': + case 'hidden': return 'pending' } } @@ -54,7 +56,8 @@ function askLine(access: CloudCreateGitHubAccess, t: Translate): string { 'An owner of {{owner}} has been asked to approve Orca’s GitHub app. This continues on its own once they do.', { owner: access.owner } ) - default: + case 'install': + case undefined: return t( 'orcaCloud.createGitHubAccess.installMeaning', 'Install Orca’s GitHub app on {{owner}} so this workspace can push. You can pull without it.', diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts index dea2bbcee51..e259c3d2310 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-create-github-access.test.ts @@ -4,17 +4,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => { type Listener = (state: { pendingWorktreeCreations: Record }) => void - const store = { - state: { - pendingWorktreeCreations: { c1: {} } as Record, - activePendingCreationId: 'c1' as string | null - }, - listeners: new Set() - } + const state: { + pendingWorktreeCreations: Record + activePendingCreationId: string | null + } = { pendingWorktreeCreations: { c1: {} }, activePendingCreationId: 'c1' } + const store = { state, listeners: new Set() } + const answers: unknown[] = [] + const pushAccess: string = 'install' return { store, - answers: [] as unknown[], - pushAccess: 'install' as string, + answers, + pushAccess, install: vi.fn(async () => true), openUrl: vi.fn(async () => undefined), shown: true From 7aef97258aa8add958610f92be1b06fbee033246 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 00:40:14 -0800 Subject: [PATCH 10/35] feat(cloud): after 2 min held with no answer, "Open now, set up later" leads (not remembered as a skip) --- .../VmBuildGitHubAccessRow.tsx | 22 ++++- .../VmBuildSheetGitHubAccess.fixture.tsx | 5 ++ src/renderer/src/i18n/locales/en.json | 3 +- .../cloud-create-github-access-actions.ts | 72 +++++++++++++++++ .../cloud-create-github-access-model.ts | 2 + .../cloud-create-github-access.test.ts | 21 ++++- .../orca-cloud/cloud-create-github-access.ts | 80 +++---------------- 7 files changed, 130 insertions(+), 75 deletions(-) create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-github-access-actions.ts diff --git a/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx index 6b9c70b7f06..c5f03cc4538 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildGitHubAccessRow.tsx @@ -3,13 +3,13 @@ import { CircleSlash, ExternalLink, Github } from 'lucide-react' import { Button } from '@/components/ui/button' import { cn } from '@/lib/class-names' import { useTranslate, type Translate } from '@/i18n/use-translate' +import type { CloudCreateGitHubAccess } from '@/lib/orca-cloud/cloud-create-github-access' import { openCloudCreateGitHubAccess, recheckCloudCreateGitHubAccess, reopenCloudCreateGitHubAccess, - skipCloudCreateGitHubAccess, - type CloudCreateGitHubAccess -} from '@/lib/orca-cloud/cloud-create-github-access' + skipCloudCreateGitHubAccess +} from '@/lib/orca-cloud/cloud-create-github-access-actions' import { useCloudCreateGitHubAccess } from '@/lib/orca-cloud/cloud-create-github-access-registry' import { ownerRequestLabel, useOwnerRequestCopy } from '@/lib/orca-cloud/owner-request' import { StepIcon } from './WorktreeSetupSteps' @@ -17,6 +17,8 @@ import { StepIcon } from './WorktreeSetupSteps' export type VmBuildGitHubAccessActions = { open: () => void skip: () => void + /** "Open now, set up later": this create goes on; the next one asks again. */ + openNow: () => void reopen: () => void copyRequest: () => void copied: boolean @@ -158,8 +160,19 @@ export function VmBuildGitHubAccessRowView({

      ) : null}
      + {/* Held a while with no answer: opening leads; granting stays one click away. */} + {access.holdingLong ? ( + + ) : null} {access.ask === 'install' || access.ask === 'configure' ? ( -
      ';\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# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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 'noreply@orca.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'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\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\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\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 // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\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/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\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 stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\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 stored) {\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\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\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 out.signature = sign(out, signingKey(stateDir))\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 = { workspaceCheckout, seal, sign, signingKey, 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=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} -export const VM_SCRIPTS_HASH: string = "2cb89ff2" -export const VM_SCRIPTS_STAMP: number = 1794730652 +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# ORCA_DOCKER (on|off: the control plane's Docker switch for the `docker` shim).\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)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\n# PARITY-DOCKER: the control plane's Docker switch (SANDBOX_DOCKER) for the `docker` shim. Only a\n# start that says so changes it; a retried or repair start (no ORCA_DOCKER) keeps the last answer.\ncase \"${ORCA_DOCKER:-}\" in\n off) : >\"$STATE/docker.off\" ;;\n on) rm -f \"$STATE/docker.off\" ;;\nesac\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# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\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.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\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# OpenCode's first run in a VM installs its plugin SDK into ~/.config/opencode, creates its database\n# and fetches its model list: ~2.5 s more on the first launch (5.2 s vs 2.7 s warm, n72). orca-sandbox-env\n# just wrote that config, so do the first run now, in the background at low priority, with no\n# credentials (`opencode models` does all of it and exits). The SDK install only happens once orcad\n# has put Orca's plugin in ~/.config/opencode/plugins (~10 s after this, n73), so wait for it (up to\n# 60 s) first. Skipped once it has run on this disk.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && [ ! -d \"$HOME/.config/opencode/node_modules\" ]; then\n (\n cd \"$HOME\" || exit 0\n # shellcheck disable=SC2016 # expanded by the inner shell\n env -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 PATH=\"$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin\" \\\n OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c '\n for _ in $(seq 1 120); do [ -d \"$HOME/.config/opencode/plugins\" ] && break; sleep 0.5; done\n exec timeout 120 \"$1\" models\n ' opencode-first-run \"$ORCA_HOME/tools/bin/opencode\" /dev/null 2>&1 9>&- &\n )\nfi\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\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\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 ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\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# The agent CLIs are large and a fresh VM pages them in lazily from the snapshot, so the first agent\n# launch paid for it (OpenCode 11 s cold vs 3.75 s warm, n71). Read them into the page cache in the\n# background at idle IO priority, after orcad is starting. Best effort; detached so it outlives this\n# script, and never on the ready path.\nprefetch_dirs=()\nfor dir in @anthropic-ai @openai opencode-ai; do\n if [ -d \"$ORCA_HOME/tools/lib/node_modules/$dir\" ]; then\n prefetch_dirs+=(\"$ORCA_HOME/tools/lib/node_modules/$dir\")\n fi\ndone\nif [ \"${#prefetch_dirs[@]}\" -gt 0 ]; then\n # shellcheck disable=SC2016 # expanded by the inner shell\n setsid nohup nice -n 19 bash -c '\n command -v ionice >/dev/null && ionice -c 3 -p $$ 2>/dev/null\n find \"$@\" -type f -size +256k -print0 2>/dev/null | xargs -0 -r cat >/dev/null 2>&1\n ' agent-prefetch \"${prefetch_dirs[@]}\" /dev/null 2>&1 9>&- &\nfi\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)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(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=''\nanthropic_key_scrub=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\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 # G9: pre-approve only an Orca placeholder. A real key (placeholders off) is never written, not even its\n # tail: Claude Code asks once instead, and a tail an older image wrote is scrubbed.\n ANTHROPIC_API_KEY)\n case \"$(printf '%s' \"$b64\" | base64 -d)\" in\n orca-ph-*) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n *) anthropic_key_scrub=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\n ;;\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 the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$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 elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\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 elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\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# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\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_KEY_SCRUB=\"$anthropic_key_scrub\" 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\nconst scrub = process.env.ORCA_KEY_SCRUB\nif (scrub && c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\") {\n const r = c.customApiKeyResponses\n for (const list of [\"approved\", \"rejected\"]) if (Array.isArray(r[list])) r[list] = r[list].filter((t) => t !== scrub)\n}\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\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\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\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\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) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\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-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\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// Vercel closes a WebSocket on a *.vercel.run route after ~340 s with no traffic (1006). A preview\n// app's socket can sit silent that long, so once an upgrade is a WebSocket the proxy watches the app's\n// frames and, after KEEPALIVE_MS with nothing either way, sends the visitor a ping control frame\n// between two frames (never inside one). The visitor's pong reaches the app, which RFC 6455 says to\n// ignore (an unsolicited pong needs no answer).\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\n// Well under Vercel's ~340 s idle cut. ORCA_SHARE_PROXY_KEEPALIVE_MS is for tests.\nconst KEEPALIVE_MS = Number(process.env.ORCA_SHARE_PROXY_KEEPALIVE_MS || 30_000)\n// FIN + ping opcode, empty payload, unmasked (server to client).\nconst PING_FRAME = Buffer.from([0x89, 0x00])\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/**\n * Follows the app's WebSocket frames (server to client: header, then payload) just closely enough to\n * know when the stream sits between two frames, where a control frame may be inserted.\n */\nfunction frameBoundaries() {\n let header = []\n let remaining = 0\n return {\n push(chunk) {\n let i = 0\n while (i < chunk.length) {\n if (remaining > 0) {\n const take = Math.min(remaining, chunk.length - i)\n remaining -= take\n i += take\n continue\n }\n header.push(chunk[i++])\n if (header.length < 2) {\n continue\n }\n const len7 = header[1] & 0x7f\n const need = 2 + (len7 === 126 ? 2 : len7 === 127 ? 8 : 0) + (header[1] & 0x80 ? 4 : 0)\n if (header.length < need) {\n continue\n }\n const bytes = Buffer.from(header)\n remaining = len7 === 126 ? bytes.readUInt16BE(2) : len7 === 127 ? Number(bytes.readBigUInt64BE(2)) : len7\n header = []\n }\n },\n atBoundary: () => header.length === 0 && remaining === 0\n }\n}\n\n/** The app's answer to the upgrade: its head is passed through; only a 101 to `websocket` gets keepalives. */\nfunction upgradeAnswer() {\n let head = Buffer.alloc(0)\n let state = 'head'\n const frames = frameBoundaries()\n return {\n push(chunk) {\n if (state === 'head') {\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end === -1) {\n if (head.length > 64 * 1024) {\n state = 'raw'\n }\n return\n }\n const text = head.subarray(0, end).toString('latin1')\n state = /^HTTP\\/1\\.1 101/.test(text) && /^upgrade:\\s*websocket\\s*$/im.test(text) ? 'ws' : 'raw'\n chunk = head.subarray(end + 4)\n head = Buffer.alloc(0)\n }\n if (state === 'ws') {\n frames.push(chunk)\n }\n },\n canPing: () => state === 'ws' && frames.atBoundary()\n }\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 // App to visitor by hand (with backpressure) so the keepalive knows where frames start and end.\n const answer = upgradeAnswer()\n let lastTraffic = Date.now()\n socket.on('data', () => {\n lastTraffic = Date.now()\n })\n target.on('data', (chunk) => {\n lastTraffic = Date.now()\n answer.push(chunk)\n if (!socket.write(chunk)) {\n target.pause()\n socket.once('drain', () => target.resume())\n }\n })\n target.on('end', () => socket.end())\n const keepalive = setInterval(() => {\n if (Date.now() - lastTraffic >= KEEPALIVE_MS && answer.canPing() && socket.writable) {\n socket.write(PING_FRAME)\n lastTraffic = Date.now()\n }\n }, Math.max(50, Math.floor(KEEPALIVE_MS / 3)))\n socket.once('close', () => clearInterval(keepalive))\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# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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 'noreply@orca.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'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\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\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\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 // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\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/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\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 stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\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 stored) {\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\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\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 out.signature = sign(out, signingKey(stateDir))\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 = { workspaceCheckout, seal, sign, signingKey, 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=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPTS_HASH: string = "ad897b32" +export const VM_SCRIPTS_STAMP: number = 1794733957 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 # The stamp must describe this commit's scripts, never the Worker's: a commit from before stamps\n # leaves it unset (the image then reads as stamp 0).\n unset ORCA_VM_SCRIPTS_STAMP\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 and ORCA_CLONE_FILTER, plus\n# ORCA_BUILD_SECRET_NAMES (space list of the team secrets the environment names; each value rides in\n# the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get).\n# `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk.\n# ORCA_AUTO_INSTALL=1 (automatic environments, no install script): install from the lockfile, never failing.\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\"\n\n# SEC-2: the snapshot of this VM is the team's saved environment, booted by every member's workspace,\n# so a secret's value must never be in it. Secrets are for the install script alone: take_secrets\n# moves them out of this script's environment (clones and Orca's own steps never see them), the\n# install step hands them to that one child, and scan_secrets searches the disk before the build\n# may succeed.\nsecret_names=()\nsecret_values=()\ntake_secrets() {\n local name\n for name in ${ORCA_BUILD_SECRET_NAMES:-}; do\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n [ -n \"${!name:-}\" ] || continue\n secret_names+=(\"$name\")\n secret_values+=(\"${!name}\")\n unset \"$name\"\n done\n unset ORCA_BUILD_SECRET_NAMES\n # Only a file that changes after this marker can hold a value: the base image never saw one.\n : >\"$OUT/.scan-since\"\n}\n\n# Fails (non-zero) when a secret's value is in a file the build created or changed, anywhere on the\n# disk the snapshot captures. Plain text only: a value the script encoded, encrypted or compressed is\n# not found, and neither is one shorter than 8 characters (it would match ordinary text). A search\n# that cannot run fails too. Prints names and paths, never a value.\n# ORCA_SCAN_ROOT: tests only (a scratch tree); the control plane never sets it.\nscan_secrets() {\n [ \"${#secret_names[@]}\" -gt 0 ] || return 0\n local root=\"${ORCA_SCAN_ROOT:-/}\" i line pattern hit named=0\n local names=() patterns=() args=() newer=() sudo=()\n for i in \"${!secret_names[@]}\"; do\n # grep -F reads a newline as \"or\": a multi-line value (a PEM key) is searched by its longest line.\n pattern=\"\"\n while IFS= read -r line; do\n case \"$line\" in -----*) continue ;; esac\n if [ \"${#line}\" -gt \"${#pattern}\" ]; then pattern=\"$line\"; fi\n done < <(printf '%s\\n' \"${secret_values[$i]}\") # a pipe, not a here-string temp file\n [ \"${#pattern}\" -ge 8 ] || continue\n names+=(\"${secret_names[$i]}\")\n patterns+=(\"$pattern\")\n args+=(-e \"$pattern\")\n done\n [ \"${#patterns[@]}\" -gt 0 ] || return 0\n if ! command -v find >/dev/null 2>&1 || ! command -v grep >/dev/null 2>&1 || ! command -v xargs >/dev/null 2>&1; then\n echo \"::orca-error:: Orca couldn’t check the build for secrets, so the environment wasn’t saved.\"\n return 1\n fi\n # Root-owned files count too (`sudo npm config set` writes /root/.npmrc).\n if sudo -n true 2>/dev/null; then sudo=(sudo -n); fi\n # A missing marker (the install script removed it) means every file is searched.\n if [ -f \"$OUT/.scan-since\" ]; then newer=(-cnewer \"$OUT/.scan-since\"); fi\n changed_files() {\n ${sudo[@]+\"${sudo[@]}\"} find \"$root\" \\( -path /proc -o -path /sys -o -path /dev -o -path /run \\) -prune \\\n -o -type f ${newer[@]+\"${newer[@]}\"} -print0 2>/dev/null\n }\n # One pass for every value; the per-secret passes only run on a build that is about to fail.\n if [ -z \"$(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF \"${args[@]}\" -- 2>/dev/null | head -n 1)\" ]; then\n return 0\n fi\n for i in \"${!names[@]}\"; do\n while IFS= read -r hit; do\n [ -n \"$hit\" ] || continue\n named=1\n echo \"::orca-error:: ${names[$i]} was left in $hit. Saved environments are shared with your team, so remove it before the install script ends.\"\n done < <(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF -e \"${patterns[$i]}\" -- 2>/dev/null | head -n 5)\n done\n if [ \"$named\" -eq 0 ]; then\n # The file moved between the two passes: still a build that held a value on disk.\n echo \"::orca-error:: The install script left a secret on disk, so the environment wasn’t saved. Remove it before the script ends, then save again.\"\n fi\n return 1\n}\n\n# PARITY-AUTO-ENV-DEPS: an automatic environment (ORCA_AUTO_INSTALL=1, no install script) installs the\n# first repo's JavaScript dependencies from its lockfile, so new workspaces start with them (the deps\n# step below carries node_modules into each worktree). Soft by design: a failure, a lockfile out of date\n# or the time cap leaves the clone as it was (no half-installed node_modules) and the build goes on.\n# Package managers the image doesn't have (bun, uv, bundler, go, cargo) are only named in the log.\n# ORCA_AUTO_INSTALL_TIMEOUT: tests only.\nauto_install() {\n local dir=\"$1\" pm=\"\" declared=\"\" rc=0 started f\n local cmd=() others=()\n for f in bun.lock bun.lockb uv.lock poetry.lock Pipfile.lock Gemfile.lock go.sum Cargo.lock; do\n [ -f \"$dir/$f\" ] && others+=(\"$f\")\n done\n if [ -f \"$dir/package.json\" ]; then\n # package.json's packageManager (\"pnpm@9.1.0\") wins over the lockfile guess.\n declared=$(sed -n 's/.*\"packageManager\"[[:space:]]*:[[:space:]]*\"\\([a-z]*\\)@.*/\\1/p' \"$dir/package.json\" | head -n 1)\n case \"$declared\" in\n pnpm | yarn | npm) pm=\"$declared\" ;;\n *)\n if [ -f \"$dir/pnpm-lock.yaml\" ]; then pm=pnpm\n elif [ -f \"$dir/yarn.lock\" ]; then pm=yarn\n elif [ -f \"$dir/package-lock.json\" ] || [ -f \"$dir/npm-shrinkwrap.json\" ]; then pm=npm\n fi\n ;;\n esac\n fi\n if [ \"${#others[@]}\" -gt 0 ]; then\n echo \"Not installed automatically: ${others[*]}. Add an install script to the environment to install these.\"\n fi\n if [ -z \"$pm\" ]; then\n [ \"${#others[@]}\" -gt 0 ] || echo \"No lockfile found; the build keeps the cloned repos.\"\n return 0\n fi\n # Through corepack, so pnpm and yarn come at the version the repo pins (Node ships corepack).\n case \"$pm\" in\n pnpm) cmd=(corepack pnpm install --frozen-lockfile) ;;\n yarn)\n if [ -f \"$dir/.yarnrc.yml\" ]; then cmd=(corepack yarn install --immutable)\n else cmd=(corepack yarn install --frozen-lockfile)\n fi\n ;;\n npm) cmd=(npm ci) ;;\n esac\n echo \"Installing dependencies automatically: ${cmd[*]}\"\n started=$(date +%s)\n (cd \"$dir\" && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 timeout \"${ORCA_AUTO_INSTALL_TIMEOUT:-900}\" \"${cmd[@]}\") /dev/null || true\n return 0\n fi\n echo \"Installed dependencies in $(($(date +%s) - started))s.\"\n}\n\ntake_secrets\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 # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${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 for name in ${ORCA_BUILD_WITHHELD_SECRETS:-}; do\n echo \"$name is a model key, so environment builds don’t get it. Agents in workspaces still do.\"\n done\n (\n cd \"${first:-$ROOT}\" || exit 1\n if [ \"${#secret_names[@]}\" -gt 0 ]; then\n for i in \"${!secret_names[@]}\"; do export \"${secret_names[$i]}=${secret_values[$i]}\"; done\n fi\n exec bash -euo pipefail \"$OUT/install.sh\"\n ) /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\" \"$OUT/.scan-since\" \"$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-start b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start index caa98f7817b..f6081682ae2 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start @@ -194,13 +194,18 @@ unset ORCA_SECRET_ENV # OpenCode's first run in a VM installs its plugin SDK into ~/.config/opencode, creates its database # and fetches its model list: ~2.5 s more on the first launch (5.2 s vs 2.7 s warm, n72). orca-sandbox-env # just wrote that config, so do the first run now, in the background at low priority, with no -# credentials (`opencode models` does all of it and exits). Skipped once it has run on this disk. +# credentials (`opencode models` does all of it and exits). The SDK install only happens once orcad +# has put Orca's plugin in ~/.config/opencode/plugins (~10 s after this, n73), so wait for it (up to +# 60 s) first. Skipped once it has run on this disk. if [ -x "$ORCA_HOME/tools/bin/opencode" ] && [ ! -d "$HOME/.config/opencode/node_modules" ]; then ( cd "$HOME" || exit 0 + # shellcheck disable=SC2016 # expanded by the inner shell env -i HOME="$HOME" USER="$(id -un)" LANG=C.UTF-8 PATH="$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin" \ - OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 timeout 120 \ - "$ORCA_HOME/tools/bin/opencode" models /dev/null 2>&1 9>&- & + OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c ' + for _ in $(seq 1 120); do [ -d "$HOME/.config/opencode/plugins" ] && break; sleep 0.5; done + exec timeout 120 "$1" models + ' opencode-first-run "$ORCA_HOME/tools/bin/opencode" /dev/null 2>&1 9>&- & ) fi From 763932e856c2bb4a51150f7b898224bd8524e877 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 02:35:25 -0800 Subject: [PATCH 16/35] test: the VM create test stubs the GitHub access step --- .../src/lib/ephemeral-vm-worktree-creation.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts index f877ebba84d..8f80a1bfa86 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts @@ -22,6 +22,11 @@ const { state, gate, cleanup, retry } = vi.hoisted(() => { } }) +// CREATE-GH-STEP has its own tests; here it never holds the create. +vi.mock('@/lib/orca-cloud/cloud-create-github-access', () => ({ + beginCloudCreateGitHubAccess: () => undefined, + gateCloudCreateOnGitHubAccess: async () => ({ proceed: true, grantedDuringCreate: false }) +})) vi.mock('@/store', () => ({ useAppStore: { getState: () => ({ @@ -41,7 +46,9 @@ vi.mock('@/store', () => ({ } })) vi.mock('sonner', () => ({ toast: { error: vi.fn(), warning: vi.fn() } })) -vi.mock('@/runtime/ephemeral-vm/ephemeral-vm-environment-check', () => ({ gateVmCreateOnEnvironmentCheck: gate })) +vi.mock('@/runtime/ephemeral-vm/ephemeral-vm-environment-check', () => ({ + gateVmCreateOnEnvironmentCheck: gate +})) vi.mock('@/runtime/ephemeral-vm/ephemeral-vm-failed-create-cleanup', () => ({ cleanupFailedEphemeralVmWorkspace: cleanup })) From a94ca739f35929b1500cef5b2515da8ec88830c4 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 02:45:42 -0800 Subject: [PATCH 17/35] cloud: start new workspaces and environments in the served region nearest the caller A create or new environment with nothing pinned used to start in pdx1 whatever the caller's location, and every frame of a remote session paid that round trip. Now the sandbox-control Worker ranks the served regions (the default and its fallbacks with an active golden) by distance from Cloudflare's request geolocation and starts in the nearest. - Explicit regions (request, API project) and an environment's build region stay authoritative. - Environments record their region (migration 0061): builds, golden refreshes, staleness and the security floor use it, so snapshots stay bootable and workspaces from them stay together. Legacy environments (NULL) live in the default region as before. - Automatic environments live where the create that made them ran. - The capacity fallback tries the next nearest served region. - The warm pool keeps VMs in every served region. - VERCEL_NEAREST_REGION=off restores default-region-only. - Desktop: the workspace card's Details shows the region (e.g. Portland (pdx1)). --- .../migrations/0061_environment_region.sql | 4 + .../sandbox-control/src/auto-environments.ts | 20 +- cloud/apps/sandbox-control/src/env.ts | 2 + .../sandbox-control/src/environment-builds.ts | 28 ++- .../src/environment-golden-refresh.ts | 60 +++-- .../sandbox-control/src/environment-routes.ts | 5 +- .../src/environment-staleness.ts | 8 +- .../apps/sandbox-control/src/environments.ts | 12 +- cloud/apps/sandbox-control/src/index.ts | 9 +- cloud/apps/sandbox-control/src/lifecycle.ts | 20 +- cloud/apps/sandbox-control/src/pool.ts | 67 ++++-- cloud/apps/sandbox-control/src/regions.ts | 111 +++++++++ cloud/apps/sandbox-control/test/harness.ts | 6 +- .../test/nearest-region.test.ts | 219 ++++++++++++++++++ .../hosted-workspace-runtime.test.ts | 8 +- .../hosted-workspace-runtime.ts | 8 + .../hosted-workspace-service.ts | 4 +- .../orca-cloud/CloudWorkspaceCardDetails.tsx | 7 + src/renderer/src/i18n/locales/en.json | 1 + .../orca-cloud-workspace-state.test.ts | 7 + .../orca-cloud/orca-cloud-workspace-state.ts | 30 +++ .../hosted-sandbox/cloud-workspace-api.ts | 2 + 22 files changed, 574 insertions(+), 64 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0061_environment_region.sql create mode 100644 cloud/apps/sandbox-control/test/nearest-region.test.ts diff --git a/cloud/apps/sandbox-control/migrations/0061_environment_region.sql b/cloud/apps/sandbox-control/migrations/0061_environment_region.sql new file mode 100644 index 00000000000..6f1bcfaacc2 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0061_environment_region.sql @@ -0,0 +1,4 @@ +-- Nearest region: an environment records the region it lives in (the served region nearest whoever +-- created it), so its builds and the workspaces booted from it stay there (a snapshot only boots in +-- its own region). NULL: made before this was recorded, lives in the default region. Additive. +ALTER TABLE environments ADD COLUMN region TEXT; diff --git a/cloud/apps/sandbox-control/src/auto-environments.ts b/cloud/apps/sandbox-control/src/auto-environments.ts index d841c35a26c..57f0c3804d4 100644 --- a/cloud/apps/sandbox-control/src/auto-environments.ts +++ b/cloud/apps/sandbox-control/src/auto-environments.ts @@ -7,7 +7,7 @@ // it on the current image. Unused for 14 days it is deleted with its snapshots, unless an admin edited // it (that makes it an ordinary 'org' environment). import type { SandboxCaller } from './auth' -import { listBuilds, startBuild, TERMINAL, type BuildConfig, type BuildDeps } from './environment-builds' +import { environmentRegion, listBuilds, startBuild, TERMINAL, type BuildConfig, type BuildDeps } from './environment-builds' import { canonicalRepoUrl, parseRepos, repoDir, type EnvironmentRow } from './environments' import { normalizeRepo } from './secrets' import type { SandboxProviderApi } from './sandbox-provider' @@ -52,16 +52,22 @@ export type AutoEnvironmentOutcome = 'created' | 'rebuilt' | 'exists' | 'skipped * A create of `repoUrl` booted without an environment: make (or retry building) the account's automatic * environment for it. Never throws; the create it rides behind already succeeded. */ -export async function ensureAutoEnvironment(deps: BuildDeps, accountId: string, repoUrl: string): Promise { +export async function ensureAutoEnvironment( + deps: BuildDeps, + accountId: string, + repoUrl: string, + /** The create's region: the environment lives (and builds) there, so the next create of the repo lands there too. */ + region?: string +): Promise { try { - return await ensure(deps, accountId, repoUrl) + return await ensure(deps, accountId, repoUrl, region) } catch (error) { log('auto_environment_failed', { error: String(error).slice(0, 200) }) return 'skipped' } } -async function ensure(deps: BuildDeps, accountId: string, repoUrl: string): Promise { +async function ensure(deps: BuildDeps, accountId: string, repoUrl: string, region?: string): Promise { const url = canonicalRepoUrl(repoUrl) const wanted = normalizeRepo(url) if (!url || !wanted) { @@ -90,11 +96,11 @@ async function ensure(deps: BuildDeps, accountId: string, repoUrl: string): Prom await deps.db .prepare( `INSERT OR IGNORE INTO environments (id, account_id, name, repos, install_script, env_var_names, machine_size, - revision, next_build_number, created_by, updated_by, created_at, updated_at, kind, last_used_at) - VALUES (?, ?, ?, ?, '', '[]', 'standard', 1, 1, ?, ?, ?, ?, 'auto', ?)` + revision, next_build_number, created_by, updated_by, created_at, updated_at, kind, last_used_at, region) + VALUES (?, ?, ?, ?, '', '[]', 'standard', 1, 1, ?, ?, ?, ?, 'auto', ?, ?)` ) .bind(id, accountId, repoDir(url), JSON.stringify([{ url, defaultBranch: null }]), AUTO_ENVIRONMENT_USER, - AUTO_ENVIRONMENT_USER, now, now, now) + AUTO_ENVIRONMENT_USER, now, now, now, environmentRegion(deps.config, region)) .run() const environment = await deps.db .prepare('SELECT * FROM environments WHERE id = ? AND deleted_at IS NULL') diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 8030c89af7a..e1c956c8aca 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -15,6 +15,8 @@ export type Env = { VERCEL_REGION?: string /** Comma list tried in order when the default region's create fails on capacity (default `iad1`; "" = none). */ VERCEL_FALLBACK_REGIONS?: string + /** 'off': new workspaces and environments always start in the default region, not the one nearest the caller. */ + VERCEL_NEAREST_REGION?: string /** Overrides the Vercel API origin (tests only). */ VERCEL_API_BASE?: string /** Seed golden image (orcad + agent CLIs), adopted when its region has none yet; see image/. */ diff --git a/cloud/apps/sandbox-control/src/environment-builds.ts b/cloud/apps/sandbox-control/src/environment-builds.ts index 482a51f7e8f..f39659b6d87 100644 --- a/cloud/apps/sandbox-control/src/environment-builds.ts +++ b/cloud/apps/sandbox-control/src/environment-builds.ts @@ -162,8 +162,12 @@ export type BuildDeps = { goldenSnapshotId: string /** Every region's golden image (staleness compares a build with its own region's). */ goldenSnapshots?: Record - /** The default region: new builds run here. */ + /** The default region: builds of an environment without a served region of its own run here. */ region: string + /** Served regions, default first (each has a golden image); an environment may live in any of them. */ + regions?: readonly string[] + /** A new environment lives in the served region nearest the admin who creates it (off: VERCEL_NEAREST_REGION=off). */ + nearestRegion?: boolean guardrails?: GuardrailConfig /** The workspace base allowlist (ORCA_PLATFORM_HOST_SUFFIXES included); the smoke boot uses it too. */ egressAllowlist?: readonly string[] @@ -174,6 +178,24 @@ export type BuildDeps = { const log = (event: string, fields: Record) => console.log(JSON.stringify({ event, ...fields })) +type RegionConfig = Pick + +/** + * Where an environment's builds run: the region it records, while that region is still served (has a + * golden image); else the default. A null region (an environment from before regions were recorded) is the default. + */ +export function environmentRegion(config: RegionConfig, region: string | null | undefined): string { + if (region && region !== config.region && config.regions?.includes(region) && config.goldenSnapshots?.[region]) { + return region + } + return config.region +} + +/** The golden image a new build of an environment living in `region` (environmentRegion) starts from. */ +export function regionGolden(config: RegionConfig, region: string): string { + return region === config.region ? config.goldenSnapshotId : (config.goldenSnapshots?.[region] ?? config.goldenSnapshotId) +} + function randomId(): string { const bytes = crypto.getRandomValues(new Uint8Array(10)) return `bld_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}` @@ -303,6 +325,8 @@ export async function startBuild( } const now = deps.now() const id = randomId() + // A snapshot only boots in its own region: the build runs where the environment lives. + const region = environmentRegion(deps.config, environment.region) const base: BuildConfig = options.config ?? { revision: environment.revision, repos, @@ -336,7 +360,7 @@ export async function startBuild( WHERE changes() = 1` ) .bind(id, environment.id, environment.account_id, environment.next_build_number, JSON.stringify(config), - deps.config.goldenSnapshotId, deps.config.region, `orca-${deps.config.environment}-envbuild-${id}`, caller.userId, now, now) + regionGolden(deps.config, region), region, `orca-${deps.config.environment}-envbuild-${id}`, caller.userId, now, now) ]) } if (bumped[0]?.meta.changes !== 1) { diff --git a/cloud/apps/sandbox-control/src/environment-golden-refresh.ts b/cloud/apps/sandbox-control/src/environment-golden-refresh.ts index ebdd89a22db..87bf2aa63cd 100644 --- a/cloud/apps/sandbox-control/src/environment-golden-refresh.ts +++ b/cloud/apps/sandbox-control/src/environment-golden-refresh.ts @@ -15,12 +15,14 @@ // - an environment below the security floor (environment-security.ts) is rebuilt regardless; // - refresh builds are metered internally, never charged to the team (reportBuildUsage). // Staleness is exact: environment_builds.base_snapshot_id is the golden snapshot each build started from. -// Regions (U17): an environment lives in the default region, so a build is compared with the default -// region's golden. An older build from another region (iad1 before pdx1 became the default) is stale -// by that rule and is rebuilt in the default region; its workspaces boot in the build's own region -// until the new build is active. +// Regions (U17): an environment lives in its recorded region while that region is served, else the +// default (environmentRegion), so a build is compared with that region's golden. A build from another +// region (iad1 before pdx1 became the default, for an environment that records none) is stale by that +// rule and is rebuilt where the environment lives; its workspaces boot in the build's own region until +// the new build is active. import type { SandboxCaller } from './auth' import { + environmentRegion, GOLDEN_REFRESH_USER, parseConfig, startBuild, @@ -53,13 +55,42 @@ type StaleRow = EnvironmentRow & { active_created_at: number } +// The golden a new build of e starts from: its region's (?1, region -> golden JSON of the served +// regions), else the default region's (?2). The same rule as environmentRegion + regionGolden. +const TARGET_GOLDEN = `coalesce(json_extract(?1, '$.' || e.region), ?2)` const STALE_SQL = `SELECT e.*, b.config AS active_config, b.base_snapshot_id AS active_base, b.created_at AS active_created_at FROM environments e JOIN environment_builds b ON b.id = e.active_build_id - WHERE e.deleted_at IS NULL AND b.base_snapshot_id != ? + WHERE e.deleted_at IS NULL AND b.base_snapshot_id != ${TARGET_GOLDEN} AND NOT EXISTS ( SELECT 1 FROM environment_builds x WHERE x.environment_id = e.id AND (x.status IN ('starting', 'running', 'snapshotting') - OR (x.base_snapshot_id = ? AND x.status != 'canceled')))` + OR (x.base_snapshot_id = ${TARGET_GOLDEN} AND x.status != 'canceled')))` + +/** ?1 of TARGET_GOLDEN: each served region other than the default, with its golden. */ +function servedGoldens(config: BuildDeps['config']): string { + const goldens: Record = {} + for (const region of config.regions ?? []) { + const golden = config.goldenSnapshots?.[region] + if (region !== config.region && golden) { + goldens[region] = golden + } + } + return JSON.stringify(goldens) +} + +/** The security floor of the region each environment builds in, read once per region. */ +function floors(deps: BuildDeps): (environment: EnvironmentRow) => Promise { + const cache = new Map>() + return (environment) => { + const region = environmentRegion(deps.config, environment.region) + let floor = cache.get(region) + if (!floor) { + floor = securityFloor(deps.db, region) + cache.set(region, floor) + } + return floor + } +} /** Why a stale environment rebuilds now ('security' | 'due'), or null to wait. */ async function refreshReason( @@ -95,13 +126,15 @@ export async function refreshStaleEnvironments( deps: BuildDeps, options: GoldenRefreshOptions = {} ): Promise { - const golden = deps.config.goldenSnapshotId const maxStarts = options.maxStartsPerTick ?? 2 const maxInFlight = options.maxInFlight ?? 3 const minIntervalMs = options.minIntervalMs ?? DEFAULT_REFRESH_MIN_INTERVAL_MS const recentMs = options.recentMs ?? DEFAULT_REFRESH_RECENT_MS - const { results: stale } = await deps.db.prepare(`${STALE_SQL} ORDER BY e.updated_at DESC`).bind(golden, golden).all() - const floor = await securityFloor(deps.db, deps.config.region) + const { results: stale } = await deps.db + .prepare(`${STALE_SQL} ORDER BY e.updated_at DESC`) + .bind(servedGoldens(deps.config), deps.config.goldenSnapshotId) + .all() + const floorOf = floors(deps) const inFlight = (await deps.db .prepare(`SELECT count(*) AS n FROM environment_builds WHERE status IN ('starting', 'running', 'snapshotting')`) @@ -110,7 +143,7 @@ export async function refreshStaleEnvironments( const ranked: { environment: StaleRow; reason: 'security' | 'due' }[] = [] let deferred = 0 for (const environment of stale) { - const reason = await refreshReason(deps, environment, floor, { minIntervalMs, recentMs }) + const reason = await refreshReason(deps, environment, await floorOf(environment), { minIntervalMs, recentMs }) if (reason) { ranked.push({ environment, reason }) } else { @@ -147,15 +180,14 @@ export async function refreshEnvironment( options: Pick = {} ): Promise<'started' | 'current' | 'deferred' | 'skipped'> { try { - const golden = deps.config.goldenSnapshotId const environment = await deps.db - .prepare(`${STALE_SQL} AND e.id = ?`) - .bind(golden, golden, environmentId) + .prepare(`${STALE_SQL} AND e.id = ?3`) + .bind(servedGoldens(deps.config), deps.config.goldenSnapshotId, environmentId) .first() if (!environment) { return 'current' } - const floor = await securityFloor(deps.db, deps.config.region) + const floor = await securityFloor(deps.db, environmentRegion(deps.config, environment.region)) // Used right now, so no recency test: only the interval (or the floor) decides. const reason = await refreshReason(deps, environment, floor, { minIntervalMs: options.minIntervalMs ?? DEFAULT_REFRESH_MIN_INTERVAL_MS diff --git a/cloud/apps/sandbox-control/src/environment-routes.ts b/cloud/apps/sandbox-control/src/environment-routes.ts index 65dc4382472..d79479caa69 100644 --- a/cloud/apps/sandbox-control/src/environment-routes.ts +++ b/cloud/apps/sandbox-control/src/environment-routes.ts @@ -26,6 +26,7 @@ import { type BuildRow } from './environment-builds' import { checkStaleness } from './environment-staleness' +import { nearestRegions } from './regions' import { CreateEnvironmentSchema, EnvironmentError, @@ -135,7 +136,9 @@ export async function handleEnvironmentRoute( if (!body.success) { return json({ error: 'invalid_request', reason: body.error.issues[0]?.path.join('.') }, 400) } - return json({ environment: environmentView(await createEnvironment(db, caller, body.data, deps.now())) }) + // Its builds run, and its workspaces boot, where it lives: the served region nearest whoever creates it. + const region = nearestRegions(request, deps.config.regions ?? [], deps.config.nearestRegion !== false)?.[0] ?? null + return json({ environment: environmentView(await createEnvironment(db, caller, body.data, deps.now(), region)) }) } return json({ error: 'not_found' }, 404) } diff --git a/cloud/apps/sandbox-control/src/environment-staleness.ts b/cloud/apps/sandbox-control/src/environment-staleness.ts index 4d95aa9490d..106faf14c1d 100644 --- a/cloud/apps/sandbox-control/src/environment-staleness.ts +++ b/cloud/apps/sandbox-control/src/environment-staleness.ts @@ -2,7 +2,7 @@ // call per repo answers both "the branch moved" and "a lockfile changed" (installed deps are stale). // Uses the GitHub App token when the repo is bound, anonymous otherwise (public repos). Cached briefly // per isolate so a settings page polling it costs GitHub nothing extra. -import { LOCKFILES, getBuild, parseConfig, parseResult, type BuildDeps } from './environment-builds' +import { LOCKFILES, environmentRegion, getBuild, parseConfig, parseResult, regionGolden, type BuildDeps } from './environment-builds' import { parseRepos, type EnvironmentRow } from './environments' import { parseGitHubRepo } from './github-app' @@ -37,7 +37,7 @@ export type Staleness = { const LOCKFILE_NAMES = new Set(LOCKFILES) export async function checkStaleness( - deps: Pick & { githubFetch?: typeof fetch; config?: { goldenSnapshotId: string } }, + deps: Pick & { githubFetch?: typeof fetch; config?: Parameters[0] }, environment: EnvironmentRow, refresh = false ): Promise { @@ -54,7 +54,9 @@ export async function checkStaleness( const config = parseConfig(build) const result = parseResult(build) const configChanged = config.revision !== environment.revision - const imageUpdated = !!deps.config && build.base_snapshot_id !== deps.config.goldenSnapshotId + // Compared with the golden of the region the environment builds in (its own, or the default). + const imageUpdated = + !!deps.config && build.base_snapshot_id !== regionGolden(deps.config, environmentRegion(deps.config, environment.region)) const repos: RepoStaleness[] = [] for (const repo of parseRepos(environment)) { const built = result?.repos?.find((r) => r.url === repo.url) diff --git a/cloud/apps/sandbox-control/src/environments.ts b/cloud/apps/sandbox-control/src/environments.ts index 8933aa81ba1..22ac05da6ba 100644 --- a/cloud/apps/sandbox-control/src/environments.ts +++ b/cloud/apps/sandbox-control/src/environments.ts @@ -37,6 +37,8 @@ export type EnvironmentRow = { */ kind?: 'org' | 'auto' last_used_at?: number | null + /** Where it builds and its workspaces boot (environmentRegion); null for environments made before this was recorded. */ + region?: string | null } export class EnvironmentError extends Error { @@ -173,7 +175,9 @@ export async function createEnvironment( db: D1Database, caller: SandboxCaller, input: z.infer, - now: number + now: number, + /** The served region nearest the admin creating it; null leaves it to the default region. */ + region: string | null = null ): Promise { requireAdmin(caller) const repos = checkedRepos(input.repos) @@ -188,11 +192,11 @@ export async function createEnvironment( await db .prepare( `INSERT INTO environments (id, account_id, name, repos, install_script, env_var_names, machine_size, - revision, next_build_number, created_by, updated_by, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, 1, 1, ?, ?, ?, ?)` + revision, next_build_number, created_by, updated_by, created_at, updated_at, region) + VALUES (?, ?, ?, ?, ?, ?, ?, 1, 1, ?, ?, ?, ?, ?)` ) .bind(id, caller.accountId, input.name, JSON.stringify(repos), input.installScript, - JSON.stringify([...new Set(input.envVarNames)]), input.machineSize, caller.userId, caller.userId, now, now) + JSON.stringify([...new Set(input.envVarNames)]), input.machineSize, caller.userId, caller.userId, now, now, region) .run() return (await getEnvironment(db, caller.accountId, id))! } diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 7b7317c60a0..c93f9579677 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -64,7 +64,7 @@ import { createRoutinesApi } from './routines/api' import { handleRoutineHook, isRoutineHookPath } from './routines/hooks' import { tickRoutines } from './routines/runs' import { activeGoldenSnapshots, advanceGoldenImages } from './golden-images' -import { sandboxRegions, seedRegion } from './regions' +import { nearestRegionEnabled, nearestRegions, sandboxRegions, seedRegion, servedRegions } from './regions' import { handleRuntimeBundleRoute, runtimeBundleFor, runtimeBundleUrl } from './runtime-bundles' import { createIdTokenSource, relayingFetch } from './chatgpt-relay' import { NO_CREDENTIALS, handleEgressProxy, type CredentialBroker, type ProxiedRoute } from './egress-proxy' @@ -982,7 +982,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise ensureAutoEnvironment(buildDeps(life, deps, env), accountId, repoUrl), + ensure: (accountId, repoUrl, region) => ensureAutoEnvironment(buildDeps(life, deps, env), accountId, repoUrl, region), touch: (environmentId) => touchEnvironment(env.SANDBOX_DB, environmentId, life.now()) } } @@ -1051,6 +1051,8 @@ function buildDeps(life: LifecycleDeps, deps: Deps, env?: Env): BuildDeps { goldenSnapshotId: life.config.goldenSnapshotId, goldenSnapshots: life.config.goldenSnapshots, region: life.config.defaultRegion, + regions: servedRegions(life.config), + nearestRegion: env ? nearestRegionEnabled(env) : true, guardrails: life.config.guardrails, egressAllowlist: life.config.egressAllowlist, egressAllowlistError: life.config.egressAllowlistError @@ -1861,8 +1863,11 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise + /** `region`: where the create that asked runs; the environment builds there (a snapshot is region-bound). */ + ensure(accountId: string, repoUrl: string, region: string): Promise touch(environmentId: string): Promise } /** @@ -776,7 +777,13 @@ export async function createSandbox( request: { workspaceId: string machineSize: MachineSize + /** Explicit (the caller's or its project's): authoritative, and never moved by the capacity fallback. */ region?: string + /** + * Served regions nearest the caller first (regions.ts nearestRegions): where a create with nothing + * pinned starts, and the capacity fallback's order. Absent: the default region, then its fallbacks. + */ + nearRegions?: readonly string[] repo?: { url: string; ref?: string } /** Boot from exactly this environment build (bld_...). */ environmentBuildId?: string @@ -837,7 +844,12 @@ export async function createSandbox( const machineSize = source && !source.auto ? source.machineSize : request.machineSize await timer.time('entitlement', () => requireStart(deps, caller.accountId, caller.userId, machineSize)) // A snapshot only boots in its own region: an environment build pins the region it was built in. - const region = source?.region ?? request.region ?? deps.config.defaultRegion + // Then an explicit region; else the nearest served one (each has a golden image). + const region = + source?.region ?? + request.region ?? + request.nearRegions?.find((candidate) => goldenFor(deps, candidate)) ?? + deps.config.defaultRegion const bootSnapshotId = source?.snapshotId ?? goldenFor(deps, region) if (!bootSnapshotId) { throw new LifecycleError('conflict', 'region_unavailable') @@ -927,7 +939,7 @@ export async function createSandbox( const work = source?.auto ? deps.autoEnvironment.touch(source.environmentId) : !source - ? deps.autoEnvironment.ensure(caller.accountId, request.repo.url) + ? deps.autoEnvironment.ensure(caller.accountId, request.repo.url, region) : null if (work) { const settled = work.catch(() => undefined) @@ -1013,7 +1025,7 @@ export async function createSandbox( // Only a create nothing pinned to a region moves on: no explicit region, no environment build. const fallback = options.fallback !== false && !request.region && !source && isRegionalFailure(error) - ? deps.config.fallbackRegions?.find((candidate) => candidate !== region && goldenFor(deps, candidate)) + ? (request.nearRegions ?? deps.config.fallbackRegions)?.find((candidate) => candidate !== region && goldenFor(deps, candidate)) : undefined if (fallback) { console.log(JSON.stringify({ event: 'region_fallback', from: region, to: fallback, error: String(error).slice(0, 200) })) diff --git a/cloud/apps/sandbox-control/src/pool.ts b/cloud/apps/sandbox-control/src/pool.ts index ac58fe6806a..7a1bced9499 100644 --- a/cloud/apps/sandbox-control/src/pool.ts +++ b/cloud/apps/sandbox-control/src/pool.ts @@ -2,15 +2,18 @@ // A create claims one instead of booting (saves the provider create, ~2 s p50 / ~4 s p95 measured), // then applies the caller's policy and starts orcad exactly as a fresh VM would. The pooled id becomes // the sandbox id, so the provider name and ownership tag line up without renaming anything. -// SANDBOX_POOL_SIZE=0 (the default) turns it off; the kill switch drains it. +// SANDBOX_POOL_SIZE=0 (the default) turns it off; the kill switch drains it. Every served region (the +// default and its fallbacks, each with a golden image) keeps its own: a create starts in the region +// nearest the caller (regions.ts), and a snapshot only boots in its own region. import type { MachineSize } from './entitlements' import { killSwitchOn, type GuardrailConfig } from './guardrails' import type { SandboxProviderApi } from './sandbox-provider' import { ORCAD_PORT, SHARE_PROXY_PORT } from './sandbox-vm-commands' import { SANDBOX_VCPUS } from './machine-size' +import { servedRegions } from './regions' export type PoolConfig = { - /** Ready VMs kept per (machine size, region); only `standard` in the default region is pooled. */ + /** Ready VMs kept per (machine size, region); only `standard` is pooled, in every served region. */ size: number /** Recycle a pooled VM after this long so a claimed session keeps most of its 24 h budget. */ maxAgeMs: number @@ -36,11 +39,13 @@ export type PoolDeps = { now: () => number config: { environment: string - /** The default region's golden image: the pool warms VMs in the default region only. */ + /** The default region's golden image. */ goldenSnapshotId: string /** Every region's golden image; never deleted with a pooled VM. */ goldenSnapshots?: Record defaultRegion: string + /** Served besides the default (each has a golden image): pooled too. */ + fallbackRegions?: readonly string[] guardrails?: GuardrailConfig snapshotExpirationMs?: number pool?: PoolConfig @@ -91,7 +96,7 @@ export async function claimPooledVm( snapshotId: string = deps.config.goldenSnapshotId ): Promise { const pool = deps.config.pool - if (!pool || machineSize !== POOLED_SIZE || region !== deps.config.defaultRegion) { + if (!pool || machineSize !== POOLED_SIZE || !servedRegions(deps.config).includes(region)) { return null } return deps.db @@ -141,29 +146,43 @@ async function takeLease(deps: PoolDeps): Promise { return taken !== null } +/** How many warm VMs of one image to keep, and the region it boots in (the image's own). */ +type PoolTarget = { want: number; region: string } + +/** Each served region's golden image, by region. */ +function servedGoldens(config: PoolDeps['config']): [region: string, snapshotId: string][] { + return servedRegions(config).flatMap((region) => { + const golden = region === config.defaultRegion ? config.goldenSnapshotId : config.goldenSnapshots?.[region] + return golden ? [[region, golden] as [string, string]] : [] + }) +} + /** - * Images worth a warm VM: the golden image (`size`), plus the active build of every environment in - * use lately (BUILD_POOL_SIZE each), so a create from an org environment skips the provider boot too. + * Images worth a warm VM: each served region's golden image (`size`), plus the active build of every + * environment in use lately (BUILD_POOL_SIZE each, in its build's region), so a create from an org + * environment skips the provider boot too. */ -async function poolTargets(deps: PoolDeps, size: number): Promise> { - const targets = new Map([[deps.config.goldenSnapshotId, size]]) +async function poolTargets(deps: PoolDeps, size: number): Promise> { + const goldens = servedGoldens(deps.config) + const targets = new Map(goldens.map(([region, snapshotId]) => [snapshotId, { want: size, region }])) + const regions = goldens.map(([region]) => region) const since = deps.now() - HOT_BUILD_WINDOW_MS // Hot = a workspace was created from the environment lately (not merely built). Most recent first, // so the chosen set is stable tick to tick; capped per account and overall. const hot = await deps.db .prepare( - `SELECT b.snapshot_id AS snapshot_id, e.account_id AS account_id, + `SELECT b.snapshot_id AS snapshot_id, b.region AS region, e.account_id AS account_id, (SELECT MAX(s.created_at) FROM sandboxes s WHERE s.environment_id = e.id) AS used_at FROM environments e JOIN environment_builds b ON b.id = e.active_build_id WHERE e.deleted_at IS NULL AND b.status = 'succeeded' AND b.snapshot_id IS NOT NULL AND b.snapshot_deleted_at IS NULL AND json_extract(b.config, '$.machineSize') = ? - AND b.region = ? AND used_at > ? + AND b.region IN (${regions.map(() => '?').join(', ') || 'NULL'}) AND used_at > ? ORDER BY used_at DESC LIMIT ?` ) - // Pooled VMs boot in the default region; a build snapshot from another region cannot boot there. - .bind(POOLED_SIZE, deps.config.defaultRegion, since, MAX_HOT_BUILDS * 4) - .all<{ snapshot_id: string; account_id: string }>() - .catch(() => ({ results: [] as { snapshot_id: string; account_id: string }[] })) + // A build's VM boots in the build's own region, which must be served. + .bind(POOLED_SIZE, ...regions, since, MAX_HOT_BUILDS * 4) + .all<{ snapshot_id: string; region: string; account_id: string }>() + .catch(() => ({ results: [] as { snapshot_id: string; region: string; account_id: string }[] })) const perAccount = new Map() let hotCount = 0 for (const row of hot.results) { @@ -173,7 +192,7 @@ async function poolTargets(deps: PoolDeps, size: number): Promise { const draining = !pool || (deps.config.guardrails ? await killSwitchOn(deps.db, deps.config.guardrails) : false) const all = (await deps.db.prepare(`SELECT * FROM sandbox_pool WHERE status != 'lease'`).all()).results const maxAge = pool?.maxAgeMs ?? DEFAULT_POOL_MAX_AGE_MS - const targets = draining || !pool ? new Map() : await poolTargets(deps, pool.size) + const targets = draining || !pool ? new Map() : await poolTargets(deps, pool.size) const expired = (vm: PooledVm) => draining || !targets.has(vm.snapshot_id) || @@ -197,7 +216,7 @@ async function maintain(deps: PoolDeps): Promise { for (const vm of keep) { const count = (kept.get(vm.snapshot_id) ?? 0) + 1 kept.set(vm.snapshot_id, count) - if (count > (targets.get(vm.snapshot_id) ?? 0)) { + if (count > (targets.get(vm.snapshot_id)?.want ?? 0)) { extras.push(vm) } } @@ -222,17 +241,19 @@ async function maintain(deps: PoolDeps): Promise { if (draining || !pool) { return { created: 0, recycled, ready: Math.max(0, live) } } - const boots: string[] = [] - for (const [snapshotId, want] of targets) { + const boots: { snapshotId: string; region: string }[] = [] + for (const [snapshotId, { want, region }] of targets) { const have = Math.min(kept.get(snapshotId) ?? 0, want) for (let i = have; i < want; i++) { - boots.push(snapshotId) + boots.push({ snapshotId, region }) } } if (boots.length === 0) { return { created: 0, recycled, ready: Math.max(0, live) } } - const results = await Promise.allSettled(boots.slice(0, MAX_BOOTS_PER_TICK).map((snapshotId) => bootPooledVm(deps, snapshotId))) + const results = await Promise.allSettled( + boots.slice(0, MAX_BOOTS_PER_TICK).map((boot) => bootPooledVm(deps, boot.snapshotId, boot.region)) + ) const created = results.filter((r) => r.status === 'fulfilled').length for (const failure of results.filter((r) => r.status === 'rejected')) { console.log(JSON.stringify({ event: 'pool_boot_failed', error: String(failure.reason).slice(0, 200) })) @@ -240,14 +261,14 @@ async function maintain(deps: PoolDeps): Promise { return { created, recycled, ready: live + created } } -async function bootPooledVm(deps: PoolDeps, snapshotId: string): Promise { +async function bootPooledVm(deps: PoolDeps, snapshotId: string, region: string): Promise { const id = poolId() const now = deps.now() const row: PooledVm = { id, provider_name: `orca-${deps.config.environment}-${id}`, machine_size: POOLED_SIZE, - region: deps.config.defaultRegion, + region, snapshot_id: snapshotId, status: 'warming', session_id: null, diff --git a/cloud/apps/sandbox-control/src/regions.ts b/cloud/apps/sandbox-control/src/regions.ts index d3fe9b879f5..4210f69f760 100644 --- a/cloud/apps/sandbox-control/src/regions.ts +++ b/cloud/apps/sandbox-control/src/regions.ts @@ -7,6 +7,11 @@ // provider error. Automatic, not operator-driven: the create has no state yet and a person is // waiting on it, and a regional capacity blip is over long before anyone could flip a var. // VERCEL_FALLBACK_REGIONS="" turns it off. +// - a desktop create or a new environment with nothing pinned starts in the served region nearest the +// caller (Cloudflare's request geolocation), not always the default: every frame of a remote session +// pays the round trip. Served = the default and its fallbacks that have an active golden (and so a +// warm pool, pool.ts). The environment records its region, so its builds and workspaces stay there. +// VERCEL_NEAREST_REGION=off turns it off. import { ProviderError } from './sandbox-provider' export const DEFAULT_REGION = 'pdx1' @@ -39,3 +44,109 @@ export function isRegionalFailure(error: unknown): boolean { } return error instanceof TypeError } + +/** Where each Vercel region is (approximate city coordinates). A region missing here is never "nearest". */ +const REGION_SITES: Record = { + iad1: [38.9, -77.0], // Washington, D.C. + cle1: [41.5, -81.7], // Cleveland + pdx1: [45.5, -122.7], // Portland + sfo1: [37.8, -122.4], // San Francisco + yul1: [45.5, -73.6], // Montréal + gru1: [-23.6, -46.6], // São Paulo + dub1: [53.3, -6.3], // Dublin + lhr1: [51.5, -0.1], // London + cdg1: [48.9, 2.4], // Paris + fra1: [50.1, 8.7], // Frankfurt + arn1: [59.3, 18.1], // Stockholm + cpt1: [-33.9, 18.4], // Cape Town + dxb1: [25.2, 55.3], // Dubai + bom1: [19.1, 72.9], // Mumbai + sin1: [1.4, 103.8], // Singapore + hkg1: [22.3, 114.2], // Hong Kong + icn1: [37.6, 127.0], // Seoul + kix1: [34.7, 135.5], // Osaka + hnd1: [35.7, 139.7], // Tokyo + syd1: [-33.9, 151.2] // Sydney +} + +/** A rough middle of each continent, for a request Cloudflare located only that far. */ +const CONTINENT_SITES: Record = { + NA: [40, -95], + SA: [-15, -60], + EU: [50, 10], + AF: [5, 20], + AS: [30, 100], + OC: [-25, 140] +} + +export type RequestGeo = { latitude?: number; longitude?: number; continent?: string } + +/** Cloudflare's geolocation of the caller (`request.cf`); null outside the Workers runtime or when it has none. */ +export function requestGeo(request: Request): RequestGeo | null { + const cf = (request as { cf?: { latitude?: unknown; longitude?: unknown; continent?: unknown } }).cf + if (!cf) { + return null + } + const latitude = Number(cf.latitude) + const longitude = Number(cf.longitude) + const continent = typeof cf.continent === 'string' ? cf.continent : undefined + const located = cf.latitude != null && cf.longitude != null && Number.isFinite(latitude) && Number.isFinite(longitude) + if (!located && !continent) { + return null + } + return { ...(located ? { latitude, longitude } : {}), ...(continent ? { continent } : {}) } +} + +/** Great-circle distance in km. */ +function distanceKm(a: readonly [number, number], b: readonly [number, number]): number { + const rad = Math.PI / 180 + const dLat = (b[0] - a[0]) * rad + const dLon = (b[1] - a[1]) * rad + const h = Math.sin(dLat / 2) ** 2 + Math.cos(a[0] * rad) * Math.cos(b[0] * rad) * Math.sin(dLon / 2) ** 2 + return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(h))) +} + +/** + * `served` (default region first) reordered nearest-first for a caller at `geo`. Unchanged when the + * caller can't be located; a region with no known site keeps its place after the located ones. + */ +export function regionsByDistance(geo: RequestGeo | null, served: readonly string[]): string[] { + const at: readonly [number, number] | undefined = + geo?.latitude !== undefined && geo.longitude !== undefined + ? [geo.latitude, geo.longitude] + : geo?.continent + ? CONTINENT_SITES[geo.continent] + : undefined + if (!at) { + return [...served] + } + const ranked = served.map((region, index) => { + const site = REGION_SITES[region] + return { region, index, km: site ? distanceKm(at, site) : Number.POSITIVE_INFINITY } + }) + // Stable: equal distances (and unknown sites) keep the configured order, so the default wins ties. + ranked.sort((a, b) => a.km - b.km || a.index - b.index) + return ranked.map((entry) => entry.region) +} + +/** False when VERCEL_NEAREST_REGION=off: new workspaces and environments start in the default region. */ +export function nearestRegionEnabled(env: { VERCEL_NEAREST_REGION?: string }): boolean { + return env.VERCEL_NEAREST_REGION?.trim() !== 'off' +} + +/** + * The served regions (default first) nearest-first for this request, or undefined (the default region + * decides) when the caller can't be located, there is nothing to choose, or the choice is turned off. + */ +export function nearestRegions(request: Request, served: readonly string[], enabled = true): string[] | undefined { + if (!enabled || served.length < 2) { + return undefined + } + const geo = requestGeo(request) + return geo ? regionsByDistance(geo, served) : undefined +} + +/** The regions new sandboxes may use, default first: each has an active golden image. */ +export function servedRegions(config: { defaultRegion: string; fallbackRegions?: readonly string[] }): string[] { + return [...new Set([config.defaultRegion, ...(config.fallbackRegions ?? [])])] +} diff --git a/cloud/apps/sandbox-control/test/harness.ts b/cloud/apps/sandbox-control/test/harness.ts index 0be90343740..82f28179479 100644 --- a/cloud/apps/sandbox-control/test/harness.ts +++ b/cloud/apps/sandbox-control/test/harness.ts @@ -88,7 +88,8 @@ export async function createHarness(overrides: Partial = {}, extraDeps: Par async function call( method: string, path: string, - init: { body?: unknown; as?: string; bearer?: string; headers?: Record } = {} + /** `cf`: Cloudflare's request properties (geolocation), which the Workers runtime sets on a real request. */ + init: { body?: unknown; as?: string; bearer?: string; headers?: Record; cf?: Record } = {} ) { const bearer = init.bearer ?? (await token(init.as ?? 'alice')) const request = new Request(`https://sandbox.test${path}`, { @@ -96,6 +97,9 @@ export async function createHarness(overrides: Partial = {}, extraDeps: Par headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json', ...init.headers }, body: init.body === undefined ? undefined : JSON.stringify(init.body) }) + if (init.cf) { + Object.defineProperty(request, 'cf', { value: init.cf }) + } const response = await handleRequest(request, env, deps) return { status: response.status, body: (await response.json()) as any } } diff --git a/cloud/apps/sandbox-control/test/nearest-region.test.ts b/cloud/apps/sandbox-control/test/nearest-region.test.ts new file mode 100644 index 00000000000..365b0d7ae8a --- /dev/null +++ b/cloud/apps/sandbox-control/test/nearest-region.test.ts @@ -0,0 +1,219 @@ +// Nearest region: a create or a new environment with nothing pinned starts in the served region +// nearest the caller (Cloudflare's request geolocation); explicit regions and environments win. +import { describe, expect, it } from 'vitest' +import { refreshStaleEnvironments } from '../src/environment-golden-refresh' +import { maintainPool, poolConfigFromEnv, type PoolDeps } from '../src/pool' +import { nearestRegions, regionsByDistance, requestGeo, servedRegions } from '../src/regions' +import { GOLDEN, createHarness } from './harness' + +const SAN_FRANCISCO = { latitude: '37.7749', longitude: '-122.4194', continent: 'NA', country: 'US' } +const NEW_YORK = { latitude: '40.7128', longitude: '-74.0060', continent: 'NA', country: 'US' } +const LONDON = { latitude: '51.5072', longitude: '-0.1276', continent: 'EU', country: 'GB' } +const TOKYO = { latitude: '35.6762', longitude: '139.6503', continent: 'AS', country: 'JP' } +const PDX1_GOLDEN = 'snap_pdx1' +const REPO = 'https://github.com/acme/web.git' + +function located(cf: Record): Request { + const request = new Request('https://sandbox.test/v1/sandboxes') + Object.defineProperty(request, 'cf', { value: cf }) + return request +} + +describe('regionsByDistance', () => { + const served = ['pdx1', 'iad1'] + it('orders the served regions nearest the caller first', () => { + expect(regionsByDistance(requestGeo(located(SAN_FRANCISCO)), served)).toEqual(['pdx1', 'iad1']) + expect(regionsByDistance(requestGeo(located(NEW_YORK)), served)).toEqual(['iad1', 'pdx1']) + expect(regionsByDistance(requestGeo(located(LONDON)), served)).toEqual(['iad1', 'pdx1']) + expect(regionsByDistance(requestGeo(located(TOKYO)), served)).toEqual(['pdx1', 'iad1']) + expect(regionsByDistance(requestGeo(located(LONDON)), ['pdx1', 'iad1', 'fra1'])).toEqual(['fra1', 'iad1', 'pdx1']) + }) + + it('uses the continent when Cloudflare has no coordinates, and keeps the configured order without either', () => { + expect(regionsByDistance({ continent: 'EU' }, served)).toEqual(['iad1', 'pdx1']) + expect(regionsByDistance({ continent: 'XX' }, served)).toEqual(served) + expect(regionsByDistance(null, served)).toEqual(served) + }) + + it('puts a region with no known site after the located ones, in its configured place', () => { + expect(regionsByDistance(requestGeo(located(NEW_YORK)), ['zzz1', 'pdx1', 'iad1'])).toEqual(['iad1', 'pdx1', 'zzz1']) + }) + + it('reads request.cf, and nothing outside the Workers runtime', () => { + expect(requestGeo(located(NEW_YORK))).toEqual({ latitude: 40.7128, longitude: -74.006, continent: 'NA' }) + expect(requestGeo(located({ continent: 'EU' }))).toEqual({ continent: 'EU' }) + expect(requestGeo(located({ latitude: 'x', longitude: '1' }))).toBeNull() + expect(requestGeo(new Request('https://sandbox.test/'))).toBeNull() + }) + + it('decides nothing when off, unlocated, or with a single served region', () => { + expect(nearestRegions(located(NEW_YORK), served)).toEqual(['iad1', 'pdx1']) + expect(nearestRegions(located(NEW_YORK), served, false)).toBeUndefined() + expect(nearestRegions(new Request('https://sandbox.test/'), served)).toBeUndefined() + expect(nearestRegions(located(NEW_YORK), ['pdx1'])).toBeUndefined() + expect(servedRegions({ defaultRegion: 'pdx1', fallbackRegions: ['iad1', 'pdx1'] })).toEqual(['pdx1', 'iad1']) + }) +}) + +/** pdx1 the default and iad1 its fallback, each with an active golden (iad1's is the seed, GOLDEN). */ +async function twoRegions(overrides: Record = {}, waitUntil?: (work: Promise) => void) { + const h = await createHarness({ VERCEL_REGION: 'pdx1', VERCEL_FALLBACK_REGIONS: 'iad1', ...overrides }, waitUntil ? { waitUntil } : {}) + h.raw + .prepare( + `INSERT INTO golden_images (id, region, source, status, snapshot_id, created_at, updated_at, activated_at) + VALUES ('g1', 'pdx1', 'seed', 'active', ?, 1, 1, 1)` + ) + .run(PDX1_GOLDEN) + const box = (id: string) => h.vercel.boxes.get(`orca-test-${id}`)!.params + return { h, box } +} + +describe('nearest region on create', () => { + it('creates in the served region nearest the caller, on that region’s golden', async () => { + const { h, box } = await twoRegions() + const east = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ny', machineSize: 'standard' }, cf: NEW_YORK }) + expect(east.status).toBe(200) + expect(east.body.sandbox.region).toBe('iad1') + expect(box(east.body.sandbox.id)).toMatchObject({ region: 'iad1', snapshotId: GOLDEN }) + const west = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-sf', machineSize: 'standard' }, cf: SAN_FRANCISCO }) + expect(west.body.sandbox.region).toBe('pdx1') + expect(box(west.body.sandbox.id)).toMatchObject({ region: 'pdx1', snapshotId: PDX1_GOLDEN }) + // Unlocated (no request.cf): the default region, as before. + const unknown = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-x', machineSize: 'standard' } }) + expect(unknown.body.sandbox.region).toBe('pdx1') + }) + + it('keeps an explicit region authoritative', async () => { + const { h } = await twoRegions() + const pinned = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard', region: 'pdx1' }, cf: NEW_YORK }) + expect(pinned.body.sandbox.region).toBe('pdx1') + // Pinned means pinned: a capacity failure there is not moved to the nearer region. + h.vercel.failCreateRegions.add('pdx1') + const refused = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-2', machineSize: 'standard', region: 'pdx1' }, cf: NEW_YORK }) + expect(refused.status).not.toBe(200) + }) + + it('never picks a region without an active golden, and falls back to the next nearest on capacity', async () => { + // iad1 is the default here and pdx1 has no image: a caller nearest pdx1 still lands in iad1. + const h = await createHarness({ VERCEL_REGION: 'iad1', VERCEL_FALLBACK_REGIONS: 'pdx1' }) + const west = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-sf', machineSize: 'standard' }, cf: SAN_FRANCISCO }) + expect(west.body.sandbox.region).toBe('iad1') + + const { h: two } = await twoRegions() + two.vercel.failCreateRegions.add('iad1') + const moved = await two.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ny', machineSize: 'standard' }, cf: NEW_YORK }) + expect(moved.status).toBe(200) + expect(moved.body.sandbox.region).toBe('pdx1') + }) + + it('VERCEL_NEAREST_REGION=off keeps every create in the default region', async () => { + const { h } = await twoRegions({ VERCEL_NEAREST_REGION: 'off' }) + const east = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ny', machineSize: 'standard' }, cf: NEW_YORK }) + expect(east.body.sandbox.region).toBe('pdx1') + }) + + it('resumes a sandbox in the region it was created in, wherever the caller is now', async () => { + const { h, box } = await twoRegions() + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ny', machineSize: 'standard' }, cf: NEW_YORK }) + const id = created.body.sandbox.id + expect((await h.call('POST', `/v1/sandboxes/${id}/suspend`, { cf: SAN_FRANCISCO })).status).toBe(200) + const resumed = await h.call('POST', `/v1/sandboxes/${id}/resume`, { cf: SAN_FRANCISCO }) + expect(resumed.status).toBe(200) + expect(resumed.body.sandbox.region).toBe('iad1') + expect(h.vercel.boxes.size).toBe(1) + expect(box(id).region).toBe('iad1') + expect((h.raw.prepare('SELECT region FROM sandboxes WHERE id = ?').get(id) as { region: string }).region).toBe('iad1') + }) +}) + +describe('nearest region for environments', () => { + async function environmentIn(cf: Record) { + const { h, box } = await twoRegions() + h.vercel.buildResult = JSON.stringify({ repos: [{ url: REPO, dir: 'acme/web', branch: 'main', commit: 'a'.repeat(40), lockfiles: {} }] }) + const env = await h.call('POST', '/v1/environments', { body: { name: 'Default', repos: [{ url: 'acme/web' }] }, cf }) + expect(env.status).toBe(200) + const envId = env.body.environment.id as string + const started = await h.call('POST', `/v1/environments/${envId}/builds`, { cf: SAN_FRANCISCO }) + ;[...h.vercel.buildCommands.values()].at(-1)!.exitCode = 0 + const build = (await h.call('GET', `/v1/environments/${envId}/builds/${started.body.build.id}`)).body.build + expect(build.status).toBe('succeeded') + return { h, box, envId, buildId: build.id as string } + } + + it('records the region nearest the admin who creates it, builds there, and boots its workspaces there', async () => { + const { h, box, envId, buildId } = await environmentIn(NEW_YORK) + expect(h.raw.prepare('SELECT region FROM environments WHERE id = ?').get(envId)).toEqual({ region: 'iad1' }) + // Built in iad1 from iad1's golden, whoever pressed Build and wherever they are. + expect(h.raw.prepare('SELECT region, base_snapshot_id FROM environment_builds WHERE id = ?').get(buildId)).toEqual({ region: 'iad1', base_snapshot_id: GOLDEN }) + // A teammate on the west coast boots from it in iad1: the snapshot only boots there. + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-sf', machineSize: 'standard', repo: { url: REPO } }, cf: SAN_FRANCISCO }) + expect(created.status).toBe(200) + expect(created.body.sandbox).toMatchObject({ region: 'iad1', environmentBuildId: buildId }) + expect(box(created.body.sandbox.id).region).toBe('iad1') + }) + + it('compares an environment with its own region’s golden: no refresh churn for an iad1 environment', async () => { + const { h, envId } = await environmentIn(NEW_YORK) + const deps = { + db: h.env.SANDBOX_DB, + provider: h.vercel, + entitlements: { checkStart: async () => h.billing.decision, reportUsage: async () => h.billing.usageAnswer, listSuspensions: async () => [] }, + now: h.now, + config: { environment: 'test', goldenSnapshotId: PDX1_GOLDEN, goldenSnapshots: { pdx1: PDX1_GOLDEN, iad1: GOLDEN }, region: 'pdx1', regions: ['pdx1', 'iad1'] } + } + expect(await refreshStaleEnvironments(deps as never, { minIntervalMs: 0 })).toMatchObject({ stale: 0, started: 0 }) + // An environment from before regions were recorded lives in the default region: its iad1 build is stale. + h.raw.prepare('UPDATE environments SET region = NULL WHERE id = ?').run(envId) + expect(await refreshStaleEnvironments(deps as never, { minIntervalMs: 0 })).toMatchObject({ stale: 1, started: 1 }) + expect(h.raw.prepare('SELECT region, base_snapshot_id FROM environment_builds WHERE environment_id = ? ORDER BY number DESC').get(envId)).toEqual({ + region: 'pdx1', + base_snapshot_id: PDX1_GOLDEN + }) + }) + + it('an environment made in the default region (west coast admin) stays there', async () => { + const { h, envId, buildId } = await environmentIn(SAN_FRANCISCO) + expect(h.raw.prepare('SELECT region FROM environments WHERE id = ?').get(envId)).toEqual({ region: 'pdx1' }) + expect(h.raw.prepare('SELECT region, base_snapshot_id FROM environment_builds WHERE id = ?').get(buildId)).toEqual({ region: 'pdx1', base_snapshot_id: PDX1_GOLDEN }) + }) + + it('an automatic environment lives where the create that made it ran', async () => { + const pending: Promise[] = [] + const { h } = await twoRegions({ AUTO_ENVIRONMENTS: 'on' }, (work) => void pending.push(work)) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } }, cf: NEW_YORK }) + expect(created.body.sandbox.region).toBe('iad1') + while (pending.length > 0) { + await Promise.all(pending.splice(0)) + } + expect(h.raw.prepare(`SELECT region FROM environments WHERE kind = 'auto'`).all()).toEqual([{ region: 'iad1' }]) + expect(h.raw.prepare('SELECT region, base_snapshot_id FROM environment_builds').all()).toEqual([{ region: 'iad1', base_snapshot_id: GOLDEN }]) + }) +}) + +describe('warm pool per served region', () => { + it('keeps warm VMs in every served region, and a create claims one in its nearest region', async () => { + const { h } = await twoRegions({ SANDBOX_POOL_SIZE: '1' }) + const deps: PoolDeps = { + db: h.env.SANDBOX_DB, + provider: h.vercel, + now: h.now, + config: { + environment: 'test', + goldenSnapshotId: PDX1_GOLDEN, + goldenSnapshots: { pdx1: PDX1_GOLDEN, iad1: GOLDEN }, + defaultRegion: 'pdx1', + fallbackRegions: ['iad1'], + pool: poolConfigFromEnv(h.env) + } + } + expect(await maintainPool(deps)).toMatchObject({ created: 2 }) + const pool = () => h.raw.prepare(`SELECT id, region, snapshot_id FROM sandbox_pool WHERE status = 'ready' ORDER BY region`).all() as { id: string; region: string; snapshot_id: string }[] + expect(pool().map(({ region, snapshot_id }) => ({ region, snapshot_id }))).toEqual([ + { region: 'iad1', snapshot_id: GOLDEN }, + { region: 'pdx1', snapshot_id: PDX1_GOLDEN } + ]) + const warmEast = pool().find((vm) => vm.region === 'iad1')!.id + const east = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ny', machineSize: 'standard' }, cf: NEW_YORK }) + expect(east.body.sandbox).toMatchObject({ id: warmEast, region: 'iad1' }) + }) +}) diff --git a/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts b/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts index d3b57499f53..f5729d40d79 100644 --- a/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts +++ b/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts @@ -6,7 +6,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { noteCloudPairingBindings } from '../cloud-workspaces/cloud-paired-environment-ids' -import { createOomTracker, withGitSetup } from './hosted-workspace-runtime' +import { createOomTracker, withGitSetup, withSandboxFacts } from './hosted-workspace-runtime' import { findCloudSandbox } from './cloud-workspace-target' function status(checkedAt: number, uptimeSeconds: number, oomKills: number): HostedWorkspaceStatus { @@ -96,6 +96,12 @@ describe('GIT-SETUP on the status read', () => { expect(withGitSetup(read, {})).toBe(read) }) + it('carries the sandbox region for the card details', () => { + const read = status(1_000, 10, 0) + expect(withSandboxFacts(read, { region: 'iad1' })).toEqual({ ...read, region: 'iad1' }) + expect(withSandboxFacts(read, { region: 'pdx1', gitSetup: 'failed' })).toEqual({ ...read, gitSetupFailed: true, region: 'pdx1' }) + }) + it('the strict sandbox view accepts the field the server sends with feature git-setup', () => { const view = { id: 'sb_1', diff --git a/src/main/hosted-sandbox/hosted-workspace-runtime.ts b/src/main/hosted-sandbox/hosted-workspace-runtime.ts index b674eb7d126..54cd4ac79b0 100644 --- a/src/main/hosted-sandbox/hosted-workspace-runtime.ts +++ b/src/main/hosted-sandbox/hosted-workspace-runtime.ts @@ -168,6 +168,14 @@ export function withGitSetup( return sandbox.gitSetup === 'failed' ? { ...status, gitSetupFailed: true } : status } +/** withGitSetup plus the region the sandbox runs in, for the card's details. */ +export function withSandboxFacts( + status: HostedWorkspaceStatus, + sandbox: Pick +): CloudWorkspaceStatus { + return { ...withGitSetup(status, sandbox), region: sandbox.region } +} + let current: HostedWorkspaceService | null = null export function setHostedWorkspaceService(next: HostedWorkspaceService | null): void { current = next diff --git a/src/main/hosted-sandbox/hosted-workspace-service.ts b/src/main/hosted-sandbox/hosted-workspace-service.ts index ccc89d1172d..2b20115deef 100644 --- a/src/main/hosted-sandbox/hosted-workspace-service.ts +++ b/src/main/hosted-sandbox/hosted-workspace-service.ts @@ -41,7 +41,7 @@ import { findCloudRuntime, readCachedCheckouts, announceWakeUsable, - withGitSetup, + withSandboxFacts, type CloudRuntime } from './hosted-workspace-runtime' @@ -204,7 +204,7 @@ export function installHostedWorkspaceService(deps: { try { const { sandbox, status } = await deps.client.workspaceStatus(found.sandboxId) oom.observe(args.workspaceId, found.sandboxId, status) - return { ok: true, value: withGitSetup(status, sandbox) } + return { ok: true, value: withSandboxFacts(status, sandbox) } } catch (error) { // Gone server-side: prune it now rather than show "Couldn't start" until the next relist. if (isEnvironmentProviderError(error, 'not_found')) { diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx index 28df0f00977..4c84dd78025 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx @@ -7,6 +7,7 @@ import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' import { formatBytes, + formatCloudRegion, formatDuration, formatShortDate, percentOf @@ -146,6 +147,12 @@ export function CloudWorkspaceCardDetails({ value={formatDuration(status.uptimeMs)} /> ) : null} + {status.region ? ( + + ) : null} { expect(percentOf(1, 0)).toBe(0) expect(wakeElapsedSeconds(NOW - 3_400, NOW)).toBe(3) }) + + it('names a region by its city, and shows an unknown one as its code', () => { + expect(formatCloudRegion('pdx1')).toBe('Portland (pdx1)') + expect(formatCloudRegion('iad1')).toBe('Washington, D.C. (iad1)') + expect(formatCloudRegion('zzz9')).toBe('zzz9') + }) }) describe('buildFileTree', () => { diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts index f5cc15b6c47..c2cad9da465 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts @@ -199,6 +199,36 @@ export function formatShortDate(at: number): string { return new Intl.DateTimeFormat(getIntlLocale(), { month: 'short', day: 'numeric' }).format(at) } +// City names are proper nouns: shown as-is in every language. +const REGION_CITIES: Record = { + iad1: 'Washington, D.C.', + cle1: 'Cleveland', + pdx1: 'Portland', + sfo1: 'San Francisco', + yul1: 'Montréal', + gru1: 'São Paulo', + dub1: 'Dublin', + lhr1: 'London', + cdg1: 'Paris', + fra1: 'Frankfurt', + arn1: 'Stockholm', + cpt1: 'Cape Town', + dxb1: 'Dubai', + bom1: 'Mumbai', + sin1: 'Singapore', + hkg1: 'Hong Kong', + icn1: 'Seoul', + kix1: 'Osaka', + hnd1: 'Tokyo', + syd1: 'Sydney' +} + +/** "Portland (pdx1)"; the bare code for a region this build doesn't know. */ +export function formatCloudRegion(region: string): string { + const city = REGION_CITIES[region] + return city ? `${city} (${region})` : region +} + export type DiffStat = { files: number; insertions: number; deletions: number } /** Parses a `--shortstat` line ("2 files changed, 41 insertions(+), 6 deletions(-)"). */ diff --git a/src/shared/hosted-sandbox/cloud-workspace-api.ts b/src/shared/hosted-sandbox/cloud-workspace-api.ts index d69a0fcd4ec..b2d96596b36 100644 --- a/src/shared/hosted-sandbox/cloud-workspace-api.ts +++ b/src/shared/hosted-sandbox/cloud-workspace-api.ts @@ -71,6 +71,8 @@ export type GitHubInstallRights = { admin: boolean; ownerType: 'User' | 'Organiz export type CloudWorkspaceStatus = HostedWorkspaceStatus & { /** GIT-SETUP: commits and pushes are refused in the VM until a boot installs the identities. */ gitSetupFailed?: true + /** The provider region the sandbox runs in (e.g. `pdx1`), from the sandbox view. */ + region?: string } export type CloudArchiveInfo = NonNullable From d1b2394a9a55874735fa16644f102aea3e40936b Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 02:47:25 -0800 Subject: [PATCH 18/35] desktop: type the card details status as CloudWorkspaceStatus (it carries region) --- .../components/orca-cloud/CloudWorkspaceCardDetails.tsx | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx index 4c84dd78025..bfc529b7eee 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceCardDetails.tsx @@ -12,10 +12,8 @@ import { formatShortDate, percentOf } from '@/lib/orca-cloud/orca-cloud-workspace-state' -import { - ORCA_CLOUD_SANDBOX_SPEC, - type HostedWorkspaceStatus -} from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' +import type { CloudWorkspaceStatus } from '../../../../shared/hosted-sandbox/cloud-workspace-api' +import { ORCA_CLOUD_SANDBOX_SPEC } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' const METER_ROWS = 3 @@ -96,7 +94,7 @@ export function CloudWorkspaceCardDetails({ restarting }: { id: string - status: HostedWorkspaceStatus + status: CloudWorkspaceStatus showMeters: boolean restarting: boolean }): React.JSX.Element { From 8a9e198923e7caa425b59e72197de40d299796e4 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 02:48:00 -0800 Subject: [PATCH 19/35] cloud: log each desktop create's region order --- cloud/apps/sandbox-control/src/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index c93f9579677..435dfce40ae 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -1865,6 +1865,8 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise Date: Sun, 15 Nov 2026 02:56:55 -0800 Subject: [PATCH 20/35] cloud: renumber the environment region migration to 0062 (0061 landed concurrently) --- .../{0061_environment_region.sql => 0062_environment_region.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename cloud/apps/sandbox-control/migrations/{0061_environment_region.sql => 0062_environment_region.sql} (100%) diff --git a/cloud/apps/sandbox-control/migrations/0061_environment_region.sql b/cloud/apps/sandbox-control/migrations/0062_environment_region.sql similarity index 100% rename from cloud/apps/sandbox-control/migrations/0061_environment_region.sql rename to cloud/apps/sandbox-control/migrations/0062_environment_region.sql From 22e21d88e154412c9a7c0df01072158bc72264bd Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 02:57:29 -0800 Subject: [PATCH 21/35] feat(cloud): sign in inside the workspace, an alternative to signing in once per agent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A per-person default Source 'in-workspace' for Claude and Codex. Orca stores and injects nothing for that agent: no account placeholder, no API key, and so no egress route on the vendor's hosts. The agent starts as it is and shows its own sign-in in the pane; its token stays in the workspace's home directory and survives sleep. - sandbox-control: migration 0062 widens agent_sources.source (table rebuilt, rows kept); PUT /v1/agent-sources accepts 'in-workspace' as a default only (400 with workspaceId); agentModesFor maps it to 'omit'; GET adds inWorkspace per agent while defaults/effective keep their two values for older desktops. - Desktop: coverage kind 'inWorkspace' (no hold, no per-host sign-in gate on Orca Cloud); 'Set up once' strip gets a quiet ⋯ choice 'Sign in inside this workspace instead' that saves the choice and starts every launch held on it; Settings › Cloud agent sign-ins offers it on a not-set-up row and shows 'Signs in inside each workspace' with a way back. - Tests: Worker (env, open/limited policy, live switch, migration) and renderer (model, hold, spawn gate, strip, settings, build row); fixtures for the strip menu and the settings row. --- .../0062_agent_sources_in_workspace.sql | 17 ++ .../apps/sandbox-control/src/agent-sources.ts | 41 +++-- .../test/agent-sources-in-workspace.test.ts | 161 ++++++++++++++++++ .../agent-credentials-client.ts | 6 +- .../orca-cloud-agents-ipc.ts | 7 +- .../orca-cloud-agents-service.ts | 3 +- src/preload/api/orca-cloud-agents-bridge.ts | 3 +- .../CloudAgentsAndSecretsLink.tsx | 1 + .../CloudAgentsPanelSection.tsx | 4 +- .../cloud-agents-panel-model.ts | 5 +- .../CloudAgentSignInStrip.fixture.tsx | 15 ++ .../CloudAgentSignInStrip.tsx | 25 +++ .../cloud-agent-setup-strip-model.test.ts | 34 ++++ .../cloud-agent-setup-strip-model.ts | 17 +- .../cloud-agent-strip-model.ts | 7 + .../cloud-setup-strip-actions.ts | 11 ++ .../use-cloud-held-strip.ts | 11 +- .../new-workspace/OrcaCloudAgentSetupRow.tsx | 5 + .../agent-accounts/OrcaCloudAccountRow.tsx | 67 +++++++- .../OrcaCloudAccounts.fixture.tsx | 6 + .../agent-accounts/OrcaCloudAccounts.test.tsx | 41 +++++ .../OrcaCloudAccountsSection.tsx | 14 +- .../orca-cloud-accounts-types.ts | 4 +- .../overview/agent-accounts-overview-model.ts | 4 + .../agent-accounts/overview/overview-copy.ts | 5 + .../spawn/agent-sign-in-spawn-gate.ts | 3 + .../cloud-agent-credential-spawn-gate.test.ts | 53 +++++- .../cloud-agent-credential-spawn-gate.ts | 20 ++- src/renderer/src/i18n/locales/en.json | 16 +- .../cloud-agent-launch-hold.test.ts | 34 ++++ .../lib/orca-cloud/cloud-agent-launch-hold.ts | 27 ++- .../cloud-first-start-agent-coverage.ts | 3 +- .../orca-cloud/cloud-running-agent-signout.ts | 1 + .../orca-cloud-agent-accounts-model.test.ts | 55 +++++- .../orca-cloud-agent-accounts-model.ts | 18 ++ .../orca-cloud-agent-accounts-store.ts | 24 +++ .../orca-cloud-agent-picker-status.ts | 1 + .../orca-cloud/orca-cloud-agent-setup-row.ts | 5 +- .../orca-cloud-build-agents-row.test.ts | 9 + .../orca-cloud/orca-cloud-build-agents-row.ts | 7 +- .../orca-cloud-agents-wire.ts | 24 ++- 41 files changed, 754 insertions(+), 60 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0062_agent_sources_in_workspace.sql create mode 100644 cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts diff --git a/cloud/apps/sandbox-control/migrations/0062_agent_sources_in_workspace.sql b/cloud/apps/sandbox-control/migrations/0062_agent_sources_in_workspace.sql new file mode 100644 index 00000000000..343a74a1446 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0062_agent_sources_in_workspace.sql @@ -0,0 +1,17 @@ +-- "Sign in inside this workspace" (agent-sources contract §2): a per-person default Source of +-- 'in-workspace' stores nothing and injects nothing for that agent, so its own login inside each +-- sandbox wins. SQLite can't widen a CHECK in place, so the table is rebuilt with every row kept. +CREATE TABLE agent_sources_next ( + 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', 'in-workspace', 'accepted', 'declined')), + updated_at INTEGER NOT NULL, + PRIMARY KEY (user_id, scope, agent) +); +INSERT INTO agent_sources_next (user_id, account_id, scope, agent, source, updated_at) + SELECT user_id, account_id, scope, agent, source, updated_at FROM agent_sources; +DROP TABLE agent_sources; +ALTER TABLE agent_sources_next RENAME TO agent_sources; +CREATE INDEX agent_sources_scope ON agent_sources (scope); diff --git a/cloud/apps/sandbox-control/src/agent-sources.ts b/cloud/apps/sandbox-control/src/agent-sources.ts index 784bf675bbe..25e3b65ec2e 100644 --- a/cloud/apps/sandbox-control/src/agent-sources.ts +++ b/cloud/apps/sandbox-control/src/agent-sources.ts @@ -1,7 +1,9 @@ // 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). +// A default can also be "Sign in inside this workspace" ('in-workspace'): Orca stores and injects nothing +// for that agent (no account placeholder, no key), and its own login inside each sandbox wins. // GET /v1/agent-sources[?workspaceId=] -// PUT /v1/agent-sources {agent, source: 'sign-in'|'key'|null, workspaceId?} +// PUT /v1/agent-sources {agent, source: 'sign-in'|'key'|'in-workspace'|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 @@ -23,13 +25,16 @@ const OFFER_SCOPE = 'offer' type SourceRow = { scope: string; agent: CredentialAgent; source: string } const AgentSchema = z.enum(['claude', 'codex']) +const IN_WORKSPACE = 'in-workspace' export const PutSourceSchema = z .object({ agent: AgentSchema, - source: z.enum(['sign-in', 'key']).nullable(), + source: z.enum(['sign-in', 'key', IN_WORKSPACE]).nullable(), workspaceId: z.string().min(1).max(128).optional() }) .strict() + // Signing in inside the workspace is a per-person default, never a one-workspace override. + .refine((body) => !(body.source === IN_WORKSPACE && body.workspaceId)) export const PutOfferSchema = z.object({ agent: AgentSchema, answer: z.enum(['accepted', 'declined']) }).strict() export class AgentSourceError extends Error { @@ -60,12 +65,15 @@ function byAgent(rows: SourceRow[], scope: string): Record): 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')) +/** Agents this person signs in inside each workspace (their default is 'in-workspace'). */ +function inWorkspaceAgents(rows: SourceRow[]): Record { + const out = { claude: false, codex: false } as Record + for (const row of rows) { + if (row.scope === DEFAULT_SCOPE && row.source === IN_WORKSPACE) { + out[row.agent] = true + } + } + return out } /** Drops the credential names of agents on "Your sign-in" (after preset derivation, so derived ones go too). */ @@ -111,6 +119,7 @@ export async function agentSourcesView( 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 inWorkspace = inWorkspaceAgents(rows) 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))) @@ -135,6 +144,10 @@ export async function agentSourcesView( if (defaults[agent]) { return [agent, { source: defaults[agent], origin: 'default' }] } + // `source` keeps its two values for older desktops; `inWorkspace` says what this one is. + if (inWorkspace[agent]) { + return [agent, { source: null, origin: 'default' }] + } return [agent, { source: covered[agent] ? 'key' : usable[agent] ? 'sign-in' : null, origin: 'implicit' }] }) ) @@ -145,7 +158,7 @@ export async function agentSourcesView( } // D13: personal accounts never apply in a workspace shared with teammates. const sharedWorkspace = row ? isSharedWorkspace(row) : false - return { defaults, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner, sharedWorkspace } + return { defaults, inWorkspace, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner, sharedWorkspace } } async function upsert(db: D1Database, caller: SandboxCaller, scope: string, agent: CredentialAgent, source: string | null, now: number) { @@ -200,7 +213,8 @@ export async function deleteAgentSourcesForSandbox(db: D1Database, sandboxId: st /** * How each agent authenticates in this session (D10): * - 'account': the owner's Orca-account credential through an egress placeholder (keys for that agent dropped); - * - 'omit': kill-switch fallback (Source sign-in, provider off): keys dropped, the agent's own login in the sandbox; + * - 'omit': the agent's own login in the sandbox, keys dropped: the owner signs in inside each workspace + * ('in-workspace'), or the kill-switch fallback (Source sign-in, provider off); * - 'keep': API keys as resolved (precedence), the default. * Source: explicit (workspace, then default), else implicit: a covering key wins, else a usable account. */ @@ -219,9 +233,16 @@ export async function agentModesFor( const rows = await rowsFor(db, row.user_id, [row.id, DEFAULT_SCOPE]) const workspace = byAgent(rows, row.id) const defaults = byAgent(rows, DEFAULT_SCOPE) + const inWorkspace = inWorkspaceAgents(rows) const covered = coveredByKey(new Set(Object.keys(env))) const modes = {} as Record for (const agent of CREDENTIAL_AGENTS) { + if (!workspace[agent] && inWorkspace[agent]) { + // Nothing of Orca's for this agent: no placeholder, no key, no egress route, so the login the person + // makes inside the sandbox (stored in its home, kept across sleep) reaches the vendor untouched. + modes[agent] = 'omit' + continue + } const explicit = workspace[agent] ?? defaults[agent] const provider = accountProvider(agent) const enabled = options.providerEnabled[agent] && provider !== undefined diff --git a/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts b/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts new file mode 100644 index 00000000000..1a16e447ffd --- /dev/null +++ b/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts @@ -0,0 +1,161 @@ +// "Sign in inside this workspace": a per-person default Source under which Orca stores and injects +// nothing for that agent, so the agent's own login inside the sandbox reaches the vendor untouched. +import { readFileSync, readdirSync } from 'node:fs' +import { DatabaseSync } from 'node:sqlite' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +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 SETUP_TOKEN = 'sk-ant-oat01-FAKEsetupTOKEN_for_tests_only_000000000000' +const TEAM_KEY = 'sk-ant-api03-TEAM-fake-0000-aaaa' +const OPENAI_KEY = 'sk-proj-FAKE-openai-0000-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 [SETUP_TOKEN, TEAM_KEY, OPENAI_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')] + }) + ) +} + +/** Vendor hosts the agents' own sign-in and model calls use. */ +const VENDOR_HOSTS = ['api.anthropic.com', 'claude.ai', 'platform.claude.com', 'console.anthropic.com', 'chatgpt.com', 'auth.openai.com', 'api.openai.com'] + +async function setup(overrides: Record = {}) { + const h = await createHarness({ + SECRETS_KEK: KEK, + EGRESS_PROXY_URL: PROXY_URL, + SECRETS_EGRESS_PLACEHOLDERS: 'on', + AGENT_ACCOUNTS_CLAUDE: 'on', + ...overrides + }) + const as = (sub: string, org?: string, role?: string) => h.token(sub, org, 'sandbox', role ? { orgRole: role } : {}) + const lastEnv = (command: string) => decode(h.vercel.commands.filter((c) => c.command === command).at(-1)?.env.ORCA_SECRET_ENV) + const policy = () => [...h.vercel.boxes.values()].at(-1)!.policy.allow + return { h, as, lastEnv, policy } +} + +describe('Source "in-workspace" (sign in inside this workspace)', () => { + it('injects nothing for that agent even with a stored account and a team key, and leaves its hosts unruled', async () => { + const { h, as, lastEnv, policy } = await setup() + const ada = await as('ada', 'acme', 'admin') + const mia = await as('mia', 'acme', 'member') + await h.call('PUT', '/v1/secrets/org/ANTHROPIC_API_KEY', { bearer: ada, body: { value: TEAM_KEY } }) + await h.call('PUT', '/v1/secrets/personal/OPENAI_API_KEY', { bearer: mia, body: { value: OPENAI_KEY } }) + await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + for (const agent of ['claude', 'codex']) { + const put = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent, source: 'in-workspace' } }) + expect(put.status).toBe(200) + } + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const env = lastEnv(START_COMMAND) + for (const name of ['CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'ORCA_CODEX_AUTH_PLACEHOLDER']) { + expect(env[name]).toBeUndefined() + } + expect(Object.values(env).some((value) => value.startsWith('orca-ph-'))).toBe(false) + // Open egress: "*" plus only hosts that carry rules. No vendor host carries one (no claim, no 403). + const allow = policy() + expect(allow['*']).toEqual([]) + for (const host of VENDOR_HOSTS) { + expect(allow[host]).toBeUndefined() + } + const view = (await h.call('GET', '/v1/agent-sources', { bearer: mia })).body + expect(view.inWorkspace).toEqual({ claude: true, codex: true }) + // Older desktops read `defaults` and `effective.source` with two values only: neither ever says 'in-workspace'. + expect(view.defaults).toEqual({ claude: null, codex: null }) + expect(view.effective.claude).toEqual({ source: null, origin: 'default' }) + }) + + it('limited egress still reaches every vendor sign-in and API host unmodified', async () => { + const { h, as, policy } = await setup({ SANDBOX_EGRESS_PRESET: 'limited' }) + const mia = await as('mia') + await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'in-workspace' } }) + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const allow = policy() + expect(allow['*']).toBeUndefined() + const reachable = (host: string) => { + const parent = `*.${host.split('.').slice(1).join('.')}` + return allow[host] ?? allow[parent] + } + for (const host of VENDOR_HOSTS) { + expect(reachable(host), host).toEqual([]) + } + }) + + it('switching a running workspace\'s owner to it drops the account placeholder live; choosing the account again brings it back', async () => { + const { h, as, lastEnv } = await setup() + const mia = await as('mia') + await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const id: string = created.body.sandbox.id + expect(lastEnv(START_COMMAND).CLAUDE_CODE_OAUTH_TOKEN).toBe(`orca-ph-claude-account-${id}`) + await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'in-workspace' } }) + expect(lastEnv(ENV_COMMAND).CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined() + expect([...h.vercel.boxes.values()][0]!.policy.allow['api.anthropic.com']).toBeUndefined() + await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: null } }) + expect(lastEnv(ENV_COMMAND).CLAUDE_CODE_OAUTH_TOKEN).toBe(`orca-ph-claude-account-${id}`) + }) + + it('is a per-person default only: a workspace override is refused, and an explicit workspace Source still wins', async () => { + const { h, as, lastEnv } = await setup() + const mia = await as('mia') + await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const id: string = created.body.sandbox.id + const refused = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'in-workspace', workspaceId: id } }) + expect(refused.status).toBe(400) + await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in', workspaceId: id } }) + await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'in-workspace' } }) + expect(lastEnv(ENV_COMMAND).CLAUDE_CODE_OAUTH_TOKEN).toBe(`orca-ph-claude-account-${id}`) + }) + + it('the migration keeps every row written before the table was widened', () => { + const dir = fileURLToPath(new URL('../migrations/', import.meta.url).href) + const files = readdirSync(dir).filter((name) => name.endsWith('.sql')).sort() + const widen = files.indexOf('0062_agent_sources_in_workspace.sql') + expect(widen).toBeGreaterThan(0) + const raw = new DatabaseSync(':memory:') + for (const file of files.slice(0, widen)) { + raw.exec(readFileSync(`${dir}${file}`, 'utf8')) + } + const insert = raw.prepare('INSERT INTO agent_sources (user_id, account_id, scope, agent, source, updated_at) VALUES (?, ?, ?, ?, ?, ?)') + insert.run('mia', 'acme', 'default', 'codex', 'key', 1) + insert.run('mia', 'acme', 'offer', 'claude', 'declined', 2) + insert.run('mia', 'acme', 'sbx-1', 'claude', 'sign-in', 3) + expect(() => insert.run('mia', 'acme', 'default', 'claude', 'in-workspace', 4)).toThrow(/CHECK/) + raw.exec(readFileSync(`${dir}${files[widen]}`, 'utf8')) + insert.run('mia', 'acme', 'default', 'claude', 'in-workspace', 4) + expect(raw.prepare('SELECT scope, agent, source, updated_at FROM agent_sources ORDER BY updated_at').all()).toEqual([ + { scope: 'default', agent: 'codex', source: 'key', updated_at: 1 }, + { scope: 'offer', agent: 'claude', source: 'declined', updated_at: 2 }, + { scope: 'sbx-1', agent: 'claude', source: 'sign-in', updated_at: 3 }, + { scope: 'default', agent: 'claude', source: 'in-workspace', updated_at: 4 } + ]) + expect(() => insert.run('mia', 'acme', 'default', 'claude', 'bogus', 5)).toThrow(/CHECK/) + expect(raw.prepare(`SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'agent_sources'`).all()).toContainEqual({ name: 'agent_sources_scope' }) + }) +}) diff --git a/src/main/orca-cloud-agents/agent-credentials-client.ts b/src/main/orca-cloud-agents/agent-credentials-client.ts index 4785bad5a11..e2d0d77f77d 100644 --- a/src/main/orca-cloud-agents/agent-credentials-client.ts +++ b/src/main/orca-cloud-agents/agent-credentials-client.ts @@ -7,6 +7,7 @@ import { CodexBrokerStartResponseSchema, CodexBrokerStatusResponseSchema, type AgentCredentialsView, + type AgentDefaultSourceChoice, type AgentSource, type AgentSourcesView, type CodexBrokerStart, @@ -28,7 +29,10 @@ export type AgentCredentialsClient = { /** Main only, right after setup-token on this computer or a paste. */ putClaude(token: string, label?: string): Promise remove(agent: OrcaCloudAccountAgent): Promise - setDefaultSource(agent: OrcaCloudAccountAgent, source: AgentSource): Promise + setDefaultSource( + agent: OrcaCloudAccountAgent, + source: AgentDefaultSourceChoice + ): Promise /** The Source for one workspace (sandbox id); the reply describes that workspace. */ setWorkspaceSource( agent: OrcaCloudAccountAgent, diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts index 6c58b52b3b6..4c0321f36ed 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts @@ -3,6 +3,7 @@ import { BrowserWindow, app, ipcMain, shell } from 'electron' import { z } from 'zod' import { + IN_WORKSPACE_SOURCE, ORCA_CLOUD_ACCOUNT_AGENTS, type OrcaCloudAgentSetups } from '../../shared/orca-cloud-agents/orca-cloud-agents-wire' @@ -27,6 +28,10 @@ const PasteRequest = z.object({ token: z.string().min(1).max(1024) }) // The code (or callback URL) from Claude's sign-in page; main normalizes it. const CodeRequest = z.object({ code: z.string().min(1).max(2048) }) const SourceRequest = z.object({ agent: Agent, source: z.enum(['sign-in', 'key']).nullable() }) +const DefaultSourceRequest = z.object({ + agent: Agent, + source: z.enum(['sign-in', 'key', IN_WORKSPACE_SOURCE]).nullable() +}) // A runtime environment, never a raw sandbox id: main resolves only sandboxes this desktop made. const RuntimeEnvironment = z.string().min(1).max(256) const WorkspaceRequest = z.object({ runtimeEnvironmentId: RuntimeEnvironment }) @@ -153,7 +158,7 @@ export function registerOrcaCloudAgentsHandlers(userDataPath: string): void { return request.success ? service.remove(request.data.agent) : invalid }) ipcMain.handle('orcaCloudAgents:setDefaultSource', (_event, raw: unknown) => { - const request = SourceRequest.safeParse(raw) + const request = DefaultSourceRequest.safeParse(raw) return request.success ? service.setDefaultSource(request.data.agent, request.data.source) : invalid diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts index 368c01ee56c..c42a8640868 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts @@ -5,6 +5,7 @@ import { CLAUDE_SETUP_TOKEN_PATTERN, IDLE_ORCA_CLOUD_AGENT_SETUPS, type AgentCredentialsView, + type AgentDefaultSourceChoice, type AgentSource, type AgentSourcesView, type OrcaCloudAccountAgent, @@ -339,7 +340,7 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) { setDefaultSource: ( agent: OrcaCloudAccountAgent, - source: AgentSource + source: AgentDefaultSourceChoice ): Promise> => attempt((client) => client.setDefaultSource(agent, source)), diff --git a/src/preload/api/orca-cloud-agents-bridge.ts b/src/preload/api/orca-cloud-agents-bridge.ts index 5323dbcbab4..45d8c4e009c 100644 --- a/src/preload/api/orca-cloud-agents-bridge.ts +++ b/src/preload/api/orca-cloud-agents-bridge.ts @@ -1,6 +1,7 @@ import { ipcRenderer } from 'electron' import type { AgentCredentialsView, + AgentDefaultSourceChoice, AgentSource, AgentSourcesView, OrcaCloudAccountAgent, @@ -29,7 +30,7 @@ export type OrcaCloudAgentsApi = { }) => Promise> setDefaultSource: (request: { agent: OrcaCloudAccountAgent - source: AgentSource + source: AgentDefaultSourceChoice }) => Promise> /** Main's answer (runtime store + pairing bindings): is this runtime environment Orca Cloud? */ isCloudEnvironment: (request: { runtimeEnvironmentId: string }) => Promise diff --git a/src/renderer/src/components/agent-host-panel/CloudAgentsAndSecretsLink.tsx b/src/renderer/src/components/agent-host-panel/CloudAgentsAndSecretsLink.tsx index a52bc959333..eff45fe3e76 100644 --- a/src/renderer/src/components/agent-host-panel/CloudAgentsAndSecretsLink.tsx +++ b/src/renderer/src/components/agent-host-panel/CloudAgentsAndSecretsLink.tsx @@ -47,6 +47,7 @@ export function agentsSummary( break case 'killSwitch': case 'unavailable': + case 'inWorkspace': rest.push( t('agentHostPanel.summary.agentSignsInHere', '{{agent}} signs in for this workspace', { agent diff --git a/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx b/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx index 81e43653140..f4499e7cc9f 100644 --- a/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx +++ b/src/renderer/src/components/agent-host-panel/CloudAgentsPanelSection.tsx @@ -85,7 +85,9 @@ function statusCopy(row: CloudAgentPanelRow, t: Translate): { line: string; deta detail: row.status.reason === 'paused' ? t('vmBuildAgents.paused', 'Orca account sign-in is paused') - : t('vmBuildAgents.notOffered', 'Signs in for each cloud workspace for now') + : row.status.reason === 'chosen' + ? t('agentHostPanel.cloud.signsInHereChosen', 'Orca doesn’t store this sign-in') + : t('vmBuildAgents.notOffered', 'Signs in for each cloud workspace for now') } } } diff --git a/src/renderer/src/components/agent-host-panel/cloud-agents-panel-model.ts b/src/renderer/src/components/agent-host-panel/cloud-agents-panel-model.ts index 119313a3b65..2a07a965b11 100644 --- a/src/renderer/src/components/agent-host-panel/cloud-agents-panel-model.ts +++ b/src/renderer/src/components/agent-host-panel/cloud-agents-panel-model.ts @@ -19,7 +19,7 @@ export type CloudAgentPanelStatus = | { kind: 'notSetUp' } | { kind: 'expired' } /** No account path and no key: the agent signs in inside this workspace (§5c). */ - | { kind: 'signsInHere'; reason: 'paused' | 'notOffered' } + | { kind: 'signsInHere'; reason: 'paused' | 'notOffered' | 'chosen' } /** D13: a shared workspace never uses personal accounts or keys, and no team key covers it. */ | { kind: 'sharedUnavailable' } @@ -96,6 +96,9 @@ export function cloudAgentPanelRows( return { agent, status: { kind: 'signsInHere', reason: 'paused' }, source } case 'unavailable': return { agent, status: { kind: 'signsInHere', reason: 'notOffered' }, source } + case 'inWorkspace': + // Nothing of Orca's applies, so there is no Source to switch here either. + return { agent, status: { kind: 'signsInHere', reason: 'chosen' }, source: null } } }) } diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx index 96da8d236e0..604e6c83542 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx @@ -239,6 +239,21 @@ export const runningRestartFailedNarrow = fixture({ /** PC-3b: the launch holds; Set up once runs the one-time Orca Cloud setup in the pane. */ export const notSetUp = fixture({ setUp: { setup: { phase: 'idle' } } }) export const notSetUpCompact = fixture({ setUp: { setup: { phase: 'idle' } }, width: 320 }) +/** The quiet second choice on "Set up once": the agent signs in inside this workspace instead. */ +export const notSetUpSignInInside = defineFixture({ + width: 940, + render: () => ( +
      + +
      + ), + interact: async (frame) => { + frame + .querySelector('button[aria-label="More choices"]') + ?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) + await new Promise((resolve) => setTimeout(resolve, 200)) + } +}) /** A half-width split: the held strip wraps its detail rather than cutting it off. */ export const notSetUpNarrow = fixture({ setUp: { setup: { phase: 'idle' } }, width: 440 }) export const notSetUpBrowser = fixture({ diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx index 0757f00dc61..57f8bde2427 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx @@ -340,6 +340,31 @@ export function CloudAgentSignInStrip({ ) : null} + {model.alternative && !model.otherWays ? ( + + + + + + model.alternative && actions.primary(model.alternative.action)} + > + {model.alternative.label} + + {model.alternative.detail} + + + + + ) : null} {model.settingsLink && !stacked ? ( ) : null} diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.test.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.test.ts index 52c61eeb922..5fd1c33a8a2 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.test.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.test.ts @@ -112,4 +112,38 @@ describe('cloudAgentSetupStripModel (PC-3b)', () => { primary: { label: 'Start Claude', action: { kind: 'start' } } }) }) + + it('offers signing in inside this workspace as a quiet second choice, only while nothing runs', () => { + const idle = cloudAgentSetupStripModel({ + agent: 'codex', + setup: { phase: 'idle' }, + ready: false, + t + }) + expect(idle.primary?.action).toEqual({ kind: 'setUpOnce' }) + expect(idle.alternative).toEqual({ + label: 'Sign in inside this workspace instead', + detail: 'Orca won’t store your sign-in. You’ll sign in again in each new workspace.', + action: { kind: 'signInInsideWorkspace' } + }) + const failed = cloudAgentSetupStripModel({ + agent: 'claude', + setup: { phase: 'failed', error: 'denied' }, + ready: false, + t + }) + expect(failed.alternative?.action).toEqual({ kind: 'signInInsideWorkspace' }) + for (const setup of [ + { phase: 'browser', startedAt: 1, canReopen: true }, + { phase: 'saving' } + ] as const) { + expect( + cloudAgentSetupStripModel({ agent: 'claude', setup, ready: false, t }).alternative + ).toBeUndefined() + } + expect( + cloudAgentSetupStripModel({ agent: 'claude', setup: { phase: 'idle' }, ready: true, t }) + .alternative + ).toBeUndefined() + }) }) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts index d96fc47f8ba..3cfb831cc44 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts @@ -30,6 +30,20 @@ function base(agent: string, t: Translate): CloudStripModel { } } +/** "Sign in inside this workspace instead": the in-VM login, as a quiet second choice to Set up once. */ +export function signInInsideWorkspaceAlternative( + t: Translate +): NonNullable { + return { + label: t('agentSignInStrip.signInInsideWorkspace', 'Sign in inside this workspace instead'), + detail: t( + 'agentSignInStrip.signInInsideWorkspaceDetail', + 'Orca won’t store your sign-in. You’ll sign in again in each new workspace.' + ), + action: { kind: 'signInInsideWorkspace' } + } +} + /** A detail with `inline code` marks, as one sentence for a screen reader. */ function plainText(text: string): string { return text.replaceAll('`', '') @@ -100,7 +114,7 @@ export function cloudAgentSetupStripModel(args: { switch (setup.phase) { case 'idle': case 'saved': - return need + return { ...need, alternative: signInInsideWorkspaceAlternative(t) } case 'browser': return { ...need, @@ -223,6 +237,7 @@ export function cloudAgentSetupStripModel(args: { action: { kind: 'reopenSetup' } } : { label: t('agentSignInStrip.tryAgain', 'Try again'), action: { kind: 'setUpOnce' } }, + alternative: signInInsideWorkspaceAlternative(t), announcement: copy.title } } diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts index 2929c452ddd..7f814ebbea5 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts @@ -25,6 +25,8 @@ export type CloudStripPrimary = | { kind: 'reopenSetup' } /** PC-3b: the setup finished; start the held agent. */ | { kind: 'start' } + /** The quiet alternative to "Set up once": the agent signs in inside each workspace, Orca stores nothing. */ + | { kind: 'signInInsideWorkspace' } export type CloudStripModel = { status: CloudStripStatus @@ -57,6 +59,11 @@ export type CloudStripModel = { } | null /** "Other ways" under ⋯: the code fallback and the key path. */ otherWays: boolean + /** + * A quiet second choice under ⋯ (the strip has no "Other ways"): a label and one sentence on what + * it means, e.g. "Sign in inside this workspace instead" on "Set up once". + */ + alternative?: { label: string; detail: string; action: CloudStripPrimary } /** Already on a code: ⋯ offers the paste fallback and Cancel instead of "Use a code". */ codeStep?: boolean /** diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts index 1d3e0f03a52..ef9adf4d9bc 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts @@ -10,6 +10,7 @@ import { import { reloadOrcaCloudAgentAccounts, runOrcaCloudAgentSetups, + setOrcaCloudAgentDefaultSource, stopOrcaCloudAgentSetups } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status' @@ -29,6 +30,8 @@ export function cloudSetupStripActions(args: { * running setup and the chat stays held on its strip. Closing the chat gives the launch up. */ keepHoldOnCancel?: boolean + /** The choice wasn't saved (nothing changed; the strip stays on "Set up once"). */ + onSaveFailed?: () => void }): CloudStripActions { const { agent, holdKey } = args const api = window.api?.orcaCloudAgents @@ -44,6 +47,14 @@ export function cloudSetupStripActions(args: { } else if (action.kind === 'start') { // HELD-STALE-COVERED: Start reads the account again; a revoked sign-in shows Renew instead. void startCloudAgentHold(holdKey) + } else if (action.kind === 'signInInsideWorkspace') { + // Remembered for this person and agent. The saved reply releases every launch held on "Set up + // once" for the agent, and each starts as it is, asking for its own sign-in in the pane. + void setOrcaCloudAgentDefaultSource(agent, 'in-workspace').then((error) => { + if (error) { + args.onSaveFailed?.() + } + }) } }, submitCode: (token) => { diff --git a/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts b/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts index 5eec8c4f067..94222e4d497 100644 --- a/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts +++ b/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts @@ -2,6 +2,7 @@ // #40228's per-workspace gate on an Orca Cloud host. Shared by a terminal pane's strip and a structured // chat's (CHAT-BANNERS), so both read the same hold and act the same way. import { openOrcaCloudSignInSheet } from '@/components/settings/agent-accounts/sign-in-sheet/orca-cloud-sign-in-sheet-store' +import { toast } from 'sonner' import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' import { isOrcaCloudEnvironmentId } from '@/lib/orca-cloud/orca-cloud-environment-id' @@ -115,7 +116,12 @@ export function useCloudHeldStrip( copyText: gateActions.copyText, openLink: gateActions.openLink, useApiKey: () => openSettings('cloud-secrets'), - keepHoldOnCancel: chat + keepHoldOnCancel: chat, + onSaveFailed: () => + toast.error( + t('orcaCloudAccounts.error.saveFailed', 'Couldn’t save to your Orca account.'), + { description: t('orcaCloudAccounts.error.nothingChanged', 'Nothing was changed.') } + ) }) : null const gateOrRecovery: CloudStripActions = { @@ -125,7 +131,8 @@ export function useCloudHeldStrip( action.kind === 'restart' || action.kind === 'setUpOnce' || action.kind === 'reopenSetup' || - action.kind === 'start' + action.kind === 'start' || + action.kind === 'signInInsideWorkspace' ) { return } diff --git a/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx b/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx index df27cd4a824..ae3f63263b2 100644 --- a/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx +++ b/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx @@ -29,6 +29,11 @@ export function orcaCloudAgentCoveredLabel( t: Translate ): string { const agent = agentName(row.agent, t) + if (row.via === 'inWorkspace') { + return t('orcaCloudAgentRow.inWorkspace', '{{agent}} · signs in inside the workspace', { + agent + }) + } return row.via === 'account' ? t('orcaCloudAgentRow.fromAccount', '{{agent}} · from your Orca account', { agent }) : t('orcaCloudAgentRow.viaKey', '{{agent}} · {{key}}', { diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx index 7ce77c2f502..72bfad5402b 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx @@ -5,9 +5,10 @@ import { useTranslate } from '@/i18n/use-translate' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import type { OrcaCloudAccountRow } from '@/lib/orca-cloud/orca-cloud-agent-accounts-model' -import type { - OrcaCloudAccountAgent, - OrcaCloudAgentsErrorCode +import { + IN_WORKSPACE_SOURCE, + type OrcaCloudAccountAgent, + type OrcaCloudAgentsErrorCode } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' import { RowShell } from './orca-cloud-account-row-shell' import { @@ -69,21 +70,69 @@ export function AccountRow({ } > - {/* The paste path stays reachable without the browser (RA-5), as a real action (JA-23). */} - {agent === 'claude' ? ( +
      + {/* The paste path stays reachable without the browser (RA-5), as a real action (JA-23). */} + {agent === 'claude' ? ( + + ) : null} + {/* The quiet alternative: the agent's own login inside each workspace; Orca stores nothing. */} - ) : null} +
      ) break + case 'inWorkspace': + content = ( + + void actions.setSource(agent, null).then((error) => { + if (error) { + setRowError(error) + } else if (!row.savedSignIn) { + // Back to signing in once: the one-time setup starts right away. + actions.start(agent) + } + }) + } + > + {useAccount} + + } + /> + ) + break case 'setup': content = break diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx index 55d5d2fd7de..5ca0547f022 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx @@ -79,6 +79,12 @@ export const notSetUp = fixture({ export const loading = fixture(null, { kind: 'loading' }) +/** The person signs in inside each workspace (Codex), Claude not set up yet (offers the same). */ +export const inWorkspace = fixture({ + claude: { kind: 'notSetUp', keyKind: null }, + codex: { kind: 'inWorkspace', savedSignIn: false } +}) + export const settingUpClaude = fixture({ claude: { kind: 'setup', diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx index 1aeee6cf3ce..01fe91d50e1 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx @@ -182,4 +182,45 @@ describe('OrcaCloudAccountsView', () => { fireEvent.click(screen.getByRole('button', { name: 'Sign in' })) expect(handlers.signIn).toHaveBeenCalled() }) + + it('offers signing in inside each workspace as a quiet choice, and switching back starts the setup', async () => { + const handlers = view({ + claude: NOT_SET_UP, + codex: { kind: 'inWorkspace', savedSignIn: false } + }) + const choose = screen.getByRole('button', { name: 'Sign in inside each workspace instead' }) + fireEvent.click(choose) + expect(handlers.setSource).toHaveBeenCalledWith('claude', 'in-workspace') + expect(screen.getByText('Signs in inside each workspace')).toBeTruthy() + expect( + screen.getByText( + 'Orca doesn’t store your ChatGPT sign-in. You sign in again in each new cloud workspace.' + ) + ).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Use my ChatGPT account' })) + expect(handlers.setSource).toHaveBeenCalledWith('codex', null) + await waitFor(() => expect(handlers.start).toHaveBeenCalledWith('codex')) + }) + + it('switching back with a saved sign-in only clears the choice', async () => { + const handlers = view({ claude: { kind: 'inWorkspace', savedSignIn: true }, codex: NOT_SET_UP }) + fireEvent.click(screen.getByRole('button', { name: 'Use my Claude account' })) + await waitFor(() => expect(handlers.setSource).toHaveBeenCalledWith('claude', null)) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(handlers.start).not.toHaveBeenCalled() + }) + + it('a choice that fails to save says so and changes nothing', async () => { + const handlers = view( + { claude: NOT_SET_UP, codex: NOT_SET_UP }, + actions({ setSource: vi.fn(async () => 'unavailable' as const) }) + ) + fireEvent.click( + screen.getAllByRole('button', { name: 'Sign in inside each workspace instead' })[0]! + ) + await waitFor(() => + expect(screen.getByText('Couldn’t save to your Orca account.')).toBeTruthy() + ) + expect(handlers.setSource).toHaveBeenCalledWith('claude', 'in-workspace') + }) }) diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx index 8b708933393..085f99de824 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx @@ -7,8 +7,8 @@ import { useWorktreeCreationClock } from '@/components/worktree-creation/worktre import { orcaCloudAccountRow } from '@/lib/orca-cloud/orca-cloud-agent-accounts-model' import { applyOrcaCloudAgentCredentials, - applyOrcaCloudAgentSources, reloadOrcaCloudAgentAccounts, + setOrcaCloudAgentDefaultSource, useOrcaCloudAgentAccounts } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' import { ORCA_CLOUD_ACCOUNT_AGENTS } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' @@ -66,17 +66,7 @@ export function OrcaCloudAccountsSection({ } return result.error }, - setSource: async (agent, source) => { - if (!api) { - return 'not_configured' - } - const result = await api.setDefaultSource({ agent, source }) - if (result.ok) { - applyOrcaCloudAgentSources(result.value) - return null - } - return result.error - }, + setSource: (agent, source) => setOrcaCloudAgentDefaultSource(agent, source), copyCode: (code) => { void window.api.ui .writeClipboardText(code) diff --git a/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts b/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts index b6c13ba49f1..5df1a6488e6 100644 --- a/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts +++ b/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-types.ts @@ -2,6 +2,7 @@ import type { OrcaCloudAccountRow } from '@/lib/orca-cloud/orca-cloud-agent-accounts-model' import type { OrcaCloudAgentAccountsLoad } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' import type { + AgentDefaultSourceChoice, OrcaCloudAccountAgent, OrcaCloudAgentsErrorCode } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' @@ -16,9 +17,10 @@ export type OrcaCloudAccountsActions = { /** Resolves with a code when the token wasn't stored; the value is never echoed back. */ pasteToken: (token: string) => Promise remove: (agent: OrcaCloudAccountAgent) => Promise + /** A default Source; null clears it ('in-workspace': sign in inside each workspace). */ setSource: ( agent: OrcaCloudAccountAgent, - source: 'sign-in' | 'key' + source: AgentDefaultSourceChoice ) => Promise copyCode: (code: string) => void retryLoad: () => void diff --git a/src/renderer/src/components/settings/agent-accounts/overview/agent-accounts-overview-model.ts b/src/renderer/src/components/settings/agent-accounts/overview/agent-accounts-overview-model.ts index a28b2b1348c..b04c8513870 100644 --- a/src/renderer/src/components/settings/agent-accounts/overview/agent-accounts-overview-model.ts +++ b/src/renderer/src/components/settings/agent-accounts/overview/agent-accounts-overview-model.ts @@ -40,6 +40,8 @@ export type OverviewCell = | { kind: 'cloudExpired' } | { kind: 'cloudPaused' } | { kind: 'cloudNotOffered' } + /** The person signs this agent in inside each workspace (their choice). */ + | { kind: 'cloudInWorkspace' } export type OverviewHost = { hostId: ExecutionHostId @@ -161,6 +163,8 @@ function cloudCell( return { kind: 'cloudPaused' } case 'unavailable': return { kind: 'cloudNotOffered' } + case 'inWorkspace': + return { kind: 'cloudInWorkspace' } } } diff --git a/src/renderer/src/components/settings/agent-accounts/overview/overview-copy.ts b/src/renderer/src/components/settings/agent-accounts/overview/overview-copy.ts index eaeeb8c0d84..22e2d934cf2 100644 --- a/src/renderer/src/components/settings/agent-accounts/overview/overview-copy.ts +++ b/src/renderer/src/components/settings/agent-accounts/overview/overview-copy.ts @@ -76,6 +76,11 @@ export function overviewCellText( text: t('vmBuildAgents.notOffered', 'Signs in for each cloud workspace for now'), tone: 'muted' } + case 'cloudInWorkspace': + return { + text: t('orcaCloudAccounts.inWorkspace', 'Signs in inside each workspace'), + tone: 'muted' + } } } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/spawn/agent-sign-in-spawn-gate.ts b/src/renderer/src/components/terminal-pane/pty-connection/spawn/agent-sign-in-spawn-gate.ts index 86e7913e9ea..8676aeef3cf 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/spawn/agent-sign-in-spawn-gate.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/spawn/agent-sign-in-spawn-gate.ts @@ -95,6 +95,9 @@ export function gateFreshSpawnOnAgentSignIn( /** A first Claude/Codex launch on a signed-out host waits for its inline sign-in. */ export function installAgentSignInSpawnGate(session: ConnectPanePtySession): void { const start = session.startFreshSpawn + // For a layer outside this gate whose launch must reach the host unasked (an Orca Cloud agent the + // person signs in inside the workspace, in the agent itself). + session.startFreshSpawnWithoutSignInGate = start session.startFreshSpawn = (startupOverride, options) => { const request = agentSignInGateRequest(session, startupOverride) return request diff --git a/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.test.ts index 09eda2ed78d..4a05ad0d84f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.test.ts @@ -5,8 +5,9 @@ const state = vi.hoisted(() => { const value: { needsHold: boolean | null mainSays: boolean - release: ((outcome: 'start' | 'cancel') => void) | null - } = { needsHold: true, mainSays: true, release: null } + inside: boolean + release: ((outcome: 'proceed' | 'cancel') => void) | null + } = { needsHold: true, mainSays: true, inside: false, release: null } return value }) @@ -20,6 +21,7 @@ vi.mock('./agent-sign-in-spawn-gate', () => ({ })) vi.mock('@/lib/orca-cloud/cloud-agent-launch-hold', () => ({ cloudAgentLaunchNeedsHold: () => state.needsHold, + cloudAgentSignsInInsideWorkspace: () => state.inside, holdCloudAgentLaunch: () => new Promise((resolve) => { state.release = resolve @@ -37,17 +39,26 @@ const { installCloudAgentCredentialGate } = await import('./cloud-agent-credenti const flush = () => new Promise((resolve) => setTimeout(resolve, 0)) function session() { + // `start` is the launch behind #40228's per-host gate; `ungated` the one in front of it. const start = vi.fn(async (_startup?: unknown, _options?: unknown) => 'pty-1') - const value = { startFreshSpawn: start, disposed: false, pendingSpawnKey: 'k', tabGeneration: 1 } + const ungated = vi.fn(async (_startup?: unknown, _options?: unknown) => 'pty-own-sign-in') + const value = { + startFreshSpawn: start, + startFreshSpawnWithoutSignInGate: ungated, + disposed: false, + pendingSpawnKey: 'k', + tabGeneration: 1 + } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the gate reads only these fields installCloudAgentCredentialGate(value as unknown as ConnectPanePtySession) - return { value, start } + return { value, start, ungated } } describe('cloud agent credential spawn gate (FAIL-CLOSED, #568)', () => { beforeEach(() => { state.needsHold = true state.mainSays = true + state.inside = false state.release = null }) @@ -57,7 +68,7 @@ describe('cloud agent credential spawn gate (FAIL-CLOSED, #568)', () => { await flush() expect(start).not.toHaveBeenCalled() expect(state.release).not.toBeNull() - state.release?.('start') + state.release?.('proceed') await expect(spawned).resolves.toBe('pty-1') expect(start).toHaveBeenCalledOnce() }) @@ -77,4 +88,36 @@ describe('cloud agent credential spawn gate (FAIL-CLOSED, #568)', () => { expect(start).toHaveBeenCalledOnce() expect(state.release).toBeNull() }) + + it('signing in inside the workspace starts the agent past every gate, so its own sign-in shows', async () => { + state.needsHold = false + state.inside = true + const { value, start, ungated } = session() + await expect(value.startFreshSpawn(undefined, {})).resolves.toBe('pty-own-sign-in') + expect(ungated).toHaveBeenCalledOnce() + expect(start).not.toHaveBeenCalled() + expect(state.release).toBeNull() + }) + + it('signing in inside the workspace never skips the per-host gate on a host that is not Orca Cloud', async () => { + state.needsHold = false + state.inside = true + state.mainSays = false + const { value, start, ungated } = session() + await expect(value.startFreshSpawn(undefined, {})).resolves.toBe('pty-1') + expect(start).toHaveBeenCalledOnce() + expect(ungated).not.toHaveBeenCalled() + }) + + it('a launch held on "Set up once" whose person chooses to sign in inside starts past the per-host gate', async () => { + const { value, start, ungated } = session() + const spawned = value.startFreshSpawn(undefined, {}) + await flush() + expect(state.release).not.toBeNull() + state.inside = true + state.release?.('proceed') + await expect(spawned).resolves.toBe('pty-own-sign-in') + expect(ungated).toHaveBeenCalledOnce() + expect(start).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.ts b/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.ts index 027c54b2442..32dbd273577 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/spawn/cloud-agent-credential-spawn-gate.ts @@ -1,9 +1,12 @@ // Private layer, Orca Cloud only: a fresh Claude/Codex launch whose Orca-account sign-in expired // (and no key covers it) waits on the account-recovery strip before #40228's per-host gate runs. // Installed outside that gate, so it wraps it; it reads #40228's exports and changes none of them. +// An agent the person signs in inside each workspace skips both: it starts as it is, and its own +// sign-in shows in the pane (the vendor's flow, its token kept in the workspace). import { useAppStore } from '@/store/index' import { cloudAgentLaunchNeedsHold, + cloudAgentSignsInInsideWorkspace, holdCloudAgentLaunch } from '@/lib/orca-cloud/cloud-agent-launch-hold' import { isOrcaCloudEnvironmentForLaunch } from '@/lib/orca-cloud/orca-cloud-environment-id' @@ -21,12 +24,22 @@ function isOrcaCloudEnvironment(environmentId: string): boolean { export function installCloudAgentCredentialGate(session: ConnectPanePtySession): void { const start = session.startFreshSpawn + const ungated: typeof start = session.startFreshSpawnWithoutSignInGate ?? start session.startFreshSpawn = (startupOverride, options) => { const request = agentSignInGateRequest(session, startupOverride) // Ready (or covered by a key): no hold, no delay; the launch starts as it always did. - if (!request || cloudAgentLaunchNeedsHold(request.agent) === false) { + if ( + !request || + (cloudAgentLaunchNeedsHold(request.agent) === false && + !cloudAgentSignsInInsideWorkspace(request.agent)) + ) { return start(startupOverride, options) } + // Read when the launch goes ahead: the choice may have been made on the strip that held it. + const launch = (override: typeof startupOverride) => + cloudAgentSignsInInsideWorkspace(request.agent) + ? ungated(override, options) + : start(override, options) // FAIL-CLOSED (#568): the catalog flag can lag a fresh pairing, so without it main is asked // before the agent may start; until it answers, nothing is spawned. const cloud = isOrcaCloudEnvironment(request.environmentId) @@ -39,6 +52,9 @@ export function installCloudAgentCredentialGate(session: ConnectPanePtySession): if (!isCloud) { return start(startupOverride, options) } + if (cloudAgentSignsInInsideWorkspace(request.agent)) { + return launch(startupOverride) + } return holdCloudAgentLaunch({ paneKey: request.key, agent: request.agent, @@ -48,7 +64,7 @@ export function installCloudAgentCredentialGate(session: ConnectPanePtySession): return null } // Cancel opens a plain shell, like cancelling the per-host sign-in. - return outcome === 'cancel' ? start(null, options) : start(startupOverride, options) + return outcome === 'cancel' ? start(null, options) : launch(startupOverride) }) }) // A remount while held waits for this launch instead of starting a second agent. diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index daeca2cb785..9bf33c0da6d 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28350,7 +28350,8 @@ "failed": "Couldn’t load your agent accounts.", "sharedUnavailable": "Not available in shared workspaces", "sharedUnavailableDetail": "Personal accounts aren’t used in shared workspaces. Ask an owner or admin to add a team key.", - "expiredDetailCloudSignIns": "Renew it once in Cloud agent sign-ins." + "expiredDetailCloudSignIns": "Renew it once in Cloud agent sign-ins.", + "signsInHereChosen": "Orca doesn’t store this sign-in" }, "kind": { "local": "This computer", @@ -28568,7 +28569,8 @@ "checking": "Checking {{agent}}", "notSetUpCloudSignIns": "{{agent}} isn’t set up for Orca Cloud yet. Set it up once in Settings → Cloud agent sign-ins.", "expiredCloudSignIns": "Your {{agent}} sign-in for Orca Cloud expired. Renew it once in Settings → Cloud agent sign-ins.", - "signedOutCloudSignIns": "{{agent}}: set up once in Settings → Cloud agent sign-ins after you sign in" + "signedOutCloudSignIns": "{{agent}}: set up once in Settings → Cloud agent sign-ins after you sign in", + "inWorkspace": "{{agent}} · signs in inside the workspace" }, "orcaCloudAccounts": { "paste": { @@ -28681,7 +28683,10 @@ "pasteTokenInstead": "Paste a token instead", "rowMenu": "{{agent}} account options", "helpAccountWide": "Set up once. Every cloud workspace uses it, including new, cloned and restarted ones.", - "deviceCodeOffHint": "If OpenAI says device code sign-in is off, turn it on in ChatGPT → Settings → Security, then try again." + "deviceCodeOffHint": "If OpenAI says device code sign-in is off, turn it on in ChatGPT → Settings → Security, then try again.", + "signInInsideWorkspace": "Sign in inside each workspace instead", + "inWorkspace": "Signs in inside each workspace", + "inWorkspaceDetail": "Orca doesn’t store your {{product}} sign-in. You sign in again in each new cloud workspace." }, "vmBuildAgents": { "menu": { @@ -28854,7 +28859,10 @@ "pasteTokenRejectedDetail": "Paste the full token from `claude setup-token`, or run it again.", "setupTokenPlaceholder": "Paste token", "pasteAgentTokenTitle": "Paste a {{agent}} token", - "pasteAgentTokenDetail": "Run `claude setup-token` in any terminal where {{agent}} is installed, then paste the token here. It’s saved to your Orca account, never to a sandbox." + "pasteAgentTokenDetail": "Run `claude setup-token` in any terminal where {{agent}} is installed, then paste the token here. It’s saved to your Orca account, never to a sandbox.", + "moreChoices": "More choices", + "signInInsideWorkspace": "Sign in inside this workspace instead", + "signInInsideWorkspaceDetail": "Orca won’t store your sign-in. You’ll sign in again in each new workspace." }, "cloudSetupPage": { "back": "Back", diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts index 53edf0cd0b2..fdc6323500e 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts @@ -5,6 +5,7 @@ import { cloudAgentHoldReason, cloudAgentLaunchHoldReason, cloudAgentLaunchNeedsHold, + cloudAgentSignsInInsideWorkspace, cloudAgentStripReason, holdCloudAgentLaunch, readCloudAgentHold, @@ -157,4 +158,37 @@ describe('cloud agent launch hold', () => { ).resolves.toBe('proceed') expect(readCloudAgentHold('tab:e')).toBeNull() }) + + it('signing in inside the workspace never holds, and choosing it on "Set up once" starts the held launch', async () => { + const inside = (state: OrcaCloudAgentAccountsState): OrcaCloudAgentAccountsState => + state.load.kind === 'ready' + ? { + ...state, + load: { + kind: 'ready', + status: { + ...state.load.status, + sources: { + ...state.load.status.sources, + inWorkspace: { claude: true, codex: false } + } + } + } + } + : state + // Even with an expired account: Orca injects nothing for the agent, so there is nothing to renew. + expect(cloudAgentHoldReason('claude', inside(accounts({ state: 'expired' })))).toBeNull() + expect(cloudAgentStripReason('claude', inside(accounts({ state: 'expired' })))).toBeNull() + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'none' })) + expect(cloudAgentSignsInInsideWorkspace('claude')).toBe(false) + const held = holdCloudAgentLaunch({ paneKey: 'tab:f', agent: 'claude', prompt: null }) + await vi.waitFor(() => + expect(readCloudAgentHold('tab:f')).toMatchObject({ reason: 'notSetUp' }) + ) + setOrcaCloudAgentAccountsStateForTest(inside(accounts({ state: 'none' }))) + await expect(held).resolves.toBe('proceed') + expect(readCloudAgentHold('tab:f')).toBeNull() + expect(cloudAgentSignsInInsideWorkspace('claude')).toBe(true) + expect(cloudAgentLaunchNeedsHold('claude')).toBe(false) + }) }) diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts index fbe3faed7c0..f3f1d99b6a2 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts @@ -3,7 +3,8 @@ // (S4-c, card 13) until Renew in S0 fixes it for every workspace. Not set up with no key (PC-3b): // the pane holds on the "Set up once" strip, which runs S0 inline and then offers "Start {{agent}}". // Kill switch or a provider never offered: no hold here; the per-workspace sign-in (#40228's gate) -// runs and the strip shows it. +// runs and the strip shows it. Signing in inside the workspace (the person's choice): no hold and no +// gate either; the agent starts as it is and shows its own sign-in in the pane. import { useSyncExternalStore } from 'react' import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status' import { orcaCloudAgentCoverageFromAccounts } from './orca-cloud-agent-accounts-model' @@ -35,6 +36,7 @@ export function cloudAgentStripReason( case 'account': case 'key': case 'notSetUp': + case 'inWorkspace': return null } } @@ -65,6 +67,7 @@ export function cloudAgentHoldReason( case 'key': case 'killSwitch': case 'unavailable': + case 'inWorkspace': return null } // A coverage kind added later starts the launch rather than holding on an unknown state. @@ -83,6 +86,17 @@ export function cloudAgentLaunchHoldReason( return accounts.load.kind === 'loading' ? 'unknown' : cloudAgentHoldReason(agent, accounts) } +/** + * The person signs this agent in inside each cloud workspace (from the cached read): its launch + * starts with nothing in front of it, neither a hold nor the per-host sign-in gate, so the agent's + * own sign-in shows in the pane and its token stays in the workspace. + */ +export function cloudAgentSignsInInsideWorkspace(agent: HostAgentSignInAgent): boolean { + return ( + orcaCloudAgentCoverageFromAccounts(agent, readOrcaCloudAgentAccounts())?.kind === 'inWorkspace' + ) +} + export type CloudAgentHold = { paneKey: string agent: HostAgentSignInAgent @@ -316,6 +330,12 @@ function redecide(entry: Entry, accounts: OrcaCloudAgentAccountsState): void { return } const coverage = orcaCloudAgentCoverageFromAccounts(entry.agent, accounts)?.kind + if (coverage === 'inWorkspace') { + // "Sign in inside this workspace instead", chosen from this strip or from Settings: nothing is + // left to wait for, so the agent starts and asks for its own sign-in in the pane. + entry.release('proceed') + return + } if (coverage !== 'account' && coverage !== 'key') { return } @@ -357,7 +377,10 @@ export async function startCloudAgentHold(paneKey: string): Promise<'started' | } const now = cloudAgentHoldReason(entry.agent, accounts) const coverage = orcaCloudAgentCoverageFromAccounts(entry.agent, accounts)?.kind - if (now !== null || (coverage !== 'account' && coverage !== 'key')) { + if ( + now !== null || + (coverage !== 'account' && coverage !== 'key' && coverage !== 'inWorkspace') + ) { if (now !== null && now !== entry.reason) { holds.set(paneKey, { ...entry, reason: now, awaiting: undefined }) notify() diff --git a/src/renderer/src/lib/orca-cloud/cloud-first-start-agent-coverage.ts b/src/renderer/src/lib/orca-cloud/cloud-first-start-agent-coverage.ts index 4f625c19f8a..59b9960ae39 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-first-start-agent-coverage.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-first-start-agent-coverage.ts @@ -11,7 +11,8 @@ let latest: { agent: string; coverage: Coverage } | null = null function coverageOf(row: OrcaCloudAgentSetupRowModel): Coverage { switch (row.kind) { case 'covered': - return row.via === 'account' ? 'account' : 'key' + // Signing in inside the workspace: nothing of Orca's covers the agent (the schema's 'none'). + return row.via === 'inWorkspace' ? 'none' : row.via === 'account' ? 'account' : 'key' case 'notSetUp': case 'expired': case 'killSwitch': diff --git a/src/renderer/src/lib/orca-cloud/cloud-running-agent-signout.ts b/src/renderer/src/lib/orca-cloud/cloud-running-agent-signout.ts index c4f140183c0..355e51b8360 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-running-agent-signout.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-running-agent-signout.ts @@ -139,6 +139,7 @@ export function cloudRunningStrip(args: { case 'killSwitch': case 'unavailable': case 'notSetUp': + case 'inWorkspace': return null } } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.test.ts index a889a2b2148..b1399986a89 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.test.ts @@ -13,6 +13,10 @@ function status(overrides: { provider?: 'on' | 'off' | 'disabled' covered?: boolean defaultSource?: 'sign-in' | 'key' | null + /** The person signs Claude in inside each workspace. */ + inWorkspace?: boolean + /** The view is for one workspace whose own Source overrides the default. */ + workspaceOverride?: 'sign-in' | 'key' }): OrcaCloudAgentsStatus { return { credentials: { @@ -23,7 +27,13 @@ function status(overrides: { }, sources: { defaults: { claude: overrides.defaultSource ?? null }, - coveredByKey: { claude: overrides.covered ?? false, codex: false } + coveredByKey: { claude: overrides.covered ?? false, codex: false }, + ...(overrides.inWorkspace !== undefined + ? { inWorkspace: { claude: overrides.inWorkspace, codex: false } } + : {}), + ...(overrides.workspaceOverride + ? { effective: { claude: { source: overrides.workspaceOverride, origin: 'workspace' } } } + : {}) } } } @@ -171,3 +181,46 @@ describe('orcaCloudAgentCoverage', () => { ).toEqual({ kind: 'key', keyKind: 'personal' }) }) }) + +describe('signing in inside each workspace', () => { + it('wins over a stored account and a covering key, in the S0 row and the coverage', () => { + const chosen = status({ claude: ACTIVE, covered: true, inWorkspace: true }) + expect(orcaCloudAccountRow('claude', chosen, IDLE, 'team')).toEqual({ + kind: 'inWorkspace', + savedSignIn: true + }) + expect(orcaCloudAgentCoverage('claude', chosen, 'team')).toEqual({ kind: 'inWorkspace' }) + expect(orcaCloudAccountRow('claude', status({ inWorkspace: true }), IDLE, null)).toEqual({ + kind: 'inWorkspace', + savedSignIn: false + }) + // Codex keeps its own Source. + expect(orcaCloudAgentCoverage('codex', chosen, null)).toEqual({ kind: 'notSetUp' }) + }) + + it('gives way to a running setup, a provider that is off, and a workspace override', () => { + const browser = { phase: 'browser', startedAt: 1, canReopen: true } as const + expect(orcaCloudAccountRow('claude', status({ inWorkspace: true }), browser, null).kind).toBe( + 'setup' + ) + expect( + orcaCloudAccountRow( + 'claude', + status({ inWorkspace: true, provider: 'off', enabled: false }), + IDLE, + null + ) + ).toEqual({ kind: 'unavailable' }) + expect( + orcaCloudAgentCoverage( + 'claude', + status({ claude: ACTIVE, inWorkspace: true, workspaceOverride: 'sign-in' }), + null + ) + ).toEqual({ kind: 'account' }) + }) + + it('an older server without the field changes nothing', () => { + expect(orcaCloudAgentCoverage('claude', status({}), null)).toEqual({ kind: 'notSetUp' }) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts index d854dcbf891..07151e02503 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts @@ -4,6 +4,7 @@ import type { CloudEffectiveSecret } from '../../../../shared/cloud-secrets/clou import { isUsableAgentCredential, orcaCloudProviderState, + signsInInsideWorkspace, type AgentKeyKind, type OrcaCloudAccountAgent, type OrcaCloudAgentSetup, @@ -68,6 +69,11 @@ export type OrcaCloudAccountRow = | { kind: 'killSwitch' } /** This server never offered the provider (flag off): nothing to set up, nothing paused. */ | { kind: 'unavailable' } + /** + * The person chose to sign in inside each workspace: Orca stores and injects nothing for the agent. + * `savedSignIn`: a sign-in once is still saved (set up elsewhere) and applies again if chosen. + */ + | { kind: 'inWorkspace'; savedSignIn: boolean } export function orcaCloudAccountRow( agent: OrcaCloudAccountAgent, @@ -92,6 +98,9 @@ export function orcaCloudAccountRow( if (setup.phase !== 'idle' && setup.phase !== 'saved') { return { kind: 'setup', setup } } + if (signsInInsideWorkspace(status.sources, agent)) { + return { kind: 'inWorkspace', savedSignIn: isUsableAgentCredential(credential.state) } + } if (credential.state === 'none') { return { kind: 'notSetUp', keyKind: fallbackKey } } @@ -124,6 +133,11 @@ export type OrcaCloudAgentCoverage = | { kind: 'killSwitch' } /** Flag off without a key: no Orca-account path here, so nothing to show. */ | { kind: 'unavailable' } + /** + * The person signs in inside each workspace: no account, no key, nothing held. The agent starts + * as it is and shows its own sign-in in the pane. + */ + | { kind: 'inWorkspace' } export function orcaCloudAgentCoverage( agent: OrcaCloudAccountAgent, @@ -136,6 +150,10 @@ export function orcaCloudAgentCoverage( const usable = provider === 'on' && isUsableAgentCredential(credential.state) const source = status.sources.effective?.[agent]?.source ?? status.sources.defaults[agent] ?? null const key: OrcaCloudAgentCoverage = { kind: 'key', keyKind: keyKind ?? 'team' } + // The control plane injects nothing for this agent then, whatever is stored or covers it. + if (signsInInsideWorkspace(status.sources, agent)) { + return { kind: 'inWorkspace' } + } if (usable && (source === 'sign-in' || !covered)) { return { kind: 'account' } } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts index baa5f797ef6..f0c522bb040 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts @@ -5,6 +5,7 @@ import { IDLE_ORCA_CLOUD_AGENT_SETUPS, ORCA_CLOUD_ACCOUNT_AGENTS, type AgentCredentialsView, + type AgentDefaultSourceChoice, type AgentKeyKind, type AgentSourcesView, type OrcaCloudAccountAgent, @@ -233,6 +234,29 @@ export function applyOrcaCloudAgentSources(sources: AgentSourcesView): void { } } +/** + * Saves a default Source and applies the reply (Settings and the "Set up once" strip). Resolves with + * an error code when nothing was saved. 'in-workspace': Orca stores and injects nothing for the agent. + */ +export async function setOrcaCloudAgentDefaultSource( + agent: OrcaCloudAccountAgent, + source: AgentDefaultSourceChoice +): Promise { + const api = bridge() + if (!api) { + return 'not_configured' + } + const result = await api.setDefaultSource({ agent, source }).catch(() => null) + if (!result) { + return 'unknown' + } + if (!result.ok) { + return result.error + } + applyOrcaCloudAgentSources(result.value) + return null +} + /** Fixtures and tests only. */ export function setOrcaCloudAgentAccountsStateForTest(next: OrcaCloudAgentAccountsState): void { started = true diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.ts index d6c8a43726a..ddcd61e4353 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.ts @@ -67,6 +67,7 @@ export function orcaCloudAgentPickerStatus( return 'setUp' case 'killSwitch': case 'unavailable': + case 'inWorkspace': return 'perWorkspace' } } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-setup-row.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-setup-row.ts index b9acb521a8f..1e80f17f2fe 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-setup-row.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-setup-row.ts @@ -13,7 +13,7 @@ export type OrcaCloudAgentSetupRowModel = | { kind: 'hidden' } | { kind: 'loading'; agent: OrcaCloudAccountAgent } /** Collapsed to one line: nothing to do. */ - | { kind: 'covered'; agent: OrcaCloudAccountAgent; via: 'account' | AgentKeyKind } + | { kind: 'covered'; agent: OrcaCloudAccountAgent; via: 'account' | 'inWorkspace' | AgentKeyKind } | { kind: 'notSetUp'; agent: OrcaCloudAccountAgent } | { kind: 'expired'; agent: OrcaCloudAccountAgent } /** §5c, info only. */ @@ -81,5 +81,8 @@ export function orcaCloudAgentSetupRow({ case 'unavailable': // Never offered here: like an agent without an account path, the composer shows no row. return { kind: 'hidden' } + case 'inWorkspace': + // The person's own choice: nothing to set up, so the row is done. + return { kind: 'covered', agent, via: 'inWorkspace' } } } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts index 6c934a2fac5..53864ddf50d 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts @@ -146,4 +146,13 @@ describe('buildAgentsRow', () => { expect(row({ ...base, load: { kind: 'unavailable' } })).toEqual({ kind: 'hidden' }) expect(buildAgentsRowDensity({ kind: 'loading' })).toBe('twoLine') }) + + it('never offers the one-time setup for an agent signed in inside each workspace', () => { + const inside = (claude: boolean, codex: boolean): OrcaCloudAgentsStatus => ({ + ...NONE, + sources: { ...NONE.sources, inWorkspace: { claude, codex } } + }) + expect(row(accounts(inside(true, false)))).toEqual({ kind: 'offer', agents: ['codex'] }) + expect(row(accounts(inside(true, true)))).toEqual({ kind: 'hidden' }) + }) }) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts index f01d3a72d2e..940d20255b1 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts @@ -68,6 +68,7 @@ function covered(coverage: OrcaCloudAgentCoverage): BuildAgentVia | null { case 'expired': case 'killSwitch': case 'unavailable': + case 'inWorkspace': return null } } @@ -132,9 +133,13 @@ export function buildAgentsRow(args: { const key = args.desktopKeys.find((candidate) => ORCA_CLOUD_ACCOUNT_AGENTS.some((agent) => agent === candidate.agent) ) + // An agent the person signs in inside each workspace is never offered the one-time setup. + const offered = coverage.filter((entry) => entry.coverage.kind !== 'inWorkspace') return key ? { kind: 'desktopKey', key } - : { kind: 'offer', agents: coverage.map((entry) => entry.agent) } + : offered.length > 0 + ? { kind: 'offer', agents: offered.map((entry) => entry.agent) } + : { kind: 'hidden' } } const viaAccount = ready.filter((entry) => entry.via === 'account') const labels = new Set( diff --git a/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts b/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts index a9d0c844145..0519d4d0356 100644 --- a/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts +++ b/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts @@ -62,22 +62,42 @@ export function orcaCloudProviderState( const Source = z.enum(['sign-in', 'key']).nullable() export type AgentSource = z.infer const PerAgentSource = z.object({ claude: Source.optional(), codex: Source.optional() }) +/** + * A default Source that is a choice, not a credential: "Sign in inside this workspace". Orca stores and + * injects nothing for the agent, and its own login inside each cloud workspace wins. Default only. + */ +export const IN_WORKSPACE_SOURCE = 'in-workspace' +/** What a default Source can be set to (PUT /v1/agent-sources without a workspace). */ +export type AgentDefaultSourceChoice = AgentSource | typeof IN_WORKSPACE_SOURCE export const AgentSourcesResponseSchema = z.looseObject({ /** The default Source ("New cloud workspaces"); null = never chosen. */ defaults: PerAgentSource, effective: z .object({ - claude: z.looseObject({ source: Source }).optional(), - codex: z.looseObject({ source: Source }).optional() + claude: z.looseObject({ source: Source, origin: z.string().optional() }).optional(), + codex: z.looseObject({ source: Source, origin: z.string().optional() }).optional() }) .optional(), /** Some agent key the caller's workspaces would get covers the agent. */ coveredByKey: z.object({ claude: z.boolean(), codex: z.boolean() }), + /** The person signs in inside each workspace (IN_WORKSPACE_SOURCE); absent from older servers. */ + inWorkspace: z.object({ claude: z.boolean(), codex: z.boolean() }).optional(), sharedWorkspace: z.boolean().optional() }) export type AgentSourcesView = z.infer +/** + * The person signs this agent in inside each cloud workspace: their default says so and no + * workspace override (when the view is for one workspace) picks something else. + */ +export function signsInInsideWorkspace( + view: AgentSourcesView, + agent: OrcaCloudAccountAgent +): boolean { + return view.inWorkspace?.[agent] === true && view.effective?.[agent]?.origin !== 'workspace' +} + export const CodexBrokerStartResponseSchema = z.object({ // Used in a request path: a leading letter or digit, so never '.' or '..'. brokerId: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/), From c939513a893bee85d2e0937670831d049e46e651 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 03:00:02 -0800 Subject: [PATCH 22/35] =?UTF-8?q?fix(strip):=20the=20=E2=8B=AF=20choice=20?= =?UTF-8?q?lays=20out=20its=20two=20lines=20in=20a=20wrapper,=20not=20on?= =?UTF-8?q?=20the=20menu=20item?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../agent-sign-in-strip/CloudAgentSignInStrip.tsx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx index 57f8bde2427..2b996d05744 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx @@ -354,12 +354,13 @@ export function CloudAgentSignInStrip({ model.alternative && actions.primary(model.alternative.action)} > - {model.alternative.label} - - {model.alternative.detail} + + {model.alternative.label} + + {model.alternative.detail} + From 3e427dc6e10a35fbc2d44123e89d6549f48503ff Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 03:00:14 -0800 Subject: [PATCH 23/35] chore(sandbox-control): agent_sources migration is 0063 (0062 is taken) --- ...ces_in_workspace.sql => 0063_agent_sources_in_workspace.sql} | 0 .../sandbox-control/test/agent-sources-in-workspace.test.ts | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename cloud/apps/sandbox-control/migrations/{0062_agent_sources_in_workspace.sql => 0063_agent_sources_in_workspace.sql} (100%) diff --git a/cloud/apps/sandbox-control/migrations/0062_agent_sources_in_workspace.sql b/cloud/apps/sandbox-control/migrations/0063_agent_sources_in_workspace.sql similarity index 100% rename from cloud/apps/sandbox-control/migrations/0062_agent_sources_in_workspace.sql rename to cloud/apps/sandbox-control/migrations/0063_agent_sources_in_workspace.sql diff --git a/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts b/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts index 1a16e447ffd..aacb4965402 100644 --- a/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts +++ b/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts @@ -136,7 +136,7 @@ describe('Source "in-workspace" (sign in inside this workspace)', () => { it('the migration keeps every row written before the table was widened', () => { const dir = fileURLToPath(new URL('../migrations/', import.meta.url).href) const files = readdirSync(dir).filter((name) => name.endsWith('.sql')).sort() - const widen = files.indexOf('0062_agent_sources_in_workspace.sql') + const widen = files.indexOf('0063_agent_sources_in_workspace.sql') expect(widen).toBeGreaterThan(0) const raw = new DatabaseSync(':memory:') for (const file of files.slice(0, widen)) { From d1bdfc909b1a692ffccc30a278ec709813df8008 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 03:08:28 -0800 Subject: [PATCH 24/35] feat(cloud): VM memory guard, /dev/shm at half of RAM, and a memory-pressure signal MEMGUARD. A build or test that eats a cloud VM's memory now costs that process, not the workspace. - orca-memguard (new VM entry point, root via sudo from orca-sandbox-start): ranks processes for the kernel OOM killer (Orca runtime -900, terminal shells and agent CLIs -500, everything else 500), stops the largest unprotected process when MemAvailable drops under 8% and records it, adds 2 GiB swap files on demand (up to 1.5x RAM) and drops them after 10 quiet minutes, and remounts /dev/shm at 50% of RAM (the provider mounts 64 MB). Reaches old snapshots through the entry-point refresh. - orca-sandbox-drain releases on-demand swap before a stop so it doesn't ride the snapshot. - Status read: the VM metrics probe reads the guard's state; status gains an optional memory {pressure, guardKills, lastGuardVictim, ...} (metrics keeps its strict shape for older desktops). - Desktop: guard kills count in the OOM tracker and show 'Orca stopped to keep the workspace responsive' with a Machine size action; the sidebar row gets a quiet memory mark under pressure (amber when critical). --- .../sandbox-control/image/golden-image.ts | 1 + .../sandbox-control/image/provision-golden.sh | 2 +- .../image/vm-scripts.generated.ts | 8 +- .../sandbox-control/image/vm/orca-memguard | 308 ++++++++++++++++++ .../image/vm/orca-sandbox-drain | 2 + .../image/vm/orca-sandbox-start | 4 + .../sandbox-control/src/sandbox-vm-inspect.ts | 67 +++- .../src/workspace-lifecycle.ts | 7 +- .../sandbox-control/test/memguard.test.ts | 85 +++++ .../test/workspace-lifecycle.test.ts | 22 ++ .../hosted-workspace-runtime.test.ts | 24 ++ .../hosted-workspace-runtime.ts | 24 +- .../CloudMemoryPressureMark.fixture.tsx | 66 ++++ .../orca-cloud/CloudMemoryPressureMark.tsx | 53 +++ .../orca-cloud/CloudWorkspaceNotice.tsx | 39 +++ .../CloudWorkspaceSurfaces.test.tsx | 24 ++ .../orca-cloud/OrcaCloudWorkspace.fixture.tsx | 19 ++ .../orca-cloud/OrcaCloudWorkspaceSurface.tsx | 8 + .../template/card-identity-parts.tsx | 3 + .../orca-cloud-workspace-state.test.ts | 20 ++ .../orca-cloud/orca-cloud-workspace-state.ts | 14 + .../hosted-sandbox/cloud-workspace-api.ts | 4 +- .../hosted-sandbox/hosted-sandbox-wire.ts | 13 + 23 files changed, 798 insertions(+), 19 deletions(-) create mode 100755 cloud/apps/sandbox-control/image/vm/orca-memguard create mode 100644 cloud/apps/sandbox-control/test/memguard.test.ts create mode 100644 src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx create mode 100644 src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx diff --git a/cloud/apps/sandbox-control/image/golden-image.ts b/cloud/apps/sandbox-control/image/golden-image.ts index d0884ec6ed3..662d87628be 100644 --- a/cloud/apps/sandbox-control/image/golden-image.ts +++ b/cloud/apps/sandbox-control/image/golden-image.ts @@ -7,6 +7,7 @@ import type { SandboxProviderApi } from '../src/sandbox-provider' export const VM_SCRIPTS = [ 'orca-sandbox-start', 'orca-sandbox-drain', + 'orca-memguard', 'orca-sandbox-env', 'orca-session-env.sh', 'orca-env', diff --git a/cloud/apps/sandbox-control/image/provision-golden.sh b/cloud/apps/sandbox-control/image/provision-golden.sh index ac3b5075a71..76e8d2bdf79 100755 --- a/cloud/apps/sandbox-control/image/provision-golden.sh +++ b/cloud/apps/sandbox-control/image/provision-golden.sh @@ -210,7 +210,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-env orca-egress-probe orca-image-wipe orca-agent-signout 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 docker; do +for name in orca-sandbox-start orca-sandbox-drain orca-memguard orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-agent-signout 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 docker; 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 6e6c943b60c..e32b35eb634 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -2,10 +2,10 @@ 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.\n# [ORCA_VM_SCRIPTS_STAMP] (VM_SCRIPTS_STAMP of those scripts; written to /opt/orca/bin/.scripts-stamp).\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-agent-signout 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 docker; 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# Which entry points this image carries (VM_SCRIPTS_STAMP): a Worker with older scripts never\n# reinstalls over them. Absent (old callers) reads as 0, so any Worker may still update the image.\nrm -f \"$ORCA_HOME/bin/.scripts-stamp\" \"$ORCA_HOME\"/bin/.entry-points-*\nif [[ \"${ORCA_VM_SCRIPTS_STAMP:-}\" =~ ^[0-9]+$ ]]; then\n printf '%s\\n' \"$ORCA_VM_SCRIPTS_STAMP\" >\"$ORCA_HOME/bin/.scripts-stamp\"\nfi\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# ORCA_DOCKER (on|off: the control plane's Docker switch for the `docker` shim).\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)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\n# PARITY-DOCKER: the control plane's Docker switch (SANDBOX_DOCKER) for the `docker` shim. Only a\n# start that says so changes it; a retried or repair start (no ORCA_DOCKER) keeps the last answer.\ncase \"${ORCA_DOCKER:-}\" in\n off) : >\"$STATE/docker.off\" ;;\n on) rm -f \"$STATE/docker.off\" ;;\nesac\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# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\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.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\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# OpenCode's first run in a VM installs its plugin SDK into ~/.config/opencode, creates its database\n# and fetches its model list: ~2.5 s more on the first launch (5.2 s vs 2.7 s warm, n72). orca-sandbox-env\n# just wrote that config, so do the first run now, in the background at low priority, with no\n# credentials (`opencode models` does all of it and exits). The SDK install only happens once orcad\n# has put Orca's plugin in ~/.config/opencode/plugins (~10 s after this, n73), so wait for it (up to\n# 60 s) first. Skipped once it has run on this disk.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && [ ! -d \"$HOME/.config/opencode/node_modules\" ]; then\n (\n cd \"$HOME\" || exit 0\n # shellcheck disable=SC2016 # expanded by the inner shell\n env -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 PATH=\"$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin\" \\\n OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c '\n for _ in $(seq 1 120); do [ -d \"$HOME/.config/opencode/plugins\" ] && break; sleep 0.5; done\n exec timeout 120 \"$1\" models\n ' opencode-first-run \"$ORCA_HOME/tools/bin/opencode\" /dev/null 2>&1 9>&- &\n )\nfi\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\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\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 ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\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# The agent CLIs are large and a fresh VM pages them in lazily from the snapshot, so the first agent\n# launch paid for it (OpenCode 11 s cold vs 3.75 s warm, n71). Read them into the page cache in the\n# background at idle IO priority, after orcad is starting. Best effort; detached so it outlives this\n# script, and never on the ready path.\nprefetch_dirs=()\nfor dir in @anthropic-ai @openai opencode-ai; do\n if [ -d \"$ORCA_HOME/tools/lib/node_modules/$dir\" ]; then\n prefetch_dirs+=(\"$ORCA_HOME/tools/lib/node_modules/$dir\")\n fi\ndone\nif [ \"${#prefetch_dirs[@]}\" -gt 0 ]; then\n # shellcheck disable=SC2016 # expanded by the inner shell\n setsid nohup nice -n 19 bash -c '\n command -v ionice >/dev/null && ionice -c 3 -p $$ 2>/dev/null\n find \"$@\" -type f -size +256k -print0 2>/dev/null | xargs -0 -r cat >/dev/null 2>&1\n ' agent-prefetch \"${prefetch_dirs[@]}\" /dev/null 2>&1 9>&- &\nfi\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)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(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=''\nanthropic_key_scrub=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\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 # G9: pre-approve only an Orca placeholder. A real key (placeholders off) is never written, not even its\n # tail: Claude Code asks once instead, and a tail an older image wrote is scrubbed.\n ANTHROPIC_API_KEY)\n case \"$(printf '%s' \"$b64\" | base64 -d)\" in\n orca-ph-*) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n *) anthropic_key_scrub=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\n ;;\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 the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$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 elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\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 elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\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# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\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_KEY_SCRUB=\"$anthropic_key_scrub\" 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\nconst scrub = process.env.ORCA_KEY_SCRUB\nif (scrub && c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\") {\n const r = c.customApiKeyResponses\n for (const list of [\"approved\", \"rejected\"]) if (Array.isArray(r[list])) r[list] = r[list].filter((t) => t !== scrub)\n}\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\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\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\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\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) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\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-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\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// Vercel closes a WebSocket on a *.vercel.run route after ~340 s with no traffic (1006). A preview\n// app's socket can sit silent that long, so once an upgrade is a WebSocket the proxy watches the app's\n// frames and, after KEEPALIVE_MS with nothing either way, sends the visitor a ping control frame\n// between two frames (never inside one). The visitor's pong reaches the app, which RFC 6455 says to\n// ignore (an unsolicited pong needs no answer).\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\n// Well under Vercel's ~340 s idle cut. ORCA_SHARE_PROXY_KEEPALIVE_MS is for tests.\nconst KEEPALIVE_MS = Number(process.env.ORCA_SHARE_PROXY_KEEPALIVE_MS || 30_000)\n// FIN + ping opcode, empty payload, unmasked (server to client).\nconst PING_FRAME = Buffer.from([0x89, 0x00])\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/**\n * Follows the app's WebSocket frames (server to client: header, then payload) just closely enough to\n * know when the stream sits between two frames, where a control frame may be inserted.\n */\nfunction frameBoundaries() {\n let header = []\n let remaining = 0\n return {\n push(chunk) {\n let i = 0\n while (i < chunk.length) {\n if (remaining > 0) {\n const take = Math.min(remaining, chunk.length - i)\n remaining -= take\n i += take\n continue\n }\n header.push(chunk[i++])\n if (header.length < 2) {\n continue\n }\n const len7 = header[1] & 0x7f\n const need = 2 + (len7 === 126 ? 2 : len7 === 127 ? 8 : 0) + (header[1] & 0x80 ? 4 : 0)\n if (header.length < need) {\n continue\n }\n const bytes = Buffer.from(header)\n remaining = len7 === 126 ? bytes.readUInt16BE(2) : len7 === 127 ? Number(bytes.readBigUInt64BE(2)) : len7\n header = []\n }\n },\n atBoundary: () => header.length === 0 && remaining === 0\n }\n}\n\n/** The app's answer to the upgrade: its head is passed through; only a 101 to `websocket` gets keepalives. */\nfunction upgradeAnswer() {\n let head = Buffer.alloc(0)\n let state = 'head'\n const frames = frameBoundaries()\n return {\n push(chunk) {\n if (state === 'head') {\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end === -1) {\n if (head.length > 64 * 1024) {\n state = 'raw'\n }\n return\n }\n const text = head.subarray(0, end).toString('latin1')\n state = /^HTTP\\/1\\.1 101/.test(text) && /^upgrade:\\s*websocket\\s*$/im.test(text) ? 'ws' : 'raw'\n chunk = head.subarray(end + 4)\n head = Buffer.alloc(0)\n }\n if (state === 'ws') {\n frames.push(chunk)\n }\n },\n canPing: () => state === 'ws' && frames.atBoundary()\n }\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 // App to visitor by hand (with backpressure) so the keepalive knows where frames start and end.\n const answer = upgradeAnswer()\n let lastTraffic = Date.now()\n socket.on('data', () => {\n lastTraffic = Date.now()\n })\n target.on('data', (chunk) => {\n lastTraffic = Date.now()\n answer.push(chunk)\n if (!socket.write(chunk)) {\n target.pause()\n socket.once('drain', () => target.resume())\n }\n })\n target.on('end', () => socket.end())\n const keepalive = setInterval(() => {\n if (Date.now() - lastTraffic >= KEEPALIVE_MS && answer.canPing() && socket.writable) {\n socket.write(PING_FRAME)\n lastTraffic = Date.now()\n }\n }, Math.max(50, Math.floor(KEEPALIVE_MS / 3)))\n socket.once('close', () => clearInterval(keepalive))\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# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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 'noreply@orca.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'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\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\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\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 // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\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/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\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 stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\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 stored) {\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\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\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 out.signature = sign(out, signingKey(stateDir))\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 = { workspaceCheckout, seal, sign, signingKey, 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=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} -export const VM_SCRIPTS_HASH: string = "ad897b32" -export const VM_SCRIPTS_STAMP: number = 1794733957 +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.\n# [ORCA_VM_SCRIPTS_STAMP] (VM_SCRIPTS_STAMP of those scripts; written to /opt/orca/bin/.scripts-stamp).\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-memguard orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-agent-signout 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 docker; 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# Which entry points this image carries (VM_SCRIPTS_STAMP): a Worker with older scripts never\n# reinstalls over them. Absent (old callers) reads as 0, so any Worker may still update the image.\nrm -f \"$ORCA_HOME/bin/.scripts-stamp\" \"$ORCA_HOME\"/bin/.entry-points-*\nif [[ \"${ORCA_VM_SCRIPTS_STAMP:-}\" =~ ^[0-9]+$ ]]; then\n printf '%s\\n' \"$ORCA_VM_SCRIPTS_STAMP\" >\"$ORCA_HOME/bin/.scripts-stamp\"\nfi\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# ORCA_DOCKER (on|off: the control plane's Docker switch for the `docker` shim).\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)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\n# PARITY-DOCKER: the control plane's Docker switch (SANDBOX_DOCKER) for the `docker` shim. Only a\n# start that says so changes it; a retried or repair start (no ORCA_DOCKER) keeps the last answer.\ncase \"${ORCA_DOCKER:-}\" in\n off) : >\"$STATE/docker.off\" ;;\n on) rm -f \"$STATE/docker.off\" ;;\nesac\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\n# MEMGUARD: OOM-killer ranks that spare orcad and terminals, a guard that stops the largest build or\n# test before the VM stalls, on-demand swap and a /dev/shm sized for browsers. Before the\n# already-started exit so a repair start brings a dead guard back; it returns at once.\nsudo -n \"$ORCA_HOME/bin/orca-memguard\" start /dev/null 2>&1 9>&- || true\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# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\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.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\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# OpenCode's first run in a VM installs its plugin SDK into ~/.config/opencode, creates its database\n# and fetches its model list: ~2.5 s more on the first launch (5.2 s vs 2.7 s warm, n72). orca-sandbox-env\n# just wrote that config, so do the first run now, in the background at low priority, with no\n# credentials (`opencode models` does all of it and exits). The SDK install only happens once orcad\n# has put Orca's plugin in ~/.config/opencode/plugins (~10 s after this, n73), so wait for it (up to\n# 60 s) first. Skipped once it has run on this disk.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && [ ! -d \"$HOME/.config/opencode/node_modules\" ]; then\n (\n cd \"$HOME\" || exit 0\n # shellcheck disable=SC2016 # expanded by the inner shell\n env -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 PATH=\"$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin\" \\\n OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c '\n for _ in $(seq 1 120); do [ -d \"$HOME/.config/opencode/plugins\" ] && break; sleep 0.5; done\n exec timeout 120 \"$1\" models\n ' opencode-first-run \"$ORCA_HOME/tools/bin/opencode\" /dev/null 2>&1 9>&- &\n )\nfi\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\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\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 ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\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# The agent CLIs are large and a fresh VM pages them in lazily from the snapshot, so the first agent\n# launch paid for it (OpenCode 11 s cold vs 3.75 s warm, n71). Read them into the page cache in the\n# background at idle IO priority, after orcad is starting. Best effort; detached so it outlives this\n# script, and never on the ready path.\nprefetch_dirs=()\nfor dir in @anthropic-ai @openai opencode-ai; do\n if [ -d \"$ORCA_HOME/tools/lib/node_modules/$dir\" ]; then\n prefetch_dirs+=(\"$ORCA_HOME/tools/lib/node_modules/$dir\")\n fi\ndone\nif [ \"${#prefetch_dirs[@]}\" -gt 0 ]; then\n # shellcheck disable=SC2016 # expanded by the inner shell\n setsid nohup nice -n 19 bash -c '\n command -v ionice >/dev/null && ionice -c 3 -p $$ 2>/dev/null\n find \"$@\" -type f -size +256k -print0 2>/dev/null | xargs -0 -r cat >/dev/null 2>&1\n ' agent-prefetch \"${prefetch_dirs[@]}\" /dev/null 2>&1 9>&- &\nfi\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 # On-demand swap files would ride the stop snapshot (2 GiB each). Best effort, bounded.\n [ -x /opt/orca/bin/orca-memguard ] && sudo -n timeout 20 /opt/orca/bin/orca-memguard release-swap >/dev/null 2>&1 || true\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-memguard":"#!/usr/bin/env bash\n# Memory guard for the workspace VM (runs as root: `sudo -n orca-memguard start`). A build or test\n# that eats the VM's memory must cost that process, never the workspace: without this the kernel\n# thrashes for minutes before its OOM killer picks something, and the VM looks dead meanwhile.\n# start start the guard for this boot unless it already runs (returns at once)\n# run the guard loop itself (start runs it detached)\n# release-swap turn off and delete on-demand swap (before a stop, so the snapshot stays small)\n# sweep apply OOM-killer priorities once and exit (tests, diagnostics)\n# victim print \" \" of the process the guard would stop now (no kill)\n# Every few seconds it ranks processes for the kernel's OOM killer (oom_score_adj):\n# -900 Orca's own runtime: orcad, its terminal daemon, the share proxy (Orca's bundled Node)\n# -500 terminal shells (children of the terminal daemon) and agent CLIs\n# 500 everything else (builds, tests, dev servers, browsers); never lowered\n# When MemAvailable falls under KILL_PCT (8%) of RAM it kills the largest process ranked 0 or more,\n# records it in $RUN/kills and $RUN/state, and waits for memory to return. The kernel's OOM killer\n# stays the backstop for allocations faster than the guard's 200 ms look, with the same ranks.\n# Swap is added on demand (2 GiB files up to 1.5x RAM) when memory runs low, if the kernel takes it,\n# and dropped after 10 quiet minutes. It also sizes /dev/shm to half of RAM (the provider mounts\n# 64 MB, which crashes Chrome and Electron renderers).\n# $RUN/state (key=value, world-readable) is what the control plane's status probe reads.\nset -uo pipefail\nRUN=/run/orca-memguard\n# Tests point it at a fake process table.\nPROC=\"${ORCA_MEMGUARD_PROC:-/proc}\"\nSWAP_DIR=/var/lib/orca-memguard\nORCA_HOME=/opt/orca\nKILL_PCT=\"${ORCA_MEMGUARD_KILL_PCT:-8}\"\nHIGH_PCT=15\nSWAP_ADD_PCT=20\nQUIET_PCT=50\nQUIET_SECONDS=600\nTICK=1\nFAST_TICK=0.2\nSWEEP_EVERY=3\nSTATE_EVERY=15\nSWAP_CHUNK_KIB=$((2 * 1024 * 1024))\n\nboot_id() { local id; read -r id >\"$RUN/memguard.log\"; }\n\n# Name of a process for people: the script a node/python/... runs, else its command name.\nproc_name() {\n local pid=\"$1\" comm arg name='' skip=0 module=0 args=()\n read -r comm 2>/dev/null <\"$PROC/$pid/comm\" || comm=''\n mapfile -d '' -t args 2>/dev/null <\"$PROC/$pid/cmdline\" || true\n case \"${args[0]##*/}\" in\n node | nodejs | bun | deno | python* | ruby | perl | java | sh | bash | dash | zsh)\n for arg in \"${args[@]:1}\"; do\n if [ \"$skip\" -eq 1 ]; then skip=0; continue; fi\n if [ \"$module\" -eq 1 ]; then name=\"${arg##*/}\"; break; fi\n case \"$arg\" in\n # Inline code is no name (and may hold anything): the interpreter's name it is.\n -e | -p | -c | --eval | --print) break ;;\n -m | -jar) module=1 ;; # python -m pytest, java -jar gradle.jar: the module or jar\n -r | --require | --import | --loader | -X | -W | -cp | -classpath) skip=1 ;;\n -*) ;;\n *) name=\"${arg##*/}\"; break ;;\n esac\n done ;;\n esac\n [ -n \"$name\" ] || name=\"${args[0]##*/}\"\n [ -n \"$name\" ] || name=\"$comm\"\n name=\"${name%.js}\"\n name=\"${name%.mjs}\"\n name=\"${name%.cjs}\"\n name=\"${name%.jar}\"\n name=\"${name//[^A-Za-z0-9._+-]/}\"\n printf '%s' \"${name:0:40}\"\n}\n\n# The terminal daemon's pid(s): Orca-runtime node processes running the daemon entry.\ndaemon_pids=' '\n# Sets RANK to the oom_score_adj a process should have; returns 1 for a kernel thread or a gone pid.\nRANK=500\nrank() {\n local pid=\"$1\" args=() stat ppid\n mapfile -d '' -t -n 3 args 2>/dev/null <\"$PROC/$pid/cmdline\" || return 1\n [ \"${#args[@]}\" -gt 0 ] || return 1\n RANK=-900\n case \"${args[0]}\" in \"$ORCA_HOME\"/runtime/runtimes/*) return 0 ;; esac\n RANK=-500\n read -r stat 2>/dev/null <\"$PROC/$pid/stat\" || return 1\n stat=\"${stat##*) }\"\n ppid=\"${stat#* }\"\n ppid=\"${ppid%% *}\"\n case \"$daemon_pids\" in *\" $ppid \"*) return 0 ;; esac\n case \"${args[0]}/${args[1]:-}/${args[2]:-}\" in \"$ORCA_HOME\"/tools/* | */\"$ORCA_HOME\"/tools/*) return 0 ;; esac\n case \"${args[0]##*/}\" in claude | codex | opencode | gemini | cursor-agent | copilot | amp | droid) return 0 ;; esac\n RANK=500\n}\n\nsweep() {\n local p pid want adj args=()\n daemon_pids=' '\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n mapfile -d '' -t -n 3 args 2>/dev/null <\"$p/cmdline\" || continue\n [ \"${#args[@]}\" -ge 2 ] || continue\n case \"${args[0]}\" in \"$ORCA_HOME\"/runtime/runtimes/*) ;; *) continue ;; esac\n case \"${args[*]:1}\" in *\"$ORCA_HOME\"/runtime/orcad/daemon*) daemon_pids+=\"$pid \" ;; esac\n done\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n [ \"$pid\" -gt 1 ] && [ \"$pid\" != \"$$\" ] || continue\n read -r adj 2>/dev/null <\"$p/oom_score_adj\" || continue\n # -1000 is a process that asked for it as root (sshd): leave it alone.\n [ \"$adj\" -gt -1000 ] || continue\n rank \"$pid\" || continue\n want=\"$RANK\"\n # Never lower what a process raised for itself (Chrome ranks its renderers above its browser).\n if [ \"$want\" -eq 500 ]; then\n [ \"$adj\" -lt 500 ] || continue\n fi\n [ \"$adj\" -ne \"$want\" ] || continue\n printf '%s\\n' \"$want\" 2>/dev/null >\"$p/oom_score_adj\" || true\n done\n}\n\nmem_total=0 mem_avail=0 swap_total=0 swap_free=0\nread_mem() {\n local key value _\n while read -r key value _; do\n case \"$key\" in\n MemTotal:) mem_total=\"$value\" ;;\n MemAvailable:) mem_avail=\"$value\" ;;\n SwapTotal:) swap_total=\"$value\" ;;\n SwapFree:) swap_free=\"$value\" ;;\n esac\n done <\"$PROC/meminfo\"\n}\n\n# PSI percentages (avg10, integer part); 0 when the kernel doesn't report them.\npsi_some=0 psi_full=0\nread_psi() {\n local kind avg _\n psi_some=0 psi_full=0\n [ -r \"$PROC/pressure/memory\" ] || return 0\n while read -r kind avg _; do\n avg=\"${avg#avg10=}\"\n avg=\"${avg%%.*}\"\n case \"$kind\" in some) psi_some=\"$avg\" ;; full) psi_full=\"$avg\" ;; esac\n done 2>/dev/null <\"$PROC/pressure/memory\" || true\n}\n\nkills=0 last_kill_name='' last_kill_at=0 swap_mode=on-demand level=ok\nwrite_state() {\n local pct=\"$1\"\n {\n printf 'bootId=%s\\nat=%s\\npid=%s\\nlevel=%s\\navailPct=%s\\nmemTotalKiB=%s\\nmemAvailKiB=%s\\n' \\\n \"$BOOT\" \"$(now_ms)\" \"$$\" \"$level\" \"$pct\" \"$mem_total\" \"$mem_avail\"\n printf 'swapTotalKiB=%s\\nswapFreeKiB=%s\\nswap=%s\\npsiSome10=%s\\npsiFull10=%s\\n' \\\n \"$swap_total\" \"$swap_free\" \"$swap_mode\" \"$psi_some\" \"$psi_full\"\n printf 'kills=%s\\nlastKillName=%s\\nlastKillAt=%s\\n' \"$kills\" \"$last_kill_name\" \"$last_kill_at\"\n } >\"$RUN/state.tmp\" && mv -f \"$RUN/state.tmp\" \"$RUN/state\"\n}\n\n# Sets VICTIM/VICTIM_RSS (pages) to the largest process ranked 0 or more; returns 1 when there is none.\nVICTIM=0 VICTIM_RSS=0\nchoose_victim() {\n local p pid adj rss _ best=0 best_rss=0 args=()\n sweep\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n [ \"$pid\" -gt 1 ] && [ \"$pid\" != \"$$\" ] || continue\n read -r adj 2>/dev/null <\"$p/oom_score_adj\" || continue\n [ \"$adj\" -ge 0 ] || continue\n read -r _ rss _ 2>/dev/null <\"$p/statm\" || continue\n # Kernel threads have no command line (and /proc sizes read 0, so `-s` can't tell).\n mapfile -d '' -t -n 1 args 2>/dev/null <\"$p/cmdline\" || continue\n [ \"${#args[@]}\" -gt 0 ] || continue\n if [ \"$rss\" -gt \"$best_rss\" ]; then\n best=\"$pid\" best_rss=\"$rss\"\n fi\n done\n # Nothing big enough to matter (64 MiB): what fills memory is protected, so leave it to the kernel.\n [ \"$best\" -gt 1 ] && [ \"$best_rss\" -ge 16384 ] || return 1\n VICTIM=\"$best\" VICTIM_RSS=\"$best_rss\"\n}\n\n# Kills the largest process ranked 0 or more ($1: MemAvailable %). Returns 1 when there is none.\nkill_largest() {\n choose_victim || return 1\n local best=\"$VICTIM\" best_rss=\"$VICTIM_RSS\" name at\n name=\"$(proc_name \"$best\")\"\n kill -KILL \"$best\" 2>/dev/null || return 1\n at=\"$(now_ms)\"\n kills=$((kills + 1)) last_kill_name=\"${name:-process}\" last_kill_at=\"$at\"\n printf '%s %s %s %s %s\\n' \"$at\" \"$best\" \"$((best_rss * 4))\" \"$1\" \"$last_kill_name\" >>\"$RUN/kills\"\n tail -n 50 \"$RUN/kills\" >\"$RUN/kills.tmp\" && mv -f \"$RUN/kills.tmp\" \"$RUN/kills\"\n log \"killed pid=$best name=$last_kill_name rssKiB=$((best_rss * 4)) availPct=$1\"\n # Shells hear it like a kernel OOM kill (exit 137); this says why where someone may look.\n logger -t orca-memguard \"stopped $last_kill_name (pid $best, $((best_rss * 4)) KiB) at $1% memory available\" 2>/dev/null || true\n return 0\n}\n\nswap_files() { compgen -G \"$SWAP_DIR/swap-*\" || true; }\nadd_swap() {\n [ \"$swap_mode\" = on-demand ] || return 1\n [ $((swap_total + SWAP_CHUNK_KIB)) -le $((mem_total * 3 / 2)) ] || return 1\n local free_kib file\n free_kib=\"$(df -k --output=avail \"$SWAP_DIR\" 2>/dev/null | tail -n 1 | tr -d ' ')\"\n # Keep 4 GiB of the disk for the workspace itself.\n [ \"${free_kib:-0}\" -gt $((SWAP_CHUNK_KIB + 4 * 1024 * 1024)) ] || return 1\n file=\"$SWAP_DIR/swap-$(now_ms)\"\n if fallocate -l \"$((SWAP_CHUNK_KIB))K\" \"$file\" 2>/dev/null && chmod 600 \"$file\" \\\n && mkswap -q \"$file\" >/dev/null 2>&1 && swapon \"$file\" 2>/dev/null; then\n log \"swap on $file\"\n return 0\n fi\n rm -f \"$file\"\n # One refusal means this kernel or disk won't swap: don't retry every tick.\n swap_mode=unsupported\n log 'swap unavailable; guard kills only'\n return 1\n}\nrelease_swap() {\n local file\n for file in $(swap_files | sort -r); do\n swapoff \"$file\" 2>/dev/null && rm -f \"$file\" && log \"swap off $file\"\n done\n}\n\nrun() {\n BOOT=\"$(boot_id)\"\n mkdir -p \"$RUN\" \"$SWAP_DIR\"\n chmod 0755 \"$RUN\"\n chmod 0700 \"$SWAP_DIR\"\n # A resumed disk carries the last session's files: its kills and swap belong to that boot.\n rm -f \"$RUN/kills\" \"$RUN/state\" \"$RUN\"/*.tmp\n for file in $(swap_files); do\n grep -q \"^$file \" /proc/swaps 2>/dev/null || rm -f \"$file\"\n done\n printf '%s %s\\n' \"$BOOT\" \"$$\" >\"$RUN/pid\"\n echo -1000 >/proc/self/oom_score_adj\n read_mem\n # Half of RAM for /dev/shm (tmpfs only takes pages that are written).\n mount -o remount,size=50% /dev/shm 2>/dev/null && log \"/dev/shm $(df -h --output=size /dev/shm | tail -n 1 | tr -d ' ')\"\n log \"start mem=${mem_total}KiB\"\n local tick=0 pct quiet_since=0 prev='' now\n while :; do\n read_mem\n read_psi\n pct=$((mem_total > 0 ? mem_avail * 100 / mem_total : 100))\n if [ $((tick % SWEEP_EVERY)) -eq 0 ]; then\n sweep\n fi\n if [ \"$pct\" -lt \"$SWAP_ADD_PCT\" ] && { [ \"$swap_total\" -eq 0 ] || [ $((swap_free * 4)) -lt \"$swap_total\" ]; }; then\n add_swap && read_mem\n fi\n # Swap only raises MemAvailable by paging idle memory out: a fast allocator outruns it (the\n # kernel OOM-killed a 300 MB/s hog with 1.7 GB of swap free), so the threshold ignores swap.\n if [ \"$pct\" -lt \"$KILL_PCT\" ]; then\n level=critical\n if kill_largest \"$pct\"; then\n write_state \"$pct\"\n prev=\"$level:$kills\"\n sleep 1 # let the kernel reclaim the victim's memory before judging again\n tick=$((tick + 1))\n continue\n fi\n elif [ \"$psi_full\" -ge 10 ]; then\n level=critical\n elif [ \"$pct\" -lt \"$HIGH_PCT\" ] || [ \"$psi_some\" -ge 20 ]; then\n level=high\n else\n level=ok\n fi\n now=\"${EPOCHSECONDS}\"\n if [ \"$pct\" -ge \"$QUIET_PCT\" ] && [ \"$swap_total\" -gt 0 ]; then\n [ \"$quiet_since\" -gt 0 ] || quiet_since=\"$now\"\n if [ $((now - quiet_since)) -ge \"$QUIET_SECONDS\" ] && [ $(((swap_total - swap_free) * 2)) -lt \"$mem_avail\" ]; then\n release_swap\n quiet_since=0\n fi\n else\n quiet_since=0\n fi\n if [ \"$level:$kills\" != \"$prev\" ] || [ $((tick % STATE_EVERY)) -eq 0 ]; then\n write_state \"$pct\"\n prev=\"$level:$kills\"\n fi\n tick=$((tick + 1))\n # Memory can go from 15% to nothing in two seconds: look five times as often when it is low.\n if [ \"$level\" = ok ]; then sleep \"$TICK\"; else sleep \"$FAST_TICK\"; fi\n done\n}\n\nrunning() {\n local boot pid\n read -r boot pid <\"$RUN/pid\" 2>/dev/null || return 1\n [ \"$boot\" = \"$(boot_id)\" ] && [ -n \"$pid\" ] && kill -0 \"$pid\" 2>/dev/null \\\n && grep -qa orca-memguard \"/proc/$pid/cmdline\" 2>/dev/null\n}\n\ncase \"${1:-}\" in\n start)\n [ \"$(id -u)\" -eq 0 ] || { echo 'orca-memguard: needs root' >&2; exit 1; }\n running && exit 0\n mkdir -p \"$RUN\"\n setsid nohup \"$0\" run /dev/null 2>>\"$RUN/memguard.log\" &\n exit 0 ;;\n run) run ;;\n sweep) sweep ;;\n victim) choose_victim && printf '%s %s %s\\n' \"$VICTIM\" \"$((VICTIM_RSS * 4))\" \"$(proc_name \"$VICTIM\")\" ;;\n release-swap) release_swap ;;\n *) echo 'usage: orca-memguard start|run|sweep|victim|release-swap' >&2; exit 2 ;;\nesac\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)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(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=''\nanthropic_key_scrub=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\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 # G9: pre-approve only an Orca placeholder. A real key (placeholders off) is never written, not even its\n # tail: Claude Code asks once instead, and a tail an older image wrote is scrubbed.\n ANTHROPIC_API_KEY)\n case \"$(printf '%s' \"$b64\" | base64 -d)\" in\n orca-ph-*) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n *) anthropic_key_scrub=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\n ;;\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 the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$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 elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\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 elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\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# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\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_KEY_SCRUB=\"$anthropic_key_scrub\" 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\nconst scrub = process.env.ORCA_KEY_SCRUB\nif (scrub && c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\") {\n const r = c.customApiKeyResponses\n for (const list of [\"approved\", \"rejected\"]) if (Array.isArray(r[list])) r[list] = r[list].filter((t) => t !== scrub)\n}\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\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\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\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\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) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\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-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\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// Vercel closes a WebSocket on a *.vercel.run route after ~340 s with no traffic (1006). A preview\n// app's socket can sit silent that long, so once an upgrade is a WebSocket the proxy watches the app's\n// frames and, after KEEPALIVE_MS with nothing either way, sends the visitor a ping control frame\n// between two frames (never inside one). The visitor's pong reaches the app, which RFC 6455 says to\n// ignore (an unsolicited pong needs no answer).\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\n// Well under Vercel's ~340 s idle cut. ORCA_SHARE_PROXY_KEEPALIVE_MS is for tests.\nconst KEEPALIVE_MS = Number(process.env.ORCA_SHARE_PROXY_KEEPALIVE_MS || 30_000)\n// FIN + ping opcode, empty payload, unmasked (server to client).\nconst PING_FRAME = Buffer.from([0x89, 0x00])\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/**\n * Follows the app's WebSocket frames (server to client: header, then payload) just closely enough to\n * know when the stream sits between two frames, where a control frame may be inserted.\n */\nfunction frameBoundaries() {\n let header = []\n let remaining = 0\n return {\n push(chunk) {\n let i = 0\n while (i < chunk.length) {\n if (remaining > 0) {\n const take = Math.min(remaining, chunk.length - i)\n remaining -= take\n i += take\n continue\n }\n header.push(chunk[i++])\n if (header.length < 2) {\n continue\n }\n const len7 = header[1] & 0x7f\n const need = 2 + (len7 === 126 ? 2 : len7 === 127 ? 8 : 0) + (header[1] & 0x80 ? 4 : 0)\n if (header.length < need) {\n continue\n }\n const bytes = Buffer.from(header)\n remaining = len7 === 126 ? bytes.readUInt16BE(2) : len7 === 127 ? Number(bytes.readBigUInt64BE(2)) : len7\n header = []\n }\n },\n atBoundary: () => header.length === 0 && remaining === 0\n }\n}\n\n/** The app's answer to the upgrade: its head is passed through; only a 101 to `websocket` gets keepalives. */\nfunction upgradeAnswer() {\n let head = Buffer.alloc(0)\n let state = 'head'\n const frames = frameBoundaries()\n return {\n push(chunk) {\n if (state === 'head') {\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end === -1) {\n if (head.length > 64 * 1024) {\n state = 'raw'\n }\n return\n }\n const text = head.subarray(0, end).toString('latin1')\n state = /^HTTP\\/1\\.1 101/.test(text) && /^upgrade:\\s*websocket\\s*$/im.test(text) ? 'ws' : 'raw'\n chunk = head.subarray(end + 4)\n head = Buffer.alloc(0)\n }\n if (state === 'ws') {\n frames.push(chunk)\n }\n },\n canPing: () => state === 'ws' && frames.atBoundary()\n }\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 // App to visitor by hand (with backpressure) so the keepalive knows where frames start and end.\n const answer = upgradeAnswer()\n let lastTraffic = Date.now()\n socket.on('data', () => {\n lastTraffic = Date.now()\n })\n target.on('data', (chunk) => {\n lastTraffic = Date.now()\n answer.push(chunk)\n if (!socket.write(chunk)) {\n target.pause()\n socket.once('drain', () => target.resume())\n }\n })\n target.on('end', () => socket.end())\n const keepalive = setInterval(() => {\n if (Date.now() - lastTraffic >= KEEPALIVE_MS && answer.canPing() && socket.writable) {\n socket.write(PING_FRAME)\n lastTraffic = Date.now()\n }\n }, Math.max(50, Math.floor(KEEPALIVE_MS / 3)))\n socket.once('close', () => clearInterval(keepalive))\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# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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 'noreply@orca.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'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\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\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\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 // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\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/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\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 stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\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 stored) {\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\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\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 out.signature = sign(out, signingKey(stateDir))\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 = { workspaceCheckout, seal, sign, signingKey, 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=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPTS_HASH: string = "e85c0739" +export const VM_SCRIPTS_STAMP: number = 1794740971 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 # The stamp must describe this commit's scripts, never the Worker's: a commit from before stamps\n # leaves it unset (the image then reads as stamp 0).\n unset ORCA_VM_SCRIPTS_STAMP\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 and ORCA_CLONE_FILTER, plus\n# ORCA_BUILD_SECRET_NAMES (space list of the team secrets the environment names; each value rides in\n# the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get).\n# `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk.\n# ORCA_AUTO_INSTALL=1 (automatic environments, no install script): install from the lockfile, never failing.\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\"\n\n# SEC-2: the snapshot of this VM is the team's saved environment, booted by every member's workspace,\n# so a secret's value must never be in it. Secrets are for the install script alone: take_secrets\n# moves them out of this script's environment (clones and Orca's own steps never see them), the\n# install step hands them to that one child, and scan_secrets searches the disk before the build\n# may succeed.\nsecret_names=()\nsecret_values=()\ntake_secrets() {\n local name\n for name in ${ORCA_BUILD_SECRET_NAMES:-}; do\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n [ -n \"${!name:-}\" ] || continue\n secret_names+=(\"$name\")\n secret_values+=(\"${!name}\")\n unset \"$name\"\n done\n unset ORCA_BUILD_SECRET_NAMES\n # Only a file that changes after this marker can hold a value: the base image never saw one.\n : >\"$OUT/.scan-since\"\n}\n\n# Fails (non-zero) when a secret's value is in a file the build created or changed, anywhere on the\n# disk the snapshot captures. Plain text only: a value the script encoded, encrypted or compressed is\n# not found, and neither is one shorter than 8 characters (it would match ordinary text). A search\n# that cannot run fails too. Prints names and paths, never a value.\n# ORCA_SCAN_ROOT: tests only (a scratch tree); the control plane never sets it.\nscan_secrets() {\n [ \"${#secret_names[@]}\" -gt 0 ] || return 0\n local root=\"${ORCA_SCAN_ROOT:-/}\" i line pattern hit named=0\n local names=() patterns=() args=() newer=() sudo=()\n for i in \"${!secret_names[@]}\"; do\n # grep -F reads a newline as \"or\": a multi-line value (a PEM key) is searched by its longest line.\n pattern=\"\"\n while IFS= read -r line; do\n case \"$line\" in -----*) continue ;; esac\n if [ \"${#line}\" -gt \"${#pattern}\" ]; then pattern=\"$line\"; fi\n done < <(printf '%s\\n' \"${secret_values[$i]}\") # a pipe, not a here-string temp file\n [ \"${#pattern}\" -ge 8 ] || continue\n names+=(\"${secret_names[$i]}\")\n patterns+=(\"$pattern\")\n args+=(-e \"$pattern\")\n done\n [ \"${#patterns[@]}\" -gt 0 ] || return 0\n if ! command -v find >/dev/null 2>&1 || ! command -v grep >/dev/null 2>&1 || ! command -v xargs >/dev/null 2>&1; then\n echo \"::orca-error:: Orca couldn’t check the build for secrets, so the environment wasn’t saved.\"\n return 1\n fi\n # Root-owned files count too (`sudo npm config set` writes /root/.npmrc).\n if sudo -n true 2>/dev/null; then sudo=(sudo -n); fi\n # A missing marker (the install script removed it) means every file is searched.\n if [ -f \"$OUT/.scan-since\" ]; then newer=(-cnewer \"$OUT/.scan-since\"); fi\n changed_files() {\n ${sudo[@]+\"${sudo[@]}\"} find \"$root\" \\( -path /proc -o -path /sys -o -path /dev -o -path /run \\) -prune \\\n -o -type f ${newer[@]+\"${newer[@]}\"} -print0 2>/dev/null\n }\n # One pass for every value; the per-secret passes only run on a build that is about to fail.\n if [ -z \"$(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF \"${args[@]}\" -- 2>/dev/null | head -n 1)\" ]; then\n return 0\n fi\n for i in \"${!names[@]}\"; do\n while IFS= read -r hit; do\n [ -n \"$hit\" ] || continue\n named=1\n echo \"::orca-error:: ${names[$i]} was left in $hit. Saved environments are shared with your team, so remove it before the install script ends.\"\n done < <(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF -e \"${patterns[$i]}\" -- 2>/dev/null | head -n 5)\n done\n if [ \"$named\" -eq 0 ]; then\n # The file moved between the two passes: still a build that held a value on disk.\n echo \"::orca-error:: The install script left a secret on disk, so the environment wasn’t saved. Remove it before the script ends, then save again.\"\n fi\n return 1\n}\n\n# PARITY-AUTO-ENV-DEPS: an automatic environment (ORCA_AUTO_INSTALL=1, no install script) installs the\n# first repo's JavaScript dependencies from its lockfile, so new workspaces start with them (the deps\n# step below carries node_modules into each worktree). Soft by design: a failure, a lockfile out of date\n# or the time cap leaves the clone as it was (no half-installed node_modules) and the build goes on.\n# Package managers the image doesn't have (bun, uv, bundler, go, cargo) are only named in the log.\n# ORCA_AUTO_INSTALL_TIMEOUT: tests only.\nauto_install() {\n local dir=\"$1\" pm=\"\" declared=\"\" rc=0 started f\n local cmd=() others=()\n for f in bun.lock bun.lockb uv.lock poetry.lock Pipfile.lock Gemfile.lock go.sum Cargo.lock; do\n [ -f \"$dir/$f\" ] && others+=(\"$f\")\n done\n if [ -f \"$dir/package.json\" ]; then\n # package.json's packageManager (\"pnpm@9.1.0\") wins over the lockfile guess.\n declared=$(sed -n 's/.*\"packageManager\"[[:space:]]*:[[:space:]]*\"\\([a-z]*\\)@.*/\\1/p' \"$dir/package.json\" | head -n 1)\n case \"$declared\" in\n pnpm | yarn | npm) pm=\"$declared\" ;;\n *)\n if [ -f \"$dir/pnpm-lock.yaml\" ]; then pm=pnpm\n elif [ -f \"$dir/yarn.lock\" ]; then pm=yarn\n elif [ -f \"$dir/package-lock.json\" ] || [ -f \"$dir/npm-shrinkwrap.json\" ]; then pm=npm\n fi\n ;;\n esac\n fi\n if [ \"${#others[@]}\" -gt 0 ]; then\n echo \"Not installed automatically: ${others[*]}. Add an install script to the environment to install these.\"\n fi\n if [ -z \"$pm\" ]; then\n [ \"${#others[@]}\" -gt 0 ] || echo \"No lockfile found; the build keeps the cloned repos.\"\n return 0\n fi\n # Through corepack, so pnpm and yarn come at the version the repo pins (Node ships corepack).\n case \"$pm\" in\n pnpm) cmd=(corepack pnpm install --frozen-lockfile) ;;\n yarn)\n if [ -f \"$dir/.yarnrc.yml\" ]; then cmd=(corepack yarn install --immutable)\n else cmd=(corepack yarn install --frozen-lockfile)\n fi\n ;;\n npm) cmd=(npm ci) ;;\n esac\n echo \"Installing dependencies automatically: ${cmd[*]}\"\n started=$(date +%s)\n (cd \"$dir\" && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 timeout \"${ORCA_AUTO_INSTALL_TIMEOUT:-900}\" \"${cmd[@]}\") /dev/null || true\n return 0\n fi\n echo \"Installed dependencies in $(($(date +%s) - started))s.\"\n}\n\ntake_secrets\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 # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${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 for name in ${ORCA_BUILD_WITHHELD_SECRETS:-}; do\n echo \"$name is a model key, so environment builds don’t get it. Agents in workspaces still do.\"\n done\n (\n cd \"${first:-$ROOT}\" || exit 1\n if [ \"${#secret_names[@]}\" -gt 0 ]; then\n for i in \"${!secret_names[@]}\"; do export \"${secret_names[$i]}=${secret_values[$i]}\"; done\n fi\n exec bash -euo pipefail \"$OUT/install.sh\"\n ) /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\" \"$OUT/.scan-since\" \"$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-memguard b/cloud/apps/sandbox-control/image/vm/orca-memguard new file mode 100755 index 00000000000..51b368083a1 --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-memguard @@ -0,0 +1,308 @@ +#!/usr/bin/env bash +# Memory guard for the workspace VM (runs as root: `sudo -n orca-memguard start`). A build or test +# that eats the VM's memory must cost that process, never the workspace: without this the kernel +# thrashes for minutes before its OOM killer picks something, and the VM looks dead meanwhile. +# start start the guard for this boot unless it already runs (returns at once) +# run the guard loop itself (start runs it detached) +# release-swap turn off and delete on-demand swap (before a stop, so the snapshot stays small) +# sweep apply OOM-killer priorities once and exit (tests, diagnostics) +# victim print " " of the process the guard would stop now (no kill) +# Every few seconds it ranks processes for the kernel's OOM killer (oom_score_adj): +# -900 Orca's own runtime: orcad, its terminal daemon, the share proxy (Orca's bundled Node) +# -500 terminal shells (children of the terminal daemon) and agent CLIs +# 500 everything else (builds, tests, dev servers, browsers); never lowered +# When MemAvailable falls under KILL_PCT (8%) of RAM it kills the largest process ranked 0 or more, +# records it in $RUN/kills and $RUN/state, and waits for memory to return. The kernel's OOM killer +# stays the backstop for allocations faster than the guard's 200 ms look, with the same ranks. +# Swap is added on demand (2 GiB files up to 1.5x RAM) when memory runs low, if the kernel takes it, +# and dropped after 10 quiet minutes. It also sizes /dev/shm to half of RAM (the provider mounts +# 64 MB, which crashes Chrome and Electron renderers). +# $RUN/state (key=value, world-readable) is what the control plane's status probe reads. +set -uo pipefail +RUN=/run/orca-memguard +# Tests point it at a fake process table. +PROC="${ORCA_MEMGUARD_PROC:-/proc}" +SWAP_DIR=/var/lib/orca-memguard +ORCA_HOME=/opt/orca +KILL_PCT="${ORCA_MEMGUARD_KILL_PCT:-8}" +HIGH_PCT=15 +SWAP_ADD_PCT=20 +QUIET_PCT=50 +QUIET_SECONDS=600 +TICK=1 +FAST_TICK=0.2 +SWEEP_EVERY=3 +STATE_EVERY=15 +SWAP_CHUNK_KIB=$((2 * 1024 * 1024)) + +boot_id() { local id; read -r id >"$RUN/memguard.log"; } + +# Name of a process for people: the script a node/python/... runs, else its command name. +proc_name() { + local pid="$1" comm arg name='' skip=0 module=0 args=() + read -r comm 2>/dev/null <"$PROC/$pid/comm" || comm='' + mapfile -d '' -t args 2>/dev/null <"$PROC/$pid/cmdline" || true + case "${args[0]##*/}" in + node | nodejs | bun | deno | python* | ruby | perl | java | sh | bash | dash | zsh) + for arg in "${args[@]:1}"; do + if [ "$skip" -eq 1 ]; then skip=0; continue; fi + if [ "$module" -eq 1 ]; then name="${arg##*/}"; break; fi + case "$arg" in + # Inline code is no name (and may hold anything): the interpreter's name it is. + -e | -p | -c | --eval | --print) break ;; + -m | -jar) module=1 ;; # python -m pytest, java -jar gradle.jar: the module or jar + -r | --require | --import | --loader | -X | -W | -cp | -classpath) skip=1 ;; + -*) ;; + *) name="${arg##*/}"; break ;; + esac + done ;; + esac + [ -n "$name" ] || name="${args[0]##*/}" + [ -n "$name" ] || name="$comm" + name="${name%.js}" + name="${name%.mjs}" + name="${name%.cjs}" + name="${name%.jar}" + name="${name//[^A-Za-z0-9._+-]/}" + printf '%s' "${name:0:40}" +} + +# The terminal daemon's pid(s): Orca-runtime node processes running the daemon entry. +daemon_pids=' ' +# Sets RANK to the oom_score_adj a process should have; returns 1 for a kernel thread or a gone pid. +RANK=500 +rank() { + local pid="$1" args=() stat ppid + mapfile -d '' -t -n 3 args 2>/dev/null <"$PROC/$pid/cmdline" || return 1 + [ "${#args[@]}" -gt 0 ] || return 1 + RANK=-900 + case "${args[0]}" in "$ORCA_HOME"/runtime/runtimes/*) return 0 ;; esac + RANK=-500 + read -r stat 2>/dev/null <"$PROC/$pid/stat" || return 1 + stat="${stat##*) }" + ppid="${stat#* }" + ppid="${ppid%% *}" + case "$daemon_pids" in *" $ppid "*) return 0 ;; esac + case "${args[0]}/${args[1]:-}/${args[2]:-}" in "$ORCA_HOME"/tools/* | */"$ORCA_HOME"/tools/*) return 0 ;; esac + case "${args[0]##*/}" in claude | codex | opencode | gemini | cursor-agent | copilot | amp | droid) return 0 ;; esac + RANK=500 +} + +sweep() { + local p pid want adj args=() + daemon_pids=' ' + for p in "$PROC"/[0-9]*; do + pid="${p#"$PROC"/}" + mapfile -d '' -t -n 3 args 2>/dev/null <"$p/cmdline" || continue + [ "${#args[@]}" -ge 2 ] || continue + case "${args[0]}" in "$ORCA_HOME"/runtime/runtimes/*) ;; *) continue ;; esac + case "${args[*]:1}" in *"$ORCA_HOME"/runtime/orcad/daemon*) daemon_pids+="$pid " ;; esac + done + for p in "$PROC"/[0-9]*; do + pid="${p#"$PROC"/}" + [ "$pid" -gt 1 ] && [ "$pid" != "$$" ] || continue + read -r adj 2>/dev/null <"$p/oom_score_adj" || continue + # -1000 is a process that asked for it as root (sshd): leave it alone. + [ "$adj" -gt -1000 ] || continue + rank "$pid" || continue + want="$RANK" + # Never lower what a process raised for itself (Chrome ranks its renderers above its browser). + if [ "$want" -eq 500 ]; then + [ "$adj" -lt 500 ] || continue + fi + [ "$adj" -ne "$want" ] || continue + printf '%s\n' "$want" 2>/dev/null >"$p/oom_score_adj" || true + done +} + +mem_total=0 mem_avail=0 swap_total=0 swap_free=0 +read_mem() { + local key value _ + while read -r key value _; do + case "$key" in + MemTotal:) mem_total="$value" ;; + MemAvailable:) mem_avail="$value" ;; + SwapTotal:) swap_total="$value" ;; + SwapFree:) swap_free="$value" ;; + esac + done <"$PROC/meminfo" +} + +# PSI percentages (avg10, integer part); 0 when the kernel doesn't report them. +psi_some=0 psi_full=0 +read_psi() { + local kind avg _ + psi_some=0 psi_full=0 + [ -r "$PROC/pressure/memory" ] || return 0 + while read -r kind avg _; do + avg="${avg#avg10=}" + avg="${avg%%.*}" + case "$kind" in some) psi_some="$avg" ;; full) psi_full="$avg" ;; esac + done 2>/dev/null <"$PROC/pressure/memory" || true +} + +kills=0 last_kill_name='' last_kill_at=0 swap_mode=on-demand level=ok +write_state() { + local pct="$1" + { + printf 'bootId=%s\nat=%s\npid=%s\nlevel=%s\navailPct=%s\nmemTotalKiB=%s\nmemAvailKiB=%s\n' \ + "$BOOT" "$(now_ms)" "$$" "$level" "$pct" "$mem_total" "$mem_avail" + printf 'swapTotalKiB=%s\nswapFreeKiB=%s\nswap=%s\npsiSome10=%s\npsiFull10=%s\n' \ + "$swap_total" "$swap_free" "$swap_mode" "$psi_some" "$psi_full" + printf 'kills=%s\nlastKillName=%s\nlastKillAt=%s\n' "$kills" "$last_kill_name" "$last_kill_at" + } >"$RUN/state.tmp" && mv -f "$RUN/state.tmp" "$RUN/state" +} + +# Sets VICTIM/VICTIM_RSS (pages) to the largest process ranked 0 or more; returns 1 when there is none. +VICTIM=0 VICTIM_RSS=0 +choose_victim() { + local p pid adj rss _ best=0 best_rss=0 args=() + sweep + for p in "$PROC"/[0-9]*; do + pid="${p#"$PROC"/}" + [ "$pid" -gt 1 ] && [ "$pid" != "$$" ] || continue + read -r adj 2>/dev/null <"$p/oom_score_adj" || continue + [ "$adj" -ge 0 ] || continue + read -r _ rss _ 2>/dev/null <"$p/statm" || continue + # Kernel threads have no command line (and /proc sizes read 0, so `-s` can't tell). + mapfile -d '' -t -n 1 args 2>/dev/null <"$p/cmdline" || continue + [ "${#args[@]}" -gt 0 ] || continue + if [ "$rss" -gt "$best_rss" ]; then + best="$pid" best_rss="$rss" + fi + done + # Nothing big enough to matter (64 MiB): what fills memory is protected, so leave it to the kernel. + [ "$best" -gt 1 ] && [ "$best_rss" -ge 16384 ] || return 1 + VICTIM="$best" VICTIM_RSS="$best_rss" +} + +# Kills the largest process ranked 0 or more ($1: MemAvailable %). Returns 1 when there is none. +kill_largest() { + choose_victim || return 1 + local best="$VICTIM" best_rss="$VICTIM_RSS" name at + name="$(proc_name "$best")" + kill -KILL "$best" 2>/dev/null || return 1 + at="$(now_ms)" + kills=$((kills + 1)) last_kill_name="${name:-process}" last_kill_at="$at" + printf '%s %s %s %s %s\n' "$at" "$best" "$((best_rss * 4))" "$1" "$last_kill_name" >>"$RUN/kills" + tail -n 50 "$RUN/kills" >"$RUN/kills.tmp" && mv -f "$RUN/kills.tmp" "$RUN/kills" + log "killed pid=$best name=$last_kill_name rssKiB=$((best_rss * 4)) availPct=$1" + # Shells hear it like a kernel OOM kill (exit 137); this says why where someone may look. + logger -t orca-memguard "stopped $last_kill_name (pid $best, $((best_rss * 4)) KiB) at $1% memory available" 2>/dev/null || true + return 0 +} + +swap_files() { compgen -G "$SWAP_DIR/swap-*" || true; } +add_swap() { + [ "$swap_mode" = on-demand ] || return 1 + [ $((swap_total + SWAP_CHUNK_KIB)) -le $((mem_total * 3 / 2)) ] || return 1 + local free_kib file + free_kib="$(df -k --output=avail "$SWAP_DIR" 2>/dev/null | tail -n 1 | tr -d ' ')" + # Keep 4 GiB of the disk for the workspace itself. + [ "${free_kib:-0}" -gt $((SWAP_CHUNK_KIB + 4 * 1024 * 1024)) ] || return 1 + file="$SWAP_DIR/swap-$(now_ms)" + if fallocate -l "$((SWAP_CHUNK_KIB))K" "$file" 2>/dev/null && chmod 600 "$file" \ + && mkswap -q "$file" >/dev/null 2>&1 && swapon "$file" 2>/dev/null; then + log "swap on $file" + return 0 + fi + rm -f "$file" + # One refusal means this kernel or disk won't swap: don't retry every tick. + swap_mode=unsupported + log 'swap unavailable; guard kills only' + return 1 +} +release_swap() { + local file + for file in $(swap_files | sort -r); do + swapoff "$file" 2>/dev/null && rm -f "$file" && log "swap off $file" + done +} + +run() { + BOOT="$(boot_id)" + mkdir -p "$RUN" "$SWAP_DIR" + chmod 0755 "$RUN" + chmod 0700 "$SWAP_DIR" + # A resumed disk carries the last session's files: its kills and swap belong to that boot. + rm -f "$RUN/kills" "$RUN/state" "$RUN"/*.tmp + for file in $(swap_files); do + grep -q "^$file " /proc/swaps 2>/dev/null || rm -f "$file" + done + printf '%s %s\n' "$BOOT" "$$" >"$RUN/pid" + echo -1000 >/proc/self/oom_score_adj + read_mem + # Half of RAM for /dev/shm (tmpfs only takes pages that are written). + mount -o remount,size=50% /dev/shm 2>/dev/null && log "/dev/shm $(df -h --output=size /dev/shm | tail -n 1 | tr -d ' ')" + log "start mem=${mem_total}KiB" + local tick=0 pct quiet_since=0 prev='' now + while :; do + read_mem + read_psi + pct=$((mem_total > 0 ? mem_avail * 100 / mem_total : 100)) + if [ $((tick % SWEEP_EVERY)) -eq 0 ]; then + sweep + fi + if [ "$pct" -lt "$SWAP_ADD_PCT" ] && { [ "$swap_total" -eq 0 ] || [ $((swap_free * 4)) -lt "$swap_total" ]; }; then + add_swap && read_mem + fi + # Swap only raises MemAvailable by paging idle memory out: a fast allocator outruns it (the + # kernel OOM-killed a 300 MB/s hog with 1.7 GB of swap free), so the threshold ignores swap. + if [ "$pct" -lt "$KILL_PCT" ]; then + level=critical + if kill_largest "$pct"; then + write_state "$pct" + prev="$level:$kills" + sleep 1 # let the kernel reclaim the victim's memory before judging again + tick=$((tick + 1)) + continue + fi + elif [ "$psi_full" -ge 10 ]; then + level=critical + elif [ "$pct" -lt "$HIGH_PCT" ] || [ "$psi_some" -ge 20 ]; then + level=high + else + level=ok + fi + now="${EPOCHSECONDS}" + if [ "$pct" -ge "$QUIET_PCT" ] && [ "$swap_total" -gt 0 ]; then + [ "$quiet_since" -gt 0 ] || quiet_since="$now" + if [ $((now - quiet_since)) -ge "$QUIET_SECONDS" ] && [ $(((swap_total - swap_free) * 2)) -lt "$mem_avail" ]; then + release_swap + quiet_since=0 + fi + else + quiet_since=0 + fi + if [ "$level:$kills" != "$prev" ] || [ $((tick % STATE_EVERY)) -eq 0 ]; then + write_state "$pct" + prev="$level:$kills" + fi + tick=$((tick + 1)) + # Memory can go from 15% to nothing in two seconds: look five times as often when it is low. + if [ "$level" = ok ]; then sleep "$TICK"; else sleep "$FAST_TICK"; fi + done +} + +running() { + local boot pid + read -r boot pid <"$RUN/pid" 2>/dev/null || return 1 + [ "$boot" = "$(boot_id)" ] && [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null \ + && grep -qa orca-memguard "/proc/$pid/cmdline" 2>/dev/null +} + +case "${1:-}" in + start) + [ "$(id -u)" -eq 0 ] || { echo 'orca-memguard: needs root' >&2; exit 1; } + running && exit 0 + mkdir -p "$RUN" + setsid nohup "$0" run /dev/null 2>>"$RUN/memguard.log" & + exit 0 ;; + run) run ;; + sweep) sweep ;; + victim) choose_victim && printf '%s %s %s\n' "$VICTIM" "$((VICTIM_RSS * 4))" "$(proc_name "$VICTIM")" ;; + release-swap) release_swap ;; + *) echo 'usage: orca-memguard start|run|sweep|victim|release-swap' >&2; exit 2 ;; +esac diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-drain b/cloud/apps/sandbox-control/image/vm/orca-sandbox-drain index 8fbdbe82508..3963b5ea710 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-drain +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-drain @@ -12,6 +12,8 @@ kill -TERM "$pid" for _ in $(seq 1 $((WAIT_SECONDS * 10))); do if ! kill -0 "$pid" 2>/dev/null; then rm -f "$STATE/orcad.pid" "$STATE/ready.json" + # On-demand swap files would ride the stop snapshot (2 GiB each). Best effort, bounded. + [ -x /opt/orca/bin/orca-memguard ] && sudo -n timeout 20 /opt/orca/bin/orca-memguard release-swap >/dev/null 2>&1 || true exit 0 fi sleep 0.1 diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start index f6081682ae2..f32cff2d798 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start @@ -110,6 +110,10 @@ case "${ORCA_DOCKER:-}" in esac start_share_proxy unset ORCA_SHARE_PROXY_KEY +# MEMGUARD: OOM-killer ranks that spare orcad and terminals, a guard that stops the largest build or +# test before the VM stalls, on-demand swap and a /dev/shm sized for browsers. Before the +# already-started exit so a repair start brings a dead guard back; it returns at once. +sudo -n "$ORCA_HOME/bin/orca-memguard" start /dev/null 2>&1 9>&- || true if [ "$(cat "$STATE/boot-id" 2>/dev/null || true)" = "$boot_id" ] && [ -s "$STATE/ready.json" ] \ && kill -0 "$(cat "$STATE/orcad.pid" 2>/dev/null || echo 0)" 2>/dev/null; then print_ready diff --git a/cloud/apps/sandbox-control/src/sandbox-vm-inspect.ts b/cloud/apps/sandbox-control/src/sandbox-vm-inspect.ts index b981b2f59b3..fbdb718fb42 100644 --- a/cloud/apps/sandbox-control/src/sandbox-vm-inspect.ts +++ b/cloud/apps/sandbox-control/src/sandbox-vm-inspect.ts @@ -6,6 +6,8 @@ import { z } from 'zod' import { ProviderError, type SandboxProviderApi } from './sandbox-provider' const PROJECT = '/vercel/sandbox/project' +/** Written by the VM's memory guard (image/vm/orca-memguard). */ +const GUARD_STATE = '/run/orca-memguard/state' /** * CPU from two /proc/stat samples 250 ms apart, memory from /proc/meminfo, disk for the project @@ -28,9 +30,22 @@ victim=$(sudo -n dmesg 2>/dev/null | grep -oE 'Killed process [0-9]+ \([^)]{1,64 [ "$victim" = MainThread ] && victim=node orcad=false; pid=$(cat "$HOME/.orca-sandbox/orcad.pid" 2>/dev/null || echo 0); [ "$pid" -gt 1 ] 2>/dev/null && kill -0 "$pid" 2>/dev/null && orcad=true load=$(awk '{print $1}' /proc/loadavg) -printf '{"cpuPercent":%d,"cpus":%d,"load1":%s,"memTotalBytes":%d,"memUsedBytes":%d,"diskTotalBytes":%d,"diskUsedBytes":%d,"uptimeSeconds":%d,"oomKills":%d,"lastOomVictim":%s,"orcadAlive":%s}\n' \ +# MEMGUARD: the memory guard's state (orca-memguard), when it runs this boot and wrote in the last minute. +guard=null +if [ -r ${GUARD_STATE} ]; then + g() { sed -n "s/^$1=//p" ${GUARD_STATE} | head -n 1; } + g_at=$(g at); g_level=$(g level); g_kills=$(g kills); g_name=$(g lastKillName | tr -cd 'A-Za-z0-9._+-' | head -c 40); g_kill_at=$(g lastKillAt) + g_swap=$(g swapTotalKiB); [[ "$g_swap" =~ ^[0-9]+$ ]] && g_swap=$((g_swap * 1024)) || g_swap=0 + now_ms=$(( $(date +%s%3N) )) + if [ "$(g bootId)" = "$(cat /proc/sys/kernel/random/boot_id)" ] && [[ "$g_at" =~ ^[0-9]+$ ]] && [ $((now_ms - g_at)) -lt 60000 ] \ + && [[ "$g_level" =~ ^(ok|high|critical)$ ]] && [[ "$g_kills" =~ ^[0-9]+$ ]] && [[ "$g_kill_at" =~ ^[0-9]+$ ]]; then + guard=$(printf '{"level":"%s","kills":%d,"lastKillName":%s,"lastKillAt":%s,"swapBytes":%d}' "$g_level" "$g_kills" \ + "$( [ -n "$g_name" ] && printf '"%s"' "$g_name" || printf null )" "$( [ "$g_kill_at" -gt 0 ] && printf '%s' "$g_kill_at" || printf null )" "$g_swap") + fi +fi +printf '{"cpuPercent":%d,"cpus":%d,"load1":%s,"memTotalBytes":%d,"memUsedBytes":%d,"diskTotalBytes":%d,"diskUsedBytes":%d,"uptimeSeconds":%d,"oomKills":%d,"lastOomVictim":%s,"orcadAlive":%s,"guard":%s}\n' \ "$cpu_pct" "$(nproc)" "$load" "$mem_total" "$((mem_total-mem_avail))" "\${disk_total:-0}" "\${disk_used:-0}" "$uptime_s" "$oom" \ - "$( [ -n "$victim" ] && printf '"%s"' "$victim" || printf null )" "$orcad" + "$( [ -n "$victim" ] && printf '"%s"' "$victim" || printf null )" "$orcad" "$guard" `.replaceAll('\\${', '${') export const VmMetricsSchema = z @@ -51,6 +66,41 @@ export const VmMetricsSchema = z export type VmMetrics = z.infer +/** The memory guard's last word: its pressure level, the processes it stopped this boot, its swap. */ +export const VmGuardSchema = z + .object({ + level: z.enum(['ok', 'high', 'critical']), + kills: z.number().int().min(0), + lastKillName: z.string().max(40).nullable(), + lastKillAt: z.number().int().positive().nullable(), + swapBytes: z.number().int().min(0) + }) + .strict() +export type VmGuard = z.infer + +// The probe's line: the metrics plus the guard (null when no guard ran this boot: an older image). +const VmProbeSchema = VmMetricsSchema.extend({ guard: VmGuardSchema.nullable().optional() }).strict() + +/** Memory pressure for the status read: the guard's level, else one from MemAvailable alone. */ +export type WorkspaceMemory = { + pressure: 'ok' | 'high' | 'critical' + /** Processes the guard stopped this boot (the kernel's own OOM kills are `metrics.oomKills`). */ + guardKills: number + lastGuardVictim: string | null + lastGuardKillAt: number | null + /** False when the VM runs no guard: pressure is then MemAvailable's, and nothing is stopped early. */ + guarded: boolean +} + +export function workspaceMemory(metrics: VmMetrics, guard: VmGuard | null): WorkspaceMemory { + if (guard) { + return { pressure: guard.level, guardKills: guard.kills, lastGuardVictim: guard.lastKillName, lastGuardKillAt: guard.lastKillAt, guarded: true } + } + const availPct = metrics.memTotalBytes > 0 ? ((metrics.memTotalBytes - metrics.memUsedBytes) * 100) / metrics.memTotalBytes : 100 + const pressure = availPct < 8 ? 'critical' : availPct < 15 ? 'high' : 'ok' + return { pressure, guardKills: 0, lastGuardVictim: null, lastGuardKillAt: null, guarded: false } +} + const MAX_TREE = 2000 const MAX_CHANGED = 300 const MAX_COMMITS = 20 @@ -164,8 +214,17 @@ async function runJson( } /** Null when the VM did not answer in time (the status panel shows "Unresponsive"). */ -export function readVmMetrics(provider: SandboxProviderApi, sessionId: string): Promise { - return runJson(provider, sessionId, METRICS_SCRIPT, VmMetricsSchema, 8_000) +export async function readVmMetrics( + provider: SandboxProviderApi, + sessionId: string +): Promise<{ metrics: VmMetrics; memory: WorkspaceMemory } | null> { + const probe = await runJson(provider, sessionId, METRICS_SCRIPT, VmProbeSchema, 8_000) + if (!probe) { + return null + } + // `metrics` keeps its exact shape: desktops parse it strictly. + const { guard, ...metrics } = probe + return { metrics, memory: workspaceMemory(metrics, guard ?? null) } } export function captureArchiveMetadata(provider: SandboxProviderApi, sessionId: string): Promise { diff --git a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts index 838731a3154..8ea7889ac24 100644 --- a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts +++ b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts @@ -22,6 +22,7 @@ import { ArchiveMetadataSchema, captureArchiveMetadata, readVmMetrics, + type WorkspaceMemory, type ArchiveMetadata, type VmMetrics } from './sandbox-vm-inspect' @@ -359,6 +360,8 @@ export async function expiredArchives(db: D1Database, now: number): Promise spawnSync(path, ['-c', '[ "${BASH_VERSINFO[0]}${BASH_VERSINFO[1]}" -ge 44 ]']).status === 0 +) + +const NODE = '/opt/orca/runtime/runtimes/node-abc/bin/node' +let proc = '' + +function fake(pid: number, opts: { ppid: number; adj: number; rssPages: number; argv: string[]; comm?: string }): void { + const dir = join(proc, String(pid)) + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, 'cmdline'), opts.argv.length ? `${opts.argv.join('\0')}\0` : '') + writeFileSync(join(dir, 'comm'), `${opts.comm ?? 'x'}\n`) + writeFileSync(join(dir, 'stat'), `${pid} (${opts.comm ?? 'x'}) S ${opts.ppid} ${pid} ${pid} 0 -1\n`) + writeFileSync(join(dir, 'statm'), `${opts.rssPages * 2} ${opts.rssPages} 100 1 0 1 0\n`) + writeFileSync(join(dir, 'oom_score_adj'), `${opts.adj}\n`) +} +const adj = (pid: number): number => Number(readFileSync(join(proc, String(pid), 'oom_score_adj'), 'utf8').trim()) +const guard = (command: string) => spawnSync(bash!, [GUARD, command], { env: { PATH: process.env.PATH, ORCA_MEMGUARD_PROC: proc }, encoding: 'utf8' }) + +beforeEach(() => { + proc = mkdtempSync(join(tmpdir(), 'orca-memguard-proc-')) + fake(1, { ppid: 0, adj: 500, rssPages: 3000, argv: ['/run/vercel/share/sandbox-init'] }) + fake(100, { ppid: 1, adj: 500, rssPages: 2_000_000, argv: [NODE, '/opt/orca/bin/orcad-boot', '--code-cache'], comm: 'MainThread' }) + fake(101, { ppid: 100, adj: 500, rssPages: 20_000, argv: [NODE, '--max-semi-space-size=4', '/opt/orca/runtime/orcad/daemon-entry.js'] }) + // A terminal's shell, and a typecheck it started (inherited the shell's rank). + fake(102, { ppid: 101, adj: 500, rssPages: 1_000, argv: ['/bin/bash', '-l'], comm: 'bash' }) + fake(103, { ppid: 102, adj: -500, rssPages: 900_000, argv: ['node', '--max-old-space-size=8192', '/w/node_modules/typescript/bin/tsc', '-p', '.'], comm: 'MainThread' }) + fake(104, { ppid: 102, adj: 300, rssPages: 40_000, argv: ['/opt/google/chrome/chrome', '--type=renderer'], comm: 'chrome' }) + fake(105, { ppid: 102, adj: 800, rssPages: 40_000, argv: ['/usr/bin/some-tool'] }) + fake(106, { ppid: 1, adj: -1000, rssPages: 600, argv: ['sshd: /opt/orca/openssh/sshd'] }) + fake(107, { ppid: 102, adj: 500, rssPages: 400_000, argv: ['/opt/orca/tools/bin/claude'], comm: 'claude' }) + fake(108, { ppid: 2, adj: 0, rssPages: 0, argv: [] }) // a kernel thread +}) +afterEach(() => rmSync(proc, { recursive: true, force: true })) + +describe.skipIf(!bash)('orca-memguard', () => { + it('protects the runtime, terminals and agents, and makes everything else the first victim', () => { + expect(guard('sweep').status).toBe(0) + expect([100, 101].map(adj)).toEqual([-900, -900]) + expect(adj(102)).toBe(-500) // the terminal's shell + expect(adj(107)).toBe(-500) // an agent CLI + expect(adj(103)).toBe(500) // the shell's typecheck no longer inherits its rank + expect(adj(104)).toBe(500) + expect(adj(105)).toBe(800) // a process that raised its own rank keeps it + expect(adj(106)).toBe(-1000) // what root pinned stays pinned + expect(adj(108)).toBe(0) // kernel threads are not touched + expect(adj(1)).toBe(500) + }) + + it('would stop the largest unprotected process and names it by its script', () => { + const result = guard('victim') + expect(result.status).toBe(0) + expect(result.stdout.trim()).toBe(`103 ${900_000 * 4} tsc`) + }) + + it('names inline code by its interpreter, and leaves small processes to the kernel', () => { + fake(103, { ppid: 102, adj: 500, rssPages: 900_000, argv: ['node', '-e', 'const secret = 1'], comm: 'MainThread' }) + expect(guard('victim').stdout.trim()).toBe(`103 ${900_000 * 4} node`) + rmSync(join(proc, '103'), { recursive: true }) + rmSync(join(proc, '104'), { recursive: true }) + rmSync(join(proc, '105'), { recursive: true }) + // Only protected memory is large: nothing worth stopping. + expect(guard('victim').status).toBe(1) + }) + + it('starts from orca-sandbox-start before its already-running exit', () => { + const start = readFileSync(START, 'utf8') + const launch = start.indexOf('orca-memguard" start') + expect(launch).toBeGreaterThan(0) + expect(launch).toBeLessThan(start.indexOf('print_ready\n exit 0')) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspace-lifecycle.test.ts b/cloud/apps/sandbox-control/test/workspace-lifecycle.test.ts index f567534e665..e43d476afee 100644 --- a/cloud/apps/sandbox-control/test/workspace-lifecycle.test.ts +++ b/cloud/apps/sandbox-control/test/workspace-lifecycle.test.ts @@ -154,6 +154,28 @@ describe('status panel', () => { expect(status.metrics).toMatchObject({ oomKills: 1, lastOomVictim: 'node' }) }) + it('reports memory pressure and guard kills beside the metrics, which keep their strict shape', async () => { + const { h, id } = await running() + const guard = { level: 'high', kills: 2, lastKillName: 'tsc', lastKillAt: 1_800_000_000_000, swapBytes: 2 ** 31 } + h.vercel.onScript = (script) => (script === METRICS_SCRIPT ? { exitCode: 0, stdout: `${metricsLine({ guard })}\n`, stderr: '' } : undefined) + const body = (await h.call('GET', `/v1/sandboxes/${id}/status`)).body + expect(body.status.metrics).not.toHaveProperty('guard') + const { status } = HostedWorkspaceStatusResponseSchema.parse(body) + expect(status.state).toBe('ready') + expect(status.memory).toEqual({ pressure: 'high', guardKills: 2, lastGuardVictim: 'tsc', lastGuardKillAt: 1_800_000_000_000, guarded: true }) + }) + + it('derives pressure from MemAvailable when the VM runs no guard (an older image)', async () => { + const { h, id } = await running() + h.vercel.onScript = (script) => + script === METRICS_SCRIPT ? { exitCode: 0, stdout: `${metricsLine({ memUsedBytes: 7.5e9, guard: null })}\n`, stderr: '' } : undefined + const { status } = HostedWorkspaceStatusResponseSchema.parse((await h.call('GET', `/v1/sandboxes/${id}/status`)).body) + expect(status.memory).toEqual({ pressure: 'critical', guardKills: 0, lastGuardVictim: null, lastGuardKillAt: null, guarded: false }) + h.vercel.onScript = (script) => (script === METRICS_SCRIPT ? { exitCode: 0, stdout: `${metricsLine()}\n`, stderr: '' } : undefined) + const again = HostedWorkspaceStatusResponseSchema.parse((await h.call('GET', `/v1/sandboxes/${id}/status`)).body) + expect(again.status.memory?.pressure).toBe('ok') + }) + it('counts settled sessions in the cost and does not probe a sleeping VM', async () => { const { h, id } = await running() h.advance(60 * 60_000) diff --git a/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts b/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts index f5729d40d79..f80d520adb7 100644 --- a/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts +++ b/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts @@ -57,6 +57,30 @@ describe('OOM tracker', () => { expect(events).toHaveLength(3) }) + it('announces guard kills as the guard stopping a named process, counted with kernel kills', () => { + const events: CloudOomEvent[] = [] + const tracker = createOomTracker((event) => events.push(event)) + const guarded = (checkedAt: number, uptime: number, kernel: number, guardKills: number) => ({ + ...status(checkedAt, uptime, kernel), + memory: { + pressure: 'high' as const, + guardKills, + lastGuardVictim: guardKills ? 'tsc' : null, + lastGuardKillAt: guardKills ? checkedAt : null, + guarded: true + } + }) + const t0 = 1_000_000_000 + tracker.observe('ws', 'sbx', guarded(t0, 100, 0, 0)) + tracker.observe('ws', 'sbx', guarded(t0 + 60_000, 160, 0, 1)) + tracker.observe('ws', 'sbx', guarded(t0 + 120_000, 220, 0, 1)) + tracker.observe('ws', 'sbx', guarded(t0 + 180_000, 280, 1, 1)) + expect(events).toEqual([ + { workspaceId: 'ws', oomKills: 1, victim: 'tsc', stoppedBy: 'guard', at: expect.any(Number) }, + { workspaceId: 'ws', oomKills: 2, victim: 'node', at: expect.any(Number) } + ]) + }) + it('ignores a status without metrics', () => { const events: CloudOomEvent[] = [] createOomTracker((event) => events.push(event)).observe('ws', 'sbx', { diff --git a/src/main/hosted-sandbox/hosted-workspace-runtime.ts b/src/main/hosted-sandbox/hosted-workspace-runtime.ts index 54cd4ac79b0..27dbc7b29e0 100644 --- a/src/main/hosted-sandbox/hosted-workspace-runtime.ts +++ b/src/main/hosted-sandbox/hosted-workspace-runtime.ts @@ -115,12 +115,13 @@ export function trimCheckouts(input: HostedArchiveCheckout[]): HostedArchiveChec } /** - * Announces each new kernel OOM kill once. The counter resets per VM boot; two readings belong to - * one boot when their implied boot times agree within two minutes (uptime and checkedAt come from + * Announces each new OOM kill once: the kernel's, and the memory guard's (MEMGUARD: processes the + * VM stopped before the kernel had to). Both counters reset per VM boot; two readings belong to one + * boot when their implied boot times agree within two minutes (uptime and checkedAt come from * different clocks). */ export function createOomTracker(announce: (event: CloudOomEvent) => void) { - const seen = new Map() + const seen = new Map() return { observe( workspaceId: string, @@ -132,19 +133,26 @@ export function createOomTracker(announce: (event: CloudOomEvent) => void) { if (!metrics) { return } + const guardKills = status.memory?.guardKills ?? 0 const bootAt = status.checkedAt - metrics.uptimeSeconds * 1000 const previous = seen.get(sandboxId) const sameBoot = previous !== undefined && Math.abs(previous.bootAt - bootAt) < 120_000 - const announced = sameBoot ? previous.kills : 0 + const kernel = sameBoot ? previous.kernel : 0 + const guard = sameBoot ? previous.guard : 0 seen.set(sandboxId, { bootAt: sameBoot ? previous.bootAt : bootAt, - kills: Math.max(announced, metrics.oomKills) + kernel: Math.max(kernel, metrics.oomKills), + guard: Math.max(guard, guardKills) }) - if (metrics.oomKills > announced) { + const byGuard = guardKills > guard + if (byGuard || metrics.oomKills > kernel) { announce({ workspaceId, - oomKills: metrics.oomKills, - victim: metrics.lastOomVictim, + // One count for dismissal: either kind of new kill shows the notice again. + oomKills: Math.max(kernel, metrics.oomKills) + Math.max(guard, guardKills), + // The guard names the process it chose; the kernel's name comes from its log. + victim: byGuard ? (status.memory?.lastGuardVictim ?? null) : metrics.lastOomVictim, + ...(byGuard ? { stoppedBy: 'guard' as const } : {}), at: now }) } diff --git a/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx new file mode 100644 index 00000000000..8ce10ae2616 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx @@ -0,0 +1,66 @@ +import { Cloud } from 'lucide-react' +import { defineFixture } from '../../component-fixtures/component-fixture' +import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import type { HostedWorkspaceStatus } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' +import { CloudMemoryPressureMark } from './CloudMemoryPressureMark' + +type Pressure = 'high' | 'critical' + +// MEMGUARD: a running cloud workspace's sidebar row while its VM is short of memory. +function seed(pressure: Pressure): void { + const status: HostedWorkspaceStatus = { + state: 'ready', + metrics: null, + memory: { + pressure, + guardKills: 0, + lastGuardVictim: null, + lastGuardKillAt: null, + guarded: true + }, + uptimeMs: 60_000, + usage: { totalMs: 60_000, centsPerHour: 75, costCents: 1 }, + archive: null, + checkedAt: Date.now() + } + seedCloudWorkspaceSnapshot({ + ids: new Set(['gudgeon']), + idsLoaded: true, + status: { gudgeon: { status, loading: false, error: null, fetchedAt: Date.now() } } + }) +} + +function Row(): React.JSX.Element { + return ( +
      + + gudgeon + +
      + ) +} + +const markFixture = (pressure: Pressure) => + defineFixture({ + width: 380, + render: () => { + seed(pressure) + return ( +
      + +
      + ) + }, + interact: async (frame: HTMLElement) => { + await new Promise((resolve) => setTimeout(resolve, 50)) + const mark = frame.querySelector('[data-cloud-memory-pressure]') + mark?.dispatchEvent(new PointerEvent('pointermove', { bubbles: true })) + mark?.dispatchEvent(new PointerEvent('pointerenter', { bubbles: true })) + await new Promise((resolve) => setTimeout(resolve, 900)) + } + }) + +/** Memory is low (under 15% available, or the kernel stalls on it): the quiet mark. */ +export const sidebarRowMemoryHigh = markFixture('high') +/** Under 8%: Orca's guard may stop the largest process. Amber. */ +export const sidebarRowMemoryCritical = markFixture('critical') diff --git a/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx new file mode 100644 index 00000000000..78f3eeb5ecd --- /dev/null +++ b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx @@ -0,0 +1,53 @@ +import React from 'react' +import { MemoryStick } from 'lucide-react' +import { cn } from '@/lib/class-names' +import { useTranslate } from '@/i18n/use-translate' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { useCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import { cloudMemoryPressure } from '@/lib/orca-cloud/orca-cloud-workspace-state' + +/** + * MEMGUARD: the sidebar row's mark for a cloud workspace short of memory, from the status read + * (refreshed every minute while it runs). Quiet while memory is low; amber once Orca may stop the + * largest process to keep the workspace responsive. Renders nothing otherwise. + */ +export function CloudMemoryPressureMark({ + worktreeId +}: { + worktreeId: string +}): React.JSX.Element | null { + const t = useTranslate() + const pressure = useCloudWorkspace((state) => + cloudMemoryPressure(state.status[worktreeId]?.status) + ) + if (!pressure) { + return null + } + const label = + pressure === 'critical' + ? t( + 'orcaCloud.memoryPressure.critical', + 'Out of memory. Orca may stop the largest process to keep the workspace responsive.' + ) + : t('orcaCloud.memoryPressure.high', 'Running low on memory') + return ( + + + + + + + + {label} + + + ) +} diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceNotice.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceNotice.tsx index e221143e5b1..af6b8be215b 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceNotice.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceNotice.tsx @@ -2,6 +2,7 @@ import React, { useId } from 'react' import type { LucideIcon } from 'lucide-react' import { CircleArrowUp, + Gauge, Loader2, MemoryStick, Plus, @@ -85,21 +86,59 @@ function CloudNoticeCard({ /** * The workspace stopped answering, or a process ran out of memory. Both offer Restart (same disk). + * MEMGUARD: when Orca's memory guard stopped the process, the workspace is fine and needs no + * restart: the notice says what was stopped and offers machine sizes instead. */ export function CloudWorkspaceNotice({ notice, restarting, onRestart, + onMachineSize, onDismiss }: { notice: CloudNoticeKind restarting: boolean onRestart: () => void + /** Opens where machine sizes are chosen (cloud environments); without it the guard notice has no action. */ + onMachineSize?: () => void onDismiss?: () => void }): React.JSX.Element { const t = useTranslate() const isOom = notice.kind === 'oom' const victim = isOom ? notice.oom.victim : null + if (isOom && notice.oom.stoppedBy === 'guard') { + return ( + + + {t('orcaCloudWorkspace.oom.machineSize', 'Machine size')} + + ) : null + } + /> + ) + } const title = isOom ? victim ? t('orcaCloudWorkspace.oom.titleRan', '{{name}} ran out of memory', { name: victim }) diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceSurfaces.test.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceSurfaces.test.tsx index a1e7c2a1749..bd21140f1d3 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceSurfaces.test.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceSurfaces.test.tsx @@ -260,6 +260,30 @@ describe('Orca Cloud surfaces', () => { expect(onDismiss).toHaveBeenCalled() }) + it('a guard kill says Orca stopped the process and offers machine sizes, not Restart', () => { + const onMachineSize = vi.fn() + const onRestart = vi.fn() + const { getByRole, queryByRole } = render( + + ) + const text = getByRole('alert').textContent + expect(text).toContain('Orca stopped tsc to keep the workspace responsive') + expect(text).toContain('The workspace was out of memory. Consider a larger machine.') + expect(queryByRole('button', { name: 'Restart' })).toBeNull() + fireEvent.click(getByRole('button', { name: 'Machine size' })) + expect(onMachineSize).toHaveBeenCalled() + expect(onRestart).not.toHaveBeenCalled() + }) + it('version skew: an older sandbox offers a new workspace, a newer one an update', () => { const onCheckForUpdates = vi.fn() const onCreateWorkspace = vi.fn() diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx index 88b504bd78f..ad744652264 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx @@ -308,6 +308,25 @@ export const noticeOom = defineFixture({ ) }) +/** MEMGUARD: Orca's memory guard stopped the process; the workspace stayed up, so no Restart. */ +export const noticeOomGuard = defineFixture({ + width: 420, + render: () => ( +
      + +
      + ) +}) + function IdleToast(): React.JSX.Element { useEffect(() => { showIdleSleepNotice('ws', 'fix-auth-redirect', 20 * 60_000) diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx index 46e552cea4b..a6980dc4292 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx @@ -44,6 +44,13 @@ import { clearWakeInput } from '@/components/terminal-pane/input/wake-input-buff import { runUnarchiveCloudWorkspace, wakeCloudWorkspace } from './cloud-workspace-actions' import { keepWorkspaceAwakeDuringSleep } from '@/components/sidebar/workspace-actions/sleep/workspace-sleep-follower' +/** Machine sizes live on the team's cloud environments (MEMGUARD's "Consider a larger machine"). */ +function openMachineSizes(): void { + const store = useAppStore.getState() + store.openSettingsTarget({ pane: 'cloud-environments', repoId: null }) + store.openSettingsPage() +} + /** * The Orca Cloud layer over the active workspace, one mount for all of it: the archived view, * the "Waking…" overlay, the asleep (cached, read-only) view, and the not-responding / out-of- @@ -265,6 +272,7 @@ function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Eleme notice={{ kind: 'oom', oom: view.oom }} restarting={view.pending === 'restart'} onRestart={restart} + onMachineSize={openMachineSizes} onDismiss={() => dismissCloudOom(workspaceId)} /> ) diff --git a/src/renderer/src/components/sidebar/workspace-card/template/card-identity-parts.tsx b/src/renderer/src/components/sidebar/workspace-card/template/card-identity-parts.tsx index 230bfd25ed2..adcd04e447e 100644 --- a/src/renderer/src/components/sidebar/workspace-card/template/card-identity-parts.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/template/card-identity-parts.tsx @@ -26,6 +26,7 @@ import { WorktreeHostContextBadge } from '../host/WorktreeHostContextBadge' import { WorktreeCardHostMark, WorktreeCardHostStateWord } from '../host/WorktreeCardHostMark' import { WorktreeTitleInlineRename } from '../identity/WorktreeTitleInlineRename' import { CloudAgentHeldMark } from '@/components/orca-cloud/CloudAgentHeldMark' +import { CloudMemoryPressureMark } from '@/components/orca-cloud/CloudMemoryPressureMark' import { cardElement } from './card-template-compiler' type Card = WorktreeCardController @@ -58,6 +59,8 @@ function title(props: Readonly>, card: Card): React.Reac /> {/* N-03: the agent waits on its pane's strip (Orca Cloud): this mark is the signal away. */} {card.titleRenaming ? null : } + {/* MEMGUARD: the cloud VM is short of memory. */} + {card.titleRenaming ? null : } ) } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts index 6a83c1412df..70bdf3a0c84 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/cloud-workspace-api' import type { HostedWorkspaceStatus } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' import { + cloudMemoryPressure, buildFileTree, deriveCloudDotState, formatBytes, @@ -150,6 +151,25 @@ describe('visibleOom', () => { ).toBe('archived') }) + it('marks memory pressure only on a ready VM that is short of memory', () => { + const memory = (pressure: 'ok' | 'high' | 'critical') => ({ + pressure, + guardKills: 0, + lastGuardVictim: null, + lastGuardKillAt: null, + guarded: true + }) + expect(cloudMemoryPressure({ ...status('ready'), memory: memory('high') })).toBe('high') + expect(cloudMemoryPressure({ ...status('ready'), memory: memory('critical') })).toBe('critical') + expect(cloudMemoryPressure({ ...status('ready'), memory: memory('ok') })).toBeNull() + // An older control plane says nothing; a sleeping or unresponsive VM shows its own state. + expect(cloudMemoryPressure(status('ready'))).toBeNull() + expect( + cloudMemoryPressure({ ...status('unresponsive'), memory: memory('critical') }) + ).toBeNull() + expect(cloudMemoryPressure(null)).toBeNull() + }) + it('hides kills the user dismissed and shows newer ones', () => { const oom = { workspaceId: 'w', oomKills: 2, victim: 'node', at: NOW } expect(visibleOom(oom, undefined)).toBe(oom) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts index c2cad9da465..62576814c8e 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts @@ -100,6 +100,20 @@ export function deriveCloudDotState(input: { } } +/** + * MEMGUARD: the sidebar row's memory mark. Only for a VM read as ready (a sleeping or unresponsive + * one has its own state), and only when memory is short. + */ +export function cloudMemoryPressure( + status: HostedWorkspaceStatus | null | undefined +): 'high' | 'critical' | null { + if (status?.state !== 'ready') { + return null + } + const pressure = status.memory?.pressure + return pressure === 'high' || pressure === 'critical' ? pressure : null +} + /** An OOM notice shows for kills the user has not dismissed. */ export function visibleOom( oom: CloudOomEvent | undefined, diff --git a/src/shared/hosted-sandbox/cloud-workspace-api.ts b/src/shared/hosted-sandbox/cloud-workspace-api.ts index b2d96596b36..0c33ef39d90 100644 --- a/src/shared/hosted-sandbox/cloud-workspace-api.ts +++ b/src/shared/hosted-sandbox/cloud-workspace-api.ts @@ -55,9 +55,11 @@ export type CloudWakeProgressEvent = { export type CloudOomEvent = { workspaceId: string - /** Kernel OOM-kill counter after this notice (monotonic per VM boot). */ + /** Kernel plus memory-guard kills after this notice (monotonic per VM boot). */ oomKills: number victim: string | null + /** MEMGUARD: Orca's memory guard stopped it (the workspace stayed responsive), not the kernel. */ + stoppedBy?: 'guard' at: number } diff --git a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts index a9535d11474..675701dac84 100644 --- a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts +++ b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts @@ -272,6 +272,19 @@ export const HostedWorkspaceStatusSchema = z archive: z.object({ archivedAt: Millis, expiresAt: Millis.nullable() }).strict().nullable(), // Optional: older control planes omit it; the desktop then uses its 15 min fallback. idleSleepMinutes: z.number().int().positive().max(1440).optional(), + // Optional: older control planes omit it. MEMGUARD: memory pressure in the VM and the processes + // its memory guard stopped this boot (kernel OOM kills stay in `metrics.oomKills`). + memory: z + .object({ + pressure: z.enum(['ok', 'high', 'critical']), + guardKills: z.number().int().nonnegative(), + lastGuardVictim: z.string().max(64).nullable(), + lastGuardKillAt: Millis.nullable(), + guarded: z.boolean() + }) + .strip() + .nullable() + .optional(), // Optional (feature `wake-hints`): predictive wake's inputs. The last sleep someone chose, from // any client (not the idle timer), and sandboxes running against the owner's seat and account. lastUserSleepAt: Millis.nullable().optional(), From 554bf8fd9818070ea3aeffe4d44cf55cd0b99571 Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 03:10:34 -0800 Subject: [PATCH 25/35] perf(cloud): the image carries OpenCode's config-dir install; a fresh home gets a copy, so the first launch never fetches --- .../sandbox-control/image/provision-golden.sh | 10 +++++++ .../image/vm-scripts.generated.ts | 8 ++--- .../image/vm/orca-sandbox-start | 30 +++++++++++-------- 3 files changed, 32 insertions(+), 16 deletions(-) diff --git a/cloud/apps/sandbox-control/image/provision-golden.sh b/cloud/apps/sandbox-control/image/provision-golden.sh index ac3b5075a71..fdb440c053a 100755 --- a/cloud/apps/sandbox-control/image/provision-golden.sh +++ b/cloud/apps/sandbox-control/image/provision-golden.sh @@ -98,6 +98,16 @@ if [ -x "$opencode_pkg/bin/opencode.exe" ]; then [ "$(stat -c %i "$variant/bin/opencode" 2>/dev/null)" = "$picked" ] || rm -rf "$variant" done "$opencode_pkg/bin/opencode.exe" --version >/dev/null + # OpenCode installs @opencode-ai/plugin (its own version) into ~/.config/opencode on every start + # until that dir has node_modules and a lock listing it, and draws nothing until that install ends + # once a plugin is configured (Orca's is): with a slow or unreachable registry the first launch + # sat blank ~85 s (n73). Install it here once; orca-sandbox-start copies it into a fresh home. + oc_seed="$ORCA_HOME/opencode-config-seed" + mkdir -p "$oc_seed" + printf '{\n "dependencies": {\n "@opencode-ai/plugin": "%s"\n }\n}\n' \ + "$("$opencode_pkg/bin/opencode.exe" --version)" >"$oc_seed/package.json" + (cd "$oc_seed" && npm install --no-fund --no-audit --ignore-scripts >/dev/null) + test -s "$oc_seed/package-lock.json" && test -d "$oc_seed/node_modules/@opencode-ai/plugin" fi # Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 6e6c943b60c..faa91834c3f 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -2,10 +2,10 @@ 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.\n# [ORCA_VM_SCRIPTS_STAMP] (VM_SCRIPTS_STAMP of those scripts; written to /opt/orca/bin/.scripts-stamp).\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-agent-signout 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 docker; 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# Which entry points this image carries (VM_SCRIPTS_STAMP): a Worker with older scripts never\n# reinstalls over them. Absent (old callers) reads as 0, so any Worker may still update the image.\nrm -f \"$ORCA_HOME/bin/.scripts-stamp\" \"$ORCA_HOME\"/bin/.entry-points-*\nif [[ \"${ORCA_VM_SCRIPTS_STAMP:-}\" =~ ^[0-9]+$ ]]; then\n printf '%s\\n' \"$ORCA_VM_SCRIPTS_STAMP\" >\"$ORCA_HOME/bin/.scripts-stamp\"\nfi\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# ORCA_DOCKER (on|off: the control plane's Docker switch for the `docker` shim).\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)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\n# PARITY-DOCKER: the control plane's Docker switch (SANDBOX_DOCKER) for the `docker` shim. Only a\n# start that says so changes it; a retried or repair start (no ORCA_DOCKER) keeps the last answer.\ncase \"${ORCA_DOCKER:-}\" in\n off) : >\"$STATE/docker.off\" ;;\n on) rm -f \"$STATE/docker.off\" ;;\nesac\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# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\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.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\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# OpenCode's first run in a VM installs its plugin SDK into ~/.config/opencode, creates its database\n# and fetches its model list: ~2.5 s more on the first launch (5.2 s vs 2.7 s warm, n72). orca-sandbox-env\n# just wrote that config, so do the first run now, in the background at low priority, with no\n# credentials (`opencode models` does all of it and exits). The SDK install only happens once orcad\n# has put Orca's plugin in ~/.config/opencode/plugins (~10 s after this, n73), so wait for it (up to\n# 60 s) first. Skipped once it has run on this disk.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && [ ! -d \"$HOME/.config/opencode/node_modules\" ]; then\n (\n cd \"$HOME\" || exit 0\n # shellcheck disable=SC2016 # expanded by the inner shell\n env -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 PATH=\"$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin\" \\\n OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c '\n for _ in $(seq 1 120); do [ -d \"$HOME/.config/opencode/plugins\" ] && break; sleep 0.5; done\n exec timeout 120 \"$1\" models\n ' opencode-first-run \"$ORCA_HOME/tools/bin/opencode\" /dev/null 2>&1 9>&- &\n )\nfi\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\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\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 ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\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# The agent CLIs are large and a fresh VM pages them in lazily from the snapshot, so the first agent\n# launch paid for it (OpenCode 11 s cold vs 3.75 s warm, n71). Read them into the page cache in the\n# background at idle IO priority, after orcad is starting. Best effort; detached so it outlives this\n# script, and never on the ready path.\nprefetch_dirs=()\nfor dir in @anthropic-ai @openai opencode-ai; do\n if [ -d \"$ORCA_HOME/tools/lib/node_modules/$dir\" ]; then\n prefetch_dirs+=(\"$ORCA_HOME/tools/lib/node_modules/$dir\")\n fi\ndone\nif [ \"${#prefetch_dirs[@]}\" -gt 0 ]; then\n # shellcheck disable=SC2016 # expanded by the inner shell\n setsid nohup nice -n 19 bash -c '\n command -v ionice >/dev/null && ionice -c 3 -p $$ 2>/dev/null\n find \"$@\" -type f -size +256k -print0 2>/dev/null | xargs -0 -r cat >/dev/null 2>&1\n ' agent-prefetch \"${prefetch_dirs[@]}\" /dev/null 2>&1 9>&- &\nfi\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)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(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=''\nanthropic_key_scrub=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\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 # G9: pre-approve only an Orca placeholder. A real key (placeholders off) is never written, not even its\n # tail: Claude Code asks once instead, and a tail an older image wrote is scrubbed.\n ANTHROPIC_API_KEY)\n case \"$(printf '%s' \"$b64\" | base64 -d)\" in\n orca-ph-*) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n *) anthropic_key_scrub=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\n ;;\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 the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$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 elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\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 elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\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# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\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_KEY_SCRUB=\"$anthropic_key_scrub\" 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\nconst scrub = process.env.ORCA_KEY_SCRUB\nif (scrub && c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\") {\n const r = c.customApiKeyResponses\n for (const list of [\"approved\", \"rejected\"]) if (Array.isArray(r[list])) r[list] = r[list].filter((t) => t !== scrub)\n}\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\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\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\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\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) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\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-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\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// Vercel closes a WebSocket on a *.vercel.run route after ~340 s with no traffic (1006). A preview\n// app's socket can sit silent that long, so once an upgrade is a WebSocket the proxy watches the app's\n// frames and, after KEEPALIVE_MS with nothing either way, sends the visitor a ping control frame\n// between two frames (never inside one). The visitor's pong reaches the app, which RFC 6455 says to\n// ignore (an unsolicited pong needs no answer).\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\n// Well under Vercel's ~340 s idle cut. ORCA_SHARE_PROXY_KEEPALIVE_MS is for tests.\nconst KEEPALIVE_MS = Number(process.env.ORCA_SHARE_PROXY_KEEPALIVE_MS || 30_000)\n// FIN + ping opcode, empty payload, unmasked (server to client).\nconst PING_FRAME = Buffer.from([0x89, 0x00])\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/**\n * Follows the app's WebSocket frames (server to client: header, then payload) just closely enough to\n * know when the stream sits between two frames, where a control frame may be inserted.\n */\nfunction frameBoundaries() {\n let header = []\n let remaining = 0\n return {\n push(chunk) {\n let i = 0\n while (i < chunk.length) {\n if (remaining > 0) {\n const take = Math.min(remaining, chunk.length - i)\n remaining -= take\n i += take\n continue\n }\n header.push(chunk[i++])\n if (header.length < 2) {\n continue\n }\n const len7 = header[1] & 0x7f\n const need = 2 + (len7 === 126 ? 2 : len7 === 127 ? 8 : 0) + (header[1] & 0x80 ? 4 : 0)\n if (header.length < need) {\n continue\n }\n const bytes = Buffer.from(header)\n remaining = len7 === 126 ? bytes.readUInt16BE(2) : len7 === 127 ? Number(bytes.readBigUInt64BE(2)) : len7\n header = []\n }\n },\n atBoundary: () => header.length === 0 && remaining === 0\n }\n}\n\n/** The app's answer to the upgrade: its head is passed through; only a 101 to `websocket` gets keepalives. */\nfunction upgradeAnswer() {\n let head = Buffer.alloc(0)\n let state = 'head'\n const frames = frameBoundaries()\n return {\n push(chunk) {\n if (state === 'head') {\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end === -1) {\n if (head.length > 64 * 1024) {\n state = 'raw'\n }\n return\n }\n const text = head.subarray(0, end).toString('latin1')\n state = /^HTTP\\/1\\.1 101/.test(text) && /^upgrade:\\s*websocket\\s*$/im.test(text) ? 'ws' : 'raw'\n chunk = head.subarray(end + 4)\n head = Buffer.alloc(0)\n }\n if (state === 'ws') {\n frames.push(chunk)\n }\n },\n canPing: () => state === 'ws' && frames.atBoundary()\n }\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 // App to visitor by hand (with backpressure) so the keepalive knows where frames start and end.\n const answer = upgradeAnswer()\n let lastTraffic = Date.now()\n socket.on('data', () => {\n lastTraffic = Date.now()\n })\n target.on('data', (chunk) => {\n lastTraffic = Date.now()\n answer.push(chunk)\n if (!socket.write(chunk)) {\n target.pause()\n socket.once('drain', () => target.resume())\n }\n })\n target.on('end', () => socket.end())\n const keepalive = setInterval(() => {\n if (Date.now() - lastTraffic >= KEEPALIVE_MS && answer.canPing() && socket.writable) {\n socket.write(PING_FRAME)\n lastTraffic = Date.now()\n }\n }, Math.max(50, Math.floor(KEEPALIVE_MS / 3)))\n socket.once('close', () => clearInterval(keepalive))\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# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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 'noreply@orca.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'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\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\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\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 // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\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/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\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 stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\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 stored) {\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\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\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 out.signature = sign(out, signingKey(stateDir))\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 = { workspaceCheckout, seal, sign, signingKey, 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=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} -export const VM_SCRIPTS_HASH: string = "ad897b32" -export const VM_SCRIPTS_STAMP: number = 1794733957 +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.\n# [ORCA_VM_SCRIPTS_STAMP] (VM_SCRIPTS_STAMP of those scripts; written to /opt/orca/bin/.scripts-stamp).\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\n # OpenCode installs @opencode-ai/plugin (its own version) into ~/.config/opencode on every start\n # until that dir has node_modules and a lock listing it, and draws nothing until that install ends\n # once a plugin is configured (Orca's is): with a slow or unreachable registry the first launch\n # sat blank ~85 s (n73). Install it here once; orca-sandbox-start copies it into a fresh home.\n oc_seed=\"$ORCA_HOME/opencode-config-seed\"\n mkdir -p \"$oc_seed\"\n printf '{\\n \"dependencies\": {\\n \"@opencode-ai/plugin\": \"%s\"\\n }\\n}\\n' \\\n \"$(\"$opencode_pkg/bin/opencode.exe\" --version)\" >\"$oc_seed/package.json\"\n (cd \"$oc_seed\" && npm install --no-fund --no-audit --ignore-scripts >/dev/null)\n test -s \"$oc_seed/package-lock.json\" && test -d \"$oc_seed/node_modules/@opencode-ai/plugin\"\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-agent-signout 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 docker; 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# Which entry points this image carries (VM_SCRIPTS_STAMP): a Worker with older scripts never\n# reinstalls over them. Absent (old callers) reads as 0, so any Worker may still update the image.\nrm -f \"$ORCA_HOME/bin/.scripts-stamp\" \"$ORCA_HOME\"/bin/.entry-points-*\nif [[ \"${ORCA_VM_SCRIPTS_STAMP:-}\" =~ ^[0-9]+$ ]]; then\n printf '%s\\n' \"$ORCA_VM_SCRIPTS_STAMP\" >\"$ORCA_HOME/bin/.scripts-stamp\"\nfi\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# ORCA_DOCKER (on|off: the control plane's Docker switch for the `docker` shim).\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)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\n# PARITY-DOCKER: the control plane's Docker switch (SANDBOX_DOCKER) for the `docker` shim. Only a\n# start that says so changes it; a retried or repair start (no ORCA_DOCKER) keeps the last answer.\ncase \"${ORCA_DOCKER:-}\" in\n off) : >\"$STATE/docker.off\" ;;\n on) rm -f \"$STATE/docker.off\" ;;\nesac\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# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\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.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\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# OpenCode installs @opencode-ai/plugin into ~/.config/opencode and, with Orca's plugin configured,\n# draws nothing until that install ends (blank ~85 s on a slow registry, n73). The image carries the\n# install (provision-golden.sh): copy it into a home that has neither node_modules nor a package.json\n# of its own, so the first launch never fetches.\noc_seed=\"$ORCA_HOME/opencode-config-seed\"\noc_dir=\"$HOME/.config/opencode\"\nif [ -d \"$oc_seed/node_modules\" ] && [ ! -e \"$oc_dir/node_modules\" ] && [ ! -e \"$oc_dir/package.json\" ]; then\n mkdir -p \"$oc_dir\" \\\n && cp -R \"$oc_seed/node_modules\" \"$oc_dir/node_modules\" \\\n && cp \"$oc_seed/package.json\" \"$oc_seed/package-lock.json\" \"$oc_dir/\" \\\n || echo 'opencode config seed not copied' >&2\nfi\n# The rest of OpenCode's first run (its database, the model list): ~2.5 s on the first launch\n# (5.2 s vs 2.7 s warm, n72). Done now in the background at low priority with no credentials\n# (`opencode models` does it and exits). Skipped once it has run on this disk.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && [ ! -e \"$HOME/.local/share/opencode/opencode.db\" ]; then\n (\n cd \"$HOME\" || exit 0\n env -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 PATH=\"$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin\" \\\n OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 timeout 120 \\\n \"$ORCA_HOME/tools/bin/opencode\" models /dev/null 2>&1 9>&- &\n )\nfi\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\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\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 ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\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# The agent CLIs are large and a fresh VM pages them in lazily from the snapshot, so the first agent\n# launch paid for it (OpenCode 11 s cold vs 3.75 s warm, n71). Read them into the page cache in the\n# background at idle IO priority, after orcad is starting. Best effort; detached so it outlives this\n# script, and never on the ready path.\nprefetch_dirs=()\nfor dir in @anthropic-ai @openai opencode-ai; do\n if [ -d \"$ORCA_HOME/tools/lib/node_modules/$dir\" ]; then\n prefetch_dirs+=(\"$ORCA_HOME/tools/lib/node_modules/$dir\")\n fi\ndone\nif [ \"${#prefetch_dirs[@]}\" -gt 0 ]; then\n # shellcheck disable=SC2016 # expanded by the inner shell\n setsid nohup nice -n 19 bash -c '\n command -v ionice >/dev/null && ionice -c 3 -p $$ 2>/dev/null\n find \"$@\" -type f -size +256k -print0 2>/dev/null | xargs -0 -r cat >/dev/null 2>&1\n ' agent-prefetch \"${prefetch_dirs[@]}\" /dev/null 2>&1 9>&- &\nfi\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)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(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=''\nanthropic_key_scrub=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\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 # G9: pre-approve only an Orca placeholder. A real key (placeholders off) is never written, not even its\n # tail: Claude Code asks once instead, and a tail an older image wrote is scrubbed.\n ANTHROPIC_API_KEY)\n case \"$(printf '%s' \"$b64\" | base64 -d)\" in\n orca-ph-*) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n *) anthropic_key_scrub=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\n ;;\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 the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$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 elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\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 elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\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# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\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_KEY_SCRUB=\"$anthropic_key_scrub\" 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\nconst scrub = process.env.ORCA_KEY_SCRUB\nif (scrub && c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\") {\n const r = c.customApiKeyResponses\n for (const list of [\"approved\", \"rejected\"]) if (Array.isArray(r[list])) r[list] = r[list].filter((t) => t !== scrub)\n}\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\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\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\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\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) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\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-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\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// Vercel closes a WebSocket on a *.vercel.run route after ~340 s with no traffic (1006). A preview\n// app's socket can sit silent that long, so once an upgrade is a WebSocket the proxy watches the app's\n// frames and, after KEEPALIVE_MS with nothing either way, sends the visitor a ping control frame\n// between two frames (never inside one). The visitor's pong reaches the app, which RFC 6455 says to\n// ignore (an unsolicited pong needs no answer).\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\n// Well under Vercel's ~340 s idle cut. ORCA_SHARE_PROXY_KEEPALIVE_MS is for tests.\nconst KEEPALIVE_MS = Number(process.env.ORCA_SHARE_PROXY_KEEPALIVE_MS || 30_000)\n// FIN + ping opcode, empty payload, unmasked (server to client).\nconst PING_FRAME = Buffer.from([0x89, 0x00])\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/**\n * Follows the app's WebSocket frames (server to client: header, then payload) just closely enough to\n * know when the stream sits between two frames, where a control frame may be inserted.\n */\nfunction frameBoundaries() {\n let header = []\n let remaining = 0\n return {\n push(chunk) {\n let i = 0\n while (i < chunk.length) {\n if (remaining > 0) {\n const take = Math.min(remaining, chunk.length - i)\n remaining -= take\n i += take\n continue\n }\n header.push(chunk[i++])\n if (header.length < 2) {\n continue\n }\n const len7 = header[1] & 0x7f\n const need = 2 + (len7 === 126 ? 2 : len7 === 127 ? 8 : 0) + (header[1] & 0x80 ? 4 : 0)\n if (header.length < need) {\n continue\n }\n const bytes = Buffer.from(header)\n remaining = len7 === 126 ? bytes.readUInt16BE(2) : len7 === 127 ? Number(bytes.readBigUInt64BE(2)) : len7\n header = []\n }\n },\n atBoundary: () => header.length === 0 && remaining === 0\n }\n}\n\n/** The app's answer to the upgrade: its head is passed through; only a 101 to `websocket` gets keepalives. */\nfunction upgradeAnswer() {\n let head = Buffer.alloc(0)\n let state = 'head'\n const frames = frameBoundaries()\n return {\n push(chunk) {\n if (state === 'head') {\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end === -1) {\n if (head.length > 64 * 1024) {\n state = 'raw'\n }\n return\n }\n const text = head.subarray(0, end).toString('latin1')\n state = /^HTTP\\/1\\.1 101/.test(text) && /^upgrade:\\s*websocket\\s*$/im.test(text) ? 'ws' : 'raw'\n chunk = head.subarray(end + 4)\n head = Buffer.alloc(0)\n }\n if (state === 'ws') {\n frames.push(chunk)\n }\n },\n canPing: () => state === 'ws' && frames.atBoundary()\n }\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 // App to visitor by hand (with backpressure) so the keepalive knows where frames start and end.\n const answer = upgradeAnswer()\n let lastTraffic = Date.now()\n socket.on('data', () => {\n lastTraffic = Date.now()\n })\n target.on('data', (chunk) => {\n lastTraffic = Date.now()\n answer.push(chunk)\n if (!socket.write(chunk)) {\n target.pause()\n socket.once('drain', () => target.resume())\n }\n })\n target.on('end', () => socket.end())\n const keepalive = setInterval(() => {\n if (Date.now() - lastTraffic >= KEEPALIVE_MS && answer.canPing() && socket.writable) {\n socket.write(PING_FRAME)\n lastTraffic = Date.now()\n }\n }, Math.max(50, Math.floor(KEEPALIVE_MS / 3)))\n socket.once('close', () => clearInterval(keepalive))\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# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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 'noreply@orca.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'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\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\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\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 // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\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/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\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 stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\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 stored) {\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\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\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 out.signature = sign(out, signingKey(stateDir))\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 = { workspaceCheckout, seal, sign, signingKey, 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=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPTS_HASH: string = "c2d5603b" +export const VM_SCRIPTS_STAMP: number = 1794741013 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 # The stamp must describe this commit's scripts, never the Worker's: a commit from before stamps\n # leaves it unset (the image then reads as stamp 0).\n unset ORCA_VM_SCRIPTS_STAMP\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 and ORCA_CLONE_FILTER, plus\n# ORCA_BUILD_SECRET_NAMES (space list of the team secrets the environment names; each value rides in\n# the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get).\n# `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk.\n# ORCA_AUTO_INSTALL=1 (automatic environments, no install script): install from the lockfile, never failing.\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\"\n\n# SEC-2: the snapshot of this VM is the team's saved environment, booted by every member's workspace,\n# so a secret's value must never be in it. Secrets are for the install script alone: take_secrets\n# moves them out of this script's environment (clones and Orca's own steps never see them), the\n# install step hands them to that one child, and scan_secrets searches the disk before the build\n# may succeed.\nsecret_names=()\nsecret_values=()\ntake_secrets() {\n local name\n for name in ${ORCA_BUILD_SECRET_NAMES:-}; do\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n [ -n \"${!name:-}\" ] || continue\n secret_names+=(\"$name\")\n secret_values+=(\"${!name}\")\n unset \"$name\"\n done\n unset ORCA_BUILD_SECRET_NAMES\n # Only a file that changes after this marker can hold a value: the base image never saw one.\n : >\"$OUT/.scan-since\"\n}\n\n# Fails (non-zero) when a secret's value is in a file the build created or changed, anywhere on the\n# disk the snapshot captures. Plain text only: a value the script encoded, encrypted or compressed is\n# not found, and neither is one shorter than 8 characters (it would match ordinary text). A search\n# that cannot run fails too. Prints names and paths, never a value.\n# ORCA_SCAN_ROOT: tests only (a scratch tree); the control plane never sets it.\nscan_secrets() {\n [ \"${#secret_names[@]}\" -gt 0 ] || return 0\n local root=\"${ORCA_SCAN_ROOT:-/}\" i line pattern hit named=0\n local names=() patterns=() args=() newer=() sudo=()\n for i in \"${!secret_names[@]}\"; do\n # grep -F reads a newline as \"or\": a multi-line value (a PEM key) is searched by its longest line.\n pattern=\"\"\n while IFS= read -r line; do\n case \"$line\" in -----*) continue ;; esac\n if [ \"${#line}\" -gt \"${#pattern}\" ]; then pattern=\"$line\"; fi\n done < <(printf '%s\\n' \"${secret_values[$i]}\") # a pipe, not a here-string temp file\n [ \"${#pattern}\" -ge 8 ] || continue\n names+=(\"${secret_names[$i]}\")\n patterns+=(\"$pattern\")\n args+=(-e \"$pattern\")\n done\n [ \"${#patterns[@]}\" -gt 0 ] || return 0\n if ! command -v find >/dev/null 2>&1 || ! command -v grep >/dev/null 2>&1 || ! command -v xargs >/dev/null 2>&1; then\n echo \"::orca-error:: Orca couldn’t check the build for secrets, so the environment wasn’t saved.\"\n return 1\n fi\n # Root-owned files count too (`sudo npm config set` writes /root/.npmrc).\n if sudo -n true 2>/dev/null; then sudo=(sudo -n); fi\n # A missing marker (the install script removed it) means every file is searched.\n if [ -f \"$OUT/.scan-since\" ]; then newer=(-cnewer \"$OUT/.scan-since\"); fi\n changed_files() {\n ${sudo[@]+\"${sudo[@]}\"} find \"$root\" \\( -path /proc -o -path /sys -o -path /dev -o -path /run \\) -prune \\\n -o -type f ${newer[@]+\"${newer[@]}\"} -print0 2>/dev/null\n }\n # One pass for every value; the per-secret passes only run on a build that is about to fail.\n if [ -z \"$(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF \"${args[@]}\" -- 2>/dev/null | head -n 1)\" ]; then\n return 0\n fi\n for i in \"${!names[@]}\"; do\n while IFS= read -r hit; do\n [ -n \"$hit\" ] || continue\n named=1\n echo \"::orca-error:: ${names[$i]} was left in $hit. Saved environments are shared with your team, so remove it before the install script ends.\"\n done < <(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF -e \"${patterns[$i]}\" -- 2>/dev/null | head -n 5)\n done\n if [ \"$named\" -eq 0 ]; then\n # The file moved between the two passes: still a build that held a value on disk.\n echo \"::orca-error:: The install script left a secret on disk, so the environment wasn’t saved. Remove it before the script ends, then save again.\"\n fi\n return 1\n}\n\n# PARITY-AUTO-ENV-DEPS: an automatic environment (ORCA_AUTO_INSTALL=1, no install script) installs the\n# first repo's JavaScript dependencies from its lockfile, so new workspaces start with them (the deps\n# step below carries node_modules into each worktree). Soft by design: a failure, a lockfile out of date\n# or the time cap leaves the clone as it was (no half-installed node_modules) and the build goes on.\n# Package managers the image doesn't have (bun, uv, bundler, go, cargo) are only named in the log.\n# ORCA_AUTO_INSTALL_TIMEOUT: tests only.\nauto_install() {\n local dir=\"$1\" pm=\"\" declared=\"\" rc=0 started f\n local cmd=() others=()\n for f in bun.lock bun.lockb uv.lock poetry.lock Pipfile.lock Gemfile.lock go.sum Cargo.lock; do\n [ -f \"$dir/$f\" ] && others+=(\"$f\")\n done\n if [ -f \"$dir/package.json\" ]; then\n # package.json's packageManager (\"pnpm@9.1.0\") wins over the lockfile guess.\n declared=$(sed -n 's/.*\"packageManager\"[[:space:]]*:[[:space:]]*\"\\([a-z]*\\)@.*/\\1/p' \"$dir/package.json\" | head -n 1)\n case \"$declared\" in\n pnpm | yarn | npm) pm=\"$declared\" ;;\n *)\n if [ -f \"$dir/pnpm-lock.yaml\" ]; then pm=pnpm\n elif [ -f \"$dir/yarn.lock\" ]; then pm=yarn\n elif [ -f \"$dir/package-lock.json\" ] || [ -f \"$dir/npm-shrinkwrap.json\" ]; then pm=npm\n fi\n ;;\n esac\n fi\n if [ \"${#others[@]}\" -gt 0 ]; then\n echo \"Not installed automatically: ${others[*]}. Add an install script to the environment to install these.\"\n fi\n if [ -z \"$pm\" ]; then\n [ \"${#others[@]}\" -gt 0 ] || echo \"No lockfile found; the build keeps the cloned repos.\"\n return 0\n fi\n # Through corepack, so pnpm and yarn come at the version the repo pins (Node ships corepack).\n case \"$pm\" in\n pnpm) cmd=(corepack pnpm install --frozen-lockfile) ;;\n yarn)\n if [ -f \"$dir/.yarnrc.yml\" ]; then cmd=(corepack yarn install --immutable)\n else cmd=(corepack yarn install --frozen-lockfile)\n fi\n ;;\n npm) cmd=(npm ci) ;;\n esac\n echo \"Installing dependencies automatically: ${cmd[*]}\"\n started=$(date +%s)\n (cd \"$dir\" && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 timeout \"${ORCA_AUTO_INSTALL_TIMEOUT:-900}\" \"${cmd[@]}\") /dev/null || true\n return 0\n fi\n echo \"Installed dependencies in $(($(date +%s) - started))s.\"\n}\n\ntake_secrets\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 # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${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 for name in ${ORCA_BUILD_WITHHELD_SECRETS:-}; do\n echo \"$name is a model key, so environment builds don’t get it. Agents in workspaces still do.\"\n done\n (\n cd \"${first:-$ROOT}\" || exit 1\n if [ \"${#secret_names[@]}\" -gt 0 ]; then\n for i in \"${!secret_names[@]}\"; do export \"${secret_names[$i]}=${secret_values[$i]}\"; done\n fi\n exec bash -euo pipefail \"$OUT/install.sh\"\n ) /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\" \"$OUT/.scan-since\" \"$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-start b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start index f6081682ae2..6c49d491da4 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start @@ -191,21 +191,27 @@ fi "$ORCA_HOME/bin/orca-sandbox-env" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2 unset ORCA_SECRET_ENV -# OpenCode's first run in a VM installs its plugin SDK into ~/.config/opencode, creates its database -# and fetches its model list: ~2.5 s more on the first launch (5.2 s vs 2.7 s warm, n72). orca-sandbox-env -# just wrote that config, so do the first run now, in the background at low priority, with no -# credentials (`opencode models` does all of it and exits). The SDK install only happens once orcad -# has put Orca's plugin in ~/.config/opencode/plugins (~10 s after this, n73), so wait for it (up to -# 60 s) first. Skipped once it has run on this disk. -if [ -x "$ORCA_HOME/tools/bin/opencode" ] && [ ! -d "$HOME/.config/opencode/node_modules" ]; then +# OpenCode installs @opencode-ai/plugin into ~/.config/opencode and, with Orca's plugin configured, +# draws nothing until that install ends (blank ~85 s on a slow registry, n73). The image carries the +# install (provision-golden.sh): copy it into a home that has neither node_modules nor a package.json +# of its own, so the first launch never fetches. +oc_seed="$ORCA_HOME/opencode-config-seed" +oc_dir="$HOME/.config/opencode" +if [ -d "$oc_seed/node_modules" ] && [ ! -e "$oc_dir/node_modules" ] && [ ! -e "$oc_dir/package.json" ]; then + mkdir -p "$oc_dir" \ + && cp -R "$oc_seed/node_modules" "$oc_dir/node_modules" \ + && cp "$oc_seed/package.json" "$oc_seed/package-lock.json" "$oc_dir/" \ + || echo 'opencode config seed not copied' >&2 +fi +# The rest of OpenCode's first run (its database, the model list): ~2.5 s on the first launch +# (5.2 s vs 2.7 s warm, n72). Done now in the background at low priority with no credentials +# (`opencode models` does it and exits). Skipped once it has run on this disk. +if [ -x "$ORCA_HOME/tools/bin/opencode" ] && [ ! -e "$HOME/.local/share/opencode/opencode.db" ]; then ( cd "$HOME" || exit 0 - # shellcheck disable=SC2016 # expanded by the inner shell env -i HOME="$HOME" USER="$(id -un)" LANG=C.UTF-8 PATH="$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin" \ - OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c ' - for _ in $(seq 1 120); do [ -d "$HOME/.config/opencode/plugins" ] && break; sleep 0.5; done - exec timeout 120 "$1" models - ' opencode-first-run "$ORCA_HOME/tools/bin/opencode" /dev/null 2>&1 9>&- & + OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 timeout 120 \ + "$ORCA_HOME/tools/bin/opencode" models /dev/null 2>&1 9>&- & ) fi From 10e26123c6ba63f979da190a6cbbc2626c28f88d Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 03:13:40 -0800 Subject: [PATCH 26/35] fix(cloud): memguard desktop pieces under file-size limits; catalog keys --- .../CloudMemoryPressureMark.fixture.tsx | 22 +++++++++++++ .../orca-cloud/CloudMemoryPressureMark.tsx | 2 +- .../orca-cloud/OrcaCloudWorkspace.fixture.tsx | 19 ----------- src/renderer/src/i18n/locales/en.json | 10 +++++- .../orca-cloud/cloud-memory-pressure.test.ts | 33 +++++++++++++++++++ .../lib/orca-cloud/cloud-memory-pressure.ts | 15 +++++++++ .../orca-cloud-workspace-state.test.ts | 20 ----------- .../orca-cloud/orca-cloud-workspace-state.ts | 14 -------- .../hosted-sandbox/hosted-sandbox-wire.ts | 16 ++------- .../hosted-workspace-memory-wire.ts | 17 ++++++++++ 10 files changed, 100 insertions(+), 68 deletions(-) create mode 100644 src/renderer/src/lib/orca-cloud/cloud-memory-pressure.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-memory-pressure.ts create mode 100644 src/shared/hosted-sandbox/hosted-workspace-memory-wire.ts diff --git a/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx index 8ce10ae2616..f82593b1cae 100644 --- a/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.fixture.tsx @@ -3,6 +3,9 @@ import { defineFixture } from '../../component-fixtures/component-fixture' import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store' import type { HostedWorkspaceStatus } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' import { CloudMemoryPressureMark } from './CloudMemoryPressureMark' +import { CloudWorkspaceNotice } from './CloudWorkspaceNotice' + +const noop = (): void => {} type Pressure = 'high' | 'critical' @@ -64,3 +67,22 @@ const markFixture = (pressure: Pressure) => export const sidebarRowMemoryHigh = markFixture('high') /** Under 8%: Orca's guard may stop the largest process. Amber. */ export const sidebarRowMemoryCritical = markFixture('critical') + +/** MEMGUARD: Orca's memory guard stopped the process; the workspace stayed up, so no Restart. */ +export const noticeOomGuard = defineFixture({ + width: 420, + render: () => ( +
      + +
      + ) +}) diff --git a/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx index 78f3eeb5ecd..49e66d1c081 100644 --- a/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx +++ b/src/renderer/src/components/orca-cloud/CloudMemoryPressureMark.tsx @@ -4,7 +4,7 @@ import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' -import { cloudMemoryPressure } from '@/lib/orca-cloud/orca-cloud-workspace-state' +import { cloudMemoryPressure } from '@/lib/orca-cloud/cloud-memory-pressure' /** * MEMGUARD: the sidebar row's mark for a cloud workspace short of memory, from the status read diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx index ad744652264..88b504bd78f 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspace.fixture.tsx @@ -308,25 +308,6 @@ export const noticeOom = defineFixture({ ) }) -/** MEMGUARD: Orca's memory guard stopped the process; the workspace stayed up, so no Restart. */ -export const noticeOomGuard = defineFixture({ - width: 420, - render: () => ( -
      - -
      - ) -}) - function IdleToast(): React.JSX.Element { useEffect(() => { showIdleSleepNotice('ws', 'fix-auth-redirect', 20 * 60_000) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index daeca2cb785..9e201f4df61 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -27542,7 +27542,11 @@ "oom": { "titleRan": "{{name}} ran out of memory", "titleProcess": "A process ran out of memory", - "stopped": "It was stopped so the sandbox stays up. Restart to recover." + "stopped": "It was stopped so the sandbox stays up. Restart to recover.", + "guardTitle": "Orca stopped {{name}} to keep the workspace responsive", + "guardTitleProcess": "Orca stopped a process to keep the workspace responsive", + "guardDetail": "The workspace was out of memory. Consider a larger machine.", + "machineSize": "Machine size" }, "unresponsive": { "sandboxTitle": "This sandbox isn’t responding" @@ -28203,6 +28207,10 @@ "waiting": "Waiting for GitHub… This continues on its own once access is granted.", "holding": "Your sandbox is ready. It opens as soon as you grant access or skip.", "openNow": "Open now, set up later" + }, + "memoryPressure": { + "critical": "Out of memory. Orca may stop the largest process to keep the workspace responsive.", + "high": "Running low on memory" } }, "runActions": { diff --git a/src/renderer/src/lib/orca-cloud/cloud-memory-pressure.test.ts b/src/renderer/src/lib/orca-cloud/cloud-memory-pressure.test.ts new file mode 100644 index 00000000000..d6212026642 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-memory-pressure.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import type { HostedWorkspaceStatus } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' +import { cloudMemoryPressure } from './cloud-memory-pressure' + +const status = (state: HostedWorkspaceStatus['state']): HostedWorkspaceStatus => ({ + state, + metrics: null, + uptimeMs: null, + usage: { totalMs: 0, centsPerHour: 75, costCents: 0 }, + archive: null, + checkedAt: 1 +}) + +describe('cloudMemoryPressure', () => { + it('marks memory pressure only on a ready VM that is short of memory', () => { + const memory = (pressure: 'ok' | 'high' | 'critical') => ({ + pressure, + guardKills: 0, + lastGuardVictim: null, + lastGuardKillAt: null, + guarded: true + }) + expect(cloudMemoryPressure({ ...status('ready'), memory: memory('high') })).toBe('high') + expect(cloudMemoryPressure({ ...status('ready'), memory: memory('critical') })).toBe('critical') + expect(cloudMemoryPressure({ ...status('ready'), memory: memory('ok') })).toBeNull() + // An older control plane says nothing; a sleeping or unresponsive VM shows its own state. + expect(cloudMemoryPressure(status('ready'))).toBeNull() + expect( + cloudMemoryPressure({ ...status('unresponsive'), memory: memory('critical') }) + ).toBeNull() + expect(cloudMemoryPressure(null)).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-memory-pressure.ts b/src/renderer/src/lib/orca-cloud/cloud-memory-pressure.ts new file mode 100644 index 00000000000..5aee72b2174 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-memory-pressure.ts @@ -0,0 +1,15 @@ +import type { HostedWorkspaceStatus } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' + +/** + * MEMGUARD: the sidebar row's memory mark. Only for a VM read as ready (a sleeping or unresponsive + * one has its own state), and only when memory is short. + */ +export function cloudMemoryPressure( + status: HostedWorkspaceStatus | null | undefined +): 'high' | 'critical' | null { + if (status?.state !== 'ready') { + return null + } + const pressure = status.memory?.pressure + return pressure === 'high' || pressure === 'critical' ? pressure : null +} diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts index 70bdf3a0c84..6a83c1412df 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest' import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/cloud-workspace-api' import type { HostedWorkspaceStatus } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' import { - cloudMemoryPressure, buildFileTree, deriveCloudDotState, formatBytes, @@ -151,25 +150,6 @@ describe('visibleOom', () => { ).toBe('archived') }) - it('marks memory pressure only on a ready VM that is short of memory', () => { - const memory = (pressure: 'ok' | 'high' | 'critical') => ({ - pressure, - guardKills: 0, - lastGuardVictim: null, - lastGuardKillAt: null, - guarded: true - }) - expect(cloudMemoryPressure({ ...status('ready'), memory: memory('high') })).toBe('high') - expect(cloudMemoryPressure({ ...status('ready'), memory: memory('critical') })).toBe('critical') - expect(cloudMemoryPressure({ ...status('ready'), memory: memory('ok') })).toBeNull() - // An older control plane says nothing; a sleeping or unresponsive VM shows its own state. - expect(cloudMemoryPressure(status('ready'))).toBeNull() - expect( - cloudMemoryPressure({ ...status('unresponsive'), memory: memory('critical') }) - ).toBeNull() - expect(cloudMemoryPressure(null)).toBeNull() - }) - it('hides kills the user dismissed and shows newer ones', () => { const oom = { workspaceId: 'w', oomKills: 2, victim: 'node', at: NOW } expect(visibleOom(oom, undefined)).toBe(oom) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts index 62576814c8e..c2cad9da465 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-state.ts @@ -100,20 +100,6 @@ export function deriveCloudDotState(input: { } } -/** - * MEMGUARD: the sidebar row's memory mark. Only for a VM read as ready (a sleeping or unresponsive - * one has its own state), and only when memory is short. - */ -export function cloudMemoryPressure( - status: HostedWorkspaceStatus | null | undefined -): 'high' | 'critical' | null { - if (status?.state !== 'ready') { - return null - } - const pressure = status.memory?.pressure - return pressure === 'high' || pressure === 'critical' ? pressure : null -} - /** An OOM notice shows for kills the user has not dismissed. */ export function visibleOom( oom: CloudOomEvent | undefined, diff --git a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts index 675701dac84..b6fd6520989 100644 --- a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts +++ b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts @@ -2,6 +2,7 @@ // The Worker's tests parse its responses with these schemas, so either side drifting fails a test. import { z } from 'zod' import { HostedEnvironmentHeldSchema } from './hosted-environment-held-wire' +import { HostedWorkspaceMemorySchema } from './hosted-workspace-memory-wire' /** * Minutes of no agent work and no input before a cloud sandbox sleeps. The one source for every @@ -272,19 +273,8 @@ export const HostedWorkspaceStatusSchema = z archive: z.object({ archivedAt: Millis, expiresAt: Millis.nullable() }).strict().nullable(), // Optional: older control planes omit it; the desktop then uses its 15 min fallback. idleSleepMinutes: z.number().int().positive().max(1440).optional(), - // Optional: older control planes omit it. MEMGUARD: memory pressure in the VM and the processes - // its memory guard stopped this boot (kernel OOM kills stay in `metrics.oomKills`). - memory: z - .object({ - pressure: z.enum(['ok', 'high', 'critical']), - guardKills: z.number().int().nonnegative(), - lastGuardVictim: z.string().max(64).nullable(), - lastGuardKillAt: Millis.nullable(), - guarded: z.boolean() - }) - .strip() - .nullable() - .optional(), + // Optional: older control planes omit it (MEMGUARD). + memory: HostedWorkspaceMemorySchema.nullable().optional(), // Optional (feature `wake-hints`): predictive wake's inputs. The last sleep someone chose, from // any client (not the idle timer), and sandboxes running against the owner's seat and account. lastUserSleepAt: Millis.nullable().optional(), diff --git a/src/shared/hosted-sandbox/hosted-workspace-memory-wire.ts b/src/shared/hosted-sandbox/hosted-workspace-memory-wire.ts new file mode 100644 index 00000000000..8a5e8cfd589 --- /dev/null +++ b/src/shared/hosted-sandbox/hosted-workspace-memory-wire.ts @@ -0,0 +1,17 @@ +import { z } from 'zod' + +/** + * MEMGUARD: memory pressure in a cloud VM and the processes its memory guard stopped this boot + * (kernel OOM kills stay in the status's `metrics.oomKills`). Pressure without a guard (an older + * image) comes from MemAvailable alone, and `guarded` is false. + */ +export const HostedWorkspaceMemorySchema = z + .object({ + pressure: z.enum(['ok', 'high', 'critical']), + guardKills: z.number().int().nonnegative(), + lastGuardVictim: z.string().max(64).nullable(), + lastGuardKillAt: z.number().int().nonnegative().nullable(), + guarded: z.boolean() + }) + .strip() +export type HostedWorkspaceMemory = z.infer From 8f32582e3600cc90cd2075dc737ed7e2c6276c4c Mon Sep 17 00:00:00 2001 From: Neil Date: Sun, 15 Nov 2026 03:14:19 -0800 Subject: [PATCH 27/35] =?UTF-8?q?feat(terminal):=20the=20agent=20starting?= =?UTF-8?q?=20overlay=20says=20"Still=20starting=20=E2=80=A6"=20pas?= =?UTF-8?q?t=2010=20s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../launch-outcome/AgentStartingPortals.tsx | 9 ++++++--- .../launch-outcome/AgentStartingStatus.fixture.tsx | 2 ++ .../launch-outcome/agent-starting-state.test.ts | 10 ++++++++++ .../launch-outcome/agent-starting-state.ts | 12 ++++++++++++ src/renderer/src/i18n/locales/en.json | 1 + 5 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/components/terminal-pane/launch-outcome/AgentStartingPortals.tsx b/src/renderer/src/components/terminal-pane/launch-outcome/AgentStartingPortals.tsx index dc0b0d7eabf..c4c0d3ebc1f 100644 --- a/src/renderer/src/components/terminal-pane/launch-outcome/AgentStartingPortals.tsx +++ b/src/renderer/src/components/terminal-pane/launch-outcome/AgentStartingPortals.tsx @@ -9,7 +9,7 @@ import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-ag import type { TerminalPaneController } from '../controller/use-terminal-pane-controller' import { AGENT_STARTING_DELAY_MS, - AGENT_STARTING_SLOW_MS, + agentStartingPhase, isAgentLaunchLeaf, terminalHasVisibleContent } from './agent-starting-state' @@ -53,6 +53,7 @@ export function AgentStartingStatus({ return null } const name = TUI_AGENT_DISPLAY_NAMES[agent] ?? agent + const phase = agentStartingPhase(elapsed) return (