From a985348edea775773db3fca6fb68b9a591fa5c49 Mon Sep 17 00:00:00 2001 From: ahokik Date: Tue, 20 Oct 2026 19:01:53 +0100 Subject: [PATCH] CLI v1.5.0: orca sessions sleep puts a session's sandbox to sleep now (D6.7) - sessions sleep [--no-wait]: POST /api/sessions/{id}/sandbox/sleep, then reads GET /api/sessions/{id}/sandbox every second for up to 10 minutes. Exit 0 for asleep, already asleep, none, --no-wait and the 10-minute limit; exit 1 with the server's message for too_large, failed, interrupted and a 409 refusal. --json prints the final session.sandbox. - sessions get and get_session gain sandbox (the state), left out when the server cannot say. - MCP tool sleep_session: waits up to 60 seconds, returns the view. - README, cheatsheet and use-orca skill list the command and tool. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- package-lock.json | 4 +- package.json | 2 +- plugins/orca/.claude-plugin/plugin.json | 2 +- plugins/orca/skills/use-orca/SKILL.md | 3 +- .../use-orca/references/cli-cheatsheet.md | 1 + src/commands/sessions.tsx | 49 +++++ src/lib/api.ts | 14 ++ src/lib/sessions.ts | 81 +++++++- src/lib/types.ts | 26 +++ src/mcp/server.ts | 26 ++- test/commands/sessions.test.ts | 188 +++++++++++++++++- test/helpers/session-events.ts | 19 ++ test/lib/sessions.test.ts | 15 +- test/mcp/server.test.ts | 98 +++++++++ 15 files changed, 518 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 80ece1e..f02b9a9 100644 --- a/README.md +++ b/README.md @@ -196,6 +196,7 @@ orca sessions create --agent [--sandbox] [--template t] [--vault v]... [ orca sessions items [--limit n] orca sessions artifacts # files its turns saved under /workspace/outputs orca sessions artifacts download [artifact] [-o path|-] [--all] +orca sessions sleep [--no-wait] # put its sandbox to sleep now; its next message wakes it orca sessions delete [--yes] orca usage [--days n] [--group-by model|provider|credential|session|agent] [--session id] [--meter m] @@ -420,7 +421,8 @@ claude mcp add orca -- orca mcp serve `orca mcp serve` speaks MCP over stdio with one tool per CLI action: identity and keys, agents and models, sessions and `chat` (which sends a message and -waits for the reply; it and `create_session` take `files` to stage), a session's +waits for the reply; it and `create_session` take `files` to stage), +`sleep_session` (puts a session's sandbox to sleep now), a session's artifacts, skills, vaults, files, usage and billing, and kits (`show_kit` and `copy_kit`, which copies the version `show_kit` returned). The commands that only touch this machine (login, logout, context, doctor, update) diff --git a/package-lock.json b/package-lock.json index ec50258..95c31a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@agent-orc/cli", - "version": "1.4.2", + "version": "1.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@agent-orc/cli", - "version": "1.4.2", + "version": "1.5.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.30.0", "commander": "^15.0.0", diff --git a/package.json b/package.json index 66b048b..58b0332 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@agent-orc/cli", - "version": "1.4.2", + "version": "1.5.0", "private": true, "description": "Orca CLI: manage agents, sessions, and kits on the Orca platform", "type": "module", diff --git a/plugins/orca/.claude-plugin/plugin.json b/plugins/orca/.claude-plugin/plugin.json index 281f1ad..9c7469f 100644 --- a/plugins/orca/.claude-plugin/plugin.json +++ b/plugins/orca/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "orca", - "version": "1.4.2", + "version": "1.5.0", "description": "Use Orca (orcapods.ai) from Claude Code: device login, agents, sessions and chat, kits, and an MCP server with one tool per CLI action.", "author": { "name": "Orca", diff --git a/plugins/orca/skills/use-orca/SKILL.md b/plugins/orca/skills/use-orca/SKILL.md index b37f4c7..e2c3863 100644 --- a/plugins/orca/skills/use-orca/SKILL.md +++ b/plugins/orca/skills/use-orca/SKILL.md @@ -68,6 +68,7 @@ Work on a file in a sandbox, and get the results back: orca chat --file sales.csv "Chart /workspace/sales.csv into /workspace/outputs/chart.png" orca sessions artifacts --json # what the agent saved under /workspace/outputs orca sessions artifacts download --all -o results +orca sessions sleep # done for now: saves /workspace, stops machine time; the next message wakes it orca sessions delete --yes # stops the sandbox; its artifacts go with it ``` @@ -102,7 +103,7 @@ For extended work, register Orca's MCP server once: claude mcp add orca -- orca mcp serve ``` -It exposes one tool per CLI action: whoami and keys, agents and `list_models`, sessions, `chat` (sends a message and waits for the reply, returning the session id; it and `create_session` take `files` to stage into the sandbox), `list_artifacts` and `download_artifact`, skills, vaults, files, usage and billing, and kits (`show_kit` returns a kit's review; call `copy_kit` with the `version` it returned only after the person says yes). +It exposes one tool per CLI action: whoami and keys, agents and `list_models`, sessions, `chat` (sends a message and waits for the reply, returning the session id; it and `create_session` take `files` to stage into the sandbox), `sleep_session` (puts a session's sandbox to sleep now; refused while a turn runs), `list_artifacts` and `download_artifact`, skills, vaults, files, usage and billing, and kits (`show_kit` returns a kit's review; call `copy_kit` with the `version` it returned only after the person says yes). To ask a named agent something, call `chat` with `agent` set to that name and nothing before it: no `list_agents`, no `get_agent`. A new session's `sandbox`, `template` and `vaults` go on that same first `chat` (or on `create_session`). List tools return summaries (an agent's id, name, model and tool types, never its instructions); `get_agent` and `get_session` return one item in full. Every result is valid JSON: a page too large for one result comes back shorter with `hasMore: true` and `lastId` to pass as `after`, and a long string cut to fit ends in `[shortened from N characters]`. diff --git a/plugins/orca/skills/use-orca/references/cli-cheatsheet.md b/plugins/orca/skills/use-orca/references/cli-cheatsheet.md index a873c34..f890a53 100644 --- a/plugins/orca/skills/use-orca/references/cli-cheatsheet.md +++ b/plugins/orca/skills/use-orca/references/cli-cheatsheet.md @@ -48,6 +48,7 @@ orca sessions items [--limit n] --json orca sessions artifacts --json # files the turns saved under /workspace/outputs: id, path, size_bytes, turn_id orca sessions artifacts download [-o path|-] # one, under its own file name by default orca sessions artifacts download --all [-o folder] # every file of the newest turn +orca sessions sleep [--no-wait] --json # put its sandbox to sleep now: /workspace is saved, machine time stops, the next message wakes it orca sessions delete --yes ``` diff --git a/src/commands/sessions.tsx b/src/commands/sessions.tsx index f941ba7..a16ca04 100644 --- a/src/commands/sessions.tsx +++ b/src/commands/sessions.tsx @@ -15,12 +15,17 @@ import { addSessionCreateOptions, createSession, filesFromFlags, + goingToSleep, itemRole, itemText, + requestSleep, + sandboxStateWords, sessionUsageRows, payerLabel, sessionEnvironment, sessionView, + sleepFailure, + waitForSleep, type SessionCreateFlags, } from '../lib/sessions.js' import { stagedNote } from '../lib/staging.js' @@ -57,6 +62,9 @@ function sessionStatusColor( } } +// How long `sessions sleep` waits for the sandbox to be asleep. +const SLEEP_WAIT_MS = 10 * 60 * 1000 + export function registerSessions(program: Command): void { const sessions = program.command('sessions').description('manage agent sessions (conversations)') @@ -140,6 +148,7 @@ export function registerSessions(program: Command): void { ['payer', session.payer ?? '-'], ['status', session.status], ['environment', session.environment.type], + ...(session.sandbox ? [['sandbox', session.sandbox]] : []), ['created', formatTime(session.created_at)], ['lastActive', formatTime(session.last_active_at)], ...rows.map((row) => [row.key, row.plain]), @@ -162,6 +171,7 @@ export function registerSessions(program: Command): void { /> + {session.sandbox ? : null} {rows.map((row) => ( @@ -330,6 +340,45 @@ export function registerSessions(program: Command): void { } }) + // Sleep (sandbox-sleep D6.7): the server saves /workspace and stops the + // sandbox after it answers, so the command reads the sandbox every second + // until the sleep ends. Past SLEEP_WAIT_MS it stops waiting; the sleep goes + // on without it. + sessions + .command('sleep ') + .description('put a session\'s sandbox to sleep now; its next message wakes it') + .option('--no-wait', 'return once the sandbox starts going to sleep') + // The global --json; listed here so the help says what it prints. + .option('--json', 'print the session.sandbox object') + .action(async (id: string, opts: { wait: boolean }, cmd: Command) => { + const flags = globalFlags(cmd) + const json = outputMode(flags) === 'json' + const api = await apiContext(cmd) + let view = await withApi(api, (c) => requestSleep(c, id)) + const started = goingToSleep(view) + if (started && opts.wait) { + if (!json) console.error(hintText(`Putting the sandbox of session ${id} to sleep...`)) + view = await withApi(api, (c) => waitForSleep(c, id, view, Date.now() + SLEEP_WAIT_MS)) + } + if (json) printJson(view) + const failure = sleepFailure(view) + if (failure) throw new CliError(failure, ExitCode.Failure) + if (json) return + if (goingToSleep(view)) { + console.log(`The sandbox of session ${id} is going to sleep. Check with: orca sessions get ${id}`) + } else if (view.state === 'none') { + console.log(`Session ${id} has no sandbox to put to sleep.`) + } else if (view.state === 'asleep' && !started) { + console.log(`The sandbox of session ${id} is already asleep.`) + } else if (view.state === 'asleep' || view.last_sleep?.outcome === 'asleep') { + console.log( + `${accentVerb('Asleep.')} Session ${id} keeps its conversation and the files in /workspace; machine time has stopped. Its next message wakes it.`, + ) + } else { + console.log(`The sandbox of session ${id} is ${sandboxStateWords(view.state)}.`) + } + }) + sessions .command('delete ') .description('delete a session and its history') diff --git a/src/lib/api.ts b/src/lib/api.ts index e21ecca..96a7931 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -25,6 +25,7 @@ import type { ListPage, ModelGroups, SessionModel, + SessionSandbox, UsageEvent, UsageSummary, Wallet, @@ -342,6 +343,19 @@ export class ApiClient { return this.post(`/api/sessions/${enc(sessionId)}/model`, { model }) } + // -- Sandbox sleep ------------------------------------------------------------ + + sessionSandbox(sessionId: string): Promise { + return this.request(`/api/sessions/${enc(sessionId)}/sandbox`) + } + + // sleepSessionSandbox starts putting a session's sandbox to sleep. The + // server answers at once, going_to_sleep while it saves the files; how the + // sleep went is read with sessionSandbox. + sleepSessionSandbox(sessionId: string): Promise { + return this.post(`/api/sessions/${enc(sessionId)}/sandbox/sleep`) + } + // -- Credentials -------------------------------------------------------------- // createBasicCredential stores a login and password for an MCP server that diff --git a/src/lib/sessions.ts b/src/lib/sessions.ts index 609cce8..c961dc5 100644 --- a/src/lib/sessions.ts +++ b/src/lib/sessions.ts @@ -17,7 +17,7 @@ import type { EnvironmentParam, } from 'openai/resources/beta/agents/agents' -import type { ApiClient } from './api.js' +import { ApiError, extractErrorBody, type ApiClient } from './api.js' import { CliError, ExitCode } from './errors.js' import { formatCount } from './format.js' import { stripControlSequences } from './markdown.js' @@ -33,7 +33,7 @@ import { type StagedFile, type StagedUpload, } from './staging.js' -import type { SessionModel, UsageSummary } from './types.js' +import type { SandboxState, SessionModel, SessionSandbox, UsageSummary } from './types.js' import { groupCost } from './usage.js' // A tool line's status: running, done, failed, or stopped (cut off by the @@ -407,11 +407,15 @@ export async function createSession( // model (decision 0017); and from /api/sessions/{id}/model, the model its // next turn uses, the agent's own, and who pays (model-billing D3.13): a // switch is visible here, while the /v1 object keeps the agent's model. +// `sandbox` is where its sandbox is (sandbox-sleep D6.7), from +// /api/sessions/{id}/sandbox; absent when that read failed, as on a server +// without the route. export type SessionView = Omit & { usage: UsageSummary model: string agent_model: string payer: SessionModel['payer'] + sandbox?: SandboxState } // sessionView reads one session, its usage and its model from their one @@ -421,8 +425,79 @@ export async function sessionView(client: ApiClient, id: string): Promise view.state, + () => undefined, + ) // `usage` replaces the /v1 object's own field. - return { ...session, usage, model: model.model, agent_model: model.agent_model, payer: model.payer } + return { + ...session, + usage, + model: model.model, + agent_model: model.agent_model, + payer: model.payer, + ...(sandbox ? { sandbox } : {}), + } +} + +// -- Sandbox sleep (sandbox-sleep D6.7) ----------------------------------------- + +const SANDBOX_STATE_WORDS: Record = { + none: 'none', + awake: 'awake', + going_to_sleep: 'going to sleep', + asleep: 'asleep', + waking: 'waking up', +} + +// sandboxStateWords says a sandbox state in words; a state this CLI does not +// know yet is shown as the server sent it. +export function sandboxStateWords(state: string): string { + return SANDBOX_STATE_WORDS[state as SandboxState] ?? state +} + +// goingToSleep is true while a sleep has not ended: the server saves the +// files after it answers the request. +export function goingToSleep(view: SessionSandbox): boolean { + return view.state === 'going_to_sleep' || (view.last_sleep !== null && view.last_sleep.outcome === null) +} + +// requestSleep starts putting a session's sandbox to sleep. A refusal (a +// turn is running, or the sandbox is waking up) is the server's own message. +export async function requestSleep(client: ApiClient, id: string): Promise { + try { + return await client.sleepSessionSandbox(id) + } catch (err) { + if (err instanceof ApiError && err.code === 'conflict') { + throw new CliError(extractErrorBody(err.body) || 'the sandbox cannot be put to sleep now', ExitCode.Failure) + } + throw err + } +} + +// waitForSleep reads the sandbox every second until its sleep has ended or +// the deadline passes, and returns the last view read. The sleep goes on +// on the server either way. +export async function waitForSleep( + client: ApiClient, + id: string, + view: SessionSandbox, + deadline: number, +): Promise { + while (goingToSleep(view) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 1000)) + view = await client.sessionSandbox(id) + } + return view +} + +// sleepFailure is why a sleep that has ended left the sandbox awake (too +// large, failed, interrupted), or null when it did not. +export function sleepFailure(view: SessionSandbox): string | null { + const last = view.last_sleep + if (!last || last.outcome === null || last.outcome === 'asleep') return null + return last.message || 'The sandbox stayed awake.' } // payerLabel says who pays for a session's model, in words. diff --git a/src/lib/types.ts b/src/lib/types.ts index a63c33b..1999cf6 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -189,6 +189,32 @@ export type SessionModel = { payer: Payer | null } +// -- Sandbox sleep ------------------------------------------------------------ + +// Where a session's hosted sandbox is: none for no sandbox or a self-hosted +// one. +export type SandboxState = 'none' | 'awake' | 'going_to_sleep' | 'asleep' | 'waking' + +// The newest sleep since the sandbox last woke, whoever started it. reason is +// an open string (requested, idle, out_of_credit, hours_used_up, unpriced, +// and more later); outcome is null while it is going to sleep. +export type SandboxSleep = { + reason: string + started_at: number + finished_at: number | null + outcome: 'asleep' | 'too_large' | 'failed' | 'interrupted' | null + message: string | null +} + +// GET /api/sessions/{id}/sandbox and POST /api/sessions/{id}/sandbox/sleep. +export type SessionSandbox = { + object: 'session.sandbox' + session_id: string + environment_id: string | null + state: SandboxState + last_sleep: SandboxSleep | null +} + // POST /api/billing/checkout and /api/billing/portal. export type BillingURL = { url: string } diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 1d47e34..2649cb5 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -33,7 +33,14 @@ import { CliError, ExitCode } from '../lib/errors.js' import { findArtifact, oneDestination, saveArtifact, saveNewestTurn } from '../lib/artifacts.js' import { modelRows, withPayer } from '../lib/models.js' import { findVault } from '../lib/names.js' -import { createSession, messageText, sessionCreateParams, sessionView } from '../lib/sessions.js' +import { + createSession, + messageText, + requestSleep, + sessionCreateParams, + sessionView, + waitForSleep, +} from '../lib/sessions.js' import { collectSkillFiles } from '../lib/skills.js' import { prepareFiles, stageIntoSession, type FileSpec } from '../lib/staging.js' import { uploadFile } from '../lib/transfer.js' @@ -289,7 +296,7 @@ export function buildMcpServer(getClient: ClientSource): McpServer { tool( 'get_session', - 'Fetch one session: status, environment, error; model (what its next turn runs on), agent_model and payer (orca_credit or own_key); and usage: its all-time usage summary by model with cost in micro-USD.', + 'Fetch one session: status, environment, error; model (what its next turn runs on), agent_model and payer (orca_credit or own_key); sandbox (none, awake, going_to_sleep, asleep or waking); and usage: its all-time usage summary by model with cost in micro-USD.', { id: z.string() }, async (client, args) => sessionView(client, args.id as string), ) @@ -350,6 +357,21 @@ export function buildMcpServer(getClient: ClientSource): McpServer { }, ) + // Waits less than the CLI's 10 minutes: an MCP call is request and + // response, and the sleep goes on after the tool returns. The last poll + // starts by 55 seconds in, so the answer lands inside the 60-second request + // timeout MCP clients default to. + tool( + 'sleep_session', + 'Put a session\'s sandbox to sleep now. Files in /workspace are saved and machine time stops; the conversation stays, and the next message wakes it. Running programs stop and do not come back. Refused while a turn runs. Waits up to 60 seconds and returns state and last_sleep.', + { id: z.string() }, + async (client, args) => { + const id = args.id as string + const deadline = Date.now() + 55_000 + return waitForSleep(client, id, await requestSleep(client, id), deadline) + }, + ) + tool('delete_session', 'Delete a session and its history.', { id: z.string() }, async (client, args) => (await client.v1()).beta.agents.sessions.delete(args.id as string), ) diff --git a/test/commands/sessions.test.ts b/test/commands/sessions.test.ts index 16e0deb..95ecaa7 100644 --- a/test/commands/sessions.test.ts +++ b/test/commands/sessions.test.ts @@ -2,12 +2,12 @@ import { mkdir, mkdtemp, readdir, readFile, truncate, writeFile } from 'node:fs/ import os from 'node:os' import path from 'node:path' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { registerSessions } from '../../src/commands/sessions.js' import { ExitCode } from '../../src/lib/errors.js' import { commandHarness, list } from '../helpers/cli.js' -import { jsonResponse, stubFetch } from '../helpers/fetch-mock.js' +import { jsonResponse, stubFetch, type RouteHandler } from '../helpers/fetch-mock.js' import { AGENT_ID, SESSION_ID, @@ -15,6 +15,7 @@ import { artifact, bytesRoute, hostedSession, + sandboxView, session, sessionModelRoute, templateRoute, @@ -162,6 +163,189 @@ describe('sessions', () => { }) }) +const SANDBOX = `/api/sessions/${SESSION_ID}/sandbox` +const SLEEP = `POST ${SANDBOX}/sleep` + +// getRoutes is what `sessions get` reads, with the sandbox route given. +function getRoutes(sandbox: Record) { + return { + [`GET /v1/agents/sessions/${SESSION_ID}`]: jsonResponse(hostedSession()), + [`GET /api/usage?start=0&session=${SESSION_ID}&group_by=model`]: jsonResponse({ + object: 'usage.summary', start: 0, end: 1, session_id: SESSION_ID, cost_micro_usd: 0, meters: [], daily: [], groups: [], + }), + ...sessionModelRoute(), + ...sandbox, + } +} + +// views answers each GET with the next view, then keeps answering the last. +function views(...rows: ReturnType[]): RouteHandler { + let i = 0 + return (call) => jsonResponse(rows[Math.min(i++, rows.length - 1)])(call) +} + +// runOnFakeClock runs one command on a fake clock, stepping it a second at a +// time, so the sleep's one-second polls and its 10-minute limit stay fast. +async function runOnFakeClock(args: string[]): Promise { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }) + try { + let settled = false + const done = run(args).finally(() => { + settled = true + }) + done.catch(() => {}) + while (!settled) await vi.advanceTimersByTimeAsync(1000) + await done + } finally { + vi.useRealTimers() + } +} + +describe('sessions get: sandbox', () => { + it('shows where the sandbox is', async () => { + stubFetch(getRoutes({ [`GET ${SANDBOX}`]: jsonResponse(sandboxView('going_to_sleep', {})) })) + await run(['sessions', 'get', SESSION_ID]) + expect(stdout()).toContain('environment\topenai_hosted\nsandbox\tgoing_to_sleep\n') + }) + + it('leaves the sandbox out when the server cannot say', async () => { + stubFetch(getRoutes({ [`GET ${SANDBOX}`]: jsonResponse({ error: { message: 'no route', code: 'not_found' } }, { status: 404 }) })) + await run(['sessions', 'get', SESSION_ID]) + expect(stdout()).toContain('status\tidle') + expect(stdout()).not.toContain('sandbox') + }) + + it('adds sandbox to the --json object', async () => { + stubFetch(getRoutes({ [`GET ${SANDBOX}`]: jsonResponse(sandboxView('asleep', { outcome: 'asleep', reason: 'idle' })) })) + await run(['--json', 'sessions', 'get', SESSION_ID]) + expect(JSON.parse(stdout())).toMatchObject({ id: SESSION_ID, sandbox: 'asleep' }) + }) +}) + +describe('sessions sleep', () => { + const ASLEEP_LINE = `Asleep. Session ${SESSION_ID} keeps its conversation and the files in /workspace; machine time has stopped. Its next message wakes it.\n` + const GOING_LINE = `The sandbox of session ${SESSION_ID} is going to sleep. Check with: orca sessions get ${SESSION_ID}\n` + + it('puts the sandbox to sleep and waits until it is asleep', async () => { + const calls = stubFetch({ + [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: views( + sandboxView('going_to_sleep', {}), + sandboxView('asleep', { outcome: 'asleep', finished_at: 1_783_245_609 }), + ), + }) + await runOnFakeClock(['sessions', 'sleep', SESSION_ID]) + expect(stderr()).toContain(`Putting the sandbox of session ${SESSION_ID} to sleep...`) + expect(stdout()).toBe(ASLEEP_LINE) + const post = calls.find((c) => c.method === 'POST') + expect(post?.path).toBe(`${SANDBOX}/sleep`) + expect(post?.body).toBeUndefined() + expect(calls.filter((c) => c.method === 'GET')).toHaveLength(2) + }) + + it('shows a sleep with a reason it does not know as asleep', async () => { + stubFetch({ + [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: views(sandboxView('asleep', { reason: 'night_shift', outcome: 'asleep' })), + }) + await runOnFakeClock(['sessions', 'sleep', SESSION_ID]) + expect(stdout()).toBe(ASLEEP_LINE) + }) + + it('says when the sandbox is already asleep', async () => { + const calls = stubFetch({ [SLEEP]: jsonResponse(sandboxView('asleep', { reason: 'idle', outcome: 'asleep' })) }) + await run(['sessions', 'sleep', SESSION_ID]) + expect(stdout()).toBe(`The sandbox of session ${SESSION_ID} is already asleep.\n`) + expect(calls).toHaveLength(1) + }) + + it('says when the session has no sandbox', async () => { + stubFetch({ [SLEEP]: jsonResponse(sandboxView('none')) }) + await run(['sessions', 'sleep', SESSION_ID]) + expect(stdout()).toBe(`Session ${SESSION_ID} has no sandbox to put to sleep.\n`) + }) + + it('returns once the sleep starts with --no-wait', async () => { + const calls = stubFetch({ [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }) }) + await run(['sessions', 'sleep', SESSION_ID, '--no-wait']) + expect(stdout()).toBe(GOING_LINE) + expect(stderr()).toBe('') + expect(calls).toHaveLength(1) + }) + + it('stops waiting after 10 minutes and exits 0', async () => { + const calls = stubFetch({ + [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: jsonResponse(sandboxView('going_to_sleep', {})), + }) + await runOnFakeClock(['sessions', 'sleep', SESSION_ID]) + expect(stdout()).toBe(GOING_LINE) + const polls = calls.filter((c) => c.method === 'GET').length + expect(polls).toBeGreaterThanOrEqual(599) + expect(polls).toBeLessThanOrEqual(601) + }) + + it.each([ + ['too_large', 'The sandbox stayed awake: its files are too large to save while it sleeps (over 1 GiB compressed). Delete files in /workspace, then try again.'], + ['failed', 'The sandbox stayed awake: its files could not be saved. Try again, or ask on Discord: https://discord.gg/btTYzdzvqq'], + ['interrupted', 'The sandbox stayed awake: a message or a file request reached it before it was asleep.'], + ])('exits 1 with the server\'s message when the sleep ends %s', async (outcome, message) => { + stubFetch({ + [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: views(sandboxView('awake', { outcome, message, finished_at: 1_783_245_609 })), + }) + await expect(runOnFakeClock(['sessions', 'sleep', SESSION_ID])).rejects.toMatchObject({ + exitCode: ExitCode.Failure, + message, + }) + expect(stdout()).toBe('') + }) + + it.each([ + 'A turn is running; put the sandbox to sleep once it ends.', + 'The sandbox is waking up; put it to sleep once it is awake.', + ])('exits 1 with the server\'s message on a refusal: %s', async (message) => { + stubFetch({ [SLEEP]: jsonResponse({ error: { message, type: 'conflict', param: null, code: 'conflict' } }, { status: 409 }) }) + await expect(run(['sessions', 'sleep', SESSION_ID])).rejects.toMatchObject({ exitCode: ExitCode.Failure, message }) + }) + + it('fails as not found for an unknown session', async () => { + stubFetch({ [SLEEP]: jsonResponse({ error: { message: 'session not found', code: 'not_found' } }, { status: 404 }) }) + await expect(run(['sessions', 'sleep', SESSION_ID])).rejects.toMatchObject({ exitCode: ExitCode.NotFound }) + }) + + it('prints the final session.sandbox object with --json', async () => { + const asleep = sandboxView('asleep', { outcome: 'asleep', finished_at: 1_783_245_609 }) + stubFetch({ + [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: views(asleep), + }) + await runOnFakeClock(['sessions', 'sleep', SESSION_ID, '--json']) + expect(JSON.parse(stdout())).toEqual(asleep) + expect(stderr()).toBe('') + }) + + it('prints the object and still exits 1 with --json when the sandbox stayed awake', async () => { + const message = 'The sandbox stayed awake: its files could not be saved. Try again, or ask on Discord: https://discord.gg/btTYzdzvqq' + const failed = sandboxView('awake', { outcome: 'failed', message }) + stubFetch({ + [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: views(failed), + }) + await expect(runOnFakeClock(['--json', 'sessions', 'sleep', SESSION_ID])).rejects.toMatchObject({ + exitCode: ExitCode.Failure, + message, + }) + expect(JSON.parse(stdout())).toEqual(failed) + }) + + it('prints the going-to-sleep object with --json --no-wait', async () => { + stubFetch({ [SLEEP]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }) }) + await run(['sessions', 'sleep', SESSION_ID, '--no-wait', '--json']) + expect(JSON.parse(stdout())).toMatchObject({ object: 'session.sandbox', state: 'going_to_sleep' }) + }) +}) + const ARTIFACTS = `/v1/agents/sessions/${SESSION_ID}/artifacts` const tmp = () => mkdtemp(path.join(os.tmpdir(), 'orca-artifacts-')) diff --git a/test/helpers/session-events.ts b/test/helpers/session-events.ts index 4da2545..6b07766 100644 --- a/test/helpers/session-events.ts +++ b/test/helpers/session-events.ts @@ -97,6 +97,25 @@ export function sessionModelRoute( } } +// sandboxView is SESSION_ID's session.sandbox object. A last_sleep given +// without the other fields is a requested sleep started at 1_783_245_600. +export function sandboxView(state: string, lastSleep: Record | null = null) { + return { + object: 'session.sandbox', + session_id: SESSION_ID, + environment_id: state === 'none' ? null : 'env_1', + state, + last_sleep: lastSleep && { + reason: 'requested', + started_at: 1_783_245_600, + finished_at: null, + outcome: null, + message: null, + ...lastSleep, + }, + } +} + // hostedSession is SESSION_ID in a managed sandbox, environment env_1. export function hostedSession(status = 'idle') { return session(status, { environment: { type: 'openai_hosted', id: 'env_1', files: [] } }) diff --git a/test/lib/sessions.test.ts b/test/lib/sessions.test.ts index b5ce66f..20fd44e 100644 --- a/test/lib/sessions.test.ts +++ b/test/lib/sessions.test.ts @@ -2,7 +2,7 @@ import OpenAI from 'openai' import type { AgentSessionItem } from 'openai/resources/beta/agents/agents' import { afterEach, describe, expect, it, vi } from 'vitest' -import { itemText, streamTurn, type ChatEvent } from '../../src/lib/sessions.js' +import { itemText, sandboxStateWords, streamTurn, type ChatEvent } from '../../src/lib/sessions.js' import { stubFetch } from '../helpers/fetch-mock.js' import { SESSION_ID, session, turnRoutes } from '../helpers/session-events.js' @@ -111,3 +111,16 @@ describe('itemText web search lines', () => { ) }) }) + +describe('sandboxStateWords', () => { + it('says each state in words and shows a state it does not know as sent', () => { + expect(['none', 'awake', 'going_to_sleep', 'asleep', 'waking', 'hibernating'].map(sandboxStateWords)).toEqual([ + 'none', + 'awake', + 'going to sleep', + 'asleep', + 'waking up', + 'hibernating', + ]) + }) +}) diff --git a/test/mcp/server.test.ts b/test/mcp/server.test.ts index 14b0417..183d55c 100644 --- a/test/mcp/server.test.ts +++ b/test/mcp/server.test.ts @@ -23,6 +23,7 @@ import { artifact, bytesRoute, hostedSession, + sandboxView, session, sessionModelRoute, template, @@ -83,6 +84,7 @@ describe('orca mcp serve', () => { 'get_session', 'create_session', 'list_session_items', + 'sleep_session', 'delete_session', 'chat', // artifacts @@ -228,6 +230,102 @@ describe('orca mcp serve', () => { expect(payload).toMatchObject({ id: SESSION_ID, status: 'completed', usage: summary }) }) + it('get_session adds where the sandbox is, and leaves it out when the server cannot say', async () => { + const summary = { object: 'usage.summary', start: 0, end: 1, session_id: SESSION_ID, cost_micro_usd: 0, meters: [], daily: [], groups: [] } + const routes = { + [`GET /v1/agents/sessions/${SESSION_ID}`]: jsonResponse(hostedSession()), + [`GET /api/usage?start=0&session=${SESSION_ID}&group_by=model`]: jsonResponse(summary), + ...sessionModelRoute(), + } + stubFetch({ ...routes, [`GET /api/sessions/${SESSION_ID}/sandbox`]: jsonResponse(sandboxView('waking')) }) + const client = await connect() + const payload = JSON.parse(firstText(await client.callTool({ name: 'get_session', arguments: { id: SESSION_ID } }))) + expect(payload).toMatchObject({ id: SESSION_ID, sandbox: 'waking' }) + stubFetch({ ...routes, [`GET /api/sessions/${SESSION_ID}/sandbox`]: jsonResponse({ error: { message: 'not found' } }, { status: 404 }) }) + const older = JSON.parse(firstText(await client.callTool({ name: 'get_session', arguments: { id: SESSION_ID } }))) + expect(older).toMatchObject({ id: SESSION_ID, status: 'idle' }) + expect(older).not.toHaveProperty('sandbox') + }) + + describe('sleep_session', () => { + const SANDBOX = `/api/sessions/${SESSION_ID}/sandbox` + + // callOnFakeClock calls one tool on a fake clock, stepping it a second at + // a time, so the sleep's polls and its 60-second limit stay fast. + async function callOnFakeClock(client: Client, args: Record): Promise { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }) + try { + let settled = false + const done = client.callTool({ name: 'sleep_session', arguments: args }).finally(() => { + settled = true + }) + while (!settled) await vi.advanceTimersByTimeAsync(1000) + return await done + } finally { + vi.useRealTimers() + } + } + + it('waits until the sandbox is asleep and returns the view', async () => { + const asleep = sandboxView('asleep', { outcome: 'asleep', finished_at: 1_783_245_609 }) + let polls = 0 + const calls = stubFetch({ + [`POST ${SANDBOX}/sleep`]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: (call) => jsonResponse(++polls < 3 ? sandboxView('going_to_sleep', {}) : asleep)(call), + }) + const client = await connect() + const res = await callOnFakeClock(client, { id: SESSION_ID }) + expect((res as ToolText).isError).toBeFalsy() + expect(JSON.parse(firstText(res))).toEqual(asleep) + expect(calls.filter((c) => c.method === 'GET')).toHaveLength(3) + }) + + it('returns a sleep that left the sandbox awake with its message', async () => { + const message = 'The sandbox stayed awake: a message or a file request reached it before it was asleep.' + stubFetch({ + [`POST ${SANDBOX}/sleep`]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: jsonResponse(sandboxView('awake', { outcome: 'interrupted', message })), + }) + const client = await connect() + const res = await callOnFakeClock(client, { id: SESSION_ID }) + expect(JSON.parse(firstText(res))).toMatchObject({ state: 'awake', last_sleep: { outcome: 'interrupted', message } }) + }) + + it('stops waiting inside the 60 seconds, still going to sleep', async () => { + const calls = stubFetch({ + [`POST ${SANDBOX}/sleep`]: jsonResponse(sandboxView('going_to_sleep', {}), { status: 202 }), + [`GET ${SANDBOX}`]: jsonResponse(sandboxView('going_to_sleep', {})), + }) + const client = await connect() + const res = await callOnFakeClock(client, { id: SESSION_ID }) + expect(JSON.parse(firstText(res))).toMatchObject({ state: 'going_to_sleep' }) + const polls = calls.filter((c) => c.method === 'GET').length + // A poll a second from 1 to 55 seconds in, so the answer beats the + // client's 60-second request timeout. + expect(polls).toBeGreaterThanOrEqual(54) + expect(polls).toBeLessThanOrEqual(56) + }) + + it('answers at once for no sandbox', async () => { + const calls = stubFetch({ [`POST ${SANDBOX}/sleep`]: jsonResponse(sandboxView('none')) }) + const client = await connect() + const res = await client.callTool({ name: 'sleep_session', arguments: { id: SESSION_ID } }) + expect(JSON.parse(firstText(res))).toMatchObject({ state: 'none', environment_id: null }) + expect(calls).toHaveLength(1) + }) + + it('is an error with the server\'s message while a turn runs', async () => { + const message = 'A turn is running; put the sandbox to sleep once it ends.' + stubFetch({ + [`POST ${SANDBOX}/sleep`]: jsonResponse({ error: { message, type: 'conflict', param: null, code: 'conflict' } }, { status: 409 }), + }) + const client = await connect() + const res = (await client.callTool({ name: 'sleep_session', arguments: { id: SESSION_ID } })) as ToolText + expect(res.isError).toBe(true) + expect(firstText(res)).toBe(message) + }) + }) + it('copy_kit sends the version show_kit returned and the chosen assets', async () => { const calls = stubFetch({ 'POST /api/kits/kit-AbCdEfGhIjKlMnOpQ/copy': jsonResponse({ object: 'kit.copy', created: [], credentials: [] }),