diff --git a/.github/workflows/cloud-egress-probe.yml b/.github/workflows/cloud-egress-probe.yml new file mode 100644 index 00000000000..1b5d983ffea --- /dev/null +++ b/.github/workflows/cloud-egress-probe.yml @@ -0,0 +1,81 @@ +name: Cloud Egress Probe + +# Release check for sandbox egress, against DEV, through Orca's own paths (dev workspaces driven +# over the shipped `orca` CLI's pairing code). Bogus tokens only; postman-echo.com is the echo host. +# Details and the local run: cloud/apps/sandbox-control/scripts/README.md +on: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: cloud-egress-probe + cancel-in-progress: false + +defaults: + run: + working-directory: cloud + +jobs: + probe: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + env: + DEV_TEST_JWK: ${{ secrets.ORCA_DEV_TEST_JWK }} + DEV_OPERATOR_TOKEN: ${{ secrets.ORCA_DEV_OPERATOR_TOKEN }} + steps: + - name: Check the dev credentials are configured + id: creds + working-directory: . + run: | + if [ -z "$DEV_TEST_JWK" ] || [ -z "$DEV_OPERATOR_TOKEN" ]; then + echo "::warning::ORCA_DEV_TEST_JWK / ORCA_DEV_OPERATOR_TOKEN are not set: the egress probe did not run" + echo "skip=1" >> "$GITHUB_OUTPUT" + fi + + - if: steps.creds.outputs.skip != '1' + uses: actions/checkout@v4 + + - if: steps.creds.outputs.skip != '1' + uses: ./.github/actions/setup-pnpm + with: + package-json-file: cloud/package.json + + - if: steps.creds.outputs.skip != '1' + uses: actions/setup-node@v4 + with: + node-version: 24 + check-latest: true + + - if: steps.creds.outputs.skip != '1' + run: pnpm install --frozen-lockfile --filter @orca-cloud/sandbox-control... + + # The shipped CLI from the latest release's Linux package: the same pairing path the desktop uses. + - name: Install the orca CLI + if: steps.creds.outputs.skip != '1' + working-directory: . + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download --repo stablyai/orca --pattern 'orca-ide_*_amd64.deb' --dir "$RUNNER_TEMP/orca" + dpkg-deb -x "$RUNNER_TEMP"/orca/orca-ide_*_amd64.deb "$RUNNER_TEMP/orca/x" + cli="$(find "$RUNNER_TEMP/orca/x" -path '*/bin/orca' -type f | head -n 1)" + test -x "$cli" + echo "ORCA_PROBE_CLI=$cli" >> "$GITHUB_ENV" + + - name: Probe dev egress + if: steps.creds.outputs.skip != '1' + run: | + umask 077 + printf '%s' "$DEV_TEST_JWK" > "$RUNNER_TEMP/dev-jwk.json" + printf '%s' "$DEV_OPERATOR_TOKEN" > "$RUNNER_TEMP/dev-operator" + ORCA_PROBE_DEV_JWK_FILE="$RUNNER_TEMP/dev-jwk.json" ORCA_PROBE_OPERATOR_TOKEN_FILE="$RUNNER_TEMP/dev-operator" \ + pnpm --filter @orca-cloud/sandbox-control exec tsx scripts/egress-probe.ts > "$RUNNER_TEMP/egress-probe.json" + + - uses: actions/upload-artifact@v4 + if: always() && steps.creds.outputs.skip != '1' + with: + name: cloud-egress-probe-report + path: ${{ runner.temp }}/egress-probe.json + retention-days: 14 diff --git a/.github/workflows/cloud-vm-boot-twice.yml b/.github/workflows/cloud-vm-boot-twice.yml new file mode 100644 index 00000000000..4c52c1da9b8 --- /dev/null +++ b/.github/workflows/cloud-vm-boot-twice.yml @@ -0,0 +1,83 @@ +name: Cloud VM Boot Twice + +# Provisions the golden image in a container and boots the same disk twice through the control +# plane's boot steps. The second boot runs offline and must install, fetch and redo nothing. +# Local run and details: cloud/apps/sandbox-control/image/boot-twice/README.md +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - cloud/apps/sandbox-control/image/** + - cloud/apps/sandbox-control/src/golden-images.ts + - cloud/apps/sandbox-control/src/sandbox-vm-commands.ts + - cloud/apps/sandbox-control/src/orcad-ready.ts + - .github/workflows/cloud-vm-boot-twice.yml + workflow_dispatch: + inputs: + release: + description: Orca release whose orcad bundle the image carries (vX.Y.Z or latest) + required: false + default: latest + type: string + +permissions: + contents: read + +concurrency: + group: cloud-vm-boot-twice-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + working-directory: cloud + +jobs: + boot-twice: + if: github.event_name != 'pull_request' || github.event.pull_request.draft != true + runs-on: ubuntu-24.04 + timeout-minutes: 25 + env: + RELEASE: ${{ inputs.release || 'latest' }} + CONTEXT: ${{ runner.temp }}/boot-twice + # Raises the GitHub API limit for the latest-release lookup; read-only, no secret involved. + GITHUB_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4 + + - uses: ./.github/actions/setup-pnpm + with: + package-json-file: cloud/package.json + + - uses: actions/setup-node@v4 + with: + node-version: 24 + check-latest: true + + - run: pnpm install --frozen-lockfile --filter @orca-cloud/sandbox-control... + + # The context holds exactly what provisioning reads (script + env), so its bytes key the + # layer cache: an unchanged image reuses the provisioned layer and only boots. + - name: Write the image build context + run: pnpm --filter @orca-cloud/sandbox-control exec tsx image/boot-twice/boot-twice.ts --release "$RELEASE" --context-out "$CONTEXT" + + - uses: docker/setup-buildx-action@v3 + + - name: Provision the image (cached) + uses: docker/build-push-action@v6 + with: + context: ${{ env.CONTEXT }} + target: harness + tags: orca-boot-twice:ci + load: true + cache-from: type=gha,scope=cloud-vm-boot-twice + cache-to: type=gha,mode=max,scope=cloud-vm-boot-twice + + - name: Boot twice + run: pnpm --filter @orca-cloud/sandbox-control exec tsx image/boot-twice/boot-twice.ts --release "$RELEASE" --image orca-boot-twice:ci --report "$RUNNER_TEMP/boot-twice-report.json" + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: cloud-vm-boot-twice-report + path: ${{ runner.temp }}/boot-twice-report.json + retention-days: 14 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/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/cloud/apps/sandbox-control/image/boot-twice/Dockerfile b/cloud/apps/sandbox-control/image/boot-twice/Dockerfile new file mode 100644 index 00000000000..fc7a66040f0 --- /dev/null +++ b/cloud/apps/sandbox-control/image/boot-twice/Dockerfile @@ -0,0 +1,41 @@ +# syntax=docker/dockerfile:1.7 +# Boot-twice harness image: the golden image's provisioning, run in a container instead of a Vercel +# build sandbox. boot-twice.ts writes the build context (this file, provision-golden.sh and +# provision.env, the same env build-golden-image.ts passes) and then boots the result twice. +# Base: Ubuntu 26.04 (what vercel/sandbox/node:24 is) with Node 24 and passwordless sudo for `ubuntu`, which is what the provision +# script expects from the managed image it normally runs on. +FROM node:24-bookworm-slim@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 AS node + +FROM ubuntu:26.04@sha256:065aa8626841f16057b78b027b464cd59c4fac36c204c72dcbf48d66f5fa8a96 AS base +COPY --from=node /usr/local/bin/node /usr/local/bin/node +COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules +RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \ + && ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \ + && apt-get update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends ca-certificates sudo >/dev/null \ + && rm -rf /var/lib/apt/lists/* \ + && printf 'ubuntu ALL=(ALL) NOPASSWD:ALL\n' >/etc/sudoers.d/ubuntu && chmod 0440 /etc/sudoers.d/ubuntu + +# The golden build: provision, then wipe identity, exactly as buildGoldenImage runs them. +FROM base AS golden +USER ubuntu +WORKDIR /home/ubuntu +COPY --chown=ubuntu:ubuntu provision-golden.sh provision.env /tmp/golden/ +RUN set -a && . /tmp/golden/provision.env && set +a \ + && { bash /tmp/golden/provision-golden.sh >/tmp/golden/provision.out || { tail -n 40 /tmp/golden/provision.out; exit 1; }; } \ + && sudo install -D -m 0644 /tmp/golden/provision.out /var/lib/orca-boot-twice/provision-report.json \ + && /opt/orca/bin/orca-image-wipe + +# Harness scaffolding only (outside /opt/orca): the fake per-boot kernel boot id, and a local repo +# for the workspace prelude to clone so the first boot needs no GitHub. +FROM golden AS harness +USER root +COPY boot-twice-init /usr/local/sbin/boot-twice-init +RUN chmod 0755 /usr/local/sbin/boot-twice-init \ + && git init -q --bare -b main /srv/fixture.git \ + && tmp="$(mktemp -d)" && git -C "$tmp" init -q -b main \ + && printf 'boot twice fixture\n' >"$tmp/README.md" && git -C "$tmp" add README.md \ + && git -C "$tmp" -c user.name=fixture -c user.email=fixture@orca.invalid commit -q -m fixture \ + && git -C "$tmp" push -q /srv/fixture.git main && rm -rf "$tmp" \ + && chown -R ubuntu:ubuntu /srv/fixture.git +CMD ["/usr/local/sbin/boot-twice-init"] diff --git a/cloud/apps/sandbox-control/image/boot-twice/README.md b/cloud/apps/sandbox-control/image/boot-twice/README.md new file mode 100644 index 00000000000..d579493a65e --- /dev/null +++ b/cloud/apps/sandbox-control/image/boot-twice/README.md @@ -0,0 +1,78 @@ +# Boot-twice check + +This check catches the case where the image boots but a wake reinstalls or refetches things. + +It provisions the golden image in a container, using the real `provision-golden.sh` and the same +env that `build-golden-image.ts` passes. Then it boots the same disk twice through the control +plane's own boot code: + +1. `ENTRY_POINTS_PROBE` plus the install when the image's scripts are behind (the `refreshRuntime` step). +2. `startOrcad`, with the workspace prelude on the first boot only. +3. `ensureEntryPoints`, the once-per-image entry-point sync. + +Each container start counts as one VM boot. The container gets a fresh kernel boot id, a tmpfs +`/run`, and the disk the previous boot left (`docker commit`). + +The second boot must: + +- **Come up.** It needs a pairing offer, and orcad must be alive and listening on `:6768`. +- **Install nothing.** `docker diff` against the first boot's disk may only touch boot state: + `~/.orca-sandbox`, `~/.orcad-data`, the per-boot agent config, the compile cache, `/tmp` and + `/run`. See `bootStatePaths` in `boot-twice-checks.ts`. Any `node_modules`, or any change under + `/opt/orca/bin`, `/usr`, `/etc` or a package cache, fails the check. +- **Fetch nothing.** The boot runs on an internal Docker network (no route out). Its only DNS + server is a sink that logs every name it is asked for. A lookup fails the check unless it is in + `RUNTIME_LOOKUPS`. Today that is only orcad's agent-state-rules refresh on github.com. +- **Redo nothing.** The container's init samples every process's command line every 50 ms. Any + installer, fetch or first-run command (apt, npm install, curl, git fetch, `opencode models`) + fails the check. +- **Skip the entry-point install.** No `installEntryPoints` call, and the first boot's + `.entry-points-` marker is present. +- **Carry the right files.** Every `/opt/orca/bin` entry point must be byte-identical to `image/vm/`, + `.scripts-stamp` must equal `VM_SCRIPTS_STAMP`, and every manifest pin must match the installed + version. The npm packages are compared exactly, by their `package.json`. gh, cursor-agent and + Chrome are compared by `--version`. + +## Run it locally + +You need Docker that can run `--privileged` containers: Linux, or Docker Desktop on macOS. + +```sh +cd cloud +pnpm install --filter @orca-cloud/sandbox-control... +pnpm --filter @orca-cloud/sandbox-control exec tsx image/boot-twice/boot-twice.ts --release latest +``` + +A cold run takes about 4 minutes, almost all of it provisioning (apt, agent CLIs, Chrome). +Docker's layer cache keys on the provisioning inputs: `provision-golden.sh`, the manifest and the +entry points. A rerun with those unchanged takes about 15 seconds. The command exits non-zero and +lists each failure. + +The options: + +- `--report ` writes the full JSON report: boot timings, every command, the disk diff, lookups and versions. +- `--keep` leaves the two containers, the disk image and the DNS sink for inspection. +- `--release vX.Y.Z` boots a specific orca-server release bundle. The default is the latest + release, because the manifest pins no bundle: production goldens build orcad from source. +- `--image ` boots an image you built yourself. `--context-out ` writes the build context for one. + +What this check does not cover: + +- The runtime-bundle refresh: no bundle is published here. +- The Vercel firewall and egress proxy: that is the release probe, `scripts/egress-probe.ts`. +- Vercel's own VM behaviour, such as snapshot restore timing. + +## CI + +On nwparker/orca-private, where Actions is off, the premerge gate +(`config/scripts/cloud-integration/premerge-check.sh`) runs +`config/scripts/cloud-integration/boot-twice-check.sh` whenever a branch touches +`cloud/apps/sandbox-control/image/**`, which includes every VM script. The step: + +- takes its own omarchy slot, waiting at most 5 minutes for one; +- stops after 10 minutes; +- prints each failure; +- **fails open with a loud warning when Docker is unavailable**. + +`.github/workflows/cloud-vm-boot-twice.yml` runs the same check on pull requests once Actions is +on, with the provisioned layer cached in the GitHub Actions cache. diff --git a/cloud/apps/sandbox-control/image/boot-twice/boot-twice-checks.test.ts b/cloud/apps/sandbox-control/image/boot-twice/boot-twice-checks.test.ts new file mode 100644 index 00000000000..efd44b2d124 --- /dev/null +++ b/cloud/apps/sandbox-control/image/boot-twice/boot-twice-checks.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest' +import { MANIFEST } from '../vm-scripts.generated' +import { entryPointMismatches, installerCommands, parseDockerDiff, pinnedTools, unexpectedChanges, versionMismatches } from './boot-twice-checks' + +const HOME = '/home/ubuntu' + +describe('unexpectedChanges', () => { + it('allows boot state, per-boot config and the parent directories they live in', () => { + const diff = parseDockerDiff( + [ + 'C /home', + 'C /home/ubuntu', + 'C /home/ubuntu/.orca-sandbox', + 'A /home/ubuntu/.orca-sandbox/opencode-first-run', + 'C /home/ubuntu/.orcad-data/agent-hooks/endpoint.env', + 'C /home/ubuntu/.codex/config.toml', + 'C /opt', + 'C /opt/orca', + 'C /opt/orca/compile-cache/v24-x64/712488c2', + 'A /tmp/x', + 'C /run' + ].join('\n') + ) + expect(unexpectedChanges(diff, HOME)).toEqual([]) + }) + + it('flags installs: image files, package caches and node_modules anywhere', () => { + const diff = parseDockerDiff( + [ + 'C /opt/orca/bin/orca-sandbox-start', + 'A /opt/orca/tools/lib/node_modules/x/package.json', + 'A /home/ubuntu/.npm/_cacache/index', + 'A /home/ubuntu/.config/opencode/node_modules/@opencode-ai/plugin', + 'A /home/ubuntu/.orcad-data/node_modules/x', + 'C /usr/lib/x', + 'C /etc/apt/sources.list.d/ubuntu.sources', + 'C /home/ubuntu/.config/opencode' + ].join('\n') + ) + expect(unexpectedChanges(diff, HOME).map((entry) => entry.path)).toEqual([ + '/opt/orca/bin/orca-sandbox-start', + '/opt/orca/tools/lib/node_modules/x/package.json', + '/home/ubuntu/.npm/_cacache/index', + '/home/ubuntu/.config/opencode/node_modules/@opencode-ai/plugin', + '/home/ubuntu/.orcad-data/node_modules/x', + '/usr/lib/x', + '/etc/apt/sources.list.d/ubuntu.sources' + ]) + }) + + it('does not take an added directory above an allowed path as a parent change', () => { + expect(unexpectedChanges([{ kind: 'A', path: '/opt/orca' }], HOME)).toHaveLength(1) + }) +}) + +describe('pinned versions', () => { + const tools = pinnedTools(MANIFEST) + + it('covers every agent CLI package and the pinned binaries', () => { + expect(tools.filter((tool) => tool.source === 'package')).toHaveLength(MANIFEST.agentCliPackages.length) + expect(tools.map((tool) => tool.name)).toEqual(expect.arrayContaining(['@anthropic-ai/claude-code', 'gh', 'google-chrome'])) + }) + + it('matches exact package versions and version lines that contain the pin', () => { + const observed: Record = {} + for (const tool of tools) { + observed[tool.name] = tool.source === 'package' ? tool.expect : `prefix ${tool.expect} (suffix)` + } + expect(versionMismatches(tools, observed)).toEqual([]) + const claude = tools.find((tool) => tool.name === '@anthropic-ai/claude-code')! + expect(versionMismatches([claude], { [claude.name]: '0.0.1' })).toEqual([`${claude.name}: "0.0.1" does not match the pin ${claude.expect}`]) + expect(versionMismatches([claude], {})).toEqual([`${claude.name}: missing (pinned ${claude.expect})`]) + }) + + it("reads Chrome's .deb revision off the version it reports", () => { + const chrome = tools.find((tool) => tool.name === 'google-chrome')! + expect(chrome.expect).not.toMatch(/-\d+$/) + }) +}) + +describe('entryPointMismatches', () => { + it('names missing and changed entry points', () => { + expect(entryPointMismatches({ a: '1', b: '2', c: '3' }, { a: '1', b: '9' })).toEqual([ + 'b: differs from image/vm/b', + 'c: missing from /opt/orca/bin' + ]) + }) +}) + +describe('installerCommands', () => { + it('finds installs, fetches and first-run work among sampled command lines', () => { + expect( + installerCommands([ + 'bash -c timeout 120 "$1" models && : >"$2" opencode-first-run /opt/orca/tools/bin/opencode /home/ubuntu/.orca-sandbox/opencode-first-run', + 'timeout 120 /opt/orca/tools/bin/opencode models ', + '/opt/orca/runtime/runtimes/node-x/bin/node /opt/orca/bin/orcad-boot --code-cache x', + 'curl -fsS --max-time 25 -o /tmp/b.tgz https://example.invalid/b.tgz', + 'git -C /vercel/sandbox/project fetch --progress origin', + 'git fetch origin', + 'sleep 0.05', + 'tr \\0 ', + '' + ]) + ).toEqual([ + 'timeout 120 /opt/orca/tools/bin/opencode models', + 'curl -fsS --max-time 25 -o /tmp/b.tgz https://example.invalid/b.tgz', + 'git -C /vercel/sandbox/project fetch --progress origin', + 'git fetch origin' + ]) + }) +}) diff --git a/cloud/apps/sandbox-control/image/boot-twice/boot-twice-checks.ts b/cloud/apps/sandbox-control/image/boot-twice/boot-twice-checks.ts new file mode 100644 index 00000000000..c48aa0b7ba9 --- /dev/null +++ b/cloud/apps/sandbox-control/image/boot-twice/boot-twice-checks.ts @@ -0,0 +1,125 @@ +// Pure checks for the boot-twice harness (boot-twice.ts): what a second boot of the same disk may +// change, and whether the image carries the pinned tools and this tree's entry points. +import type { GoldenImageManifest } from '../golden-image' + +export type DiffEntry = { kind: 'A' | 'C' | 'D'; path: string } + +/** `docker diff` output: one ` ` line per changed path. */ +export function parseDockerDiff(text: string): DiffEntry[] { + const entries: DiffEntry[] = [] + for (const line of text.split('\n')) { + const match = /^([ACD]) (\/.*)$/.exec(line.trim()) + if (match) { + entries.push({ kind: match[1] as DiffEntry['kind'], path: match[2]! }) + } + } + return entries +} + +/** + * What any boot may write: runtime state, logs and the per-boot config the start script rewrites. + * Everything else a second boot touches (/opt, /usr, /etc, package caches, node_modules) is an + * install that should have happened once, in the image or on the first boot. + */ +export function bootStatePaths(home: string): readonly string[] { + return [ + // orca-sandbox-start: boot id, pids, ready file, logs, start lock, git-setup marks. + `${home}/.orca-sandbox`, + // orcad's own data directory (device identity, sessions, logs). + `${home}/.orcad-data`, + // The start script's git identity fallbacks (written only when missing or on an old default). + `${home}/.gitconfig`, + // orca-sandbox-env rewrites Codex's managed config block and OpenCode's managed provider list on every start. + `${home}/.codex/config.toml`, + `${home}/.config/opencode/.orca-managed-disabled-providers`, + // orcad reads OpenCode's session database at start; SQLite readers recreate its WAL and index files. + `${home}/.local/share/opencode/opencode.db-shm`, + `${home}/.local/share/opencode/opencode.db-wal`, + // Node's compile cache: orcad's node adds or refreshes entries for code it compiles. A cache, not an install. + '/opt/orca/compile-cache', + '/tmp', + '/var/tmp', + '/run' + ] +} + +function under(path: string, prefix: string): boolean { + return path === prefix || path.startsWith(`${prefix}/`) +} + +/** Changes outside bootStatePaths. A changed directory that only contains allowed paths is fine. */ +export function unexpectedChanges(entries: readonly DiffEntry[], home: string): DiffEntry[] { + const allowed = bootStatePaths(home) + return entries.filter(({ kind, path }) => { + if (/(^|\/)node_modules(\/|$)/.test(path)) { + return true + } + if (allowed.some((prefix) => under(path, prefix))) { + return false + } + // `C /home/ubuntu`: a parent directory of an allowed path changed its mtime. + return !(kind === 'C' && allowed.some((prefix) => prefix.startsWith(`${path}/`))) + }) +} + +/** One pinned tool: where its version is read in the image and the string it must contain. */ +export type PinnedTool = { name: string; expect: string; source: 'package' | 'binary' } + +/** Every version the manifest pins that the image can report. */ +export function pinnedTools(manifest: GoldenImageManifest): PinnedTool[] { + const tools: PinnedTool[] = manifest.agentCliPackages.map((spec) => { + const at = spec.lastIndexOf('@') + return { name: spec.slice(0, at), expect: spec.slice(at + 1), source: 'package' } + }) + if (manifest.gh.version) { + tools.push({ name: 'gh', expect: `gh version ${manifest.gh.version}`, source: 'binary' }) + } + if (manifest.cursorAgent) { + tools.push({ name: 'cursor-agent', expect: manifest.cursorAgent.version, source: 'binary' }) + } + if (manifest.chrome) { + // The .deb's "157.0.8103.38-1" reports itself as "Google Chrome 157.0.8103.38". + tools.push({ name: 'google-chrome', expect: manifest.chrome.version.replace(/-\d+$/, ''), source: 'binary' }) + } + return tools +} + +/** Observed versions: npm package.json `version` by package name, else a binary's `--version` line. */ +export type ObservedVersions = Record + +export function versionMismatches(tools: readonly PinnedTool[], observed: ObservedVersions): string[] { + const problems: string[] = [] + for (const tool of tools) { + const seen = observed[tool.name] ?? null + if (seen === null) { + problems.push(`${tool.name}: missing (pinned ${tool.expect})`) + } else if (tool.source === 'package' ? seen !== tool.expect : !seen.includes(tool.expect)) { + problems.push(`${tool.name}: ${JSON.stringify(seen)} does not match the pin ${tool.expect}`) + } + } + return problems +} + +/** Entry points in the image whose bytes differ from this tree's image/vm sources. */ +export function entryPointMismatches(expected: Record, installed: Record): string[] { + return Object.entries(expected) + .filter(([name, sha]) => installed[name] !== sha) + .map(([name]) => (installed[name] ? `${name}: differs from image/vm/${name}` : `${name}: missing from /opt/orca/bin`)) +} + +/** + * Commands that install, fetch or redo first-run work. Any of them in a second boot is a step that + * should have run once. Offline they fail fast and quietly, so the command line is the evidence. + */ +const INSTALLERS = [ + /(^|\/)(apt|apt-get|dpkg|pip3?|curl|wget)( |$)/, + /(^|\/)npm (install|i|ci|add) /, + /(^|\/)git( -[Cc] \S+)* (clone|fetch|pull)( |$)/, + /(^|\/)opencode models( |$)/, + /(^|\/)tar (-?x|--extract)/ +] + +/** The installer command lines among a boot's sampled `/proc//cmdline`s. */ +export function installerCommands(commands: readonly string[]): string[] { + return [...new Set(commands.map((line) => line.trim()).filter((line) => line && INSTALLERS.some((pattern) => pattern.test(line))))] +} diff --git a/cloud/apps/sandbox-control/image/boot-twice/boot-twice-init b/cloud/apps/sandbox-control/image/boot-twice/boot-twice-init new file mode 100644 index 00000000000..0d02dd222e8 --- /dev/null +++ b/cloud/apps/sandbox-control/image/boot-twice/boot-twice-init @@ -0,0 +1,31 @@ +#!/bin/sh +# PID 1's child (under `docker run --init`) in a boot-twice container. Each container start is one +# VM boot: a fresh kernel boot id, as a restored Vercel VM gets. A container otherwise sees the +# host's boot id on every start, and the start script would take a resumed disk for the same boot. +set -eu +cat /proc/sys/kernel/random/uuid >/run/boot-twice-boot-id +mount --bind /run/boot-twice-boot-id /proc/sys/kernel/random/boot_id +# Boot 2 resolves through the harness's DNS sink, which logs every name looked up (an offline boot +# that tries to fetch something fails quietly; the lookup is what shows it). +if [ -n "${BOOT_TWICE_DNS:-}" ]; then + printf 'nameserver %s\noptions attempts:1 timeout:1\n' "$BOOT_TWICE_DNS" >/run/boot-twice-resolv.conf + mount --bind /run/boot-twice-resolv.conf /etc/resolv.conf +fi +if [ -n "${BOOT_TWICE_TRACE:-}" ]; then + # Every 50 ms, the command line of each process not seen yet: a boot's installs and first-run work + # last far longer than that. + ( + seen=' ' + while :; do + for dir in /proc/[0-9]*; do + pid="${dir#/proc/}" + case "$seen" in *" $pid "*) continue ;; esac + seen="$seen$pid " + { tr '\0' ' ' <"$dir/cmdline"; echo; } >>/run/boot-twice-procs.log 2>/dev/null || true + done + sleep 0.05 + done + ) & +fi +: >/run/boot-twice-ready +exec sleep infinity diff --git a/cloud/apps/sandbox-control/image/boot-twice/boot-twice.ts b/cloud/apps/sandbox-control/image/boot-twice/boot-twice.ts new file mode 100644 index 00000000000..167b729c0e2 --- /dev/null +++ b/cloud/apps/sandbox-control/image/boot-twice/boot-twice.ts @@ -0,0 +1,485 @@ +// Boot-twice check for the golden image: provision it in a container, then boot the same disk twice +// through the control plane's own boot steps (entry-point probe, workspace prelude + start script, +// entry-point sync). The second boot runs with no network and must install and fetch nothing. +// pnpm --filter @orca-cloud/sandbox-control exec tsx image/boot-twice/boot-twice.ts [options] +// --release orcad bundle (default: the manifest's bundleUrl, else the latest release) +// --image boot an image built elsewhere (CI builds it with the layer cache) +// --context-out only write the docker build context and exit +// --report write the JSON report there too +// --keep leave the containers and the disk image for inspection +// Needs Docker that can run --privileged containers (Linux, Docker Desktop). See README.md. +import { spawn } from 'node:child_process' +import { createHash, randomBytes } from 'node:crypto' +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { ENTRY_POINTS_PROBE, ensureEntryPoints, entryPointsBehind, installEntryPoints, parseEntryPointsProbe } from '../../src/golden-images' +import { startOrcad, type OrcadReady } from '../../src/sandbox-vm-commands' +import type { CommandResult, ProviderSandboxState, RunCommandParams, SandboxProviderApi } from '../../src/sandbox-provider' +import { ManifestSchema, VM_SCRIPTS, provisionEnv, resolveReleaseBundle, type BuildInputs, type GoldenImageManifest } from '../golden-image' +import { VM_SCRIPTS_HASH, VM_SCRIPTS_STAMP, WORKSPACE_PRELUDE_SCRIPT } from '../vm-scripts.generated' +import { entryPointMismatches, installerCommands, parseDockerDiff, pinnedTools, unexpectedChanges, versionMismatches, type DiffEntry, type ObservedVersions } from './boot-twice-checks' + +const here = (path: string): string => fileURLToPath(new URL(path, import.meta.url).href) +const HOME = '/home/ubuntu' +const FIXTURE_REPO = 'file:///srv/fixture.git' +const INSTALL_MARK = 'echo synced' + +type Options = { release?: string; image?: string; contextOut?: string; report?: string; keep: boolean } + +function parseArgs(argv: string[]): Options { + const value = (flag: string): string | undefined => { + const at = argv.indexOf(flag) + return at === -1 ? undefined : argv[at + 1] + } + return { release: value('--release'), image: value('--image'), contextOut: value('--context-out'), report: value('--report'), keep: argv.includes('--keep') } +} + +type Run = { code: number; stdout: string; stderr: string } + +function docker(args: string[], options: { input?: string; timeoutMs?: number } = {}): Promise { + return new Promise((resolve, reject) => { + const child = spawn('docker', args, { stdio: ['pipe', 'pipe', 'pipe'] }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString())) + child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString())) + const timer = options.timeoutMs ? setTimeout(() => child.kill('SIGKILL'), options.timeoutMs) : null + child.on('error', reject) + child.on('close', (code) => { + if (timer) { + clearTimeout(timer) + } + resolve({ code: code ?? 124, stdout, stderr }) + }) + child.stdin.end(options.input ?? '') + }) +} + +async function dockerOk(args: string[], options: { input?: string; timeoutMs?: number } = {}): Promise { + const run = await docker(args, options) + if (run.code !== 0) { + throw new Error(`docker ${args[0]} failed (${run.code}): ${run.stderr.slice(-1500)}`) + } + return run.stdout +} + +/** Docker in buildx/build output mode: stream it, it takes minutes on a cold cache. */ +function dockerStreamed(args: string[]): Promise { + return new Promise((resolve, reject) => { + const child = spawn('docker', args, { stdio: ['ignore', 'inherit', 'inherit'] }) + child.on('error', reject) + child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`docker ${args[0]} failed (${code})`)))) + }) +} + +// Env arrives on stdin as NUL-separated NAME=value pairs: values can be multi-line (the prelude +// script) and large (every entry point, base64), which argv `-e` handles badly. +const ENV_LOADER = 'while IFS= read -r -d "" kv; do export "$kv"; done; exec "$@"' + +type CommandRecord = { boot: number; command: string; exitCode: number; ms: number; installed: boolean } + +/** Just enough of the provider for the boot steps: runCommand and readFile, as `docker exec`. */ +function dockerProvider(boot: () => number, commands: CommandRecord[]): SandboxProviderApi { + const unsupported = (name: string) => () => Promise.reject(new Error(`boot-twice provider does not emulate ${name}`)) + return { + async runCommand(container: string, params: RunCommandParams): Promise { + const started = Date.now() + const input = Object.entries(params.env ?? {}) + .map(([key, val]) => `${key}=${val}\0`) + .join('') + const user = params.sudo ? 'root' : 'ubuntu' + const run = await docker( + ['exec', '-i', '-u', user, '-w', params.cwd ?? HOME, container, 'bash', '-c', ENV_LOADER, 'boot-twice-env', params.command, ...(params.args ?? [])], + { input, timeoutMs: params.timeoutMs } + ) + const script = params.args?.at(-1) ?? '' + commands.push({ + boot: boot(), + command: params.command === 'bash' ? `bash -c ${JSON.stringify(script.split('\n')[0]!.slice(0, 80))}` : params.command, + exitCode: run.code, + ms: Date.now() - started, + installed: script.includes(INSTALL_MARK) + }) + return { exitCode: run.code, stdout: run.stdout, stderr: run.stderr } + }, + async readFile(container: string, path: string): Promise { + const run = await docker(['exec', '-u', 'ubuntu', container, 'cat', '--', path]) + return run.code === 0 ? run.stdout : null + }, + createSandbox: unsupported('createSandbox'), + getSandbox: unsupported('getSandbox'), + stopSession: unsupported('stopSession'), + extendTimeout: unsupported('extendTimeout'), + updateNetworkPolicy: unsupported('updateNetworkPolicy'), + updatePorts: unsupported('updatePorts'), + updateSnapshotExpiration: unsupported('updateSnapshotExpiration'), + deleteSandbox: unsupported('deleteSandbox'), + listSnapshots: unsupported('listSnapshots'), + deleteSnapshot: unsupported('deleteSnapshot'), + listSandboxes: unsupported('listSandboxes'), + listProjectSnapshots: unsupported('listProjectSnapshots') + } +} + +async function latestReleaseTag(): Promise { + const headers: Record = { accept: 'application/vnd.github+json', 'user-agent': 'orca-boot-twice' } + if (process.env.GITHUB_TOKEN) { + headers.authorization = `Bearer ${process.env.GITHUB_TOKEN}` + } + const response = await fetch('https://api.github.com/repos/stablyai/orca/releases/latest', { headers }) + if (!response.ok) { + throw new Error(`latest release lookup failed (HTTP ${response.status}); pass --release vX.Y.Z`) + } + return ((await response.json()) as { tag_name: string }).tag_name +} + +function loadInputs(): BuildInputs { + const manifest = ManifestSchema.parse(JSON.parse(readFileSync(here('../golden-image.manifest.json'), 'utf8'))) + const vmScripts = Object.fromEntries(VM_SCRIPTS.map((name) => [name, readFileSync(here(`../vm/${name}`), 'utf8')])) as BuildInputs['vmScripts'] + return { manifest, provisionScript: readFileSync(here('../provision-golden.sh'), 'utf8'), vmScripts, vmScriptsStamp: VM_SCRIPTS_STAMP, buildId: 'boot-twice' } +} + +async function withBundle(inputs: BuildInputs, release: string | undefined): Promise { + if (!release && inputs.manifest.orcad.bundleUrl && inputs.manifest.orcad.sha256) { + return inputs + } + const tag = !release || release === 'latest' ? await latestReleaseTag() : release + const pinned = await resolveReleaseBundle(tag) + return { ...inputs, manifest: { ...inputs.manifest, orcad: { bundleUrl: pinned.bundleUrl, sha256: pinned.sha256 } } } +} + +/** The docker build context; its bytes are the layer cache key, so nothing in it varies per run. */ +function writeContext(dir: string, inputs: BuildInputs): void { + mkdirSync(dir, { recursive: true }) + const lines = Object.entries(provisionEnv(inputs)).map(([key, val]) => { + if (val.includes("'")) { + throw new Error(`provision env ${key} has a quote`) + } + return `${key}='${val}'` + }) + writeFileSync(join(dir, 'provision.env'), `${lines.join('\n')}\n`) + copyFileSync(here('../provision-golden.sh'), join(dir, 'provision-golden.sh')) + copyFileSync(here('./Dockerfile'), join(dir, 'Dockerfile')) + copyFileSync(here('./boot-twice-init'), join(dir, 'boot-twice-init')) +} + +type BootReport = { + boot: number + network: boolean + ms: number + steps: Record + probe: { stamp: number; marker: boolean } | null + ready: OrcadReady | null + error?: string +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +async function waitFor(container: string, test: string, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + if ((await docker(['exec', container, 'sh', '-c', test])).code === 0) { + return true + } + await sleep(250) + } + return false +} + +// Quiet: no first-run work still running, and nothing outside the boot state paths written in the +// last 3 s. orcad installs agent hooks and OpenCode's first run ends a few seconds after ready. +const QUIET = [ + 'pgrep -f "opencode [m]odels|agent-[p]refetch" >/dev/null && exit 1', + `find ${HOME} /opt/orca -xdev \\( -path ${HOME}/.orca-sandbox -o -path ${HOME}/.orcad-data \\) -prune -o -newermt "-3 seconds" -print | grep -q . && exit 1`, + 'exit 0' +].join('\n') + +async function settle(container: string): Promise { + await sleep(3_000) + await waitFor(container, QUIET, 150_000) +} + +// The DNS sink: answers every query NXDOMAIN and prints each name once ("lookup "). +const DNS_SINK = ` +const seen = new Set() +const socket = require('node:dgram').createSocket('udp4') +socket.on('message', (msg, peer) => { + if (msg.length < 12) return + const labels = [] + let at = 12 + while (at < msg.length && msg[at] !== 0) { labels.push(msg.subarray(at + 1, at + 1 + msg[at]).toString()); at += msg[at] + 1 } + const name = labels.join('.').toLowerCase() + if (!seen.has(name)) { seen.add(name); console.log('lookup ' + name) } + const reply = Buffer.from(msg.subarray(0, at + 5)) + reply[2] = 0x81; reply[3] = 0x83; reply.writeUInt16BE(0, 6); reply.writeUInt16BE(0, 8); reply.writeUInt16BE(0, 10) + socket.send(reply, peer.port, peer.address) +}) +socket.bind(53, () => console.log('sink ready')) +` + +/** Names the harness itself makes up; anything else boot 2 looks up is a fetch attempt. */ +const LOCAL_NAMES = /(^|\.)(invalid|localhost|local)$|^boot-twice(-\d+)?$/ + +type Sink = { network: string; ip: string; container: string } + +async function startSink(image: string, runId: string): Promise { + const network = `orca-boot-twice-${runId}` + const container = `orca-boot-twice-${runId}-dns` + await dockerOk(['network', 'create', '--internal', network]) + await dockerOk(['run', '-d', '--name', container, '--network', network, '--user', 'root', image, 'node', '-e', DNS_SINK]) + const ip = (await dockerOk(['inspect', '-f', `{{(index .NetworkSettings.Networks "${network}").IPAddress}}`, container])).trim() + const deadline = Date.now() + 15_000 + while (!(await docker(['logs', container])).stdout.includes('sink ready')) { + if (Date.now() > deadline) { + throw new Error('DNS sink did not start') + } + await sleep(200) + } + return { network, ip, container } +} + +/** + * Lookups every orcad start makes, by design: reported, not failed. orcad refreshes its agent-state + * rules from the orca GitHub releases at start (and keeps working on its cached copy when offline). + * The cost: a git fetch to github.com on boot 2 would hide behind this; the disk diff still catches + * one that wrote anything. + */ +const RUNTIME_LOOKUPS: Readonly> = { + 'github.com': "orcad's agent-state-rules refresh at start" +} + +async function sinkLookups(sink: Sink): Promise<{ unexpected: string[]; expected: string[] }> { + const out = (await docker(['logs', sink.container])).stdout + const names = [...out.matchAll(/^lookup (.+)$/gm)].map((match) => match[1]!).filter((name) => !LOCAL_NAMES.test(name)) + return { unexpected: names.filter((name) => !(name in RUNTIME_LOOKUPS)), expected: names.filter((name) => name in RUNTIME_LOOKUPS) } +} + +/** One VM boot: a new container on the disk image, then the steps lifecycle.ts runs on create/wake. */ +async function bootOnce( + provider: SandboxProviderApi, + image: string, + container: string, + boot: number, + options: { network: boolean; prelude: boolean; sink?: { network: string; ip: string } } +): Promise { + const steps: Record = {} + const time = async (name: string, step: () => Promise): Promise => { + const started = Date.now() + try { + return await step() + } finally { + steps[name] = Date.now() - started + } + } + const report: BootReport = { boot, network: options.network, ms: 0, steps, probe: null, ready: null } + // Offline: an internal network (no route out) whose only resolver is the DNS sink. + const network = options.network ? [] : options.sink ? ['--network', options.sink.network, '--env', `BOOT_TWICE_DNS=${options.sink.ip}`] : ['--network', 'none'] + // Every boot records the commands it runs (/run/boot-twice-procs.log, sampled by the init). + network.push('--env', 'BOOT_TWICE_TRACE=1') + await dockerOk(['run', '-d', '--init', '--privileged', '--name', container, '--hostname', `boot-twice-${boot}`, '--tmpfs', '/run', ...network, image]) + if (!(await waitFor(container, 'test -e /run/boot-twice-ready', 30_000))) { + throw new Error(`boot ${boot}: container init did not come up`) + } + const started = Date.now() + try { + // refreshRuntime (no runtime bundle published here): the probe, and an install only when behind. + const probe = await time('probe', () => provider.runCommand(container, { command: 'bash', args: ['-c', ENTRY_POINTS_PROBE], sudo: true, timeoutMs: 40_000 })) + report.probe = parseEntryPointsProbe(probe.stdout) + if (entryPointsBehind(report.probe)) { + await time('entryPointsBeforeStart', () => installEntryPoints({ provider }, container)) + } + const state: ProviderSandboxState = { + sandbox: { name: container, status: 'running', currentSessionId: container, currentSnapshotId: null, tags: {} }, + session: { id: container, status: 'running', startedAt: started, timeoutMs: 3_600_000 }, + routes: [{ port: 6768, url: 'https://boot-twice.invalid' }] + } + report.ready = await time('orcad', () => + startOrcad(provider, state, { + sandboxId: `boot-twice-${boot}`, + hostname: 'boot-twice', + repo: { url: FIXTURE_REPO, ref: 'main' }, + docker: true, + prelude: options.prelude ? { script: WORKSPACE_PRELUDE_SCRIPT } : undefined + }) + ) + // settleMemberGit after ready: the per-boot entry-point check (an install at most once per image). + await time('entryPointsAfterStart', () => ensureEntryPoints({ provider }, container)) + } catch (error) { + report.error = error instanceof Error ? error.message : String(error) + } + report.ms = Date.now() - started + return report +} + +const VERSIONS_SCRIPT = ` +const { execFileSync } = require('node:child_process') +const { readFileSync } = require('node:fs') +const [packages, binaries] = JSON.parse(process.argv[1]) +const out = {} +for (const name of packages) { + try { out[name] = JSON.parse(readFileSync('/opt/orca/tools/lib/node_modules/' + name + '/package.json', 'utf8')).version } catch { out[name] = null } +} +for (const name of binaries) { + try { + const text = execFileSync(name, ['--version'], { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'ignore'] }) + out[name] = text.trim().split('\\n')[0] || null + } catch { out[name] = null } +} +console.log(JSON.stringify(out)) +` + +// What a booted image carries: entry points (sha256), the scripts stamp and markers, orcad's +// version and whether it is listening on 6768 (0x1A70) on all interfaces. +const IMAGE_PROBE = [ + 'cd /opt/orca/bin', + 'for f in * .scripts-stamp .entry-points-*; do [ -f "$f" ] && echo "file $(sha256sum "$f" | cut -d" " -f1) $f"; done', + 'echo "stamp $(cat .scripts-stamp 2>/dev/null || echo none)"', + 'echo "orcad_version $(cat /opt/orca/runtime/orcad/.version 2>/dev/null || echo none)"', + 'kill -0 "$(cat ~/.orca-sandbox/orcad.pid 2>/dev/null || echo 0)" 2>/dev/null && echo orcad_alive=1 || echo orcad_alive=0', + 'grep -qi " 00000000:1A70 00000000:0000 0A" /proc/net/tcp && echo orcad_listening=1 || echo orcad_listening=0', + // Installers or fetchers still running after the boot answered. + 'echo "busy $(ps -eo args= | grep -E "^(apt|apt-get|dpkg|npm|npx|pip|curl|wget) |opencode [m]odels|git ([c]lone|[f]etch)" | head -3 | tr "\\n" ";")"' +].join('\n') + +type Failure = string + +async function checkImage(provider: SandboxProviderApi, container: string, manifest: GoldenImageManifest, failures: Failure[]) { + const sources = Object.fromEntries(VM_SCRIPTS.map((name) => [name, createHash('sha256').update(readFileSync(here(`../vm/${name}`))).digest('hex')])) + const probe = await provider.runCommand(container, { command: 'bash', args: ['-c', IMAGE_PROBE], timeoutMs: 30_000 }) + const installed: Record = {} + for (const match of probe.stdout.matchAll(/^file ([0-9a-f]{64}) (.+)$/gm)) { + installed[match[2]!] = match[1]! + } + failures.push(...entryPointMismatches(sources, installed).map((problem) => `entry point ${problem}`)) + const stamp = /^stamp (.+)$/m.exec(probe.stdout)?.[1] + if (stamp !== String(VM_SCRIPTS_STAMP)) { + failures.push(`/opt/orca/bin/.scripts-stamp is ${stamp ?? 'unreadable'}, expected ${VM_SCRIPTS_STAMP}`) + } + if (!(`.entry-points-${VM_SCRIPTS_HASH}` in installed)) { + failures.push(`no .entry-points-${VM_SCRIPTS_HASH} marker after two boots`) + } + if (!/^orcad_alive=1$/m.test(probe.stdout) || !/^orcad_listening=1$/m.test(probe.stdout)) { + failures.push('orcad is not running and listening on :6768 after the second boot') + } + const busy = /^busy (.*)$/m.exec(probe.stdout)?.[1]?.trim() + if (busy) { + failures.push(`still installing or fetching after the second boot: ${busy}`) + } + const tools = pinnedTools(manifest) + const run = await provider.runCommand(container, { + command: 'bash', + args: ['-lc', 'node -e "$1" "$2"', 'versions', VERSIONS_SCRIPT, JSON.stringify([tools.filter((t) => t.source === 'package').map((t) => t.name), tools.filter((t) => t.source === 'binary').map((t) => t.name)])], + timeoutMs: 180_000 + }) + let observed: ObservedVersions = {} + try { + observed = JSON.parse(run.stdout.trim().split('\n').at(-1) ?? '{}') as ObservedVersions + } catch { + failures.push(`version probe failed (exit ${run.exitCode}): ${run.stderr.slice(-300)}`) + } + failures.push(...versionMismatches(tools, observed)) + return { orcadVersion: /^orcad_version (.+)$/m.exec(probe.stdout)?.[1] ?? null, versions: observed, entryPoints: Object.keys(installed).length } +} + +async function main(): Promise { + const options = parseArgs(process.argv.slice(2)) + const inputs = await withBundle(loadInputs(), options.release) + if (options.contextOut) { + writeContext(options.contextOut, inputs) + console.log(JSON.stringify({ context: options.contextOut, bundleUrl: inputs.manifest.orcad.bundleUrl })) + return + } + const runId = randomBytes(3).toString('hex') + const started = Date.now() + let image = options.image + if (!image) { + const context = mkdtempSync(join(tmpdir(), 'orca-boot-twice-')) + writeContext(context, inputs) + image = 'orca-boot-twice:local' + console.error(`[boot-twice] building ${image} from ${context} (orcad ${inputs.manifest.orcad.bundleUrl})`) + await dockerStreamed(['build', '--target', 'harness', '-t', image, context]) + } + const buildMs = Date.now() - started + const disk = `orca-boot-twice-disk:${runId}` + const containers = [`orca-boot-twice-${runId}-1`, `orca-boot-twice-${runId}-2`] as const + const commands: CommandRecord[] = [] + let current = 1 + const provider = dockerProvider(() => current, commands) + const failures: Failure[] = [] + let diff: DiffEntry[] = [] + let unexpected: DiffEntry[] = [] + let image2: Awaited> | null = null + const boots: BootReport[] = [] + let sink: Sink | null = null + let lookups: { unexpected: string[]; expected: string[] } = { unexpected: [], expected: [] } + try { + console.error('[boot-twice] boot 1 (first boot of the image, network on)') + boots.push(await bootOnce(provider, image, containers[0], 1, { network: true, prelude: true })) + // A VM lives a while after ready: let the first boot's background work finish before the disk is kept. + await settle(containers[0]) + await dockerOk(['stop', '-t', '20', containers[0]]) + await dockerOk(['commit', containers[0], disk]) + current = 2 + console.error('[boot-twice] boot 2 (same disk, new boot id, no network)') + sink = await startSink(image, runId) + boots.push(await bootOnce(provider, disk, containers[1], 2, { network: false, prelude: false, sink })) + for (const boot of boots) { + if (boot.error || !boot.ready?.pairingCode.startsWith('orca://')) { + failures.push(`boot ${boot.boot}: orcad did not come up (${boot.error ?? 'no pairing offer'})`) + } + } + const reinstalls = commands.filter((command) => command.boot === 2 && command.installed) + if (reinstalls.length > 0) { + failures.push(`boot 2 reinstalled the entry points (${reinstalls.length}x): the first boot's marker did not stick`) + } + if (boots[1]?.probe && !boots[1].probe.marker) { + failures.push('boot 2 probe: no entry-points marker for this tree') + } + // Give the second boot the same time to do (and show) anything it starts in the background. + await settle(containers[1]) + const procs = await docker(['exec', containers[1], 'cat', '/run/boot-twice-procs.log']) + failures.push(...installerCommands(procs.stdout.split('\n')).map((command) => `boot 2 ran ${JSON.stringify(command.slice(0, 160))}`)) + lookups = await sinkLookups(sink) + failures.push(...lookups.unexpected.map((name) => `boot 2 tried to reach ${name}`)) + // The disk diff comes first: the version probe runs the agent CLIs, which write their own caches. + diff = parseDockerDiff(await dockerOk(['diff', containers[1]])) + unexpected = unexpectedChanges(diff, HOME) + failures.push(...unexpected.map((entry) => `boot 2 changed ${entry.kind} ${entry.path}`)) + image2 = await checkImage(provider, containers[1], inputs.manifest, failures) + } finally { + if (!options.keep) { + await docker(['rm', '-f', ...containers, ...(sink ? [sink.container] : [])]) + await docker(['rmi', '-f', disk]) + if (sink) { + await docker(['network', 'rm', sink.network]) + } + } + } + const report = { + ok: failures.length === 0, + failures, + image, + orcadBundle: inputs.manifest.orcad.bundleUrl, + buildMs, + boots: boots.map(({ ready, ...rest }) => ({ ...rest, ready: ready ? { projectRoot: ready.projectRoot } : null })), + commands, + boot2: { diff: diff.length, unexpected, lookups, ...image2 }, + totalMs: Date.now() - started + } + if (options.report) { + writeFileSync(options.report, `${JSON.stringify(report, null, 2)}\n`) + } + console.log(JSON.stringify(report, null, 2)) + for (const boot of boots) { + console.error(`[boot-twice] boot ${boot.boot}: ${boot.ms} ms ${JSON.stringify(boot.steps)}`) + } + console.error(report.ok ? '[boot-twice] OK: the second boot installed nothing' : `[boot-twice] FAILED:\n ${failures.join('\n ')}`) + process.exitCode = report.ok ? 0 : 1 +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.stack ?? error.message : String(error)) + process.exitCode = 1 +}) 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..e8ea616a29e 100755 --- a/cloud/apps/sandbox-control/image/provision-golden.sh +++ b/cloud/apps/sandbox-control/image/provision-golden.sh @@ -55,8 +55,11 @@ if [ ! -s "$ORCA_HOME/runtime/orcad/orcad-server.js" ]; then server="$(find "$ORCA_HOME/runtime" -name orcad-server.js -type f | head -n 1)" [ -n "$server" ] || { log 'bundle has no orcad-server.js'; exit 1; } root="$(dirname "$(dirname "$server")")" - ln -sfn "$(dirname "$server")" "$ORCA_HOME/runtime/orcad" - [ -d "$ORCA_HOME/runtime/runtimes" ] || ln -sfn "$root/runtimes" "$ORCA_HOME/runtime/runtimes" + # Move the tree up rather than linking to it: every VM script finds node with + # `find .../runtime/runtimes -type f`, and find doesn't descend into a symlinked start point + # (a linked release bundle left the build with no node). orcad's ../runtimes still resolves. + for entry in "$root"/*; do mv "$entry" "$ORCA_HOME/runtime/"; done + rmdir "$root" fi test -s "$ORCA_HOME/runtime/orcad/orcad-server.js" node="$(find "$ORCA_HOME/runtime/runtimes" -type f -name node | head -n 1)" @@ -98,6 +101,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 @@ -210,7 +223,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 f1ef52f7858..6000381bf44 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). 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 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 = "2cb89ff2" -export const VM_SCRIPTS_STAMP: number = 1794730652 +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 # Move the tree up rather than linking to it: every VM script finds node with\n # `find .../runtime/runtimes -type f`, and find doesn't descend into a symlinked start point\n # (a linked release bundle left the build with no node). orcad's ../runtimes still resolves.\n for entry in \"$root\"/*; do mv \"$entry\" \"$ORCA_HOME/runtime/\"; done\n rmdir \"$root\"\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-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 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. An image without the\n# seed (an environment snapshot from an older golden) still needs the install: then the first run\n# waits for orcad to put Orca's plugin in ~/.config/opencode/plugins (~10 s), since OpenCode only\n# finishes that install when a plugin is configured.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && { [ ! -e \"$HOME/.local/share/opencode/opencode.db\" ] || [ ! -e \"$oc_dir/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 if [ ! -e \"$HOME/.config/opencode/node_modules\" ]; then\n for _ in $(seq 1 120); do [ -d \"$HOME/.config/opencode/plugins\" ] && break; sleep 0.5; done\n fi\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=''\nsign_in_inside=''\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 # Not for shells: the agents the person signs in inside this workspace (e.g. `claude,codex`).\n if [ \"$name\" = ORCA_SIGN_IN_INSIDE ]; then\n sign_in_inside=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$sign_in_inside\" in *[!a-z,]*) sign_in_inside='' ;; esac\n fi\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 claude_inside=''\n case \",$sign_in_inside,\" in *,claude,*) claude_inside=1 ;; esac\n ORCA_CLAUDE_INSIDE=\"$claude_inside\" 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)\n// Signed in inside this workspace and no login here yet: leave first-run onboarding to Claude, so it opens\n// on its own sign-in screens instead of \"Not logged in\". Once a login exists, onboarding is done as usual.\nconst claudeCredentials = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(home, \".claude\"), \".credentials.json\")\nif (process.env.ORCA_CLAUDE_INSIDE === \"1\" && !fs.existsSync(claudeCredentials)) delete c.hasCompletedOnboarding\nelse c.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 = "700f166d" +export const VM_SCRIPTS_STAMP: number = 1794744375 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-env b/cloud/apps/sandbox-control/image/vm/orca-sandbox-env index acd169c0f4f..1bcd5eb6e38 100644 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-env +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-env @@ -36,9 +36,15 @@ anthropic_key_scrub='' gateway_key='' gemini_key='' codex_placeholder='' +sign_in_inside='' while IFS= read -r line; do name="${line%%=*}" b64="${line#*=}" # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below. + # Not for shells: the agents the person signs in inside this workspace (e.g. `claude,codex`). + if [ "$name" = ORCA_SIGN_IN_INSIDE ]; then + sign_in_inside="$(printf '%s' "$b64" | base64 -d)" + case "$sign_in_inside" in *[!a-z,]*) sign_in_inside='' ;; esac + fi if [ "$name" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then codex_placeholder="$(printf '%s' "$b64" | base64 -d)" case "$codex_placeholder" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac @@ -164,7 +170,9 @@ fi # through them, and the agent would sit there doing nothing. Merges; never touches credentials. node_bin="$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)" if [ -n "$node_bin" ]; then - ORCA_PROJECT="$PROJECT" ORCA_KEY_TAIL="$anthropic_key_tail" ORCA_KEY_SCRUB="$anthropic_key_scrub" ORCA_GEMINI_KEY="$gemini_key" \ + claude_inside='' + case ",$sign_in_inside," in *,claude,*) claude_inside=1 ;; esac + ORCA_CLAUDE_INSIDE="$claude_inside" ORCA_PROJECT="$PROJECT" ORCA_KEY_TAIL="$anthropic_key_tail" ORCA_KEY_SCRUB="$anthropic_key_scrub" ORCA_GEMINI_KEY="$gemini_key" \ ORCA_GATEWAY_MODEL="${gateway_key:+${anthropic_model:-$openai_model}}" "$node_bin" -e ' const fs = require("fs"), path = require("path"), os = require("os") const home = os.homedir() @@ -178,7 +186,11 @@ const write = (file, value) => { const claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, ".claude.json") const c = readJson(claudeFile) const before = JSON.stringify(c) -c.hasCompletedOnboarding = true +// Signed in inside this workspace and no login here yet: leave first-run onboarding to Claude, so it opens +// on its own sign-in screens instead of "Not logged in". Once a login exists, onboarding is done as usual. +const claudeCredentials = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(home, ".claude"), ".credentials.json") +if (process.env.ORCA_CLAUDE_INSIDE === "1" && !fs.existsSync(claudeCredentials)) delete c.hasCompletedOnboarding +else c.hasCompletedOnboarding = true c.theme = c.theme || "dark" c.bypassPermissionsModeAccepted = true c.projects = c.projects && typeof c.projects === "object" ? c.projects : {} diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start index caa98f7817b..18f9b606e10 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 @@ -191,16 +195,35 @@ 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). 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. An image without the +# seed (an environment snapshot from an older golden) still needs the install: then the first run +# waits for orcad to put Orca's plugin in ~/.config/opencode/plugins (~10 s), since OpenCode only +# finishes that install when a plugin is configured. +if [ -x "$ORCA_HOME/tools/bin/opencode" ] && { [ ! -e "$HOME/.local/share/opencode/opencode.db" ] || [ ! -e "$oc_dir/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 ' + if [ ! -e "$HOME/.config/opencode/node_modules" ]; then + for _ in $(seq 1 120); do [ -d "$HOME/.config/opencode/plugins" ] && break; sleep 0.5; done + fi + exec timeout 120 "$1" models + ' opencode-first-run "$ORCA_HOME/tools/bin/opencode" /dev/null 2>&1 9>&- & ) fi 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/migrations/0062_environment_region.sql b/cloud/apps/sandbox-control/migrations/0062_environment_region.sql new file mode 100644 index 00000000000..6f1bcfaacc2 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0062_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/migrations/0063_agent_sources_in_workspace.sql b/cloud/apps/sandbox-control/migrations/0063_agent_sources_in_workspace.sql new file mode 100644 index 00000000000..343a74a1446 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0063_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/scripts/README.md b/cloud/apps/sandbox-control/scripts/README.md new file mode 100644 index 00000000000..b05ebfbc173 --- /dev/null +++ b/cloud/apps/sandbox-control/scripts/README.md @@ -0,0 +1,56 @@ +# Egress release probe + +`egress-probe.ts` checks sandbox egress against **dev** before a release. It goes through Orca's own +paths: real dev workspaces created with a dev-JWK user token, with commands run in a workspace +terminal over the shipped `orca` CLI's pairing code (the desktop's E2EE path to orcad). Every +credential is bogus, and postman-echo.com plays the model provider. + +Setup for a throwaway identity, all of it removed afterwards: + +- the dev GitHub App's installation, bound for the test repo (operator route); +- a stored GitHub identity, so member placeholders exist (the dev `member-github` route); +- bogus personal secrets: + - `ANTHROPIC_API_KEY`, with `ANTHROPIC_BASE_URL` set to the echo host; + - `OPENAI_API_KEY`, with `OPENAI_BASE_URL` set to `chatgpt.com/backend-api/codex`, so its egress + takes the ChatGPT relay. + +The probe creates two workspaces through the desktop's create path (clone after ready): + +- **public**: a public repo the App isn't installed on. Member placeholder, no App token (#758). +- **app**: the App-installed test repo. App token, github.com fail-closed. + +| Host | What must happen | +|---|---| +| echo host (custom base URL) | The provider sees the bogus key where the VM sent the placeholder. The other `authorization` header is unchanged, and no `vercel-forwarded-*` header or OIDC token arrives. A foreign key gets the firewall 403 `orca-egress-denied`. | +| chatgpt.com | The placeholder reaches ChatGPT: any provider answer counts, but not the firewall 403 and not Cloudflare's edge page. A foreign bearer gets the firewall 403. | +| api.github.com | No credential gets the firewall 403. With the workspace placeholder, GitHub answers 200. | +| github.com | Anonymous `git ls-remote` works on **public** (#758) and is refused on **app**. The app repo clones, and the workspace's own git works. | +| VM env | `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` hold placeholders. This is checked by sha256, so the bogus values never cross the terminal. | + +The probe takes about 1–3 minutes, deletes what it created (`--keep` leaves it), prints one JSON +report and exits 1 on any failed expectation. It refuses any control plane other than dev. + +## Run it locally + +You need the Orca app installed (for its `orca` CLI) and `gcloud` access to the dev secrets. + +```sh +cd cloud +pnpm install --filter @orca-cloud/sandbox-control... +K=$(mktemp -d) # 0700; delete it afterwards +gcloud --account secrets versions access latest --project onorca-cloud-staging \ + --secret orca-sandbox-control-dev-test-jwk > "$K/jwk.json" +gcloud --account secrets versions access latest --project onorca-cloud-staging \ + --secret orca-sandbox-control-dev-operator-token > "$K/operator" +ORCA_PROBE_DEV_JWK_FILE="$K/jwk.json" ORCA_PROBE_OPERATOR_TOKEN_FILE="$K/operator" \ + pnpm --filter @orca-cloud/sandbox-control exec tsx scripts/egress-probe.ts +rm -rf "$K" +``` + +`ORCA_PROBE_CLI` points the probe at another `orca` CLI. The default is the installed app's. + +## CI + +`.github/workflows/cloud-egress-probe.yml` runs on manual dispatch. It installs the CLI from the +latest release's Linux package. It needs the `ORCA_DEV_TEST_JWK` and `ORCA_DEV_OPERATOR_TOKEN` +repository secrets, and warns and skips when they are missing. None are configured today. diff --git a/cloud/apps/sandbox-control/scripts/egress-probe-checks.ts b/cloud/apps/sandbox-control/scripts/egress-probe-checks.ts new file mode 100644 index 00000000000..e917d92c7b2 --- /dev/null +++ b/cloud/apps/sandbox-control/scripts/egress-probe-checks.ts @@ -0,0 +1,119 @@ +// Pure parts of the egress release probe (egress-probe.ts): the runner it starts in a workspace +// terminal, the requests that runner sends, and what each answer must look like. +import { createHash } from 'node:crypto' +import { EGRESS_DENIED_BODY } from '../src/network-policy' + +/** + * One request from inside the workspace. A header value `$NAME` is read from the VM's env (orcad's + * environment, as agents get it), so placeholders never cross the terminal. + */ +export type ProbeRequest = { name: string; url: string; method?: 'GET' | 'POST'; headers?: Record } + +/** What the answer must be. */ +export type Expectation = + /** The echo host answered as the provider: these headers (by sha256) arrived, and nothing from Vercel's hop. */ + | { kind: 'swapped'; headers: Record } + /** The firewall's own 403 (a credential host fails closed). */ + | { kind: 'denied' } + /** The request reached the provider itself: not the firewall's 403, not an edge block page. */ + | { kind: 'upstream' } + +export type ProbeCase = ProbeRequest & { expect: Expectation } + +/** What the runner reports per request: never a header value, only sha256 prefixes of the echoed ones. */ +export type Summary = { + status: number + /** Body is the firewall's deny body. */ + denied: boolean + /** An HTML 403 from Cloudflare: the provider's edge refused the proxy. */ + edgeBlocked: boolean + /** The echo host's answer: sha256 prefix of each echoed header, and Vercel hop headers seen. */ + echoed?: Record + leaked?: string[] +} + +export const sha8 = (value: string): string => createHash('sha256').update(value).digest('hex').slice(0, 8) + +/** + * Runs in the workspace (node, from a terminal): fetches each request and prints one short line per + * fact, `PRB =`, ending with `PRB-END`. Short lines survive the terminal intact. + * The echo host (postman-echo.com) answers JSON with the request's headers under `headers`. + */ +export const VM_RUNNER = ` +const { createHash } = require('node:crypto') +const cases = JSON.parse(Buffer.from(process.argv[1], 'base64').toString()) +const sha8 = (v) => createHash('sha256').update(String(v)).digest('hex').slice(0, 8) +const out = (i, k, v) => console.log('PRB ' + i + ' ' + k + '=' + v) +;(async () => { + for (const [i, c] of cases.entries()) { + const headers = {} + for (const [k, v] of Object.entries(c.headers || {})) headers[k] = v.startsWith('$') ? process.env[v.slice(1)] || '' : v + try { + const r = await fetch(c.url, { method: c.method || 'GET', headers, body: c.method === 'POST' ? '{}' : undefined, redirect: 'manual', signal: AbortSignal.timeout(25000) }) + const body = await r.text() + out(i, 's', r.status) + out(i, 'd', body.trim() === ${JSON.stringify(EGRESS_DENIED_BODY)} ? 1 : 0) + out(i, 'cf', r.status === 403 && /text\\/html/.test(r.headers.get('content-type') || '') && /cloudflare/i.test(r.headers.get('server') || '') ? 1 : 0) + let echo = null + try { echo = JSON.parse(body).headers } catch {} + if (echo && typeof echo === 'object') { + for (const [k, v] of Object.entries(echo)) { + if (/^vercel-forwarded-|oidc/i.test(k)) out(i, 'leak', k) + else if (k in (c.headers || {})) out(i, 'h.' + k, sha8(v)) + } + } + } catch (e) { + out(i, 's', 0) + } + } + console.log('PRB-END') +})() +` + +export function parseRunnerOutput(text: string, count: number): Summary[] { + const summaries: Summary[] = Array.from({ length: count }, () => ({ status: 0, denied: false, edgeBlocked: false })) + for (const match of text.matchAll(/PRB (\d+) ([a-z.-]+)=(\S+)/g)) { + const summary = summaries[Number(match[1])] + const [key, value] = [match[2]!, match[3]!] + if (!summary) { + continue + } + if (key === 's') summary.status = Number(value) + else if (key === 'd') summary.denied = value === '1' + else if (key === 'cf') summary.edgeBlocked = value === '1' + else if (key === 'leak') summary.leaked = [...(summary.leaked ?? []), value] + else if (key.startsWith('h.')) summary.echoed = { ...summary.echoed, [key.slice(2)]: value } + } + return summaries +} + +/** Problems with one answer; empty when it is what the case expects. Never quotes a header value. */ +export function judge(probe: ProbeCase, answer: Summary): string[] { + const { expect } = probe + const denied = answer.status === 403 && answer.denied + if (expect.kind === 'denied') { + return denied ? [] : [`${probe.name}: expected the firewall's 403 ${EGRESS_DENIED_BODY}, got ${answer.status}`] + } + if (expect.kind === 'upstream') { + if (denied) return [`${probe.name}: refused by the firewall`] + if (answer.edgeBlocked) return [`${probe.name}: the provider's edge refused the egress proxy (Cloudflare 403 page)`] + return answer.status === 0 ? [`${probe.name}: no answer`] : [] + } + if (answer.status !== 200 || !answer.echoed) { + return [`${probe.name}: expected the echo host's answer, got ${answer.status}${denied ? ' (denied)' : ''}`] + } + const problems = (answer.leaked ?? []).map((name) => `${probe.name}: the provider saw ${name}`) + for (const [name, value] of Object.entries(expect.headers)) { + if (answer.echoed[name] !== sha8(value)) { + problems.push(`${probe.name}: header ${name} ${answer.echoed[name] ? 'arrived with another value' : 'did not arrive'}`) + } + } + return problems +} + +/** The terminal line that runs the cases: the runner and its input both base64, one shell word each. */ +export function runnerCommand(cases: readonly ProbeRequest[]): string { + const runner = Buffer.from(VM_RUNNER).toString('base64') + const input = Buffer.from(JSON.stringify(cases.map(({ name: _name, ...request }) => request))).toString('base64') + return `node -e "$(echo ${runner} | base64 -d)" ${input}` +} diff --git a/cloud/apps/sandbox-control/scripts/egress-probe.ts b/cloud/apps/sandbox-control/scripts/egress-probe.ts new file mode 100644 index 00000000000..0f3e61d3b57 --- /dev/null +++ b/cloud/apps/sandbox-control/scripts/egress-probe.ts @@ -0,0 +1,268 @@ +// Release probe for sandbox egress, against DEV only, through Orca's own paths: real dev workspaces +// created with a dev-JWK user token, driven from a terminal over the `orca` CLI's pairing code (the +// desktop's E2EE path). Bogus tokens only; postman-echo.com plays the model provider. +// pnpm --filter @orca-cloud/sandbox-control exec tsx scripts/egress-probe.ts [--keep] +// +// A throwaway identity gets: the dev GitHub App installation bound for one test repo (operator), a +// stored GitHub identity (the dev member-github route, so member placeholders exist), and bogus +// personal secrets ANTHROPIC_API_KEY (base URL: the echo host) and OPENAI_API_KEY (base URL: +// chatgpt.com, so its egress takes the ChatGPT relay). Two workspaces: +// public a public repo the App is not installed on: member placeholder, no App token (#758) +// app the App-installed test repo: App token, github.com fail-closed +// Checks (every one names the host it is about): +// - api.anthropic-compatible echo host: the provider sees the bogus key where the VM sent the +// placeholder, the other auth header unchanged, nothing from Vercel's hop; a foreign key 403s. +// - chatgpt.com: the placeholder reaches ChatGPT (any provider answer; not the firewall's 403 and +// not Cloudflare's edge page); a foreign bearer 403s. +// - api.github.com: no credential 403s; with the workspace placeholder GitHub answers 200. +// - github.com: anonymous `git ls-remote` works on `public` (#758) and 403s on `app`; the +// workspace's own git (placeholder extraheader) works on `app`. +// - the VM holds placeholders, never the bogus values. +// +// Inputs (files, never printed): +// ORCA_PROBE_DEV_JWK_FILE dev test signing key (SM: orca-sandbox-control-dev-test-jwk) +// ORCA_PROBE_OPERATOR_TOKEN_FILE dev operator token (SM: orca-sandbox-control-dev-operator-token) +// ORCA_PROBE_CONTROL_URL default: the dev sandbox-control Worker (anything else is refused) +// ORCA_PROBE_CLI default: the installed Orca app's `orca` CLI +// Prints one JSON report; exits 1 on any failed expectation. See scripts/README.md. +import { execFile } from 'node:child_process' +import { randomBytes } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { SignJWT, importJWK, type JWK } from 'jose' +import { judge, parseRunnerOutput, runnerCommand, sha8, type ProbeCase } from './egress-probe-checks' + +const CONTROL_URL = process.env.ORCA_PROBE_CONTROL_URL ?? 'https://orca-sandbox-control-dev.lovecast.workers.dev' +const ORCA_CLI = process.env.ORCA_PROBE_CLI ?? '/Applications/Orca.app/Contents/Resources/bin/orca' +/** The dev GitHub App is installed on this repo. */ +const APP_REPO = process.env.ORCA_PROBE_APP_REPO ?? 'https://github.com/nwparker/orca-sandbox-push-test' +/** Public, and the dev App is not installed on its owner. */ +const PUBLIC_REPO = 'https://github.com/octocat/Hello-World' +const ECHO = 'https://postman-echo.com' + +if (!/^https:\/\/[a-z0-9-]+-dev\.lovecast\.workers\.dev$|^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(CONTROL_URL)) { + throw new Error(`refusing a non-dev control plane: ${CONTROL_URL}`) +} + +const keep = process.argv.includes('--keep') +const runId = randomBytes(4).toString('hex') +const sub = `egress-probe-${runId}` +const accountId = `dev:${sub}` +const fileSecret = (env: string): string => { + const file = process.env[env] + if (!file) { + throw new Error(`set ${env}`) + } + return readFileSync(file, 'utf8').trim() +} + +async function userToken(): Promise { + const jwk = JSON.parse(fileSecret('ORCA_PROBE_DEV_JWK_FILE')) as { kid: string; private: JWK; issuers?: { sandbox?: string }; audiences?: { sandbox?: string } } + return new SignJWT({ sub, purpose: 'sandbox' }) + .setProtectedHeader({ alg: 'ES256', kid: jwk.kid }) + .setIssuer(jwk.issuers?.sandbox ?? 'orca-sandbox-dev-test') + .setAudience(jwk.audiences?.sandbox ?? 'orca-sandbox') + .setIssuedAt() + .setExpirationTime('45m') + .sign(await importJWK(jwk.private, 'ES256')) +} + +type Reply = { status: number; body: Record | null } + +function client(bearer: string) { + return async (method: string, path: string, body?: unknown): Promise => { + const response = await fetch(`${CONTROL_URL}${path}`, { + method, + // clone-progress: the desktop's create, whose clone runs after ready (GET /v1/sandboxes/:id/clone). + headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json', 'x-orca-sandbox-features': 'clone-progress' }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(300_000) + }) + return { status: response.status, body: (await response.json().catch(() => null)) as Record | null } + } +} + +/** The shipped CLI over a workspace's pairing code; the code never reaches logs or the report. */ +function orca(pairingCode: string, args: string[], timeoutMs = 60_000): Promise { + return new Promise((resolve) => { + execFile(ORCA_CLI, [...args, '--json', '--pairing-code', pairingCode], { timeout: timeoutMs, maxBuffer: 8 << 20, env: { ...process.env, ORCA_PAIRING_CODE: '' } }, (_error, stdout) => { + try { + resolve(JSON.parse(stdout)) + } catch { + resolve(null) + } + }) + }) +} + +/** Every string in a CLI result, one per line (terminal output may come as a string, lines or chunks). */ +function textOf(value: unknown): string { + if (typeof value === 'string') return value + if (Array.isArray(value)) return value.map(textOf).join('\n') + if (value && typeof value === 'object') return Object.values(value).map(textOf).join('\n') + return '' +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** Runs one line in a fresh workspace terminal and returns the output once `PRB-END` shows. */ +async function inTerminal(pairingCode: string, projectRoot: string, line: string): Promise { + await orca(pairingCode, ['repo', 'add', '--path', projectRoot, '--kind', 'git']) + const created = await orca(pairingCode, ['terminal', 'create', '--worktree', `path:${projectRoot}`, '--title', 'egress-probe']) + const handle: string | undefined = created?.result?.terminal?.handle ?? created?.result?.handle ?? created?.result?.terminal?.id + if (!handle) { + throw new Error('could not open a workspace terminal') + } + // `clear` first: the read must only see this run's lines. + await orca(pairingCode, ['terminal', 'send', '--terminal', handle, '--text', `clear; ${line}`, '--enter']) + const deadline = Date.now() + 180_000 + while (Date.now() < deadline) { + const read = await orca(pairingCode, ['terminal', 'read', '--terminal', handle]) + const text = textOf(read?.result) + // The typed line is base64 past its first words, so PRB-END only shows once the runner prints it. + if (text.includes('PRB-END')) { + return text + } + await sleep(1500) + } + throw new Error('the probe did not finish in the workspace terminal') +} + +/** Git and env facts, one short line each, then the HTTP cases. */ +function factsScript(gitChecks: Record, bogus: Record): string { + const lines = Object.entries(gitChecks).map(([name, command]) => `GIT_TERMINAL_PROMPT=0 timeout 60 ${command} >/dev/null 2>&1; echo "PRB ${name} rc=$?"`) + // The VM must hold placeholders: compare by sha256 so the bogus values never cross the terminal. + for (const [name, digest] of Object.entries(bogus)) { + // The verdict word is a variable: the typed command (echoed by the terminal) must not contain it. + lines.push(`v=placeholder; [ "$(printf %s "\${${name}:-}" | sha256sum | cut -c1-8)" = ${digest} ] && v=bogus; echo "PRB env.${name} holds=$v"`) + } + return lines.join('; ') +} + +async function main(): Promise { + const failures: string[] = [] + const report: Record = { runId } + const cleanup: (() => Promise)[] = [] + const started = Date.now() + console.error(`[egress-probe] run ${runId}: throwaway identity ${sub}`) + const user = client(await userToken()) + const operator = client(fileSecret('ORCA_PROBE_OPERATOR_TOKEN_FILE')) + const bogusAnthropic = `sk-ant-api03-orcaprobe${randomBytes(16).toString('hex')}` + const bogusOpenAI = `sk-proj-orcaprobe${randomBytes(16).toString('hex')}` + try { + // Identity: the App bound for the test repo, and a stored GitHub identity (member placeholders). + const bound = await operator('POST', '/v1/internal/github/bindings', { repoUrl: APP_REPO, accountId }) + const installationId: number | undefined = bound.body?.bound?.installationId + if (bound.status !== 200 || !installationId) { + throw new Error(`bind the dev App: ${bound.status} ${bound.body?.error ?? ''}`) + } + cleanup.push(() => operator('DELETE', '/v1/internal/github/bindings', { installationId, accountId })) + const member = await operator('POST', '/v1/internal/dev/member-github', { accountId, userId: sub, repoUrl: APP_REPO, login: 'egress-probe', githubUserId: 1, name: 'egress probe' }) + if (member.status !== 200) { + throw new Error(`store the probe's GitHub identity: ${member.status} ${member.body?.error ?? ''}`) + } + for (const [name, value] of [ + ['ANTHROPIC_API_KEY', bogusAnthropic], + ['ANTHROPIC_BASE_URL', ECHO], + ['OPENAI_API_KEY', bogusOpenAI], + ['OPENAI_BASE_URL', 'https://chatgpt.com/backend-api/codex'] + ] as const) { + const put = await user('PUT', `/v1/secrets/personal/${name}`, { value }) + cleanup.push(() => user('DELETE', `/v1/secrets/personal/${name}`)) + if (put.status !== 200) { + throw new Error(`PUT secret ${name}: ${put.status} ${put.body?.error ?? ''}`) + } + } + const create = async (label: string, repo: string) => { + console.error(`[egress-probe] creating the ${label} workspace (${sub}-${label})`) + const reply = await user('POST', '/v1/sandboxes', { workspaceId: `${sub}-${label}`, machineSize: 'standard', repo: { url: repo }, useEnvironment: false }) + const id: string | undefined = reply.body?.sandbox?.id + if (id) { + cleanup.unshift(() => user('DELETE', `/v1/sandboxes/${id}`)) + } + if (reply.status !== 200 || !reply.body?.connection?.pairingCode) { + throw new Error(`create the ${label} workspace: ${reply.status} ${reply.body?.error ?? ''}`) + } + console.error(`[egress-probe] ${label} workspace ${id}`) + // The desktop's path: the clone runs after ready, and the desktop polls it. + let clone = 'unknown' + for (const until = Date.now() + 240_000; Date.now() < until; await sleep(3_000)) { + clone = String((await user('GET', `/v1/sandboxes/${id}/clone`)).body?.clone?.state ?? 'unknown') + if (clone.startsWith('done') || clone.startsWith('failed')) break + } + clones[label] = clone + return { id: id!, pairingCode: reply.body.connection.pairingCode as string, projectRoot: reply.body.connection.projectRoot as string } + } + const clones: Record = {} + const [publicBox, appBox] = await Promise.all([create('public', PUBLIC_REPO), create('app', APP_REPO)]) + report.workspaces = { public: publicBox.id, app: appBox.id } + + const anthropic: ProbeCase[] = [ + { + name: 'echo host (ANTHROPIC_BASE_URL): placeholder swapped, other auth untouched', + url: `${ECHO}/post`, + method: 'POST', + headers: { 'x-api-key': '$ANTHROPIC_API_KEY', authorization: 'Bearer probe-keep-bearer' }, + expect: { kind: 'swapped', headers: { 'x-api-key': bogusAnthropic, authorization: 'Bearer probe-keep-bearer' } } + }, + { name: 'echo host: foreign key fails closed', url: `${ECHO}/post`, method: 'POST', headers: { 'x-api-key': 'sk-ant-probe-foreign' }, expect: { kind: 'denied' } }, + { + name: 'chatgpt.com: placeholder reaches ChatGPT (relay)', + url: 'https://chatgpt.com/backend-api/codex/models', + headers: { authorization: '$PROBE_OPENAI_BEARER' }, + expect: { kind: 'upstream' } + }, + { name: 'chatgpt.com: foreign bearer fails closed', url: 'https://chatgpt.com/backend-api/codex/models', headers: { authorization: 'Bearer probe-foreign' }, expect: { kind: 'denied' } }, + { name: 'api.github.com: no credential fails closed', url: 'https://api.github.com/rate_limit', expect: { kind: 'denied' } } + ] + const appCases: ProbeCase[] = [ + { name: 'api.github.com: workspace placeholder swapped (GitHub answers 200)', url: 'https://api.github.com/rate_limit', headers: { authorization: '$PROBE_GH_BEARER' }, expect: { kind: 'upstream' } }, + { name: 'github.com: anonymous fails closed with an App token', url: `${APP_REPO}.git/info/refs?service=git-upload-pack`, expect: { kind: 'denied' } } + ] + const digests = { ANTHROPIC_API_KEY: sha8(bogusAnthropic), OPENAI_API_KEY: sha8(bogusOpenAI) } + // The runner reads whole header values from env (`$NAME`), so the Bearer forms are built here. + const prelude = 'export PROBE_OPENAI_BEARER="Bearer $OPENAI_API_KEY" PROBE_GH_BEARER="Bearer $GH_TOKEN"; ' + console.error('[egress-probe] running the checks in both workspaces') + const runs = await Promise.all([ + inTerminal(publicBox.pairingCode, publicBox.projectRoot, `${prelude}${factsScript({ 'git.public-anonymous': `git ls-remote ${PUBLIC_REPO} HEAD` }, digests)}; ${runnerCommand(anthropic)}`), + inTerminal(appBox.pairingCode, appBox.projectRoot, `${prelude}${factsScript({ 'git.app-anonymous': `git -c http.extraheader= -c http.https://github.com/.extraheader= ls-remote ${APP_REPO} HEAD`, 'git.app-workspace': 'git ls-remote origin HEAD' }, {})}; ${runnerCommand(appCases)}`) + ]) + const results: Record[] = [] + const check = (workspace: string, name: string, ok: boolean, detail: string) => { + results.push({ workspace, check: name, ok }) + if (!ok) { + failures.push(`[${workspace}] ${name}: ${detail}`) + } + } + for (const [workspace, text, cases] of [['public', runs[0], anthropic], ['app', runs[1], appCases]] as const) { + const summaries = parseRunnerOutput(text, cases.length) + cases.forEach((probeCase, i) => { + const problems = judge(probeCase, summaries[i]!) + check(workspace, probeCase.name, problems.length === 0, problems.join('; ')) + }) + } + const rc = (text: string, name: string) => new RegExp(`PRB ${name.replaceAll('.', '\\.')} rc=(\\d+)`).exec(text)?.[1] + check('public', 'github.com: anonymous git ls-remote of a public repo works (#758)', rc(runs[0], 'git.public-anonymous') === '0', `rc=${rc(runs[0], 'git.public-anonymous')}`) + check('app', 'github.com: anonymous git ls-remote is refused with an App token', rc(runs[1], 'git.app-anonymous') !== '0' && rc(runs[1], 'git.app-anonymous') !== undefined, `rc=${rc(runs[1], 'git.app-anonymous')}`) + check('app', "github.com: the workspace's own git (placeholder) works", rc(runs[1], 'git.app-workspace') === '0', `rc=${rc(runs[1], 'git.app-workspace')}`) + for (const [workspace, state] of Object.entries(clones)) { + check(workspace, 'github.com: the workspace repo clones', state === 'done', `clone ${state}`) + } + for (const name of Object.keys(digests)) { + check('public', `the VM holds a placeholder for ${name}`, new RegExp(`PRB env\\.${name} holds=placeholder`).test(runs[0]), 'the VM env holds the bogus value itself') + } + report.checks = results + } catch (error) { + failures.push(`probe error: ${error instanceof Error ? error.message : String(error)}`) + } finally { + if (!keep) { + for (const step of cleanup) { + await step().catch((error: unknown) => console.error(`[egress-probe] cleanup: ${String(error)}`)) + } + } + } + console.log(JSON.stringify({ ok: failures.length === 0, failures, ...report, ms: Date.now() - started }, null, 2)) + console.error(failures.length === 0 ? '[egress-probe] OK' : `[egress-probe] FAILED:\n ${failures.join('\n ')}`) + process.exitCode = failures.length === 0 ? 0 : 1 +} + +void main() 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/agent-sources.ts b/cloud/apps/sandbox-control/src/agent-sources.ts index 784bf675bbe..ed5764361e8 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,11 +213,12 @@ 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); + * - 'inside': the owner signs in inside each workspace ('in-workspace'): keys dropped, the agent's own login; * - 'omit': kill-switch fallback (Source sign-in, provider off): keys dropped, the agent's own login in the sandbox; * - 'keep': API keys as resolved (precedence), the default. * Source: explicit (workspace, then default), else implicit: a covering key wins, else a usable account. */ -export type AgentMode = 'account' | 'omit' | 'keep' +export type AgentMode = 'account' | 'inside' | 'omit' | 'keep' export async function agentModesFor( db: D1Database, row: Pick, @@ -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] = 'inside' + 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/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/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..2e4227f2d93 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, @@ -183,7 +160,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/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..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/. */ @@ -90,6 +92,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/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/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/src/golden-images.ts b/cloud/apps/sandbox-control/src/golden-images.ts index 035caec020a..915646cc5e8 100644 --- a/cloud/apps/sandbox-control/src/golden-images.ts +++ b/cloud/apps/sandbox-control/src/golden-images.ts @@ -362,13 +362,13 @@ export function entryPointsVersion(): string { // One round trip: the image's scripts stamp (missing = 0: images from before stamps) and whether // this Worker's entry points are already installed. -const ENTRY_POINTS_PROBE = [ +export const ENTRY_POINTS_PROBE = [ 'stamp="$(cat /opt/orca/bin/.scripts-stamp 2>/dev/null || true)"', 'echo "stamp=${stamp:-0}"', `if [ -e /opt/orca/bin/.entry-points-${VM_SCRIPTS_HASH} ]; then echo marker=1; else echo marker=0; fi` ].join('\n') -function parseEntryPointsProbe(stdout: string): { stamp: number; marker: boolean } | null { +export function parseEntryPointsProbe(stdout: string): { stamp: number; marker: boolean } | null { const marker = /^marker=([01])$/m.exec(stdout)?.[1] if (marker === undefined) { return null @@ -399,6 +399,16 @@ export async function ensureEntryPoints(deps: { provider: Pick }, sessionId: string): Promise { const env = provisionEnv({ manifest: MANIFEST, provisionScript: PROVISION_SCRIPT, vmScripts: VM_SCRIPT_SOURCES, vmScriptsStamp: VM_SCRIPTS_STAMP, buildId: 'sync' }) const scriptEnv = Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith('ORCA_VM_SCRIPT_'))) diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index b85e04b80e9..8698ddad184 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -64,8 +64,9 @@ 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' import { BillingUnavailableError, @@ -891,6 +892,34 @@ function fail(error: string, status: number, reason?: string): Response { return json(reason ? { error, reason } : { error }, status) } +/** CREATE-STEP-WATCH: logs a step still pending after 10 s and, once the create starts, every step's time. */ +export function createStepWatch(enabled: boolean, now: () => number = Date.now) { + const started = now() + const steps: Record = {} + let reported = false + return { + async step(name: string, work: Promise): Promise { + if (!enabled) { + return work + } + const at = now() + const slow = setTimeout(() => console.log(JSON.stringify({ event: 'create_step_slow', step: name, ms: now() - at })), 10_000) + try { + return await work + } finally { + clearTimeout(slow) + steps[name] = now() - at + } + }, + done() { + if (enabled && !reported) { + reported = true + console.log(JSON.stringify({ event: 'create_steps', ms: now() - started, steps })) + } + } + } +} + async function readJson(request: Request, maxBytes = MAX_JSON_BYTES): Promise { const text = await request.text() if (text.length > maxBytes) { @@ -982,7 +1011,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 +1080,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 @@ -1318,7 +1349,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 }) } @@ -1807,11 +1838,13 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise { + watch.done() // Desktops that show the clone as its own step ask for it in the background (GET .../clone). // Member identities install after the response; the VM's git holds commits and pushes until then. let ready: Ready try { + // Nothing pinned: start in the served region nearest the caller (an environment's own region still wins). + const nearRegions = body.data.region ? undefined : nearestRegions(request, servedRegions(life.config), nearestRegionEnabled(env)) + // Region order only (never the caller's location): which region a create preferred, and why. + console.log(JSON.stringify({ event: 'create_region_order', explicit: body.data.region ?? null, order: nearRegions ?? null })) ready = await createSandbox(life, caller, { ...body.data, + ...(nearRegions ? { nearRegions } : {}), cloneInBackground: features.includes('clone-progress'), deferMemberGit: true }) @@ -2863,3 +2902,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/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index b38c5e659eb..ddf08f20e75 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -15,7 +15,7 @@ import { } from './guardrails' import { DEFAULT_EGRESS_ALLOWLIST, DEFAULT_EGRESS_PRESET, KEYS_WITHHELD_BODY, compileNetworkPolicy, egressProxyMissing, gitBasicAuthorization, type CredentialRoute, type EgressPreset, type PlatformHostSuffixesConfigError } from './network-policy' import { applyQueuedRevokes } from './grant-revokes' -import { ensureEntryPoints } from './golden-images' +import { ENTRY_POINTS_PROBE, ensureEntryPoints, entryPointsBehind, installEntryPoints, parseEntryPointsProbe } from './golden-images' import { RUNTIME_REFRESH_SCRIPT, type RuntimeBundle } from './runtime-bundles' import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens' import { connectedMembers, memberGitConfigs } from './member-git' @@ -120,7 +120,8 @@ export type LifecycleDeps = { * lists, `touch` when a create booted from an automatic one. Absent: neither happens. */ autoEnvironment?: { - ensure(accountId: string, repoUrl: string): 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 } /** @@ -224,12 +225,31 @@ export function phaseTimer(now: () => number = Date.now) { failed: null as { phase: string; ms: number } | null, async time(phase: string, work: () => Promise): Promise { const started = now() + const limit = PHASE_LIMITS[phase] + let watch: ReturnType | undefined try { - return await work() + if (limit === undefined) { + return await work() + } + // A phase with nothing slow in it that still hasn't answered is stuck (a create sat 180 s + // before its write-ahead insert with no provider call stalled). Name it in the log; fail it + // unless abandoning the work could strand something (the pool claim holds a VM). + return await Promise.race([ + work(), + new Promise((_, reject) => { + watch = setTimeout(() => { + console.log(JSON.stringify({ event: 'phase_timeout', phase, ms: limit.ms, failed: limit.fail })) + if (limit.fail) { + reject(new LifecycleError('provider_unavailable', `phase_timeout_${phase}`)) + } + }, limit.ms) + }) + ]) } catch (error) { timer.failed ??= { phase, ms: now() - started } throw error } finally { + clearTimeout(watch) timings[phase] = now() - started } } @@ -237,6 +257,17 @@ export function phaseTimer(now: () => number = Date.now) { return timer } +/** + * Bounds for the phases before a create's write-ahead insert (D1 reads, billing, the pool claim). + * The VM, policy and orcad phases are bounded by the provider calls inside them. + */ +export const PHASE_DEADLINES_MS = { + environment: { ms: 20_000, fail: true }, + entitlement: { ms: 20_000, fail: true }, + pool: { ms: 45_000, fail: false } +} +const PHASE_LIMITS: Partial> = PHASE_DEADLINES_MS + /** * CREATE-BUILD-SNAPSHOT-404: a VM create from an environment build's snapshot can answer 404 just * after the build (dev, 11-11 and 11-13: the same snapshot booted seconds before and after). Once, @@ -645,7 +676,9 @@ export const MEMBERS_COMMAND = '/opt/orca/bin/orca-sandbox-members' /** * ENV-STALE boot step: a sandbox whose orcad is behind its region's active golden (booted from an environment * build snapshot, or resumed from an older image) installs the golden's runtime bundle before orcad starts. - * Best effort and quiet: any failure keeps the old orcad, and every outcome is logged with its timing. + * The same command probes the VM's entry points (ENTRY-POINTS-BEFORE-START): scripts older than this + * Worker's are installed before the start script runs, so the common case adds no round trip. + * Best effort and quiet: any failure keeps the old orcad and scripts, and every outcome is logged with its timing. */ export async function refreshRuntime(deps: LifecycleDeps, row: SandboxRow, sessionId: string): Promise { if (!deps.runtimeRefresh) { @@ -654,28 +687,41 @@ export async function refreshRuntime(deps: LifecycleDeps, row: SandboxRow, sessi const started = deps.now() let result = 'error' let target: string | null = null + let entryPoints = 'unknown' try { const plan = await deps.runtimeRefresh(row.region, started) - if (!plan) { - result = 'no_bundle' - return result - } - target = plan.bundle.commit + target = plan?.bundle.commit ?? null const run = await deps.provider.runCommand(sessionId, { command: 'bash', - args: ['-c', RUNTIME_REFRESH_SCRIPT], - env: { WANT: plan.bundle.commit, SHA: plan.bundle.sha256, RT: plan.bundle.runtime, URL: plan.url }, + args: ['-c', plan ? `${ENTRY_POINTS_PROBE}\n${RUNTIME_REFRESH_SCRIPT}` : ENTRY_POINTS_PROBE], + env: plan ? { WANT: plan.bundle.commit, SHA: plan.bundle.sha256, RT: plan.bundle.runtime, URL: plan.url } : {}, sudo: true, timeoutMs: 40_000 }) - result = run.stdout.trim().split('\n').pop() ?? 'error' + result = plan ? (run.stdout.trim().split('\n').pop() ?? 'error') : 'no_bundle' + const image = parseEntryPointsProbe(run.stdout) + entryPoints = entryPointsBehind(image) ? 'behind' : image ? 'current' : 'unknown' + if (entryPoints === 'behind') { + entryPoints = await installEntryPoints(deps, sessionId).then( + () => 'installed', + () => 'install_failed' + ) + } return result } catch { return result } finally { const [outcome, from] = result.split(' ') console.log( - JSON.stringify({ event: 'runtime_refresh', sandboxId: row.id, outcome, from: from ?? null, to: target, ms: deps.now() - started }) + JSON.stringify({ + event: 'runtime_refresh', + sandboxId: row.id, + outcome, + from: from ?? null, + to: target, + entryPoints, + ms: deps.now() - started + }) ) } } @@ -768,7 +814,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 @@ -829,7 +881,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') @@ -919,7 +976,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) @@ -1005,7 +1062,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/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/session-env.ts b/cloud/apps/sandbox-control/src/session-env.ts index 723a303c663..f3cce676a91 100644 --- a/cloud/apps/sandbox-control/src/session-env.ts +++ b/cloud/apps/sandbox-control/src/session-env.ts @@ -14,6 +14,9 @@ import { SecretsKmsError } from './secrets-kms' import type { SandboxRow } from './store' import { secretLog } from './secret-log' +/** Session env name the VM env script reads for the agents signed in inside the workspace ('claude,codex'). */ +export const SIGN_IN_INSIDE_ENV = 'ORCA_SIGN_IN_INSIDE' + export type SessionSecrets = { env: Record /** Row value for `egress_secret_hosts`. */ @@ -134,6 +137,10 @@ export async function sessionSecretEnv( const env = withoutSignInCredentials(derived, dropped) const scopes = deriveProviderScopes(stored, env, storedScopes) const egressAllowHosts = providerHosts(env).join(',') || null + // Not a secret and never in shells (ORCA_*): tells the VM env script which agents sign in there, so a + // first run with no login of its own shows the agent's sign-in screens instead of skipping them. + const inside = (Object.keys(modes) as CredentialAgent[]).filter((agent) => modes[agent] === 'inside') + const insideEnv: Record = inside.length > 0 ? { [SIGN_IN_INSIDE_ENV]: inside.join(',') } : {} // Counts only. secretLog('session_secrets', { sandboxId: row.id, injected: Object.keys(env).length, skipped }) if (withhold) { @@ -153,7 +160,7 @@ export async function sessionSecretEnv( } } const hosts = [encodeEgressSecretHosts(withheld.targets), ...accountRoutes].filter(Boolean).join(',') || null - return { env: { ...withheld.env, ...accountEnv }, egressSecretHosts: hosts, egressAllowHosts } + return { env: { ...withheld.env, ...accountEnv, ...insideEnv }, egressSecretHosts: hosts, egressAllowHosts } } if (!swap) { // An operator turned placeholders off for this account (SECRETS_EGRESS_PLACEHOLDERS=off or accounts: @@ -162,7 +169,7 @@ export async function sessionSecretEnv( if (plain > 0 && !egressSwapWanted(deps, row) && firstReadThisSession('plain', row)) { secretLog('egress_swap_disabled', { sandboxId: row.id, plainKeys: plain }) } - return { env, egressSecretHosts: null, egressAllowHosts } + return { env: { ...env, ...insideEnv }, egressSecretHosts: null, egressAllowHosts } } const swapped = applySecretPlaceholders(row, env, scopes) const accountEnv: Record = {} @@ -175,7 +182,7 @@ export async function sessionSecretEnv( } } const secretHosts = [encodeEgressSecretHosts(swapped.targets), ...accountRoutes].filter(Boolean).join(',') || null - return { env: { ...swapped.env, ...accountEnv }, egressSecretHosts: secretHosts, egressAllowHosts } + return { env: { ...swapped.env, ...accountEnv, ...insideEnv }, egressSecretHosts: secretHosts, egressAllowHosts } } /** Provider hosts from the session's secrets plus the workspace's declared tool hosts (MCP). */ 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 { 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/agent-sources-in-workspace.test.ts b/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts new file mode 100644 index 00000000000..0240bc8500e --- /dev/null +++ b/cloud/apps/sandbox-control/test/agent-sources-in-workspace.test.ts @@ -0,0 +1,165 @@ +// "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) + // The VM env script's cue (never a shell variable): these agents sign in inside the workspace. + expect(env.ORCA_SIGN_IN_INSIDE).toBe('claude,codex') + // 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() + expect(lastEnv(ENV_COMMAND).ORCA_SIGN_IN_INSIDE).toBe('claude') + 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}`) + expect(lastEnv(ENV_COMMAND).ORCA_SIGN_IN_INSIDE).toBeUndefined() + }) + + 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('0063_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/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..eaa25cc66ce 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', { @@ -381,7 +386,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() }) @@ -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/test/create-step-watch.test.ts b/cloud/apps/sandbox-control/test/create-step-watch.test.ts new file mode 100644 index 00000000000..5c772704458 --- /dev/null +++ b/cloud/apps/sandbox-control/test/create-step-watch.test.ts @@ -0,0 +1,38 @@ +// CREATE-STEP-WATCH: creates hung 180 s with no log and no row (n73); the steps before the create log. +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createStepWatch } from '../src/index' + +describe('CREATE-STEP-WATCH', () => { + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('names a step still pending after 10 s, then reports every step once the create starts', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) + const watch = createStepWatch(true, () => Date.now()) + let finish: (value: string) => void = () => undefined + const body = watch.step('body', new Promise((resolve) => (finish = resolve))) + await vi.advanceTimersByTimeAsync(10_000) + expect(log).toHaveBeenCalledWith(expect.stringContaining('"step":"body"')) + finish('{}') + await expect(body).resolves.toBe('{}') + watch.done() + watch.done() + const reports = log.mock.calls.filter(([line]) => String(line).includes('"create_steps"')) + expect(reports).toHaveLength(1) + expect(String(reports[0]![0])).toContain('"body":10000') + }) + + it('stays quiet for other routes', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) + const watch = createStepWatch(false) + const pending = watch.step('auth', new Promise(() => undefined)) + await vi.advanceTimersByTimeAsync(20_000) + watch.done() + expect(log).not.toHaveBeenCalled() + void pending + }) +}) diff --git a/cloud/apps/sandbox-control/test/egress-probe-checks.test.ts b/cloud/apps/sandbox-control/test/egress-probe-checks.test.ts new file mode 100644 index 00000000000..5701b156aa7 --- /dev/null +++ b/cloud/apps/sandbox-control/test/egress-probe-checks.test.ts @@ -0,0 +1,69 @@ +import { execFile } from 'node:child_process' +import { createServer } from 'node:http' +import type { AddressInfo } from 'node:net' +import { describe, expect, it } from 'vitest' +import { EGRESS_DENIED_BODY } from '../src/network-policy' +import { judge, parseRunnerOutput, runnerCommand, sha8, type ProbeCase, type Summary } from '../scripts/egress-probe-checks' + +const answer = (summary: Partial): Summary => ({ status: 200, denied: false, edgeBlocked: false, ...summary }) + +describe('egress probe judge', () => { + const swapped: ProbeCase = { name: 'echo', url: 'https://echo/post', expect: { kind: 'swapped', headers: { 'x-api-key': 'stand-in', authorization: 'Bearer keep' } } } + + it('accepts the provider seeing the swapped key and the other header unchanged', () => { + expect(judge(swapped, answer({ echoed: { 'x-api-key': sha8('stand-in'), authorization: sha8('Bearer keep') } }))).toEqual([]) + }) + + it('names a header that changed or never arrived, and anything leaked from the hop, never values', () => { + const problems = judge(swapped, answer({ echoed: { 'x-api-key': sha8('orca-ph-placeholder') }, leaked: ['vercel-sandbox-oidc-token'] })) + expect(problems).toEqual([ + 'echo: the provider saw vercel-sandbox-oidc-token', + 'echo: header x-api-key arrived with another value', + 'echo: header authorization did not arrive' + ]) + expect(problems.join(' ')).not.toContain('stand-in') + }) + + it("requires the firewall's own 403 for a fail-closed case", () => { + const denied: ProbeCase = { name: 'foreign', url: 'https://x', expect: { kind: 'denied' } } + expect(judge(denied, answer({ status: 403, denied: true }))).toEqual([]) + expect(judge(denied, answer({ status: 403, edgeBlocked: true }))).toHaveLength(1) + expect(judge(denied, answer({ status: 401 }))).toHaveLength(1) + }) + + it('an upstream case fails on the firewall 403, an edge block page or no answer', () => { + const upstream: ProbeCase = { name: 'chatgpt', url: 'https://chatgpt.com/x', expect: { kind: 'upstream' } } + expect(judge(upstream, answer({ status: 401 }))).toEqual([]) + expect(judge(upstream, answer({ status: 403, denied: true }))).toEqual(['chatgpt: refused by the firewall']) + expect(judge(upstream, answer({ status: 403, edgeBlocked: true }))).toHaveLength(1) + expect(judge(upstream, answer({ status: 0 }))).toEqual(['chatgpt: no answer']) + }) +}) + +describe('the in-VM runner', () => { + it('reports status, the deny body and echoed header digests from env-held values', async () => { + // A local stand-in for postman-echo.com: echoes request headers under `headers`. + const server = createServer((req, res) => { + if (req.url === '/denied') { + res.writeHead(403, { 'content-type': 'text/plain' }).end(EGRESS_DENIED_BODY) + return + } + res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ headers: { ...req.headers, 'vercel-forwarded-host': 'x' } })) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + const cases = [ + { name: 'echo', url: `${base}/post`, method: 'POST' as const, headers: { 'x-api-key': '$PH', authorization: 'Bearer keep' } }, + { name: 'denied', url: `${base}/denied` } + ] + const stdout = await new Promise((resolve, reject) => + execFile('bash', ['-c', runnerCommand(cases)], { env: { ...process.env, PH: 'secret-ph' } }, (error, out) => (error ? reject(error) : resolve(out))) + ) + server.close() + expect(stdout).toContain('PRB-END') + expect(stdout).not.toContain('secret-ph') + const [echo, denied] = parseRunnerOutput(stdout, 2) + expect(echo).toEqual({ status: 200, denied: false, edgeBlocked: false, echoed: { 'x-api-key': sha8('secret-ph'), authorization: sha8('Bearer keep') }, leaked: ['vercel-forwarded-host'] }) + expect(denied).toMatchObject({ status: 403, denied: true }) + }) +}) diff --git a/cloud/apps/sandbox-control/test/entry-points-before-start.test.ts b/cloud/apps/sandbox-control/test/entry-points-before-start.test.ts new file mode 100644 index 00000000000..cc6afc9f219 --- /dev/null +++ b/cloud/apps/sandbox-control/test/entry-points-before-start.test.ts @@ -0,0 +1,52 @@ +// ENTRY-POINTS-BEFORE-START: a boot from an environment build made on an older golden ran that golden's +// orca-sandbox-start (no agent prefetch, no OpenCode first run) until the environment was rebuilt. +// refreshRuntime's one command also probes the entry points; older ones are installed before the start. +import { describe, expect, it, vi } from 'vitest' +import { VM_SCRIPTS_STAMP } from '../image/vm-scripts.generated' +import { entryPointsBehind } from '../src/golden-images' +import { refreshRuntime, type LifecycleDeps } from '../src/lifecycle' +import type { SandboxRow } from '../src/store' + +type Call = { args?: string[]; env?: Record } + +function setup(probe: string, plan: boolean) { + const calls: Call[] = [] + const runCommand = vi.fn(async (_session: string, call: Call) => { + calls.push(call) + return calls.length === 1 ? { exitCode: 0, stdout: `${probe}\n${plan ? 'current abc' : ''}`, stderr: '' } : { exitCode: 0, stdout: 'synced\n', stderr: '' } + }) + const deps = { + provider: { runCommand }, + now: () => 0, + runtimeRefresh: async () => (plan ? { bundle: { commit: 'abc', sha256: 'f', runtime: '22' }, url: 'https://x' } : null) + } as unknown as LifecycleDeps + const row = { id: 'sbx_1', region: 'iad1' } as unknown as SandboxRow + return { calls, deps, row } +} + +describe('ENTRY-POINTS-BEFORE-START', () => { + it('installs older entry points before the start, in the same round trip as the runtime check', async () => { + const t = setup(`stamp=${VM_SCRIPTS_STAMP - 1}\nmarker=0`, true) + await expect(refreshRuntime(t.deps, t.row, 'sess')).resolves.toBe('current abc') + expect(t.calls).toHaveLength(2) + expect(t.calls[0]!.args!.at(-1)).toContain('stamp=') + expect(t.calls[0]!.args!.at(-1)).toContain('SOURCE_COMMIT') + expect(t.calls[1]!.args!.at(-1)).toContain('install -o root') + }) + + it('adds nothing when the image carries this Worker scripts (same stamp or marker)', async () => { + for (const probe of [`stamp=${VM_SCRIPTS_STAMP}\nmarker=0`, 'stamp=0\nmarker=1']) { + const t = setup(probe, true) + await refreshRuntime(t.deps, t.row, 'sess') + expect(t.calls).toHaveLength(1) + } + }) + + it('still probes without a runtime bundle, and never downgrades a newer image', async () => { + const t = setup(`stamp=${VM_SCRIPTS_STAMP - 1}\nmarker=0`, false) + await expect(refreshRuntime(t.deps, t.row, 'sess')).resolves.toBe('no_bundle') + expect(t.calls).toHaveLength(2) + expect(entryPointsBehind({ stamp: VM_SCRIPTS_STAMP + 1, marker: false })).toBe(false) + expect(entryPointsBehind(null)).toBe(false) + }) +}) 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/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/memguard.test.ts b/cloud/apps/sandbox-control/test/memguard.test.ts new file mode 100644 index 00000000000..f4d59cfaf25 --- /dev/null +++ b/cloud/apps/sandbox-control/test/memguard.test.ts @@ -0,0 +1,85 @@ +// MEMGUARD: the VM's memory guard (image/vm/orca-memguard) ranks processes for the kernel's OOM killer +// so Orca's runtime and terminals outlive a build that eats the VM's memory, and names the process it +// would stop. Run against a fake process table (ORCA_MEMGUARD_PROC); the kill itself is verified in a VM. +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const GUARD = fileURLToPath(new URL('../image/vm/orca-memguard', import.meta.url).href) +const START = fileURLToPath(new URL('../image/vm/orca-sandbox-start', import.meta.url).href) +// mapfile -d needs bash 4.4+ (the VM has 5.x; macOS's /bin/bash is 3.2). +const bash = ['/opt/homebrew/bin/bash', '/usr/local/bin/bash', '/usr/bin/bash', '/bin/bash'].find( + (path) => 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/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/cloud/apps/sandbox-control/test/orca-sandbox-env.test.ts b/cloud/apps/sandbox-control/test/orca-sandbox-env.test.ts index 626fbd95ddc..2109308ac25 100644 --- a/cloud/apps/sandbox-control/test/orca-sandbox-env.test.ts +++ b/cloud/apps/sandbox-control/test/orca-sandbox-env.test.ts @@ -135,3 +135,37 @@ describe('orca-sandbox-env: Claude Code API-key approval (G9)', () => { expect(claude(file).hasCompletedOnboarding).toBe(true) }) }) + +describe('orca-sandbox-env: Claude signed in inside the workspace', () => { + const claudeJson = (file: (path: string) => string | null) => JSON.parse(file('.claude.json') ?? '{}') + + it('with no login yet, leaves onboarding to Claude so it opens on its own sign-in screens; never a shell variable', () => { + const { run, file, sessionEnv } = scratch() + run({ ORCA_SIGN_IN_INSIDE: 'claude,codex', FOO: 'bar' }) + const c = claudeJson(file) + expect(c.hasCompletedOnboarding).toBeUndefined() + // The other first-run answers still apply. + expect(c.bypassPermissionsModeAccepted).toBe(true) + expect(sessionEnv()).not.toContain('ORCA_SIGN_IN_INSIDE') + }) + + it('clears a mark an earlier session made, and marks onboarding done once a login exists here', () => { + const { home, run, file } = scratch() + run({}) + expect(claudeJson(file).hasCompletedOnboarding).toBe(true) + run({ ORCA_SIGN_IN_INSIDE: 'claude' }) + expect(claudeJson(file).hasCompletedOnboarding).toBeUndefined() + mkdirSync(join(home, '.claude'), { recursive: true }) + writeFileSync(join(home, '.claude', '.credentials.json'), '{}') + run({ ORCA_SIGN_IN_INSIDE: 'claude' }) + expect(claudeJson(file).hasCompletedOnboarding).toBe(true) + }) + + it('only Codex inside, or a malformed value, keeps Claude onboarding done', () => { + const { run, file } = scratch() + run({ ORCA_SIGN_IN_INSIDE: 'codex' }) + expect(claudeJson(file).hasCompletedOnboarding).toBe(true) + run({ ORCA_SIGN_IN_INSIDE: 'claude;rm -rf /' }) + expect(claudeJson(file).hasCompletedOnboarding).toBe(true) + }) +}) diff --git a/cloud/apps/sandbox-control/test/phase-deadlines.test.ts b/cloud/apps/sandbox-control/test/phase-deadlines.test.ts new file mode 100644 index 00000000000..d933bcd1a64 --- /dev/null +++ b/cloud/apps/sandbox-control/test/phase-deadlines.test.ts @@ -0,0 +1,51 @@ +// PHASE-DEADLINES: a create sat 180 s at "Start sandbox" before its write-ahead insert, with no +// provider call stalled. The pre-insert phases are bounded and a stuck one is named in the log. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { LifecycleError, PHASE_DEADLINES_MS, phaseTimer } from '../src/lifecycle' + +const never = () => new Promise(() => undefined) + +describe('PHASE-DEADLINES', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.spyOn(console, 'log').mockImplementation(() => undefined) + }) + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('fails a stuck entitlement phase by name and logs it', async () => { + const timer = phaseTimer(() => Date.now()) + const run = timer.time('entitlement', never) + const caught = run.catch((error: unknown) => error) + await vi.advanceTimersByTimeAsync(PHASE_DEADLINES_MS.entitlement.ms) + const error = await caught + expect(error).toBeInstanceOf(LifecycleError) + expect((error as LifecycleError).code).toBe('provider_unavailable') + expect((error as LifecycleError).reason).toBe('phase_timeout_entitlement') + expect(timer.failed?.phase).toBe('entitlement') + expect(console.log).toHaveBeenCalledWith(expect.stringContaining('"event":"phase_timeout"')) + }) + + it('only logs a slow pool claim: abandoning it could strand the claimed VM', async () => { + const timer = phaseTimer(() => Date.now()) + let finish: (value: string) => void = () => undefined + const run = timer.time('pool', () => new Promise((resolve) => (finish = resolve))) + await vi.advanceTimersByTimeAsync(PHASE_DEADLINES_MS.pool.ms + 1_000) + expect(console.log).toHaveBeenCalledWith(expect.stringContaining('"phase":"pool"')) + finish('vm') + await expect(run).resolves.toBe('vm') + expect(timer.failed).toBeNull() + }) + + it('leaves a fast phase and the provider-bounded phases alone', async () => { + const timer = phaseTimer(() => Date.now()) + await expect(timer.time('environment', async () => 1)).resolves.toBe(1) + const vm = timer.time('vm', () => new Promise((resolve) => setTimeout(() => resolve(2), 90_000))) + await vi.advanceTimersByTimeAsync(90_000) + await expect(vm).resolves.toBe(2) + expect(console.log).not.toHaveBeenCalled() + expect(vi.getTimerCount()).toBe(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/cloud/apps/sandbox-control/tsconfig.json b/cloud/apps/sandbox-control/tsconfig.json index 13effc0cc62..b234608c2e2 100644 --- a/cloud/apps/sandbox-control/tsconfig.json +++ b/cloud/apps/sandbox-control/tsconfig.json @@ -23,6 +23,7 @@ "include": [ "src", "test", - "image" + "image", + "scripts" ] } 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': 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'], diff --git a/config/scripts/cloud-integration/boot-twice-check.sh b/config/scripts/cloud-integration/boot-twice-check.sh new file mode 100755 index 00000000000..94c2c37b8e2 --- /dev/null +++ b/config/scripts/cloud-integration/boot-twice-check.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Premerge step for image changes (premerge-check.sh runs it only when cloud/apps/sandbox-control/image/** changed): +# provisions the golden image in Docker and boots it twice; the second boot must install, fetch and redo nothing. +# See cloud/apps/sandbox-control/image/boot-twice/README.md. Run from the merged worktree's root. +# - Docker unavailable: a loud warning and exit 0 (fail open), so a host without Docker never blocks every merge. +# - On omarchy it takes its own slot (~/orca-offload/bin/slot.sh), waiting at most BOOT_TWICE_SLOT_WAIT_S (300 s). +# - Hard limit BOOT_TWICE_TIMEOUT_S (600 s); a cold image build is ~5 min, a cached one ~15 s. +set -uo pipefail +timeout_s=${BOOT_TWICE_TIMEOUT_S:-600} +slot_wait_s=${BOOT_TWICE_SLOT_WAIT_S:-300} +if ! docker info >/dev/null 2>&1; then + printf '\npremerge: WARNING ==============================================================\n' >&2 + printf 'premerge: WARNING: Docker is unavailable here, so the boot-twice image check DID NOT RUN.\n' >&2 + printf 'premerge: WARNING: run it by hand before merging this image change (see image/boot-twice/README.md).\n' >&2 + printf 'premerge: WARNING ==============================================================\n\n' >&2 + exit 0 +fi +slot_tool="$HOME/orca-offload/bin/slot.sh" +tag="boot-twice-$$-$(date +%s)" +if [[ -x "$slot_tool" ]]; then + waited=0 + until "$slot_tool" acquire "$tag" >/dev/null 2>&1; do + if ((waited >= slot_wait_s)); then + echo "premerge: FAILED: boot-twice image check found no free omarchy slot in ${slot_wait_s}s; rerun the premerge" >&2 + exit 1 + fi + sleep 15 + waited=$((waited + 15)) + done + trap '"$slot_tool" release "$tag" >/dev/null 2>&1 || rm -rf "$HOME/orca-offload/wt/$tag"' EXIT +fi +echo "premerge: boot-twice image check (limit ${timeout_s}s)" +report="$(mktemp)" +(cd cloud && pnpm install --frozen-lockfile >/dev/null) +timeout --kill-after=30 "$timeout_s" pnpm --dir cloud --filter @orca-cloud/sandbox-control exec \ + tsx image/boot-twice/boot-twice.ts --release latest --report "$report" >/dev/null +status=$? +if ((status == 124 || status == 137)); then + echo "premerge: FAILED: boot-twice image check passed its ${timeout_s}s limit (cold image build? rerun once)" >&2 +elif ((status != 0)); then + echo "premerge: FAILED: boot-twice image check: the second boot of the image is not clean:" >&2 + jq -r '.failures[]? | "premerge: " + .' "$report" >&2 2>/dev/null || true + echo "premerge: details: cloud/apps/sandbox-control/image/boot-twice/README.md" >&2 +else + echo "premerge: boot-twice image check OK ($(jq -r '"boot 2 " + (.boots[1].ms|tostring) + " ms"' "$report" 2>/dev/null))" +fi +rm -f "$report" +exit "$status" diff --git a/config/scripts/cloud-integration/premerge-check.sh b/config/scripts/cloud-integration/premerge-check.sh index cac1740953c..9a2e1d40128 100755 --- a/config/scripts/cloud-integration/premerge-check.sh +++ b/config/scripts/cloud-integration/premerge-check.sh @@ -188,5 +188,9 @@ if ((${#tc_pkgs[@]})); then (cd "$pkg" && pnpm typecheck) done fi +# Image or VM-script changes: boot the image twice (Docker); the second boot must be clean. Fails open without Docker. +if [[ -n "$(git diff --name-only "$base"...HEAD -- cloud/apps/sandbox-control/image)" ]]; then + bash config/scripts/cloud-integration/boot-twice-check.sh +fi if [[ "${PREMERGE_FULL:-}" == 1 ]]; then scope="the full vitest suite"; else scope="${#tests[@]} targeted test file(s)"; fi echo "premerge OK: $branch merges cleanly into cloud/integration with typecheck, lint and $scope green." diff --git a/src/main/hosted-sandbox/hosted-account-ipc.test.ts b/src/main/hosted-sandbox/hosted-account-ipc.test.ts index c6b3f834fb6..380c99e1dda 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).not.toHaveProperty('value.configureUrl') +}) + 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/main/hosted-sandbox/hosted-workspace-runtime.test.ts b/src/main/hosted-sandbox/hosted-workspace-runtime.test.ts index d3b57499f53..f80d520adb7 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 { @@ -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', { @@ -96,6 +120,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..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 }) } @@ -168,6 +176,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/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/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/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 c64e631a22e..f4499e7cc9f 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 { @@ -82,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-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/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..2b996d05744 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,32 @@ 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..a0ad71b482c 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,39 @@ 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. Team API keys won’t be used for this agent.', + 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 d9166b3a5ca..55e92dfa4c5 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 { @@ -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. Team API keys won’t be used for this agent.' + ), + 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-chat-sign-in-notice.test.tsx b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-sign-in-notice.test.tsx index 2128cd1eabb..222d0d075a3 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-chat-sign-in-notice.test.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-sign-in-notice.test.tsx @@ -64,3 +64,38 @@ describe('cloudChatSignInContent', () => { expect(cloudChatSignInContent(true, 'notSignedIn', 'Antigravity')).toBeUndefined() }) }) + +describe('the not-signed-in card when the agent signs in inside the workspace', () => { + it('says so and offers a terminal running the agent’s login', async () => { + cloud.on = true + const { setOrcaCloudAgentAccountsStateForTest } = + await import('@/lib/orca-cloud/orca-cloud-agent-accounts-store') + setOrcaCloudAgentAccountsStateForTest({ + load: { + kind: 'ready', + status: { + credentials: { + claude: { state: 'none' }, + codex: { state: 'none' }, + providerEnabled: { claude: true, codex: true } + }, + sources: { + defaults: {}, + coveredByKey: { claude: false, codex: false }, + inWorkspace: { claude: true, codex: false } + } + } + }, + setups: { claude: { phase: 'idle' }, codex: { phase: 'idle' } }, + keyKinds: { claude: null, codex: null }, + queue: { agents: [], index: 0 } + }) + card('Claude') + expect( + screen.getByText('Claude needs you to sign in inside this workspace') + ).toBeInTheDocument() + expect(screen.queryByText(/Renew it above/)).toBeNull() + screen.getByRole('button', { name: 'Open terminal to sign in' }).click() + expect(signIn.signIn).toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-chat-sign-in-notice.tsx b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-sign-in-notice.tsx index 7da2cdc2648..4625b0b1cdf 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-chat-sign-in-notice.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-sign-in-notice.tsx @@ -9,6 +9,9 @@ import type { RuntimeClientTarget } from '../../../../shared/runtime-client-targ import { isOrcaCloudEnvironmentId } from '@/lib/orca-cloud/orca-cloud-environment-id' import { agentSessionSetupFor } from '../../../../shared/agent-session/lifecycle/agent-session-setup-commands' import { HOST_AGENT_SIGN_IN_AGENT_NAME } from '../../../../shared/host-agent-sign-in-status' +import { useTranslate } from '@/i18n/use-translate' +import { orcaCloudAgentCoverageFromAccounts } from '@/lib/orca-cloud/orca-cloud-agent-accounts-model' +import { useOrcaCloudAgentAccounts } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' const CloudChatHostContext = createContext(false) @@ -28,15 +31,25 @@ export function useCloudChatHost(): boolean { return useContext(CloudChatHostContext) } -/** The sign-in card's words on an Orca Cloud chat, or undefined to keep the card as it is. */ +/** + * The sign-in card's words on an Orca Cloud chat, or undefined to keep the card as it is. An agent + * signed in inside the workspace keeps the generic card (its Sign in opens a terminal on the host); + * the caller words that one with useCloudChatSignInInside. + */ export function cloudChatSignInContent( cloudHost: boolean, failureKind: string | undefined, agentName: string | undefined, - t: Translate = translate + t: Translate = translate, + inside: CloudChatSignInInside | null = null ): string | undefined { const agent = agentSessionSetupFor(agentName)?.agent - if (!cloudHost || failureKind !== 'notSignedIn' || (agent !== 'claude' && agent !== 'codex')) { + if ( + inside || + !cloudHost || + failureKind !== 'notSignedIn' || + (agent !== 'claude' && agent !== 'codex') + ) { return undefined } return t( @@ -45,3 +58,38 @@ export function cloudChatSignInContent( { agent: HOST_AGENT_SIGN_IN_AGENT_NAME[agent] } ) } + +/** What a "not signed in" chat says when its agent signs in inside the workspace, and its button. */ +export type CloudChatSignInInside = { text: string; actionLabel: string } + +export function cloudChatSignInInsideWords( + agent: 'claude' | 'codex', + t: Translate = translate +): CloudChatSignInInside { + return { + text: t('orcaCloud.chatSignIn.inside', '{{agent}} needs you to sign in inside this workspace', { + agent: HOST_AGENT_SIGN_IN_AGENT_NAME[agent] + }), + actionLabel: t('orcaCloud.chatSignIn.openTerminal', 'Open terminal to sign in') + } +} + +/** + * A structured chat on Orca Cloud whose Claude or Codex the person signs in inside each workspace: + * nothing of Orca's signs it in, so "not signed in" means the agent's own login, run in a terminal on + * the workspace (the chat's Sign in button already opens one with the agent's login command). + */ +export function useCloudChatSignInInside( + agentName: string | undefined +): CloudChatSignInInside | null { + const t = useTranslate() + const cloudHost = useCloudChatHost() + const accounts = useOrcaCloudAgentAccounts(cloudHost) + const agent = agentSessionSetupFor(agentName)?.agent + if (!cloudHost || (agent !== 'claude' && agent !== 'codex')) { + return null + } + return orcaCloudAgentCoverageFromAccounts(agent, accounts)?.kind === 'inWorkspace' + ? cloudChatSignInInsideWords(agent, t) + : null +} 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..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 @@ -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). @@ -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/native-chat/host-access/NativeChatSetupButton.tsx b/src/renderer/src/components/native-chat/host-access/NativeChatSetupButton.tsx index 5d764a89ccd..f3168ab5f6c 100644 --- a/src/renderer/src/components/native-chat/host-access/NativeChatSetupButton.tsx +++ b/src/renderer/src/components/native-chat/host-access/NativeChatSetupButton.tsx @@ -7,25 +7,30 @@ import { import { useTranslate } from '../../../i18n/use-translate' export function NativeChatSetupButton({ - failureKind + failureKind, + label }: { failureKind: string | undefined + /** Words for the button in place of the default (e.g. "Open terminal to sign in"). */ + label?: string }): React.JSX.Element | null { return isNativeChatSetupFailureKind(failureKind) ? ( - + ) : null } function EligibleNativeChatSetupButton({ - failureKind + failureKind, + label }: { failureKind: string | undefined + label?: string }): React.JSX.Element | null { const t = useTranslate() const action = nativeChatSetupAction(failureKind, useNativeChatHostSetupView(), t) return action ? ( - {action.label} + {label && !action.disabled ? label : action.label} ) : null } diff --git a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx index 57134a4a836..f7f969667c0 100644 --- a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx +++ b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx @@ -1,5 +1,6 @@ import { cloudChatSignInContent, + useCloudChatSignInInside, useCloudChatHost } from '../../../agent-sign-in-strip/cloud-chat-sign-in-notice' import { @@ -92,6 +93,7 @@ export function NativeChatNoticeRow({ useTranslation() const orcaStopView = useNativeChatOrcaStopView() const cloudHost = useCloudChatHost() + const signInInside = useCloudChatSignInInside(agentName) const openForkSource = useContext(NativeChatForkedFromContext) if (block.presentation === PULL_REQUEST_EVENT_PRESENTATION) { @@ -239,7 +241,8 @@ export function NativeChatNoticeRow({ failure?.account, t ) - const cloudSignIn = cloudChatSignInContent(cloudHost, failure?.kind, agentName, t) + const insideSignIn = failure?.kind === 'notSignedIn' ? signInInside : null + const cloudSignIn = cloudChatSignInContent(cloudHost, failure?.kind, agentName, t, insideSignIn) const usageLimitContinue = block.usageLimitTurnItemId !== undefined && block.usageLimitTurnItemId === orcaStopView.usageLimitTurnItemId @@ -320,7 +323,7 @@ export function NativeChatNoticeRow({
{Icon ?