diff --git a/cloud/apps/sandbox-control/src/api/openapi.ts b/cloud/apps/sandbox-control/src/api/openapi.ts index b8dc9a45257..f18428d2ea7 100644 --- a/cloud/apps/sandbox-control/src/api/openapi.ts +++ b/cloud/apps/sandbox-control/src/api/openapi.ts @@ -69,6 +69,8 @@ const schemas: Record = { machineSize: { type: 'string' }, region: { type: 'string' }, repoUrl: { type: ['string', 'null'] }, + repoBranch: { type: ['string', 'null'], description: 'Branch the workspace was started on, when known' }, + lastActivityAt: { type: 'integer', description: 'Last agent work or input (falls back to the last state change)' }, session: { type: ['object', 'null'], properties: { startedAt: { type: 'integer' }, leaseExpiresAt: { type: 'integer' } } }, createdAt: { type: 'integer' } } diff --git a/cloud/apps/sandbox-control/src/api/workspaces.ts b/cloud/apps/sandbox-control/src/api/workspaces.ts index 324e4fb0719..944fbd2755c 100644 --- a/cloud/apps/sandbox-control/src/api/workspaces.ts +++ b/cloud/apps/sandbox-control/src/api/workspaces.ts @@ -51,6 +51,8 @@ export function workspaceView(row: WorkspaceRow) { machineSize: row.machine_size, region: row.region, repoUrl: row.repo_url, + repoBranch: row.repo_branch ?? null, + lastActivityAt: row.last_activity_at ?? row.updated_at, session, lastError: row.last_error, createdAt: row.created_at, diff --git a/src/cli/cloud/cloud-api-client.ts b/src/cli/cloud/cloud-api-client.ts index 0518e6bffc4..75f4af79d92 100644 --- a/src/cli/cloud/cloud-api-client.ts +++ b/src/cli/cloud/cloud-api-client.ts @@ -2,11 +2,12 @@ // becomes a RuntimeClientError with a stable `cloud_*` code and next steps, so `--json` callers // (agents) and people both get an actionable message. import { RuntimeClientError } from '../runtime/types' +import { cloudApiError, type CloudRequestIntent } from './cloud-api-errors' import { jsonFields, type CloudCredentials } from './cloud-credentials' -export type CloudFetch = (input: string, init: RequestInit) => Promise +export { cloudApiError, type CloudApiErrorBody } from './cloud-api-errors' -export type CloudApiErrorBody = { error?: unknown; reason?: unknown } +export type CloudFetch = (input: string, init: RequestInit) => Promise const DEFAULT_TIMEOUT_MS = 60_000 @@ -19,7 +20,13 @@ export class CloudApiClient { async request( method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', path: string, - options: { body?: unknown; timeoutMs?: number; query?: Record } = {} + options: { + body?: unknown + timeoutMs?: number + query?: Record + /** Picks create-time error copy ("Nothing was created") over "Your files are safe". */ + intent?: CloudRequestIntent + } = {} ): Promise { const url = new URL(`${this.credentials.apiUrl}${path}`) for (const [key, value] of Object.entries(options.query ?? {})) { @@ -46,15 +53,17 @@ export class CloudApiClient { throw new RuntimeClientError( 'cloud_unreachable', timedOut - ? `Orca Cloud did not answer ${method} ${path} within ${Math.round((options.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1000)}s.` - : `Could not reach Orca Cloud at ${this.credentials.apiUrl}: ${error instanceof Error ? error.message : String(error)}`, + ? `Orca Cloud didn't answer within ${Math.round((options.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1000)} seconds.` + : `Couldn't reach Orca Cloud at ${this.credentials.apiUrl}.`, { apiUrl: this.credentials.apiUrl, + request: `${method} ${path}`, + cause: error instanceof Error ? error.message : String(error), nextSteps: this.credentials.token.startsWith('orca_ws_') ? [ - "Inside an Orca Cloud workspace the control plane must be on the VM's egress allowlist; restart the workspace after a control-plane update." + "Inside a cloud workspace, Orca Cloud must be on the sandbox's egress allowlist. Restart the workspace, then try again." ] - : ['Check the network and the control-plane URL, then retry.'] + : ['Check your network and ORCA_CLOUD_API_URL, then try again.'] } ) } @@ -70,176 +79,11 @@ export class CloudApiClient { if (!response.ok) { throw cloudApiError(response.status, jsonFields(body), { credentials: this.credentials, - retryAfter: response.headers.get('retry-after') + retryAfter: response.headers.get('retry-after'), + intent: options.intent }) } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the client's typed boundary; each caller names the control-plane response shape it reads return body as T } } - -/** Maps a control-plane error response to the CLI's error. Exported for tests. */ -export function cloudApiError( - status: number, - body: CloudApiErrorBody, - context: { - credentials: Pick - retryAfter?: string | null - } -): RuntimeClientError { - const code = typeof body.error === 'string' ? body.error : `http_${status}` - const reason = typeof body.reason === 'string' ? body.reason : null - const data = (nextSteps: string[], extra: Record = {}) => ({ - status, - apiError: code, - ...(reason ? { reason } : {}), - ...extra, - ...(nextSteps.length > 0 ? { nextSteps } : {}) - }) - const inVm = context.credentials.token.startsWith('orca_ws_') - if (status === 401) { - return new RuntimeClientError( - 'cloud_unauthorized', - inVm - ? 'Orca Cloud rejected this workspace token. In-workspace CLI access may be turned off for the organization (that revokes every workspace token at once), or the token was replaced at boot or revoked on sleep.' - : 'Orca Cloud rejected the token: it is expired, revoked or for another control plane.', - data( - inVm - ? [ - 'Ask an organization owner or admin to check in-workspace CLI access in Orca Cloud settings (vmCliEnabled); once it is on, restart the workspace for a fresh token.', - 'Or set ORCA_CLOUD_TOKEN to an API key.' - ] - : context.credentials.source === 'env' - ? ['Set ORCA_CLOUD_TOKEN to a valid API key or session token.'] - : ['Run `orca cloud login --token ` with a fresh API key or session token.'] - ) - ) - } - if (status === 403 && reason === 'vm_cli_disabled') { - return new RuntimeClientError( - 'cloud_vm_cli_disabled', - 'In-workspace CLI access is turned off for this Orca Cloud organization, so this workspace cannot call Orca Cloud.', - data([ - 'Ask an organization owner or admin to turn on in-workspace CLI access in Orca Cloud settings (PUT /v1/settings {"vmCliEnabled": true}).' - ]) - ) - } - if (status === 403 && reason === 'own_workspace') { - return new RuntimeClientError( - 'cloud_forbidden', - 'A workspace cannot sleep, archive or destroy itself; pick another workspace.', - data([]) - ) - } - if ( - code === 'entitlement_denied' && - (reason === 'concurrency_limit' || reason === 'member_concurrency_limit') - ) { - return new RuntimeClientError( - 'cloud_at_capacity', - reason === 'member_concurrency_limit' - ? "You're at your limit of running sandboxes. Nothing was created." - : "You're at your team's limit of running sandboxes. Nothing was created.", - data([ - 'Put one to sleep or delete it, then try again: `orca cloud workspace list`, then `orca cloud workspace sleep `.' - ]) - ) - } - if (code === 'entitlement_denied' || code === 'billing_required' || status === 402) { - const outOfHours = reason === 'included_hours_exhausted' || reason === 'overage_cap_reached' - const payment = reason === 'payment_past_due' || reason === 'payment_grace_expired' - if (payment) { - return new RuntimeClientError( - 'cloud_payment_failed', - "Payment failed, so new sandboxes can't start. Nothing was created.", - data(['Ask an owner or admin to update the payment method.']) - ) - } - if (reason === 'machine_size_not_in_plan') { - return new RuntimeClientError( - 'cloud_plan_required', - "That sandbox size isn't in your team's plan. Nothing was created.", - data(['Use --size standard.']) - ) - } - return new RuntimeClientError( - outOfHours ? 'cloud_out_of_hours' : 'cloud_plan_required', - outOfHours - ? 'Your team is out of sandbox hours (or at its monthly spend cap). Nothing was created, and your files are safe.' - : 'Orca Cloud needs a Team plan. Nothing was created, and you weren’t charged.', - data([ - outOfHours - ? 'Ask an owner or admin to turn on overage or raise the spend cap.' - : 'Ask an owner or admin to start a Team plan in Orca → Settings → Plan & billing.' - ]) - ) - } - if (status === 403 && code === 'insufficient_scope') { - return new RuntimeClientError( - 'cloud_forbidden', - `This token lacks the ${reason ?? 'required'} scope.`, - data(['Create an API key with that scope in Orca Cloud settings and log in with it.']) - ) - } - if (status === 403) { - const why: Record = { - session_required: 'This needs a signed-in Orca session, not an API key or workspace token.', - admin_required: 'Only an organization owner or admin can do this.' - } - return new RuntimeClientError( - 'cloud_forbidden', - (reason && why[reason]) || `Orca Cloud refused the request (${reason ?? code}).`, - data([]) - ) - } - if (status === 404) { - return new RuntimeClientError( - 'cloud_not_found', - inVm - ? 'Not found. A workspace token sees only its own workspace and the workspaces it created.' - : 'Not found in this Orca Cloud account.', - data(['Run `orca cloud workspace list` to see the workspaces this token can use.']) - ) - } - if (status === 429) { - const seconds = Number(context.retryAfter) - return new RuntimeClientError( - 'cloud_rate_limited', - reason === 'workspace_creates' - ? 'Too many workspace creates for this account right now.' - : 'Too many requests to Orca Cloud right now.', - data([`Retry in ${Number.isFinite(seconds) && seconds > 0 ? seconds : 60}s.`], { - retryAfterSeconds: Number.isFinite(seconds) ? seconds : null - }) - ) - } - if (status === 400) { - return new RuntimeClientError( - 'invalid_argument', - `Orca Cloud rejected the request: ${reason ?? code}.`, - data([]) - ) - } - if (status === 409) { - return new RuntimeClientError('cloud_conflict', `Conflict: ${reason ?? code}.`, data([])) - } - if (status === 402 || code === 'entitlement_denied' || code === 'billing_required') { - return new RuntimeClientError( - 'cloud_billing', - `Orca Cloud billing refused this (${reason ?? code}).`, - data(['Check the plan and usage limits in Orca Cloud billing settings.']) - ) - } - if (status === 503 && code === 'not_configured') { - return new RuntimeClientError( - 'cloud_unavailable', - 'This Orca Cloud control plane cannot run workspaces right now (not configured).', - data([]) - ) - } - return new RuntimeClientError( - status >= 500 ? 'cloud_unavailable' : 'cloud_api_error', - `Orca Cloud returned ${status} ${code}${reason ? ` (${reason})` : ''}.`, - data(status >= 500 ? ['Retry shortly; the workspace provider may be busy.'] : []) - ) -} diff --git a/src/cli/cloud/cloud-api-errors.ts b/src/cli/cloud/cloud-api-errors.ts new file mode 100644 index 00000000000..e0f338c90f1 --- /dev/null +++ b/src/cli/cloud/cloud-api-errors.ts @@ -0,0 +1,248 @@ +// Private build only: maps a control-plane error response to the CLI's error. Messages follow the +// product glossary's error tone: say what happened in plain words, say whether anything was lost or +// charged, give one next step. API codes and reasons stay in `error.data` (seen with --json). +import { RuntimeClientError } from '../runtime/types' +import type { CloudCredentials } from './cloud-credentials' + +export type CloudApiErrorBody = { error?: unknown; reason?: unknown } + +/** What the failed request was doing; create-time copy never says "Your files are safe". */ +export type CloudRequestIntent = 'create' | 'existing' + +export type CloudApiErrorContext = { + credentials: Pick + retryAfter?: string | null + intent?: CloudRequestIntent +} + +const NOTHING_CREATED = "Nothing was created, and you weren't charged." +const FILES_SAFE = 'Your files are safe.' +const BUSY_409 = + 'This workspace is still starting or going to sleep. Nothing was changed. Try again in a moment.' + +/** "Try again in 12 seconds." (one second is singular). */ +export function tryAgainIn(seconds: number): string { + return `Try again in ${seconds} ${seconds === 1 ? 'second' : 'seconds'}.` +} + +function forbiddenMessage(reason: string | null): string { + switch (reason) { + case 'admin_required': + case 'org_admin_required': + return 'Only a team owner or admin can do this.' + case 'session_required': + return 'This needs a signed-in Orca session, not an Orca API key or workspace token.' + case 'not_owner': + return 'Only the person who created this can do that.' + default: + return "You don't have access to do this." + } +} + +function conflictMessage(reason: string | null): { message: string; nextSteps: string[] } { + if (reason === 'concurrent_transition' || (reason?.startsWith('sandbox_') ?? false)) { + return { message: BUSY_409, nextSteps: [] } + } + switch (reason) { + case 'workspace_not_running': + return { + message: "This workspace isn't running. Nothing was changed.", + nextSteps: ['Wake it first: `orca cloud workspace wake `.'] + } + case 'idempotency_in_progress': + return { + message: 'The same request is still running. Nothing was changed. Try again in a moment.', + nextSteps: [] + } + case 'environment_not_built': + return { + message: `That environment has no finished build yet. ${NOTHING_CREATED}`, + nextSteps: ['Build it first: `orca cloud env build --wait`.'] + } + case 'region_unavailable': + return { + message: `That region isn't available right now. ${NOTHING_CREATED}`, + nextSteps: ['Try again without --region.'] + } + case 'github_not_connected': + return { + message: `Orca Cloud isn't connected to GitHub for this repo. ${NOTHING_CREATED}`, + nextSteps: ['Connect GitHub in Orca → Settings → Orca Cloud, then try again.'] + } + case 'queue_full': + return { + message: 'This routine already has runs waiting. Nothing was queued.', + nextSteps: ['Try again after one of them finishes.'] + } + case 'duplicate': + return { message: 'The same run is already queued. Nothing was queued.', nextSteps: [] } + case 'project_name_taken': + return { message: 'A project with that name already exists.', nextSteps: [] } + default: + return { + message: "Orca Cloud couldn't do that right now. Nothing was changed.", + nextSteps: ['Try again in a moment.'] + } + } +} + +/** Maps a control-plane error response to the CLI's error. */ +export function cloudApiError( + status: number, + body: CloudApiErrorBody, + context: CloudApiErrorContext +): RuntimeClientError { + const code = typeof body.error === 'string' ? body.error : `http_${status}` + const reason = typeof body.reason === 'string' ? body.reason : null + const data = (nextSteps: string[], extra: Record = {}) => ({ + status, + apiError: code, + ...(reason ? { reason } : {}), + ...extra, + ...(nextSteps.length > 0 ? { nextSteps } : {}) + }) + const creating = context.intent === 'create' + const inVm = context.credentials.token.startsWith('orca_ws_') + if (status === 401) { + return new RuntimeClientError( + 'cloud_unauthorized', + inVm + ? 'Orca Cloud rejected this workspace token. In-workspace CLI access may be turned off for the team (that revokes every workspace token at once), or the token was replaced at boot or revoked on sleep.' + : 'Orca Cloud rejected the token: it is expired, revoked or for another Orca Cloud server.', + data( + inVm + ? [ + 'Ask a team owner or admin to turn on in-workspace CLI access in Orca Cloud settings, then restart the workspace for a fresh token.', + 'Or set ORCA_CLOUD_TOKEN to an Orca API key.' + ] + : context.credentials.source === 'env' + ? ['Set ORCA_CLOUD_TOKEN to a valid Orca API key or session token.'] + : ['Run `orca cloud login --token ` with a fresh Orca API key or session token.'] + ) + ) + } + if (status === 403 && reason === 'vm_cli_disabled') { + return new RuntimeClientError( + 'cloud_vm_cli_disabled', + 'In-workspace CLI access is turned off for this team, so this workspace cannot call Orca Cloud.', + data( + ['Ask a team owner or admin to turn on in-workspace CLI access in Orca Cloud settings.'], + { setting: 'vmCliEnabled' } + ) + ) + } + if (status === 403 && reason === 'own_workspace') { + return new RuntimeClientError( + 'cloud_forbidden', + "A workspace can't sleep, archive or delete itself. Nothing was changed.", + data(['Pick another workspace.']) + ) + } + const safety = creating ? NOTHING_CREATED : FILES_SAFE + if ( + code === 'entitlement_denied' && + (reason === 'concurrency_limit' || reason === 'member_concurrency_limit') + ) { + return new RuntimeClientError( + 'cloud_at_capacity', + `${ + reason === 'member_concurrency_limit' + ? "You're at your limit of running sandboxes." + : "You're at your team's limit of running sandboxes." + } ${creating ? 'Nothing was created.' : FILES_SAFE}`, + data([ + 'Put one to sleep or delete it, then try again: `orca cloud workspace list`, then `orca cloud workspace sleep `.' + ]) + ) + } + if (code === 'entitlement_denied' || code === 'billing_required' || status === 402) { + if (reason === 'payment_past_due' || reason === 'payment_grace_expired') { + return new RuntimeClientError( + 'cloud_payment_failed', + `Payment failed, so ${creating ? "new sandboxes can't start" : "this workspace can't wake"}. ${creating ? 'Nothing was created.' : FILES_SAFE}`, + data(['Ask an owner or admin to update the payment method.']) + ) + } + if (reason === 'included_hours_exhausted') { + return new RuntimeClientError( + 'cloud_out_of_hours', + `Your team is out of sandbox hours. ${safety}`, + data(['Ask an owner or admin to add hours.']) + ) + } + if (reason === 'overage_cap_reached') { + return new RuntimeClientError( + 'cloud_spend_cap_reached', + `Your team reached its monthly spend cap. ${safety}`, + data(['Ask an owner or admin to raise the spend cap.']) + ) + } + return new RuntimeClientError( + 'cloud_plan_required', + `Orca Cloud needs a Team plan. ${creating ? NOTHING_CREATED : FILES_SAFE}`, + data(['Ask an owner or admin to start a Team plan in Orca → Settings → Plan & billing.']) + ) + } + if (status === 403 && code === 'insufficient_scope') { + return new RuntimeClientError( + 'cloud_forbidden', + `This Orca API key is missing the ${reason ?? 'required'} scope.`, + data([ + 'Create an Orca API key with that scope in Orca → Settings → Orca API keys, then run `orca cloud login`.' + ]) + ) + } + if (status === 403) { + return new RuntimeClientError('cloud_forbidden', forbiddenMessage(reason), data([])) + } + if (status === 404) { + return new RuntimeClientError( + 'cloud_not_found', + inVm + ? 'Not found. A workspace token sees only its own workspace and the workspaces it created.' + : "Not found, or these credentials can't see it.", + data(['Run `orca cloud workspace list` to see the workspaces you can use.']) + ) + } + if (status === 429) { + const parsed = Number(context.retryAfter) + const seconds = Number.isFinite(parsed) && parsed > 0 ? Math.ceil(parsed) : 60 + return new RuntimeClientError( + 'cloud_rate_limited', + reason === 'workspace_creates' + ? `Too many new workspaces in a short time. ${NOTHING_CREATED}` + : 'Too many requests to Orca Cloud right now.', + data([tryAgainIn(seconds)], { retryAfterSeconds: Number.isFinite(parsed) ? parsed : null }) + ) + } + if (status === 400) { + // Reasons read ": "; the field is useful, the problem text is API wording. + const field = reason ? /^([A-Za-z0-9_.]+):/.exec(reason)?.[1] : undefined + return new RuntimeClientError( + 'invalid_argument', + field && field !== 'body' + ? `Orca Cloud didn't accept the value for ${field}. Nothing was changed.` + : "Orca Cloud didn't accept that request. Nothing was changed.", + data([]) + ) + } + if (status === 409) { + const conflict = conflictMessage(reason) + return new RuntimeClientError('cloud_conflict', conflict.message, data(conflict.nextSteps)) + } + if (status === 503 && code === 'not_configured') { + return new RuntimeClientError( + 'cloud_unavailable', + "This Orca Cloud server can't run workspaces right now.", + data([]) + ) + } + if (status >= 500) { + return new RuntimeClientError( + 'cloud_unavailable', + "Orca Cloud couldn't finish that request.", + data(['Try again in a moment.']) + ) + } + return new RuntimeClientError('cloud_api_error', "Orca Cloud couldn't do that.", data([])) +} diff --git a/src/cli/cloud/cloud-cli.test.ts b/src/cli/cloud/cloud-cli.test.ts index 54b26931fb3..6ee2dd469c5 100644 --- a/src/cli/cloud/cloud-cli.test.ts +++ b/src/cli/cloud/cloud-cli.test.ts @@ -181,7 +181,7 @@ describe('cloud credential resolution', () => { data: expect.objectContaining({ nextSteps: [ expect.stringContaining('orca cloud login'), - expect.stringContaining('vmCliEnabled') + expect.stringContaining('in-workspace CLI access turned on') ] }) }) @@ -240,7 +240,7 @@ describe('cloud API error messages', () => { it('explains token expiry differently for workspace tokens and keys', () => { expect(cloudApiError(401, { error: 'unauthorized' }, { credentials: vm }).message).toContain( - 'turned off for the organization' + 'turned off for the team' ) expect(cloudApiError(401, { error: 'unauthorized' }, { credentials: user }).data).toMatchObject( { @@ -253,7 +253,7 @@ describe('cloud API error messages', () => { expect( cloudApiError(403, { error: 'forbidden', reason: 'own_workspace' }, { credentials: vm }) .message - ).toContain('cannot sleep, archive or destroy itself') + ).toContain("can't sleep, archive or delete itself") expect(cloudApiError(404, { error: 'not_found' }, { credentials: vm }).message).toContain( 'workspaces it created' ) @@ -266,7 +266,7 @@ describe('cloud API error messages', () => { ).toContain('workspaces:write') expect( cloudApiError(429, { error: 'rate_limited' }, { credentials: user, retryAfter: '12' }).data - ).toMatchObject({ retryAfterSeconds: 12, nextSteps: ['Retry in 12s.'] }) + ).toMatchObject({ retryAfterSeconds: 12, nextSteps: ['Try again in 12 seconds.'] }) }) }) @@ -276,7 +276,7 @@ describe('orca cloud handlers', () => { 'POST /v1/workspaces': () => [201, { workspace: workspace() }] }) await createCloudHandlers(() => deps(api.fetchImpl))['cloud workspace create']( - ctx({ name: 'child', repo: 'git@github.com:acme/app.git', ref: 'main', size: 'large' }) + ctx({ name: 'child', repo: 'git@github.com:acme/app.git', ref: 'main' }) ) expect(api.calls[0]).toMatchObject({ method: 'POST', @@ -284,8 +284,7 @@ describe('orca cloud handlers', () => { auth: 'Bearer orca_sk_test', body: { name: 'child', - repo: { url: 'https://github.com/acme/app.git', ref: 'main' }, - machineSize: 'large' + repo: { url: 'https://github.com/acme/app.git', ref: 'main' } } }) const out = lastJson() @@ -326,9 +325,6 @@ describe('orca cloud handlers', () => { await expect( handlers['cloud workspace create'](ctx({ agent: 'gpt', prompt: 'x' })) ).rejects.toThrow('--agent must be one of: claude, codex') - await expect(handlers['cloud workspace create'](ctx({ size: 'huge' }))).rejects.toThrow( - '--size' - ) await expect( handlers['cloud workspace create'](ctx({ repo: 'http://x.test/a' })) ).rejects.toThrow('https') @@ -459,7 +455,8 @@ describe('orca cloud handlers', () => { ) ).rejects.toMatchObject({ code: 'cloud_message_failed', - message: expect.stringContaining('agent_launch_failed') + message: "Message msg_1 couldn't be delivered to the agent.", + data: { message: expect.objectContaining({ error: 'agent_launch_failed' }) } }) const stuck = fakeApi({ diff --git a/src/cli/cloud/cloud-credentials.ts b/src/cli/cloud/cloud-credentials.ts index 2e61cfa15a1..ea1d2fa98dc 100644 --- a/src/cli/cloud/cloud-credentials.ts +++ b/src/cli/cloud/cloud-credentials.ts @@ -70,7 +70,7 @@ const LOGIN_HINT = 'Run `orca cloud login --token --api-url `, or set ORCA_CLOUD_TOKEN and ORCA_CLOUD_API_URL.' // Inside a VM the file only appears when the org allows it, so say why it may be missing. const IN_VM_HINT = - 'Inside an Orca Cloud workspace the token is written at boot only when the organization has in-workspace CLI access turned on (Orca Cloud settings, vmCliEnabled).' + 'Inside an Orca Cloud workspace the token is written at boot only when the team has in-workspace CLI access turned on in Orca Cloud settings.' /** * Only https may carry the bearer token; plain http is allowed for loopback dev servers. diff --git a/src/cli/cloud/cloud-format.ts b/src/cli/cloud/cloud-format.ts index d9f5ba0b716..84d65ee351e 100644 --- a/src/cli/cloud/cloud-format.ts +++ b/src/cli/cloud/cloud-format.ts @@ -1,5 +1,7 @@ // Private build only: text output for `orca cloud …`. JSON output is the API view wrapped as -// { ok, schemaVersion, result } (see printCloudResult). +// { ok, schemaVersion, result } (see printCloudResult). Human output follows the product glossary: +// states and problems in words; raw API statuses and codes appear only under --json. +import { ORCA_CLOUD_SANDBOX_SPEC } from '../../shared/hosted-sandbox/hosted-sandbox-wire' export const CLOUD_CLI_SCHEMA_VERSION = 1 @@ -14,6 +16,9 @@ export type CloudWorkspace = { machineSize: string region: string | null repoUrl: string | null + /** Older control planes omit these two. */ + repoBranch?: string | null + lastActivityAt?: number | null session: { startedAt: number; leaseExpiresAt: number; deadlineAt: number | null } | null lastError: string | null createdAt: number @@ -69,7 +74,7 @@ export function printCloudResult(result: T, json: boolean, format: (value: T) console.log(format(result)) } -function ago(at: number | null | undefined, now: number): string { +export function ago(at: number | null | undefined, now: number): string { if (!at) { return '-' } @@ -86,7 +91,19 @@ function ago(at: number | null | undefined, now: number): string { return `${Math.round(seconds / 86_400)}d ago` } -function table(header: string[], rows: string[][]): string { +/** "42s", "1m 42s", "1h 5m" (the desktop's formatElapsedTime style). */ +export function formatElapsed(ms: number): string { + const seconds = Math.max(0, Math.round(ms / 1000)) + if (seconds < 60) { + return `${seconds}s` + } + if (seconds < 3600) { + return `${Math.floor(seconds / 60)}m ${seconds % 60}s` + } + return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m` +} + +export function table(header: string[], rows: string[][]): string { const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length))) const line = (cells: string[]) => cells @@ -96,48 +113,108 @@ function table(header: string[], rows: string[][]): string { return [line(header), ...rows.map(line)].join('\n') } +/** "Sandbox size: 8 vCPU · 16 GB". There is one size; it always comes from ORCA_CLOUD_SANDBOX_SPEC. */ +export const CLOUD_SANDBOX_SIZE_LINE = `Sandbox size: ${ORCA_CLOUD_SANDBOX_SPEC.vcpus} vCPU · ${ORCA_CLOUD_SANDBOX_SPEC.memoryGb} GB` + +/** The API's workspace status in glossary words (Starting, Running, Asleep, Waking, …). */ +export function cloudWorkspaceStateLabel(w: Pick): string { + switch (w.status) { + case 'starting': + return 'Starting' + case 'running': + return 'Running' + case 'sleeping': + return w.archived ? 'Archived' : 'Asleep' + case 'waking': + return 'Waking' + case 'destroying': + return 'Deleting' + case 'destroyed': + return 'Deleted' + case 'failed': + return "Couldn't start" + default: + return w.archived ? 'Archived' : 'Unknown' + } +} + +/** `https://github.com/acme/app(.git)` → `acme/app`; other hosts keep the full URL. */ +function shortRepo(url: string | null): string { + if (!url) { + return '-' + } + const github = /^https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(url) + return github ? github[1] : url +} + +function lastActive(w: CloudWorkspace): number { + return w.lastActivityAt ?? w.updatedAt +} + export function formatCloudWorkspaceList( value: { workspaces: CloudWorkspace[] }, now = Date.now() ): string { if (value.workspaces.length === 0) { - return 'No workspaces.' + return 'No cloud workspaces yet. Create one with: orca cloud workspace create' } return table( - ['ID', 'NAME', 'STATUS', 'ORIGIN', 'CREATED'], + ['ID', 'NAME', 'STATE', 'REPO', 'BRANCH', 'LAST ACTIVE'], value.workspaces.map((w) => [ w.id, w.name, - w.archived ? `${w.status} (archived)` : w.status, - w.origin, - ago(w.createdAt, now) + cloudWorkspaceStateLabel(w), + shortRepo(w.repoUrl), + w.repoBranch || '-', + ago(lastActive(w), now) ]) ) } +const ORIGIN_LABELS: Record = { + desktop: 'the Orca app', + api: 'the Orca Cloud API', + mcp: 'an MCP client', + routine: 'a routine', + vm: 'another cloud workspace' +} + +/** One plain sentence for the workspace's last problem, or null when there is nothing to say. */ +function workspaceProblem(w: CloudWorkspace): string | null { + if (w.status === 'failed') { + return `This workspace couldn't start. Delete it and create a new one: orca cloud workspace delete ${w.id}` + } + if (w.status === 'sleeping' && w.lastError === 'resume_failed') { + return `The last wake didn't finish. Your files are safe. Run: orca cloud workspace wake ${w.id}` + } + return null +} + export function formatCloudWorkspace( value: { workspace: CloudWorkspace; message?: CloudMessage; elapsedMs?: number }, now = Date.now() ): string { const w = value.workspace + const problem = workspaceProblem(w) + const origin = ORIGIN_LABELS[w.origin] const lines = [ `${w.name} (${w.id})`, - `status: ${w.status}${w.archived ? ' (archived)' : ''}`, - `origin: ${w.origin}`, - `size: ${w.machineSize}${w.region ? ` in ${w.region}` : ''}`, - ...(w.repoUrl ? [`repo: ${w.repoUrl}`] : []), - ...(w.projectId ? [`project: ${w.projectId}`] : []), - ...(w.session - ? [`session lease expires: ${new Date(w.session.leaseExpiresAt).toISOString()}`] - : []), - ...(w.lastError ? [`last error: ${w.lastError}`] : []), - `created: ${ago(w.createdAt, now)}` + `State: ${cloudWorkspaceStateLabel(w)}`, + ...(problem ? [problem] : []), + CLOUD_SANDBOX_SIZE_LINE, + ...(w.repoUrl ? [`Repo: ${w.repoUrl}${w.repoBranch ? ` (${w.repoBranch})` : ''}`] : []), + ...(w.projectId ? [`Project: ${w.projectId}`] : []), + ...(origin ? [`Created from: ${origin}`] : []), + `Last active: ${ago(lastActive(w), now)}`, + `Created: ${ago(w.createdAt, now)}` ] if (value.message) { - lines.push(`message: ${value.message.id} (${value.message.status}, ${value.message.agent})`) + lines.push( + `First message: ${value.message.status} for ${value.message.agent} (${value.message.id})` + ) } if (value.elapsedMs !== undefined) { - lines.push(`took ${(value.elapsedMs / 1000).toFixed(1)}s`) + lines.push(`Took ${formatElapsed(value.elapsedMs)}`) } return lines.join('\n') } @@ -172,7 +249,7 @@ export function formatCloudSessions( if (value.sessions.length === 0) { return value.workspaceStatus === 'running' ? 'No agent sessions.' - : `No agent sessions (workspace is ${value.workspaceStatus}; wake it to see live sessions).` + : `No agent sessions. The workspace is ${cloudWorkspaceStateLabel({ status: value.workspaceStatus, archived: false }).toLowerCase()}; wake it to see live sessions.` } return value.sessions .map((s) => @@ -189,12 +266,11 @@ export function formatCloudProjects(value: { projects: CloudProject[] }): string return 'No projects.' } return table( - ['ID', 'NAME', 'REPO', 'SIZE'], + ['ID', 'NAME', 'REPO'], value.projects.map((p) => [ p.id, p.name, - p.repo ? `${p.repo.url}${p.repo.ref ? `#${p.repo.ref}` : ''}` : '-', - p.environment.machineSize + p.repo ? `${p.repo.url}${p.repo.ref ? `#${p.repo.ref}` : ''}` : '-' ]) ) } @@ -209,7 +285,7 @@ export function formatCloudWhoami(value: { return [ `account: ${me.accountId}`, `user: ${me.userId}`, - ...(me.orgId ? [`org: ${me.orgId} (${me.role})`] : [`role: ${me.role}`]), + ...(me.orgId ? [`team: ${me.orgId} (${me.role})`] : [`role: ${me.role}`]), `via: ${me.via} (${value.tokenKind} from ${value.credentialSource})`, ...(me.workspaceId ? [`workspace: ${me.workspaceId}`] : []), `scopes: ${me.scopes.join(', ') || '-'}`, diff --git a/src/cli/cloud/cloud-glossary.test.ts b/src/cli/cloud/cloud-glossary.test.ts new file mode 100644 index 00000000000..6d1880dc14a --- /dev/null +++ b/src/cli/cloud/cloud-glossary.test.ts @@ -0,0 +1,327 @@ +// Human output of `orca cloud …` follows the product glossary: states, errors and sizes in words, +// raw API codes only under --json. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { HandlerContext } from '../dispatch' +import { cloudApiError } from './cloud-api-errors' +import { nodeCloudCredentialFs } from './cloud-credentials' +import { + cloudWorkspaceStateLabel, + formatCloudWorkspace, + formatCloudWorkspaceList, + type CloudWorkspace +} from './cloud-format' +import { createCloudHandlers, type CloudHandlerDeps } from './cloud-handlers' +import { formatRoutineList, routineRunErrorCopy } from './cloud-routines' +import type { Routine } from '../../shared/cloud-api/cloud-api-routine-types' + +const NOW = 10_000_000 + +function workspace(overrides: Partial = {}): CloudWorkspace { + return { + id: 'sbx_aa11', + name: 'child', + projectId: null, + status: 'running', + archived: false, + hidden: false, + origin: 'vm', + machineSize: 'standard', + region: 'iad1', + repoUrl: null, + session: null, + lastError: null, + createdAt: NOW - 3_600_000, + updatedAt: NOW - 60_000, + ...overrides + } +} + +const user = { source: 'env' as const, token: 'orca_sk_x', path: null } + +let logs: string[] +beforeEach(() => { + logs = [] + vi.spyOn(console, 'log').mockImplementation((line: unknown) => void logs.push(String(line))) + vi.spyOn(console, 'error').mockImplementation(() => undefined) +}) +afterEach(() => { + vi.restoreAllMocks() +}) + +function deps(routes: Record [number, unknown]>): { + deps: CloudHandlerDeps + calls: string[] +} { + const calls: string[] = [] + let clock = NOW + const fetchImpl = vi.fn(async (input: string, init: RequestInit) => { + const key = `${init.method ?? 'GET'} ${new URL(input).pathname}` + calls.push(key) + const route = routes[key] + const [status, body] = route ? route() : [404, { error: 'not_found' }] + return Response.json(body, { status }) + }) + return { + calls, + deps: { + env: { ORCA_CLOUD_TOKEN: 'orca_sk_test', ORCA_CLOUD_API_URL: 'https://cloud.test' }, + fetch: fetchImpl, + fs: nodeCloudCredentialFs, + home: '/nonexistent', + now: () => clock, + sleep: async (ms) => { + clock += ms + }, + readStdin: async () => null + } + } +} + +function ctx(flags: Record, json = false): HandlerContext { + return { + flags: new Map(Object.entries(flags)), + get client(): never { + throw new Error('cloud commands must not use the runtime client') + }, + cwd: '/', + json + } +} + +describe('workspace states and output', () => { + it('maps every API status to the glossary', () => { + const label = (status: string, archived = false) => + cloudWorkspaceStateLabel({ status, archived }) + expect(label('starting')).toBe('Starting') + expect(label('running')).toBe('Running') + expect(label('sleeping')).toBe('Asleep') + expect(label('sleeping', true)).toBe('Archived') + expect(label('waking')).toBe('Waking') + expect(label('failed')).toBe("Couldn't start") + expect(label('destroying')).toBe('Deleting') + }) + + it('lists ID NAME STATE REPO BRANCH LAST ACTIVE, falling back to updatedAt', () => { + const text = formatCloudWorkspaceList( + { + workspaces: [ + workspace({ repoUrl: 'https://github.com/acme/app', repoBranch: 'fix-login' }), + workspace({ id: 'sbx_bb22', name: 'old', status: 'failed', lastError: 'create_failed' }) + ] + }, + NOW + ) + expect(text.split('\n')).toEqual([ + 'ID NAME STATE REPO BRANCH LAST ACTIVE', + 'sbx_aa11 child Running acme/app fix-login 1m ago', + "sbx_bb22 old Couldn't start - - 1m ago" + ]) + }) + + it('shows the sandbox size from ORCA_CLOUD_SANDBOX_SPEC and no VM, size or raw codes', () => { + const text = formatCloudWorkspace( + { workspace: workspace({ status: 'sleeping', lastError: 'resume_failed' }) }, + NOW + ) + expect(text).toContain('State: Asleep') + expect(text).toContain('Sandbox size: 8 vCPU · 16 GB') + expect(text).toContain( + "The last wake didn't finish. Your files are safe. Run: orca cloud workspace wake sbx_aa11" + ) + expect(text).toContain('Created from: another cloud workspace') + expect(text).not.toMatch(/resume_failed|sleeping|standard|\bVM\b|\bvm\b|iad1/) + }) +}) + +describe('glossary error copy', () => { + it('splits out-of-hours from the spend cap and never says "files are safe" on create', () => { + const hours = cloudApiError( + 403, + { error: 'entitlement_denied', reason: 'included_hours_exhausted' }, + { credentials: user, intent: 'create' } + ) + expect(hours.code).toBe('cloud_out_of_hours') + expect(hours.message).toBe( + "Your team is out of sandbox hours. Nothing was created, and you weren't charged." + ) + expect(hours.data).toMatchObject({ nextSteps: ['Ask an owner or admin to add hours.'] }) + const cap = cloudApiError( + 403, + { error: 'entitlement_denied', reason: 'overage_cap_reached' }, + { credentials: user, intent: 'create' } + ) + expect(cap.code).toBe('cloud_spend_cap_reached') + expect(cap.data).toMatchObject({ + nextSteps: ['Ask an owner or admin to raise the spend cap.'] + }) + // Waking an existing workspace keeps its files. + expect( + cloudApiError( + 403, + { error: 'entitlement_denied', reason: 'included_hours_exhausted' }, + { credentials: user } + ).message + ).toBe('Your team is out of sandbox hours. Your files are safe.') + }) + + it('uses the exact 409, admin and rate-limit copy, with codes kept in data', () => { + const busy = cloudApiError( + 409, + { error: 'conflict', reason: 'sandbox_suspending' }, + { credentials: user } + ) + expect(busy.message).toBe( + 'This workspace is still starting or going to sleep. Nothing was changed. Try again in a moment.' + ) + expect(busy.data).toMatchObject({ apiError: 'conflict', reason: 'sandbox_suspending' }) + expect( + cloudApiError( + 403, + { error: 'forbidden', reason: 'org_admin_required' }, + { credentials: user } + ).message + ).toBe('Only a team owner or admin can do this.') + expect( + cloudApiError(429, { error: 'rate_limited' }, { credentials: user, retryAfter: '1' }).data + ).toMatchObject({ nextSteps: ['Try again in 1 second.'] }) + expect( + cloudApiError( + 400, + { error: 'invalid_request', reason: 'name: Too big' }, + { credentials: user } + ).message + ).toBe("Orca Cloud didn't accept the value for name. Nothing was changed.") + expect( + cloudApiError(502, { error: 'provider_unavailable' }, { credentials: user }).message + ).not.toContain('provider_unavailable') + }) + + it('turns a failed wake (resume_failed) into the glossary copy', async () => { + const { deps: d } = deps({ + 'POST /v1/workspaces/sbx_aa11/wake': () => [ + 200, + { + workspace: workspace({ status: 'sleeping', lastError: 'resume_failed' }), + state: 'failed' + } + ] + }) + await expect( + createCloudHandlers(() => d)['cloud workspace wake']( + ctx({ workspace: 'sbx_aa11', progress: 'none' }) + ) + ).rejects.toMatchObject({ + code: 'cloud_wake_failed', + message: + "The last wake didn't finish. Your files are safe. Run: orca cloud workspace wake sbx_aa11" + }) + }) +}) + +describe('orca cloud routine', () => { + const routine: Routine = { + id: 'rtn_a1', + name: 'Nightly triage', + projectId: null, + repo: null, + enabled: true, + trigger: { kind: 'schedule', cron: '0 9 * * 1-5', timezone: 'America/New_York' }, + agent: 'claude', + prompt: 'x', + postResults: 'none', + maxRuntimeMinutes: 30, + nextRunAt: null, + lastRun: { id: 'run_1', status: 'cancelled', finishedAt: NOW - 7_200_000 }, + createdBy: 'u', + createdByName: null, + createdAt: 1, + updatedAt: 1 + } + + it('lists routines with the trigger and last run in words', () => { + const text = formatRoutineList( + { + routines: [ + routine, + { + ...routine, + id: 'rtn_b2', + name: 'PR review', + enabled: false, + lastRun: null, + trigger: { kind: 'webhook', urlHint: null } + } + ] + }, + NOW + ) + expect(text).toContain('ID NAME') + expect(text).toMatch( + /rtn_a1 +Nightly triage +Weekdays at 9:00 AM \(America\/New_York\) +Canceled 2h ago/ + ) + expect(text).toMatch(/rtn_b2 +PR review \(paused\) +Webhook +Never run/) + expect(text).not.toContain('cancelled') + }) + + it('queues a run by id without --wait and points at --wait', async () => { + const { deps: d, calls } = deps({ + 'GET /v1/routines/rtn_a1': () => [200, { routine }], + 'POST /v1/routines/rtn_a1/run': () => [ + 202, + { run: { id: 'run_9', status: 'queued', result: null, durationMs: null, error: null } } + ] + }) + await createCloudHandlers(() => d)['cloud routine run'](ctx({ routine: 'rtn_a1' })) + expect(calls).toEqual(['GET /v1/routines/rtn_a1', 'POST /v1/routines/rtn_a1/run']) + expect(logs.at(-1)).toBe( + 'Nightly triage: Queued (run_9)\nAdd --wait to follow a run until it finishes.' + ) + }) + + it('--wait fails with the run error in words and keeps the code in data', async () => { + const failed = { + id: 'run_9', + status: 'failed', + error: 'start_failed:provider_unavailable', + result: null, + durationMs: null + } + const { deps: d } = deps({ + 'GET /v1/routines': () => [200, { routines: [routine] }], + 'POST /v1/routines/rtn_a1/run': () => [202, { run: { ...failed, status: 'queued' } }], + 'GET /v1/routines/rtn_a1/runs/run_9': () => [200, { run: failed }] + }) + await expect( + createCloudHandlers(() => d)['cloud routine run']( + ctx({ routine: 'Nightly triage', wait: true, progress: 'none' }) + ) + ).rejects.toMatchObject({ + code: 'cloud_routine_run_failed', + message: "The workspace couldn't start. Nothing was charged.", + data: { run: { error: 'start_failed:provider_unavailable' } } + }) + }) + + it('refuses --timeout without --wait and unknown names before running anything', async () => { + const { deps: d, calls } = deps({ 'GET /v1/routines': () => [200, { routines: [routine] }] }) + const handlers = createCloudHandlers(() => d) + await expect( + handlers['cloud routine run'](ctx({ routine: 'rtn_a1', timeout: '5' })) + ).rejects.toThrow('--timeout needs --wait.') + await expect(handlers['cloud routine run'](ctx({ routine: 'nope' }))).rejects.toMatchObject({ + code: 'cloud_not_found' + }) + expect(calls).toEqual(['GET /v1/routines']) + }) + + it('maps run errors to plain sentences', () => { + expect(routineRunErrorCopy('workspace_lost:suspended')).toBe( + 'The workspace went to sleep or was deleted before the run finished.' + ) + expect(routineRunErrorCopy('running_interrupted')).toBe('Orca Cloud restarted during the run.') + expect(routineRunErrorCopy('queue_expired')).toBe( + 'The run waited too long to start and was skipped.' + ) + expect(routineRunErrorCopy('weird')).toBe('The run failed.') + }) +}) diff --git a/src/cli/cloud/cloud-handler-group.ts b/src/cli/cloud/cloud-handler-group.ts index e24a84c43e6..89016c25009 100644 --- a/src/cli/cloud/cloud-handler-group.ts +++ b/src/cli/cloud/cloud-handler-group.ts @@ -13,11 +13,14 @@ export const CLOUD_HANDLER_GROUP: HandlerGroup = { 'cloud workspace sleep', 'cloud workspace wake', 'cloud workspace archive', + 'cloud workspace delete', 'cloud workspace destroy', 'cloud message', 'cloud messages', 'cloud sessions', - 'cloud projects list' + 'cloud projects list', + 'cloud routine list', + 'cloud routine run' ], load: async () => (await import('./cloud-handlers.js')).CLOUD_HANDLERS } diff --git a/src/cli/cloud/cloud-handlers.ts b/src/cli/cloud/cloud-handlers.ts index 8ea221b5079..106eee0fb69 100644 --- a/src/cli/cloud/cloud-handlers.ts +++ b/src/cli/cloud/cloud-handlers.ts @@ -1,5 +1,5 @@ // Private build only: `orca cloud …` handlers. They never touch the Orca runtime (ctx.client): they -// call the Orca Cloud public API over HTTPS, so they work inside a VM with no desktop app running. +// call the Orca Cloud public API over HTTPS, so they work inside a sandbox with no desktop app running. import type { CommandHandler } from '../dispatch' import { getOptionalPositiveIntegerFlag, @@ -37,7 +37,6 @@ import { createCloudWorkspace, defaultCloudHandlerDeps, getAgentFlag, - getSizeFlag, normalizeCloudRepoUrl, readMessageFlags, resolveCloudProjectId, @@ -49,6 +48,7 @@ import { } from './cloud-operations' import { cloudLifecycleHandler, type CloudLifecycleAction } from './cloud-lifecycle' +import { createCloudRoutineHandlers } from './cloud-routines' export type { CloudHandlerDeps } from './cloud-operations' @@ -181,7 +181,6 @@ export function createCloudHandlers( if (ref && !repoFlag) { throw new RuntimeClientError('invalid_argument', '--ref needs --repo.', { field: 'ref' }) } - const machineSize = getSizeFlag(flags) const api = cloudClient(deps) const project = getOptionalStringFlag(flags, 'project') const name = getOptionalStringFlag(flags, 'name') @@ -192,7 +191,6 @@ export function createCloudHandlers( ...(repoFlag ? { repo: { url: normalizeCloudRepoUrl(repoFlag), ...(ref ? { ref } : {}) } } : {}), - ...(machineSize ? { machineSize } : {}), ...(region ? { region } : {}), ...(prompt ? { message: { text: prompt, ...(agent ? { agent } : {}) } } : {}) } @@ -202,7 +200,9 @@ export function createCloudHandlers( 'cloud workspace sleep': mutate('sleep'), 'cloud workspace wake': mutate('wake'), 'cloud workspace archive': mutate('archive'), - 'cloud workspace destroy': mutate('destroy'), + 'cloud workspace delete': mutate('delete'), + // Hidden alias kept so scripts written before the rename keep working. + 'cloud workspace destroy': mutate('delete'), 'cloud message': async ({ flags, json }) => { const deps = getDeps() const body = readMessageFlags(flags) @@ -263,7 +263,8 @@ export function createCloudHandlers( const api = cloudClient(deps) const result = await api.request<{ projects: CloudProject[] }>('GET', '/v1/projects') printCloudResult(result, json, formatCloudProjects) - } + }, + ...createCloudRoutineHandlers(getDeps) } } diff --git a/src/cli/cloud/cloud-lifecycle.ts b/src/cli/cloud/cloud-lifecycle.ts index 173bbd143c4..ffc2469ad19 100644 --- a/src/cli/cloud/cloud-lifecycle.ts +++ b/src/cli/cloud/cloud-lifecycle.ts @@ -1,7 +1,9 @@ -// Private build only: `orca cloud workspace sleep|wake|archive|destroy`. Wake and sleep show -// progress on stderr (see cloud-progress.ts) so a multi-second wait is never silent. +// Private build only: `orca cloud workspace sleep|wake|archive|delete` (`destroy` is a hidden alias of +// delete). Wake and sleep show progress on stderr (see cloud-progress.ts) so a multi-second wait is +// never silent. import type { CommandHandler } from '../dispatch' import { getRequiredStringFlag } from '../flags' +import { RuntimeClientError } from '../runtime/types' import { formatCloudWorkspace, printCloudResult, type CloudWorkspace } from './cloud-format' import { MUTATE_TIMEOUT_MS, @@ -12,7 +14,7 @@ import { } from './cloud-operations' import { cloudProgress, readCloudProgressMode } from './cloud-progress' -export type CloudLifecycleAction = 'sleep' | 'wake' | 'archive' | 'destroy' +export type CloudLifecycleAction = 'sleep' | 'wake' | 'archive' | 'delete' export function cloudLifecycleHandler( action: CloudLifecycleAction, @@ -33,8 +35,8 @@ export function cloudLifecycleHandler( } const started = deps.now() const request = api.request<{ workspace: CloudWorkspace; state?: string }>( - action === 'destroy' ? 'DELETE' : 'POST', - action === 'destroy' ? workspacePath(id) : workspacePath(id, `/${action}`), + action === 'delete' ? 'DELETE' : 'POST', + action === 'delete' ? workspacePath(id) : workspacePath(id, `/${action}`), { timeoutMs: MUTATE_TIMEOUT_MS } ) const result = @@ -45,6 +47,14 @@ export function cloudLifecycleHandler( ) : await request const name = result.workspace.name || selector + if (action === 'wake' && result.state === 'failed') { + // The workspace went back to sleep (lastError resume_failed); its disk is untouched. + throw new RuntimeClientError( + 'cloud_wake_failed', + `The last wake didn't finish. Your files are safe. Run: orca cloud workspace wake ${id}`, + { workspace: result.workspace, state: result.state } + ) + } // The API's wake waits ~30 s; past that it answers `waking` and keeps going in the background. const stillWaking = action === 'wake' && (result.state === 'waking' || result.workspace.status === 'waking') @@ -65,7 +75,11 @@ export function cloudLifecycleHandler( }) } printCloudResult({ ...result, elapsedMs: deps.now() - started }, json, (value) => - formatCloudWorkspace(value) + action !== 'delete' + ? formatCloudWorkspace(value, deps.now()) + : value.workspace.status === 'destroyed' + ? `Deleted ${name} (${id}). Its sandbox and files are gone for good.` + : `Deleting ${name} (${id}). Its sandbox and files will be gone for good.` ) } } diff --git a/src/cli/cloud/cloud-operations.ts b/src/cli/cloud/cloud-operations.ts index 01e1b09caec..efac1293246 100644 --- a/src/cli/cloud/cloud-operations.ts +++ b/src/cli/cloud/cloud-operations.ts @@ -32,7 +32,7 @@ export function isCloudAgent(value: string): value is CloudAgent { const WORKSPACE_ID = /^sbx_[A-Za-z0-9]+$/ const PROJECT_ID = /^prj_[A-Za-z0-9]+$/ const SESSION_HANDLE = /^term_[A-Za-z0-9-]{1,80}$/ -/** A create waits for the VM to boot; the control plane bounds that, this only stops a hang. */ +/** A create waits for the sandbox to boot; the control plane bounds that, this only stops a hang. */ export const CREATE_TIMEOUT_MS = 6 * 60_000 export const MUTATE_TIMEOUT_MS = 3 * 60_000 const MESSAGE_POLL_MS = 1500 @@ -89,7 +89,7 @@ export function getAgentFlag( } /** - * `sbx_…` ids pass through; `self` is the workspace this token was minted for (inside a VM); + * `sbx_…` ids pass through; `self` is the workspace this token was minted for (inside a sandbox); * anything else is matched against workspace names this token can see. */ export async function resolveCloudWorkspaceId( @@ -154,7 +154,6 @@ export type CloudWorkspaceCreateInput = { repo?: { url: string; ref?: string } /** Team environment: `env_…` (its active build) or a build `bld_…`. */ environment?: string - machineSize?: 'standard' | 'large' region?: string message?: { text: string; agent?: (typeof CLOUD_AGENTS)[number] } } @@ -168,7 +167,7 @@ export async function createCloudWorkspace( const created = await api.request<{ workspace: CloudWorkspace; message?: CloudMessage }>( 'POST', '/v1/workspaces', - { body: input, timeoutMs: CREATE_TIMEOUT_MS } + { body: input, timeoutMs: CREATE_TIMEOUT_MS, intent: 'create' } ) return { ...created, elapsedMs: now() - started } } @@ -199,18 +198,6 @@ export function normalizeCloudRepoUrl(raw: string): string { return url.toString() } -export function getSizeFlag( - flags: Map -): 'standard' | 'large' | undefined { - const size = getOptionalStringFlag(flags, 'size') - if (size === undefined || size === 'standard' || size === 'large') { - return size - } - throw new RuntimeClientError('invalid_argument', '--size must be standard or large', { - field: 'size' - }) -} - /** Reads `--text` (required) / `--agent` / `--session` for `cloud message`. */ export function readMessageFlags(flags: Map) { const text = getRequiredStringFlag(flags, 'text') @@ -256,7 +243,7 @@ export async function waitForCloudMessage( if (current.status === 'failed') { throw new RuntimeClientError( 'cloud_message_failed', - `Message ${current.id} could not be delivered: ${current.error ?? 'unknown error'}.`, + `Message ${current.id} couldn't be delivered to the agent.`, { message: current } ) } diff --git a/src/cli/cloud/cloud-progress.test.ts b/src/cli/cloud/cloud-progress.test.ts index 85c2ba2ebb9..564272e2629 100644 --- a/src/cli/cloud/cloud-progress.test.ts +++ b/src/cli/cloud/cloud-progress.test.ts @@ -88,7 +88,7 @@ describe('orca cloud workspace wake progress', () => { ) await run(handlers['cloud workspace wake'](ctx({ workspace: 'sbx_ab12' })), 5000) expect(stderr).toEqual(['- Waking sbx_ab12...', '- child is awake (took 4.8s).']) - expect(stdout.join('\n')).toContain('status: running') + expect(stdout.join('\n')).toContain('State: Running') }) it('adds one reassurance line at 10 s', async () => { @@ -155,8 +155,8 @@ describe('worktree create --on cloud progress', () => { 13_000 ) expect(stderr).toEqual([ - '- Creating an Orca Cloud workspace...', - '- Still starting (10s). This is taking longer than usual; your files are safe.', + '- Starting your cloud workspace...', + '- Still starting (10s). This is taking longer than usual.', '- Workspace sbx_ab12 is running (took 12.0s).' ]) }) @@ -168,7 +168,7 @@ describe('worktree create --on cloud progress', () => { 7000 ) expect(stderr).toEqual([ - '- Creating an Orca Cloud workspace...', + '- Starting your cloud workspace...', '- Workspace sbx_ab12 is running (took 6.0s).' ]) }) diff --git a/src/cli/cloud/cloud-routines.ts b/src/cli/cloud/cloud-routines.ts new file mode 100644 index 00000000000..01c26f50370 --- /dev/null +++ b/src/cli/cloud/cloud-routines.ts @@ -0,0 +1,220 @@ +// Private build only: `orca cloud routine list|run`. Routines live on the control plane +// (GET /v1/routines, POST /v1/routines/:id/run, GET /v1/routines/:id/runs/:runId); each run starts +// its own cloud workspace. Human output uses the glossary's run states; --json prints the API view. +import type { CommandHandler } from '../dispatch' +import { getOptionalPositiveIntegerFlag, getRequiredStringFlag } from '../flags' +import { RuntimeClientError } from '../runtime/types' +import type { + Routine, + RoutineRun, + RoutineRunStatus +} from '../../shared/cloud-api/cloud-api-routine-types' +import { formatAutomationSchedule } from '../../shared/automations/scheduling/automation-schedules' +import type { CloudApiClient } from './cloud-api-client' +import { ago, formatElapsed, printCloudResult, table } from './cloud-format' +import { cloudClient, type CloudHandlerDeps } from './cloud-operations' +import { cloudProgress, readCloudProgressMode } from './cloud-progress' + +const ROUTINE_ID = /^rtn_[A-Za-z0-9_-]+$/ +const RUN_POLL_MS = 5000 +/** --wait without --timeout: the routine's own time limit plus room to start and post results. */ +const WAIT_SLACK_MS = 15 * 60_000 +const DEFAULT_RUNTIME_MINUTES = 60 + +const RUN_STATE_LABELS: ReadonlyMap = new Map([ + ['queued', 'Queued'], + ['starting', 'Starting'], + ['running', 'Running'], + ['posting', 'Posting results'], + ['succeeded', 'Succeeded'], + ['failed', 'Failed'], + ['cancelled', 'Canceled'], + ['timed_out', 'Timed out'] +]) + +const FINISHED: ReadonlySet = new Set(['succeeded', 'failed', 'cancelled', 'timed_out']) + +export function routineRunStateLabel(status: string): string { + return RUN_STATE_LABELS.get(status) ?? 'Unknown' +} + +/** A failed run's error code in words (codes stay in --json). */ +export function routineRunErrorCopy(error: string | null): string { + const code = error ?? '' + if (code.startsWith('start_failed')) { + return "The workspace couldn't start. Nothing was charged." + } + if (code.startsWith('workspace_lost')) { + return 'The workspace went to sleep or was deleted before the run finished.' + } + if (code.startsWith('post_failed')) { + return "The run finished, but Orca couldn't post the results." + } + if (code === 'queue_expired') { + return 'The run waited too long to start and was skipped.' + } + if (code.endsWith('_interrupted')) { + return 'Orca Cloud restarted during the run.' + } + if (code === 'routine_changed') { + return 'The routine changed while this run was queued.' + } + return 'The run failed.' +} + +function describeTrigger(trigger: Routine['trigger']): string { + if (trigger.kind === 'schedule') { + return `${formatAutomationSchedule(trigger.cron)} (${trigger.timezone})` + } + if (trigger.kind === 'webhook') { + return 'Webhook' + } + return 'GitHub' +} + +export function formatRoutineList(value: { routines: Routine[] }, now = Date.now()): string { + if (value.routines.length === 0) { + return 'No routines yet. Create one in the Orca app.' + } + return table( + ['ID', 'NAME', 'WHEN', 'LAST RUN'], + value.routines.map((r) => [ + r.id, + r.enabled ? r.name : `${r.name} (paused)`, + describeTrigger(r.trigger), + r.lastRun + ? `${routineRunStateLabel(r.lastRun.status)}${r.lastRun.finishedAt ? ` ${ago(r.lastRun.finishedAt, now)}` : ''}` + : 'Never run' + ]) + ) +} + +export function formatRoutineRun(value: { + routine: Pick + run: RoutineRun +}): string { + const { run } = value + const lines = [ + `${value.routine.name}: ${routineRunStateLabel(run.status)} (${run.id})`, + ...(run.status === 'failed' ? [routineRunErrorCopy(run.error)] : []), + ...(run.status === 'timed_out' ? ['The run hit its time limit.'] : []), + ...(run.durationMs !== null ? [`Took ${formatElapsed(run.durationMs)}`] : []), + ...(run.result?.prUrl ? [`Pull request: ${run.result.prUrl}`] : []), + ...(run.result?.commentUrl ? [`Comment: ${run.result.commentUrl}`] : []), + ...(run.workspaceId ? [`Workspace: ${run.workspaceId}`] : []), + ...(run.result?.summary ? ['', run.result.summary] : []) + ] + if (!FINISHED.has(run.status)) { + lines.push('Add --wait to follow a run until it finishes.') + } + return lines.join('\n') +} + +async function resolveRoutine(api: CloudApiClient, selector: string): Promise { + if (ROUTINE_ID.test(selector)) { + return ( + await api.request<{ routine: Routine }>('GET', `/v1/routines/${encodeURIComponent(selector)}`) + ).routine + } + const { routines } = await api.request<{ routines: Routine[] }>('GET', '/v1/routines') + const matches = routines.filter((r) => r.name === selector) + if (matches.length === 1) { + return matches[0] + } + if (matches.length === 0) { + throw new RuntimeClientError('cloud_not_found', `No routine named "${selector}".`, { + nextSteps: ['Run `orca cloud routine list` and pass the routine id (rtn_…).'] + }) + } + throw new RuntimeClientError( + 'selector_ambiguous', + `${matches.length} routines are named "${selector}". Pass the id instead.`, + { choices: matches.map((r) => ({ id: r.id, name: r.name })) } + ) +} + +function runFinishedError(routine: Routine, run: RoutineRun): RuntimeClientError | null { + if (run.status === 'failed') { + return new RuntimeClientError('cloud_routine_run_failed', routineRunErrorCopy(run.error), { + run + }) + } + if (run.status === 'timed_out') { + return new RuntimeClientError( + 'cloud_routine_run_timed_out', + `The run hit ${routine.name}'s time limit.`, + { run } + ) + } + if (run.status === 'cancelled') { + return new RuntimeClientError('cloud_routine_run_canceled', 'The run was canceled.', { run }) + } + return null +} + +export function createCloudRoutineHandlers( + getDeps: () => CloudHandlerDeps +): Record { + return { + 'cloud routine list': async ({ json }) => { + const deps = getDeps() + const api = cloudClient(deps) + const result = await api.request<{ routines: Routine[] }>('GET', '/v1/routines') + printCloudResult(result, json, (value) => formatRoutineList(value, deps.now())) + }, + 'cloud routine run': async ({ flags, json }) => { + const deps = getDeps() + const wait = flags.get('wait') === true + const timeoutSeconds = getOptionalPositiveIntegerFlag(flags, 'timeout') + if (timeoutSeconds !== undefined && !wait) { + throw new RuntimeClientError('invalid_argument', '--timeout needs --wait.', { + field: 'timeout' + }) + } + const progress = cloudProgress(wait ? readCloudProgressMode(flags, json) : 'none', deps.now) + const api = cloudClient(deps) + const routine = await resolveRoutine(api, getRequiredStringFlag(flags, 'routine')) + const routinePath = `/v1/routines/${encodeURIComponent(routine.id)}` + let { run } = await api.request<{ run: RoutineRun }>('POST', `${routinePath}/run`) + if (wait) { + const limitMs = + timeoutSeconds !== undefined + ? timeoutSeconds * 1000 + : (routine.maxRuntimeMinutes ?? DEFAULT_RUNTIME_MINUTES) * 60_000 + WAIT_SLACK_MS + const deadline = deps.now() + limitMs + progress.phase(run.status, `${routine.name}: ${routineRunStateLabel(run.status)}`, { + runId: run.id + }) + while (!FINISHED.has(run.status)) { + if (deps.now() >= deadline) { + throw new RuntimeClientError( + 'cloud_routine_run_wait_timeout', + `The run is still ${routineRunStateLabel(run.status).toLowerCase()} after ${formatElapsed(limitMs)}. It keeps going in Orca Cloud.`, + { run } + ) + } + await deps.sleep(RUN_POLL_MS) + const previous = run.status + run = ( + await api.request<{ run: RoutineRun }>( + 'GET', + `${routinePath}/runs/${encodeURIComponent(run.id)}` + ) + ).run + if (run.status !== previous) { + progress.phase(run.status, `${routine.name}: ${routineRunStateLabel(run.status)}`, { + runId: run.id + }) + } + } + const failure = runFinishedError(routine, run) + if (failure) { + throw failure + } + } + printCloudResult({ routine: { id: routine.id, name: routine.name }, run }, json, (value) => + formatRoutineRun(value) + ) + } + } +} diff --git a/src/cli/cloud/cloud-specs.ts b/src/cli/cloud/cloud-specs.ts index c384ff14620..12dac23ff33 100644 --- a/src/cli/cloud/cloud-specs.ts +++ b/src/cli/cloud/cloud-specs.ts @@ -1,9 +1,10 @@ // Private build only: `orca cloud …` command specs. import type { CommandSpec } from '../args' import { LOCAL_COMMAND_FLAGS } from '../args' +import { ORCA_CLOUD_SANDBOX_SPEC } from '../../shared/hosted-sandbox/hosted-sandbox-wire' const CREDENTIALS_NOTE = - 'Credentials: ORCA_CLOUD_TOKEN (+ ORCA_CLOUD_API_URL), else ~/.config/orca-cloud/credentials.json (written by `orca cloud login`, and at boot inside an Orca Cloud workspace when the organization allows in-workspace CLI access). These commands call Orca Cloud over HTTPS and do not need the Orca app running.' + 'Credentials: ORCA_CLOUD_TOKEN (+ ORCA_CLOUD_API_URL), else ~/.config/orca-cloud/credentials.json (written by `orca cloud login`, and at boot inside an Orca Cloud workspace when the team allows in-workspace CLI access). These commands call Orca Cloud over HTTPS and do not need the Orca app running.' const WORKSPACE_ARG_NOTE = ' is a workspace id (sbx_…), a workspace name, or `self` inside an Orca Cloud workspace.' const JSON_NOTE = @@ -12,9 +13,10 @@ const JSON_NOTE = const PROGRESS_ACTIONS: ReadonlySet = new Set(['sleep', 'wake']) const lifecycle = ( - action: 'sleep' | 'wake' | 'archive' | 'destroy', + action: 'sleep' | 'wake' | 'archive' | 'delete' | 'destroy', summary: string, - notes: string[] = [] + notes: string[] = [], + extra: Partial = {} ): CommandSpec => ({ path: ['cloud', 'workspace', action], summary, @@ -25,7 +27,7 @@ const lifecycle = ( ...(PROGRESS_ACTIONS.has(action) ? ['progress'] : []) ], positionalArgs: ['workspace'], - ...(action === 'destroy' ? { destructive: true } : {}), + ...(action === 'delete' || action === 'destroy' ? { destructive: true } : {}), notes: [ ...notes, ...(PROGRESS_ACTIONS.has(action) @@ -34,9 +36,10 @@ const lifecycle = ( ] : []), WORKSPACE_ARG_NOTE, - 'A workspace token cannot sleep, archive or destroy its own workspace.' + 'A workspace token cannot sleep, archive or delete its own workspace.' ], - examples: [`orca cloud workspace ${action} sbx_0123abcd --json`] + examples: [`orca cloud workspace ${action} sbx_0123abcd --json`], + ...extra }) export const CLOUD_COMMAND_SPECS: CommandSpec[] = [ @@ -78,7 +81,7 @@ export const CLOUD_COMMAND_SPECS: CommandSpec[] = [ allowedFlags: [...LOCAL_COMMAND_FLAGS, 'project', 'include-archived', 'all'], notes: [ '--all also lists archived and hidden workspaces.', - 'A workspace token (inside a VM) lists only the workspaces that workspace created.', + 'A workspace token (inside a sandbox) lists only the workspaces that workspace created.', JSON_NOTE ], examples: ['orca cloud workspace list', 'orca cloud workspace list --all --json'] @@ -103,14 +106,14 @@ export const CLOUD_COMMAND_SPECS: CommandSpec[] = [ 'project', 'repo', 'ref', - 'size', 'region', 'agent', 'prompt' ], notes: [ - 'Returns once the VM is running. --prompt queues a first message for --agent (default claude), delivered as soon as the VM is up; follow it with `orca cloud messages`.', - 'Inside a workspace (workspace token) the new workspace is recorded with origin "vm" and is visible to the workspace that created it.', + 'Returns once the sandbox is running. --prompt queues a first message for --agent (default claude), delivered as soon as the sandbox is up; follow it with `orca cloud messages`.', + `Every sandbox is ${ORCA_CLOUD_SANDBOX_SPEC.vcpus} vCPU · ${ORCA_CLOUD_SANDBOX_SPEC.memoryGb} GB; there is no size to pick.`, + 'Inside a workspace (workspace token) the new workspace is visible to the workspace that created it.', CREDENTIALS_NOTE, JSON_NOTE ], @@ -119,10 +122,19 @@ export const CLOUD_COMMAND_SPECS: CommandSpec[] = [ 'orca cloud workspace create --repo https://github.com/acme/app --name fix-login --agent claude --prompt "Fix the login redirect"' ] }, - lifecycle('sleep', 'Put an Orca Cloud workspace to sleep (disk kept, not billed)'), - lifecycle('wake', 'Wake a sleeping or archived Orca Cloud workspace'), - lifecycle('archive', 'Sleep an Orca Cloud workspace and hide it from default lists'), - lifecycle('destroy', 'Destroy an Orca Cloud workspace and its disk', ['This cannot be undone.']), + lifecycle( + 'sleep', + 'Put an Orca Cloud workspace to sleep (files are kept; asleep time is not billed)' + ), + lifecycle('wake', 'Wake an asleep or archived Orca Cloud workspace'), + lifecycle('archive', 'Put an Orca Cloud workspace to sleep and hide it from default lists'), + lifecycle('delete', 'Delete an Orca Cloud workspace and its sandbox for good', [ + 'This cannot be undone.' + ]), + // Renamed to `delete`; kept hidden so existing scripts keep working. + lifecycle('destroy', 'Delete an Orca Cloud workspace and its sandbox for good', [], { + hidden: true + }), { path: ['cloud', 'message'], summary: 'Send a message to an agent in an Orca Cloud workspace', @@ -140,7 +152,7 @@ export const CLOUD_COMMAND_SPECS: CommandSpec[] = [ positionalArgs: ['workspace'], notes: [ 'Without --session a new agent session starts with the text as its prompt; --session (from `orca cloud sessions` or a previous message) types it into that session.', - 'A sleeping workspace is woken first. --wait polls until the message is delivered to the agent (default timeout 180s); it does not wait for the agent to finish.', + 'An asleep workspace wakes first. --wait polls until the message is delivered to the agent (default timeout 180s); it does not wait for the agent to finish.', WORKSPACE_ARG_NOTE, JSON_NOTE ], @@ -169,7 +181,7 @@ export const CLOUD_COMMAND_SPECS: CommandSpec[] = [ allowedFlags: [...LOCAL_COMMAND_FLAGS, 'workspace'], positionalArgs: ['workspace'], notes: [ - 'Only a running workspace has live sessions; a sleeping one lists none.', + 'Only a running workspace has live sessions; an asleep one lists none.', WORKSPACE_ARG_NOTE, JSON_NOTE ], @@ -181,5 +193,31 @@ export const CLOUD_COMMAND_SPECS: CommandSpec[] = [ usage: 'orca cloud projects list [--json]', allowedFlags: [...LOCAL_COMMAND_FLAGS], notes: [JSON_NOTE] + }, + { + path: ['cloud', 'routine', 'list'], + summary: 'List Orca Cloud routines with their trigger and last run', + usage: 'orca cloud routine list [--json]', + allowedFlags: [...LOCAL_COMMAND_FLAGS], + notes: ['Needs the routines:read scope.', JSON_NOTE], + examples: ['orca cloud routine list', 'orca cloud routine list --json'] + }, + { + path: ['cloud', 'routine', 'run'], + summary: 'Run an Orca Cloud routine now', + usage: + 'orca cloud routine run [--wait [--timeout ] [--progress text|json|none]] [--json]', + allowedFlags: [...LOCAL_COMMAND_FLAGS, 'routine', 'wait', 'timeout', 'progress'], + positionalArgs: ['routine'], + notes: [ + ' is a routine id (rtn_…) or its exact name. Only the routine’s creator can run it. Needs the routines:write scope.', + 'The run starts its own cloud workspace. Run states: Queued, Starting, Running, Posting results, Succeeded, Failed, Canceled, Timed out.', + '--wait follows the run until it finishes (default timeout: the routine’s time limit plus 15 minutes) and exits non-zero if it fails, times out or is canceled. State changes go to stderr.', + JSON_NOTE + ], + examples: [ + 'orca cloud routine run "Triage new issues"', + 'orca cloud routine run rtn_0123abcd --wait --json' + ] } ] diff --git a/src/cli/cloud/index-cloud-commands.test.ts b/src/cli/cloud/index-cloud-commands.test.ts index ee83e53edf6..3e57e7817d5 100644 --- a/src/cli/cloud/index-cloud-commands.test.ts +++ b/src/cli/cloud/index-cloud-commands.test.ts @@ -104,7 +104,8 @@ describe('orca cloud via main()', () => { expect(process.exitCode).toBe(1) const body = JSON.parse(out.join('')) expect(body).toMatchObject({ ok: false, error: { code: 'cloud_vm_cli_disabled' } }) - expect(body.error.data.nextSteps[0]).toContain('vmCliEnabled') + expect(body.error.data).toMatchObject({ setting: 'vmCliEnabled' }) + expect(body.error.data.nextSteps[0]).toContain('Ask a team owner or admin') }) it('prints a readable error without --json', async () => { @@ -125,5 +126,140 @@ describe('orca cloud via main()', () => { it('shows help for the cloud group', async () => { await main(['cloud', '--help'], home) expect(out.join('')).toMatch(/workspace create +Create an Orca Cloud workspace/) + expect(out.join('')).toMatch( + /workspace delete +Delete an Orca Cloud workspace and its sandbox for good/ + ) + expect(out.join('')).toMatch(/routine run +Run an Orca Cloud routine now/) + // `destroy` still works but is hidden from help. + expect(out.join('')).not.toContain('workspace destroy') + }) + + it('deletes with `workspace delete` and the hidden `destroy` alias', async () => { + fetchMock.mockImplementation(async () => + Response.json({ workspace: { id: 'sbx_d1', name: 'old', status: 'destroyed' } }) + ) + await main(['cloud', 'workspace', 'delete', 'sbx_d1'], home) + expect(process.exitCode).toBeUndefined() + expect(out.join('\n')).toContain( + 'Deleted old (sbx_d1). Its sandbox and files are gone for good.' + ) + await main(['cloud', 'workspace', 'destroy', 'sbx_d1', '--json'], home) + expect(process.exitCode).toBeUndefined() + expect(fetchMock.mock.calls.map(([url, init]) => `${init?.method} ${url}`)).toEqual([ + 'DELETE https://cloud.test/v1/workspaces/sbx_d1', + 'DELETE https://cloud.test/v1/workspaces/sbx_d1' + ]) + }) + + it('rejects --size on workspace create before any request', async () => { + await main(['cloud', 'workspace', 'create', '--size', 'large', '--json'], home) + expect(process.exitCode).toBe(1) + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('lists workspaces with glossary states and keeps raw statuses for --json', async () => { + const listed = { + workspaces: [ + { + id: 'sbx_l1', + name: 'api', + status: 'sleeping', + archived: true, + repoUrl: 'https://github.com/acme/api.git', + repoBranch: 'main', + lastActivityAt: Date.now() - 120_000, + createdAt: 1, + updatedAt: 1 + } + ] + } + fetchMock.mockImplementation(async () => Response.json(listed)) + await main(['cloud', 'workspace', 'list'], home) + const text = out.join('\n') + expect(text).toMatch(/^ID +NAME +STATE +REPO +BRANCH +LAST ACTIVE$/m) + expect(text).toMatch(/sbx_l1 +api +Archived +acme\/api +main +2m ago/) + expect(text).not.toContain('sleeping') + out = [] + await main(['cloud', 'workspace', 'list', '--json'], home) + expect(JSON.parse(out.join(''))).toMatchObject({ + result: { workspaces: [{ status: 'sleeping', archived: true }] } + }) + }) + + it('prints glossary error copy for admin-only, rate-limited and out-of-hours errors', async () => { + fetchMock.mockResolvedValueOnce( + Response.json({ error: 'forbidden', reason: 'admin_required' }, { status: 403 }) + ) + await main(['cloud', 'workspace', 'list'], home) + expect(err.join('\n')).toContain('Only a team owner or admin can do this.') + err = [] + fetchMock.mockResolvedValueOnce( + Response.json({ error: 'rate_limited' }, { status: 429, headers: { 'retry-after': '7' } }) + ) + await main(['cloud', 'workspace', 'list'], home) + expect(err.join('\n')).toContain('Try again in 7 seconds.') + err = [] + fetchMock.mockResolvedValueOnce( + Response.json( + { error: 'entitlement_denied', reason: 'included_hours_exhausted' }, + { status: 403 } + ) + ) + await main(['cloud', 'workspace', 'create', '--name', 'x'], home) + expect(err.join('\n')).toContain( + "Your team is out of sandbox hours. Nothing was created, and you weren't charged." + ) + expect(err.join('\n')).toContain('Ask an owner or admin to add hours.') + expect(err.join('\n')).not.toMatch(/entitlement_denied|included_hours_exhausted|files are safe/) + }) + + it('runs a routine by name and follows it with --wait', async () => { + const routine = { + id: 'rtn_r1', + name: 'Triage', + enabled: true, + trigger: { kind: 'webhook' }, + maxRuntimeMinutes: 30 + } + const statuses = ['running', 'posting', 'succeeded'] + fetchMock.mockImplementation(async (input, init) => { + const url = String(input) + if (url.endsWith('/v1/routines')) { + return Response.json({ routines: [routine] }) + } + if (url.endsWith('/v1/routines/rtn_r1/run') && init?.method === 'POST') { + return Response.json( + { run: { id: 'run_1', status: 'queued', result: null, durationMs: null } }, + { status: 202 } + ) + } + const status = statuses.shift() ?? 'succeeded' + return Response.json({ + run: { + id: 'run_1', + status, + durationMs: status === 'succeeded' ? 102_000 : null, + result: status === 'succeeded' ? { prUrl: 'https://github.com/acme/api/pull/7' } : null + } + }) + }) + vi.useFakeTimers({ toFake: ['setTimeout'] }) + try { + const done = main(['cloud', 'routine', 'run', 'Triage', '--wait'], home) + await vi.runAllTimersAsync() + await done + } finally { + vi.useRealTimers() + } + expect(process.exitCode).toBeUndefined() + expect(err).toEqual([ + '- Triage: Queued', + '- Triage: Running', + '- Triage: Posting results', + '- Triage: Succeeded' + ]) + expect(out.join('\n')).toContain('Triage: Succeeded (run_1)') + expect(out.join('\n')).toContain('Took 1m 42s') + expect(out.join('\n')).toContain('Pull request: https://github.com/acme/api/pull/7') }) }) diff --git a/src/cli/cloud/index-worktree-create-on-cloud.test.ts b/src/cli/cloud/index-worktree-create-on-cloud.test.ts index 786f902adbb..8f326c53f3f 100644 --- a/src/cli/cloud/index-worktree-create-on-cloud.test.ts +++ b/src/cli/cloud/index-worktree-create-on-cloud.test.ts @@ -147,10 +147,21 @@ describe('orca worktree create --on cloud via main()', () => { [ { error: 'entitlement_denied', reason: 'included_hours_exhausted' }, 'cloud_out_of_hours', - 'out of sandbox hours' + "Your team is out of sandbox hours. Nothing was created, and you weren't charged." + ], + [ + { error: 'entitlement_denied', reason: 'overage_cap_reached' }, + 'cloud_spend_cap_reached', + "Your team reached its monthly spend cap. Nothing was created, and you weren't charged." + ], + [ + { error: 'conflict', reason: 'concurrent_transition' }, + 'cloud_conflict', + 'This workspace is still starting or going to sleep. Nothing was changed. Try again in a moment.', + 409 ] - ])('maps %o to %s with a next step', async (body, code, text) => { - fetchMock.mockResolvedValue(Response.json(body, { status: 403 })) + ])('maps %o to %s with a next step', async (body, code, text, status = 403) => { + fetchMock.mockResolvedValue(Response.json(body, { status })) await main( ['worktree', 'create', '--on', 'cloud', '--repo', 'https://github.com/acme/app', '--json'], home @@ -184,4 +195,39 @@ describe('orca worktree create --on cloud via main()', () => { expect(fetchMock).not.toHaveBeenCalled() expect(runtimeClientConstructorMock).not.toHaveBeenCalled() }) + + it('rejects --size before any request (there is one sandbox size)', async () => { + await main(['worktree', 'create', '--on', 'cloud', '--size', 'large', '--json'], home) + expect(process.exitCode).not.toBeUndefined() + expect(JSON.parse(printed())).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('prints the glossary state and the sandbox size without --json, never the raw status', async () => { + fetchMock.mockResolvedValue( + Response.json( + { + workspace: { + id: 'sbx_on3', + name: 'fix', + status: 'running', + archived: false, + origin: 'api', + repoUrl: 'https://github.com/acme/app', + createdAt: 1, + updatedAt: 1 + } + }, + { status: 201 } + ) + ) + await main( + ['worktree', 'create', '--on', 'cloud', '--repo', 'https://github.com/acme/app'], + home + ) + expect(process.exitCode).toBeUndefined() + expect(printed()).toContain('State: Running') + expect(printed()).toContain('Sandbox size: 8 vCPU · 16 GB') + expect(printed()).not.toMatch(/status: running|standard/) + }) }) diff --git a/src/cli/cloud/worktree-create-on-cloud.test.ts b/src/cli/cloud/worktree-create-on-cloud.test.ts index 38759a98369..3c70ed2201d 100644 --- a/src/cli/cloud/worktree-create-on-cloud.test.ts +++ b/src/cli/cloud/worktree-create-on-cloud.test.ts @@ -140,7 +140,7 @@ describe('worktree create --on cloud', () => { () => deps ) expect(bodies[0]).toEqual({ name: 't', projectId: 'prj_9' }) - expect(errs[0]).toContain('Creating an Orca Cloud workspace') + expect(errs[0]).toContain('Starting your cloud workspace') }) it('refuses flags and agents a cloud workspace cannot honour, before any request', async () => { diff --git a/src/cli/cloud/worktree-create-on-cloud.ts b/src/cli/cloud/worktree-create-on-cloud.ts index f9d57322e62..927296b5fc5 100644 --- a/src/cli/cloud/worktree-create-on-cloud.ts +++ b/src/cli/cloud/worktree-create-on-cloud.ts @@ -3,21 +3,20 @@ // [--agent claude|codex --prompt ] [--json] // --on cloud: uses an Orca Cloud project's repo and environment defaults. // It creates an Orca Cloud workspace through the public API with the same credentials as -// `orca cloud …`, so it works on a desktop and inside a VM (no Orca runtime involved). +// `orca cloud …`, so it works on a desktop and inside a sandbox (no Orca runtime involved). import { runProcessSync } from '@orca/process-host' import { existsSync } from 'node:fs' import { isAbsolute, resolve } from 'node:path' import type { HandlerContext } from '../dispatch' import { getOptionalStringFlag } from '../flags' import { RuntimeClientError } from '../runtime/types' -import { formatCloudWorkspace, printCloudResult } from './cloud-format' +import { cloudWorkspaceStateLabel, formatCloudWorkspace, printCloudResult } from './cloud-format' import { cloudProgress, readCloudProgressMode } from './cloud-progress' import { CLOUD_AGENTS, cloudClient, createCloudWorkspace, defaultCloudHandlerDeps, - getSizeFlag, isCloudAgent, normalizeCloudRepoUrl, resolveCloudProjectId, @@ -33,7 +32,6 @@ const SUPPORTED = new Set([ 'name', 'repo', 'base-branch', - 'size', 'agent', 'prompt', 'env', @@ -137,7 +135,7 @@ export async function createWorktreeOnCloud( if (unsupported.length > 0) { throw new RuntimeClientError( 'invalid_argument', - `--${unsupported[0]} doesn't apply to --on cloud. Supported: --name, --repo, --base-branch, --env, --size, --agent/--prompt.`, + `--${unsupported[0]} doesn't apply to --on cloud. Supported: --name, --repo, --base-branch, --env, --agent/--prompt.`, { field: unsupported[0] } ) } @@ -157,7 +155,6 @@ export async function createWorktreeOnCloud( } const progress = readCloudProgressMode(flags, json) const deps = getDeps() - const machineSize = getSizeFlag(flags) const ref = getOptionalStringFlag(flags, 'base-branch') const repo = target.project ? null : resolveCloudRepo(flags, cwd, deps.originUrl) if (ref && !repo && !target.project) { @@ -184,21 +181,20 @@ export async function createWorktreeOnCloud( ...(environment ? { environment } : {}), ...(target.project ? { projectId: await resolveCloudProjectId(api, target.project) } : {}), ...(repo ? { repo: { url: repo.url, ...(ref ? { ref } : {}) } } : {}), - ...(machineSize ? { machineSize } : {}), ...(prompt && agent ? { message: { text: prompt, agent } } : {}) } const progressLines = cloudProgress(progress) progressLines.phase( 'create', - `Creating an Orca Cloud workspace${repo ? ` from ${repo.url}` : ''}...` + `Starting your cloud workspace${repo ? ` from ${repo.url}` : ''}...` ) const created = await progressLines.track( createCloudWorkspace(api, input, deps.now), - (s) => `Still starting (${s}s). This is taking longer than usual; your files are safe.` + (s) => `Still starting (${s}s). This is taking longer than usual.` ) progressLines.phase( 'ready', - `Workspace ${created.workspace.id} is ${created.workspace.status} (took ${progressLines.elapsedSeconds()}s).`, + `Workspace ${created.workspace.id} is ${cloudWorkspaceStateLabel(created.workspace).toLowerCase()} (took ${progressLines.elapsedSeconds()}s).`, { workspaceId: created.workspace.id } ) printCloudResult( @@ -224,7 +220,7 @@ export async function maybeCreateWorktreeOnCloud( context: Pick ): Promise { const { flags } = context - if (!flags.has('on') && !flags.has('env') && !flags.has('size') && !flags.has('progress')) { + if (!flags.has('on') && !flags.has('env') && !flags.has('progress')) { return false } if (!readCloudOnTarget(flags)) { @@ -232,7 +228,7 @@ export async function maybeCreateWorktreeOnCloud( 'invalid_argument', flags.has('on') ? '--on supports `cloud` or `cloud:` in this build.' - : '--env, --size and --progress apply to `--on cloud`.', + : '--env and --progress apply to `--on cloud`.', { field: flags.has('on') ? 'on' : 'env' } ) } diff --git a/src/cli/handlers/cloud-env-format.ts b/src/cli/handlers/cloud-env-format.ts index 373c5a1bc2a..94ca047581d 100644 --- a/src/cli/handlers/cloud-env-format.ts +++ b/src/cli/handlers/cloud-env-format.ts @@ -15,11 +15,34 @@ export function formatOutcome(build: HostedEnvironmentBuildView): string { } if (build.status === 'failed') { const step = build.failedStep ? ` at the ${build.failedStep} step` : '' - return `Build #${build.number} failed${step}: ${build.error ?? 'unknown error'}.` + return `Build #${build.number} failed${step}. ${buildErrorText(build.error)}` } return `Build #${build.number} is ${build.status}.` } +/** A build's error code in words (mirrors the desktop's buildErrorCopy); --json keeps the code. */ +export function buildErrorText(error: string | null): string { + if (error === 'install_failed' || (error !== null && /^exit_\d+$/.test(error))) { + return 'The install script stopped at a failing command.' + } + if (error !== null && /^provider_\d+$/.test(error)) { + return "Orca Cloud couldn't start a sandbox. Try again in a few minutes." + } + const known: Record = { + clone_failed: + "A repository couldn't be cloned. Check that the Orca GitHub app can access it and the branch exists.", + record_failed: "Orca couldn't record the installed environment.", + timeout: 'The build ran past its time limit.', + snapshot_failed: 'Saving the snapshot failed.', + runtime_removed: 'The build sandbox was removed before it finished.', + boot_failed: 'The build sandbox failed to start.', + boot_timeout: 'The build sandbox took too long to start.', + vm_lost: 'Orca lost contact with the build sandbox.', + canceled: 'The build was canceled.' + } + return (error !== null && known[error]) || 'Something went wrong during the build.' +} + export function formatShow(data: CloudEnvironmentShowData): string { const env = data.environment const lines = [ @@ -75,10 +98,8 @@ function describeStaleness(recommendation: string, configChanged: boolean): stri function describeBuild(build: HostedEnvironmentBuildView): string { const parts = [`#${build.number} ${build.status}`] - if (build.status === 'failed') { - parts.push( - `${build.failedStep ? `at ${build.failedStep}` : ''}${build.error ? ` (${build.error})` : ''}`.trim() - ) + if (build.status === 'failed' && build.failedStep) { + parts.push(`at ${build.failedStep}`) } if (build.durationMs !== null) { parts.push(formatDuration(build.durationMs)) @@ -94,7 +115,7 @@ export function formatBuilds(data: CloudEnvironmentBuildsData): string { } const outcomes = data.builds.map((build) => build.status === 'failed' - ? `failed${build.failedStep ? ` at ${build.failedStep}` : ''}${build.error ? ` (${build.error})` : ''}` + ? `failed${build.failedStep ? ` at ${build.failedStep}` : ''}` : build.status ) // Column width from the widest outcome, so a long failure never shifts the columns after it. diff --git a/src/cli/handlers/cloud-env.test.ts b/src/cli/handlers/cloud-env.test.ts index a8a9ab1b805..eca606ee731 100644 --- a/src/cli/handlers/cloud-env.test.ts +++ b/src/cli/handlers/cloud-env.test.ts @@ -89,7 +89,9 @@ describe('orca cloud env build --wait', () => { await CLOUD_ENV_HANDLERS['cloud env build'](ctx) expect(stdout).toContain('::orca-step:: install') expect(stderr).toContain('npm ERR! missing') - expect(stderr).toContain('Build #7 failed at the install step: install_failed.') + expect(stderr).toContain( + 'Build #7 failed at the install step. The install script stopped at a failing command.' + ) expect(process.exitCode).toBe(1) }) diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index b28fd7feb1c..5f6b519ec27 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -87,12 +87,13 @@ export const ROOT_HELP_TEXT_PRIMARY = [ '', 'Orca Cloud:', ' cloud whoami Show the Orca Cloud account these credentials act as', - ' cloud login Save an Orca Cloud API key for the CLI', - ' cloud workspace List, show, create, sleep, wake, archive or destroy workspaces', + ' cloud login Save an Orca API key for the CLI', + ' cloud workspace List, show, create, sleep, wake, archive or delete workspaces', ' cloud message Send a message to an agent in a cloud workspace', ' cloud messages List or show messages sent to a cloud workspace', ' cloud sessions List agent sessions in a cloud workspace', ' cloud projects list List Orca Cloud projects', + ' cloud routine List Orca Cloud routines or run one now', '', 'Automations:', ' automations list List scheduled Orca automations', diff --git a/src/cli/specs/worktree-create.ts b/src/cli/specs/worktree-create.ts index 4d0df971e34..db656bb0579 100644 --- a/src/cli/specs/worktree-create.ts +++ b/src/cli/specs/worktree-create.ts @@ -39,7 +39,6 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { // Private build: `--on cloud` creates an Orca Cloud workspace (src/cli/cloud/worktree-create-on-cloud.ts). 'on', 'env', - 'size', 'progress' ], notes: [