Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ orca sessions create --agent <agent> [--sandbox] [--template t] [--vault v]... [
orca sessions items <id> [--limit n]
orca sessions artifacts <session> # files its turns saved under /workspace/outputs
orca sessions artifacts download <session> [artifact] [-o path|-] [--all]
orca sessions sleep <id> [--no-wait] # put its sandbox to sleep now; its next message wakes it
orca sessions delete <id> [--yes]

orca usage [--days n] [--group-by model|provider|credential|session|agent] [--session id] [--meter m]
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion plugins/orca/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
3 changes: 2 additions & 1 deletion plugins/orca/skills/use-orca/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ Work on a file in a sandbox, and get the results back:
orca chat <agent> --file sales.csv "Chart /workspace/sales.csv into /workspace/outputs/chart.png"
orca sessions artifacts <session-id> --json # what the agent saved under /workspace/outputs
orca sessions artifacts download <session-id> --all -o results
orca sessions sleep <session-id> # done for now: saves /workspace, stops machine time; the next message wakes it
orca sessions delete <session-id> --yes # stops the sandbox; its artifacts go with it
```

Expand Down Expand Up @@ -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]`.

Expand Down
1 change: 1 addition & 0 deletions plugins/orca/skills/use-orca/references/cli-cheatsheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ orca sessions items <id> [--limit n] --json
orca sessions artifacts <id> --json # files the turns saved under /workspace/outputs: id, path, size_bytes, turn_id
orca sessions artifacts download <id> <artifact-id|path> [-o path|-] # one, under its own file name by default
orca sessions artifacts download <id> --all [-o folder] # every file of the newest turn
orca sessions sleep <id> [--no-wait] --json # put its sandbox to sleep now: /workspace is saved, machine time stops, the next message wakes it
orca sessions delete <id> --yes
```

Expand Down
49 changes: 49 additions & 0 deletions src/commands/sessions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)')

Expand Down Expand Up @@ -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]),
Expand All @@ -162,6 +171,7 @@ export function registerSessions(program: Command): void {
/>
<Field width={LABEL_WIDTH} label="pays" value={payerLabel(session.payer)} />
<Field width={LABEL_WIDTH} label="environment" value={session.environment.type} />
{session.sandbox ? <Field width={LABEL_WIDTH} label="sandbox" value={sandboxStateWords(session.sandbox)} /> : null}
<Field width={LABEL_WIDTH} label="created" value={formatTime(session.created_at)} />
<Field width={LABEL_WIDTH} label="last active" value={formatTime(session.last_active_at)} />
{rows.map((row) => (
Expand Down Expand Up @@ -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 <id>')
.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 <id>')
.description('delete a session and its history')
Expand Down
14 changes: 14 additions & 0 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
ListPage,
ModelGroups,
SessionModel,
SessionSandbox,
UsageEvent,
UsageSummary,
Wallet,
Expand Down Expand Up @@ -342,6 +343,19 @@ export class ApiClient {
return this.post<SessionModel>(`/api/sessions/${enc(sessionId)}/model`, { model })
}

// -- Sandbox sleep ------------------------------------------------------------

sessionSandbox(sessionId: string): Promise<SessionSandbox> {
return this.request<SessionSandbox>(`/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<SessionSandbox> {
return this.post<SessionSandbox>(`/api/sessions/${enc(sessionId)}/sandbox/sleep`)
}

// -- Credentials --------------------------------------------------------------

// createBasicCredential stores a login and password for an MCP server that
Expand Down
81 changes: 78 additions & 3 deletions src/lib/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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
Expand Down Expand Up @@ -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<AgentSession, 'usage'> & {
usage: UsageSummary
model: string
agent_model: string
payer: SessionModel['payer']
sandbox?: SandboxState
}

// sessionView reads one session, its usage and its model from their one
Expand All @@ -421,8 +425,79 @@ export async function sessionView(client: ApiClient, id: string): Promise<Sessio
const session = await (await client.v1()).beta.agents.sessions.retrieve(id)
const usage = await client.usage({ start: 0, session: id, group_by: 'model' })
const model = await client.sessionModel(id)
// The sandbox line is extra: a failed read leaves it out, never the session.
const sandbox = await client.sessionSandbox(id).then(
(view) => 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<SandboxState, string> = {
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<SessionSandbox> {
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<SessionSandbox> {
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.
Expand Down
26 changes: 26 additions & 0 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down
26 changes: 24 additions & 2 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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),
)
Expand Down Expand Up @@ -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),
)
Expand Down
Loading