Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Named Macro Coder sandbox sizes with Daytona resize (#5818)

Wolf Mermelstein168073626a8a
diff --git a/.github/workflows/ensure_daytona_snapshot.yml b/.github/workflows/ensure_daytona_snapshot.yml
index 4c60502430..39fbac0ed0 100644
--- a/.github/workflows/ensure_daytona_snapshot.yml
+++ b/.github/workflows/ensure_daytona_snapshot.yml
@@ -56,10 +56,14 @@ jobs:
exit 1
fi
daytona login --api-key "$DAYTONA_API_KEY"
+ echo "ensuring Daytona snapshot at --cpu ${DAYTONA_SNAPSHOT_CPU} --memory ${DAYTONA_SNAPSHOT_MEMORY} --disk ${DAYTONA_SNAPSHOT_DISK}"
just --justfile crates/agent_harness/justfile ensure-daytona
shell: bash
env:
DAYTONA_API_KEY: ${{ secrets.DAYTONA_API_KEY }}
+ DAYTONA_SNAPSHOT_CPU: '8'
+ DAYTONA_SNAPSHOT_MEMORY: '16'
+ DAYTONA_SNAPSHOT_DISK: '96'
publish-image:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
name: Publish sandbox image to GHCR
diff --git a/.sqlx/query-1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e.json b/.sqlx/query-0fc5c92a46c6e80c60f28633cc7cbd74b64c7f9936e843d7b33feb3dede01855.json
similarity index 75%
rename from .sqlx/query-1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e.json
rename to .sqlx/query-0fc5c92a46c6e80c60f28633cc7cbd74b64c7f9936e843d7b33feb3dede01855.json
index dd40fd3057..f6e2bf1738 100644
--- a/.sqlx/query-1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e.json
+++ b/.sqlx/query-0fc5c92a46c6e80c60f28633cc7cbd74b64c7f9936e843d7b33feb3dede01855.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE id = $1\n ",
+ "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY created_at DESC\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -50,37 +50,43 @@
},
{
"ordinal": 9,
- "name": "acp_session_id",
+ "name": "sandbox_size",
"type_info": "Text"
},
{
"ordinal": 10,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 11,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 12,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 14,
+ "ordinal": 15,
"name": "thread_channel_id?",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
+ "Uuid",
"Uuid"
]
},
@@ -94,6 +100,7 @@
false,
true,
false,
+ false,
true,
false,
true,
@@ -102,5 +109,5 @@
null
]
},
- "hash": "1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e"
+ "hash": "0fc5c92a46c6e80c60f28633cc7cbd74b64c7f9936e843d7b33feb3dede01855"
}
diff --git a/.sqlx/query-2ee1f2f49cabab8d9e63a6bb1678ef30a17c6fe45aa68bde74de8530e13830a8.json b/.sqlx/query-2ee1f2f49cabab8d9e63a6bb1678ef30a17c6fe45aa68bde74de8530e13830a8.json
new file mode 100644
index 0000000000..74a79ecf1e
--- /dev/null
+++ b/.sqlx/query-2ee1f2f49cabab8d9e63a6bb1678ef30a17c6fe45aa68bde74de8530e13830a8.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE agent_session\n SET sandbox_size = $2,\n modified_at = NOW()\n WHERE id = $1\n AND sandbox_size IS DISTINCT FROM $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2ee1f2f49cabab8d9e63a6bb1678ef30a17c6fe45aa68bde74de8530e13830a8"
+}
diff --git a/.sqlx/query-4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5.json b/.sqlx/query-5b30724ea10ea4d87de1790c81e68a5ea0784a494010a63281a8c14dc05ece28.json
similarity index 71%
rename from .sqlx/query-4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5.json
rename to .sqlx/query-5b30724ea10ea4d87de1790c81e68a5ea0784a494010a63281a8c14dc05ece28.json
index b22638e3ff..1e5e19b631 100644
--- a/.sqlx/query-4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5.json
+++ b/.sqlx/query-5b30724ea10ea4d87de1790c81e68a5ea0784a494010a63281a8c14dc05ece28.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, acp_session_id, status,\n status_event_name\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)\n RETURNING\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n ",
+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n RETURNING\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n ",
"describe": {
"columns": [
{
@@ -50,31 +50,36 @@
},
{
"ordinal": 9,
- "name": "acp_session_id",
+ "name": "sandbox_size",
"type_info": "Text"
},
{
"ordinal": 10,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 11,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 12,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 14,
+ "ordinal": 15,
"name": "thread_channel_id?",
"type_info": "Uuid"
}
@@ -92,6 +97,7 @@
"Text",
"Text",
"Text",
+ "Text",
"Text"
]
},
@@ -105,6 +111,7 @@
false,
true,
false,
+ false,
true,
false,
true,
@@ -113,5 +120,5 @@
null
]
},
- "hash": "4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5"
+ "hash": "5b30724ea10ea4d87de1790c81e68a5ea0784a494010a63281a8c14dc05ece28"
}
diff --git a/.sqlx/query-1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039.json b/.sqlx/query-8ba5993e933bf0e8e516a647a8fa374c21b05f107a1e6d63404eb85a756f3f1f.json
similarity index 78%
rename from .sqlx/query-1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039.json
rename to .sqlx/query-8ba5993e933bf0e8e516a647a8fa374c21b05f107a1e6d63404eb85a756f3f1f.json
index 8135b925e6..7f0b49a11f 100644
--- a/.sqlx/query-1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039.json
+++ b/.sqlx/query-8ba5993e933bf0e8e516a647a8fa374c21b05f107a1e6d63404eb85a756f3f1f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY created_at DESC\n LIMIT 1\n ",
+ "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -50,38 +50,42 @@
},
{
"ordinal": 9,
- "name": "acp_session_id",
+ "name": "sandbox_size",
"type_info": "Text"
},
{
"ordinal": 10,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 11,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 12,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 14,
+ "ordinal": 15,
"name": "thread_channel_id?",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
- "Uuid",
"Uuid"
]
},
@@ -95,6 +99,7 @@
false,
true,
false,
+ false,
true,
false,
true,
@@ -103,5 +108,5 @@
null
]
},
- "hash": "1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039"
+ "hash": "8ba5993e933bf0e8e516a647a8fa374c21b05f107a1e6d63404eb85a756f3f1f"
}
diff --git a/.sqlx/query-9e4e5991f2011b694161ff3b01b9ea39cf31317183bfe06783440d6ef9c1a79d.json b/.sqlx/query-9e4e5991f2011b694161ff3b01b9ea39cf31317183bfe06783440d6ef9c1a79d.json
new file mode 100644
index 0000000000..beeb0dd24e
--- /dev/null
+++ b/.sqlx/query-9e4e5991f2011b694161ff3b01b9ea39cf31317183bfe06783440d6ef9c1a79d.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO user_agent_sandbox_size (user_id, sandbox_size, modified_at)\n VALUES ($1, $2, NOW())\n ON CONFLICT (user_id) DO UPDATE\n SET sandbox_size = EXCLUDED.sandbox_size,\n modified_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9e4e5991f2011b694161ff3b01b9ea39cf31317183bfe06783440d6ef9c1a79d"
+}
diff --git a/.sqlx/query-d36ab4c44ea383a0f1f6010e2fb9dacf41394f5a82de33f97d7ed47c8eb39419.json b/.sqlx/query-d36ab4c44ea383a0f1f6010e2fb9dacf41394f5a82de33f97d7ed47c8eb39419.json
new file mode 100644
index 0000000000..cf120e452d
--- /dev/null
+++ b/.sqlx/query-d36ab4c44ea383a0f1f6010e2fb9dacf41394f5a82de33f97d7ed47c8eb39419.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT sandbox_size\n FROM user_agent_sandbox_size\n WHERE user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sandbox_size",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "d36ab4c44ea383a0f1f6010e2fb9dacf41394f5a82de33f97d7ed47c8eb39419"
+}
diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
index e5ec4d8755..e315c8532e 100644
--- a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
@@ -12,12 +12,14 @@
import { SidePanel, useSidePanel } from '@components/app/side-panel';
import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
+import { toast } from '@core/component/Toast/Toast';
import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { formatDate } from '@core/util/date';
import { openExternalUrl } from '@core/util/url';
import GitBranch from '@phosphor/git-branch.svg';
-import { createMemo, For, onCleanup, Show } from 'solid-js';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import { createMemo, createSignal, For, onCleanup, Show } from 'solid-js';
import { useAgentSession } from '../../context/AgentSessionContext';
import {
activityCounts,
@@ -27,13 +29,35 @@ import {
import {
CountSummary,
DiffChanges,
+ type SandboxSize,
+ SandboxSizeSelector,
SessionStatusPill,
TodoList,
} from '../../ui';
import { harnessTitle } from '../AgentSplitHeader';
export function AgentSidePanelSections() {
- const { session, bot, metadata, messages, status } = useAgentSession();
+ const { session, sessionId, bot, metadata, messages, status, loadFailed } =
+ useAgentSession();
+ const [pendingSize, setPendingSize] = createSignal<SandboxSize>();
+ const [resizing, setResizing] = createSignal(false);
+ const size = () => pendingSize() ?? session()?.sandboxSize ?? 'default';
+
+ const setSandboxSize = async (next: SandboxSize) => {
+ const id = sessionId();
+ if (!id || next === size() || resizing()) return;
+ const previous = size();
+ setPendingSize(next);
+ setResizing(true);
+ const result = await agentHarnessServiceClient
+ .setSessionSandboxSize(id, next)
+ .catch(() => undefined);
+ setResizing(false);
+ if (result === undefined || result.isErr()) {
+ setPendingSize(previous);
+ toast.failure('Could not resize the sandbox');
+ }
+ };
const plan = createMemo(() => latestPlan(messages()));
const files = createMemo(() => changedFiles(messages()));
@@ -84,6 +108,13 @@ export function AgentSidePanelSections() {
<span class="truncate">{harnessTitle(session()?.harness)}</span>
</SidePanel.Pill>
</SidePanel.Row>
+ <SidePanel.Row label="Sandbox size">
+ <SandboxSizeSelector
+ size={size()}
+ disabled={loadFailed() || resizing() || !sessionId()}
+ onSelect={setSandboxSize}
+ />
+ </SidePanel.Row>
<Show when={metadata()?.model ?? session()?.model}>
{(model) => (
<SidePanel.Row label="Model">
diff --git a/apps/web/src/features/block-agent/debug/replay/driver.ts b/apps/web/src/features/block-agent/debug/replay/driver.ts
index b688a3cbc1..22918b1b56 100644
--- a/apps/web/src/features/block-agent/debug/replay/driver.ts
+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts
@@ -79,6 +79,7 @@ function sessionFixture(id: string): AgentSessionResponse {
modifiedAt: now,
ownerId: REPLAY_OWNER,
repoUrl: 'https://example.com/replay.git',
+ sandboxSize: 'default',
status: { kind: 'no_messages' },
workspace: '/workspace',
};
diff --git a/apps/web/src/features/block-agent/ui/SandboxSizeSelector.tsx b/apps/web/src/features/block-agent/ui/SandboxSizeSelector.tsx
new file mode 100644
index 0000000000..e4a6d8c2df
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/SandboxSizeSelector.tsx
@@ -0,0 +1,61 @@
+import CaretDown from '@phosphor-icons/core/regular/caret-down.svg?component-solid';
+import { Dropdown } from '@ui';
+import { For } from 'solid-js';
+
+/** Named compute tier for a managed coding-agent sandbox. */
+export type SandboxSize = 'small' | 'default' | 'large';
+
+const TIERS: {
+ id: SandboxSize;
+ label: string;
+ detail: string;
+}[] = [
+ { id: 'small', label: 'Small', detail: '2 vCPU · 4 GiB · 96 GiB' },
+ { id: 'default', label: 'Default', detail: '8 vCPU · 16 GiB · 96 GiB' },
+ { id: 'large', label: 'Large', detail: '16 vCPU · 32 GiB · 96 GiB' },
+];
+
+export interface SandboxSizeSelectorProps {
+ size: SandboxSize;
+ disabled?: boolean;
+ onSelect: (size: SandboxSize) => void;
+}
+
+export function SandboxSizeSelector(props: SandboxSizeSelectorProps) {
+ const selected = () =>
+ TIERS.find((tier) => tier.id === props.size) ?? TIERS[1]!;
+
+ return (
+ <Dropdown placement="bottom-end">
+ <Dropdown.Trigger
+ variant="ghost"
+ size="sm"
+ class="rounded-lg gap-1.5 text-xs"
+ disabled={props.disabled}
+ label={selected().label}
+ >
+ {selected().label}
+ <CaretDown />
+ </Dropdown.Trigger>
+ <Dropdown.Content>
+ <Dropdown.Group>
+ <For each={TIERS}>
+ {(tier) => (
+ <Dropdown.Item
+ class="gap-2"
+ onSelect={() => props.onSelect(tier.id)}
+ >
+ <span class="flex min-w-0 flex-col">
+ <span class="text-xs">{tier.label}</span>
+ <span class="text-[11px] text-ink-extra-muted">
+ {tier.detail}
+ </span>
+ </span>
+ </Dropdown.Item>
+ )}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+}
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index 55dbd0db66..8da6b88a3b 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -26,6 +26,11 @@ export {
QueuedPromptList,
type QueuedPromptListProps,
} from './QueuedPromptList';
+export {
+ type SandboxSize,
+ SandboxSizeSelector,
+ type SandboxSizeSelectorProps,
+} from './SandboxSizeSelector';
export {
type SessionStatusLike,
SessionStatusPill,
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
index cdbce78fcb..cfd32e92fd 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
@@ -6,8 +6,12 @@ import type {
ControlRequest,
CreateAgentSessionRequest,
CreateAgentSessionResponse,
+ SandboxSize,
+ SandboxSizeBody,
} from './generated/schemas';
+export type { SandboxSize, SandboxSizeBody };
+
const agentHarnessHost = SERVER_HOSTS['agent-harness'];
/** Authenticated client for controlling live agent sessions. */
@@ -54,4 +58,35 @@ export const agentHarnessServiceClient = {
{ method: 'DELETE' }
).then((result) => result.map(() => undefined));
},
+
+ getSandboxSize() {
+ return fetchWithToken<SandboxSizeBody>(
+ `${agentHarnessHost}/agent-sandbox-size`,
+ {
+ method: 'GET',
+ }
+ );
+ },
+
+ setSandboxSize(size: SandboxSize) {
+ return fetchWithToken<SandboxSizeBody>(
+ `${agentHarnessHost}/agent-sandbox-size`,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ size }),
+ }
+ );
+ },
+
+ setSessionSandboxSize(sessionId: string, size: SandboxSize) {
+ return fetchWithToken<SandboxSizeBody>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/sandbox-size`,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ size }),
+ }
+ );
+ },
};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index 7152401252..2ae096173f 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -11,8 +11,126 @@ import type {
ControlRequest,
CreateAgentSessionRequest,
CreateAgentSessionResponse,
+ SandboxSizeBody,
} from './schemas';
+/**
+ * @summary Read the caller's default sandbox size for new `@coder` sessions.
+ */
+export type getAgentSandboxSizeResponse200 = {
+ data: SandboxSizeBody;
+ status: 200;
+};
+
+export type getAgentSandboxSizeResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type getAgentSandboxSizeResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type getAgentSandboxSizeResponseSuccess =
+ getAgentSandboxSizeResponse200 & {
+ headers: Headers;
+ };
+export type getAgentSandboxSizeResponseError = (
+ | getAgentSandboxSizeResponse401
+ | getAgentSandboxSizeResponse500
+) & {
+ headers: Headers;
+};
+
+export type getAgentSandboxSizeResponse =
+ | getAgentSandboxSizeResponseSuccess
+ | getAgentSandboxSizeResponseError;
+
+export const getGetAgentSandboxSizeUrl = () => {
+ return `/agent-sandbox-size`;
+};
+
+export const getAgentSandboxSize = async (
+ options?: RequestInit
+): Promise<getAgentSandboxSizeResponse> => {
+ const res = await fetch(getGetAgentSandboxSizeUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAgentSandboxSizeResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAgentSandboxSizeResponse;
+};
+
+/**
+ * @summary Set the caller's default sandbox size for the next `@coder` mention.
+ */
+export type putAgentSandboxSizeResponse200 = {
+ data: SandboxSizeBody;
+ status: 200;
+};
+
+export type putAgentSandboxSizeResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type putAgentSandboxSizeResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type putAgentSandboxSizeResponseSuccess =
+ putAgentSandboxSizeResponse200 & {
+ headers: Headers;
+ };
+export type putAgentSandboxSizeResponseError = (
+ | putAgentSandboxSizeResponse401
+ | putAgentSandboxSizeResponse500
+) & {
+ headers: Headers;
+};
+
+export type putAgentSandboxSizeResponse =
+ | putAgentSandboxSizeResponseSuccess
+ | putAgentSandboxSizeResponseError;
+
+export const getPutAgentSandboxSizeUrl = () => {
+ return `/agent-sandbox-size`;
+};
+
+export const putAgentSandboxSize = async (
+ sandboxSizeBody: SandboxSizeBody,
+ options?: RequestInit
+): Promise<putAgentSandboxSizeResponse> => {
+ const res = await fetch(getPutAgentSandboxSizeUrl(), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sandboxSizeBody),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: putAgentSandboxSizeResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as putAgentSandboxSizeResponse;
+};
+
/**
* Nothing here tells the runtime where to dial: one connection per bot
carries every session it runs, so a runtime that has already dialed serves
@@ -351,3 +469,70 @@ export const getAgentSessionLog = async (
headers: res.headers,
} as getAgentSessionLogResponse;
};
+
+/**
+ * @summary Resize this session's sandbox and remember the size as the owner's default.
+ */
+export type putAgentSessionSandboxSizeResponse200 = {
+ data: SandboxSizeBody;
+ status: 200;
+};
+
+export type putAgentSessionSandboxSizeResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type putAgentSessionSandboxSizeResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type putAgentSessionSandboxSizeResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type putAgentSessionSandboxSizeResponseSuccess =
+ putAgentSessionSandboxSizeResponse200 & {
+ headers: Headers;
+ };
+export type putAgentSessionSandboxSizeResponseError = (
+ | putAgentSessionSandboxSizeResponse401
+ | putAgentSessionSandboxSizeResponse403
+ | putAgentSessionSandboxSizeResponse500
+) & {
+ headers: Headers;
+};
+
+export type putAgentSessionSandboxSizeResponse =
+ | putAgentSessionSandboxSizeResponseSuccess
+ | putAgentSessionSandboxSizeResponseError;
+
+export const getPutAgentSessionSandboxSizeUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/sandbox-size`;
+};
+
+export const putAgentSessionSandboxSize = async (
+ sessionId: string,
+ sandboxSizeBody: SandboxSizeBody,
+ options?: RequestInit
+): Promise<putAgentSessionSandboxSizeResponse> => {
+ const res = await fetch(getPutAgentSessionSandboxSizeUrl(sessionId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sandboxSizeBody),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: putAgentSessionSandboxSizeResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as putAgentSessionSandboxSizeResponse;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
index 6b4cbf6d66..62d7f45775 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
@@ -9,6 +9,7 @@ import type { AgentSessionResponseOriginatingMessageId } from './agentSessionRes
import type { AgentSessionResponseRepoUrl } from './agentSessionResponseRepoUrl';
import type { AgentSessionResponseThreadChannelId } from './agentSessionResponseThreadChannelId';
import type { AgentSessionResponseThreadId } from './agentSessionResponseThreadId';
+import type { SandboxSize } from './sandboxSize';
import type { SessionStatusDto } from './sessionStatusDto';
/**
@@ -37,6 +38,8 @@ export interface AgentSessionResponse {
ownerId: string;
/** The repository the session works with, when one was stated. */
repoUrl?: AgentSessionResponseRepoUrl;
+ /** Compute tier of the managed sandbox. */
+ sandboxSize: SandboxSize;
/** The session's status. */
status: SessionStatusDto;
/** The channel `thread_id` lives in, when the session was spawned from a
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 1fe3feca5d..d47e95c931 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -44,6 +44,8 @@ export * from './createSessionThreadThreadId';
export * from './logDirectionDto';
export * from './logFrameDto';
export * from './logFrameDtoContent';
+export * from './sandboxSize';
+export * from './sandboxSizeBody';
export * from './sessionBot';
export * from './sessionBotAvatarUrl';
export * from './sessionStatusDto';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sandboxSize.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sandboxSize.ts
new file mode 100644
index 0000000000..9d4ffd1dea
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sandboxSize.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Named compute tier for a managed sandbox.
+
+Disk is always 96 GiB; CPU and RAM vary. The API and database store the
+name, never raw resource integers.
+ */
+export type SandboxSize = (typeof SandboxSize)[keyof typeof SandboxSize];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const SandboxSize = {
+ small: 'small',
+ default: 'default',
+ large: 'large',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sandboxSizeBody.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sandboxSizeBody.ts
new file mode 100644
index 0000000000..f1653916ce
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sandboxSizeBody.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SandboxSize } from './sandboxSize';
+
+/**
+ * Request or response body for a named sandbox size.
+ */
+export interface SandboxSizeBody {
+ /** Named compute tier. */
+ size: SandboxSize;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 3e1483d1ad..2dac7e5fb8 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -10,6 +10,92 @@
"version": "0.1.0"
},
"paths": {
+ "/agent-sandbox-size": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "Read the caller's default sandbox size for new `@coder` sessions.",
+ "operationId": "get_agent_sandbox_size",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SandboxSizeBody"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Set the caller's default sandbox size for the next `@coder` mention.",
+ "operationId": "put_agent_sandbox_size",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SandboxSizeBody"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SandboxSizeBody"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions": {
"post": {
"tags": ["agent-sessions"],
@@ -335,6 +421,77 @@
}
}
}
+ },
+ "/agent-sessions/{session_id}/sandbox-size": {
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Resize this session's sandbox and remember the size as the owner's default.",
+ "operationId": "put_agent_session_sandbox_size",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SandboxSizeBody"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SandboxSizeBody"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"components": {
@@ -471,6 +628,7 @@
"model",
"harness",
"workspace",
+ "sandboxSize",
"status",
"createdAt",
"modifiedAt"
@@ -521,6 +679,10 @@
"type": ["string", "null"],
"description": "The repository the session works with, when one was stated."
},
+ "sandboxSize": {
+ "$ref": "#/components/schemas/SandboxSize",
+ "description": "Compute tier of the managed sandbox."
+ },
"status": {
"$ref": "#/components/schemas/SessionStatusDto",
"description": "The session's status."
@@ -659,6 +821,22 @@
}
}
},
+ "SandboxSize": {
+ "type": "string",
+ "description": "Named compute tier for a managed sandbox.\n\nDisk is always 96 GiB; CPU and RAM vary. The API and database store the\nname, never raw resource integers.",
+ "enum": ["small", "default", "large"]
+ },
+ "SandboxSizeBody": {
+ "type": "object",
+ "description": "Request or response body for a named sandbox size.",
+ "required": ["size"],
+ "properties": {
+ "size": {
+ "$ref": "#/components/schemas/SandboxSize",
+ "description": "Named compute tier."
+ }
+ }
+ },
"SessionBot": {
"type": "object",
"description": "The agent behind a session, as much of it as rendering a message needs.",
diff --git a/crates/agent_harness/justfile b/crates/agent_harness/justfile
index f9799e4a67..f8ec6938ca 100644
--- a/crates/agent_harness/justfile
+++ b/crates/agent_harness/justfile
@@ -23,6 +23,13 @@ set dotenv-load := true
# repository in Namespace's nscr.io workspace registry.
image_name := env_var_or_default("AGENT_HARNESS_IMAGE", "macro-agent-harness")
+# Default sandbox size baked into the snapshot. CI exports the same three
+# values. Live Daytona orgs still on the 4/8/10 per-sandbox cap cannot
+# create this until [email protected] raises the limit.
+snapshot_cpu := env_var_or_default("DAYTONA_SNAPSHOT_CPU", "8")
+snapshot_memory := env_var_or_default("DAYTONA_SNAPSHOT_MEMORY", "16")
+snapshot_disk := env_var_or_default("DAYTONA_SNAPSHOT_DISK", "96")
+
# Cheap for the agent to answer, and it proves the repo actually cloned.
default_prompt := "list the files in the repo root, then stop"
@@ -30,30 +37,64 @@ default_prompt := "list the files in the repo root, then stop"
default:
@just --list
-# Build the Daytona snapshot if missing.
+# Build the Daytona snapshot if missing. If it exists at the wrong size,
+# fail without deleting it (a recreate that 400s on per-sandbox limits
+# would leave @coder unable to spawn).
ensure-daytona:
#!/usr/bin/env bash
set -euo pipefail
# Daytona has no "build from a local Dockerfile at create time" mode, so
# the image becomes a snapshot once, out of band, and sandboxes boot from
# that.
- if daytona snapshot list | grep -qw {{image_name}}; then
- echo "snapshot {{image_name}} already exists, skipping build"
- else
- echo "building snapshot {{image_name}} (slow: the image bakes two nix dev shells)"
- # 10GB disk is the account's per-sandbox ceiling; raising it needs Daytona support.
- # `--context .` matters twice over. Without any `--context` the CLI
- # auto-detects from COPY lines and misses
- # `COPY sidecar/Cargo.toml sidecar/Cargo.lock ./`; with per-entry contexts
- # (`--context sidecar`) it uploads that directory's *contents* flattened, so
- # the `sidecar/` prefix the Dockerfile copies from does not exist. Either
- # way the build dies in the sidecar stage with "/sidecar/src: not found".
- # Passing the directory keeps paths intact - it is only ~84KB.
- ( cd container && daytona snapshot create {{image_name}} \
- --dockerfile Dockerfile \
- --context . \
- --cpu 4 --memory 8 --disk 10 )
- fi
+ name={{image_name}}
+ cpu={{snapshot_cpu}}
+ memory={{snapshot_memory}}
+ disk={{snapshot_disk}}
+ echo "desired snapshot $name at --cpu $cpu --memory $memory --disk $disk"
+ state="$(daytona snapshot list --format json | python3 -c '
+import json, sys
+name, cpu, memory, disk = sys.argv[1:5]
+found = next((item for item in json.load(sys.stdin) if item.get("name") == name), None)
+if found is None:
+ print("missing")
+ raise SystemExit(0)
+current_cpu = int(found.get("cpu") or 0)
+current_memory = int(found.get("mem") or found.get("memory") or 0)
+current_disk = int(found.get("disk") or 0)
+if current_cpu == int(cpu) and current_memory == int(memory) and current_disk == int(disk):
+ print("match")
+ raise SystemExit(0)
+print(f"mismatch cpu={current_cpu} memory={current_memory} disk={current_disk}")
+' "$name" "$cpu" "$memory" "$disk")"
+ case "$state" in
+ match)
+ echo "snapshot $name already exists at --cpu $cpu --memory $memory --disk $disk, skipping build"
+ ;;
+ mismatch*)
+ echo "$state" >&2
+ echo "snapshot $name is not --cpu $cpu --memory $memory --disk $disk" >&2
+ echo "not deleting it: recreate with 'just rebuild-daytona' after Daytona raises per-sandbox limits ([email protected])" >&2
+ exit 1
+ ;;
+ missing)
+ echo "building snapshot $name (slow: the image bakes two nix dev shells)"
+ # `--context .` matters twice over. Without any `--context` the CLI
+ # auto-detects from COPY lines and misses
+ # `COPY sidecar/Cargo.toml sidecar/Cargo.lock ./`; with per-entry contexts
+ # (`--context sidecar`) it uploads that directory's *contents* flattened, so
+ # the `sidecar/` prefix the Dockerfile copies from does not exist. Either
+ # way the build dies in the sidecar stage with "/sidecar/src: not found".
+ # Passing the directory keeps paths intact - it is only ~84KB.
+ ( cd container && daytona snapshot create "$name" \
+ --dockerfile Dockerfile \
+ --context . \
+ --cpu "$cpu" --memory "$memory" --disk "$disk" )
+ ;;
+ *)
+ echo "unexpected snapshot state: $state" >&2
+ exit 1
+ ;;
+ esac
# Build the Daytona snapshot if missing, then boot an agent in a sandbox
boot-daytona prompt=default_prompt: ensure-daytona
diff --git a/crates/agent_harness/src/domain/mod.rs b/crates/agent_harness/src/domain/mod.rs
index 585b0ec2f5..bdef7069cb 100644
--- a/crates/agent_harness/src/domain/mod.rs
+++ b/crates/agent_harness/src/domain/mod.rs
@@ -1,5 +1,7 @@
pub mod error;
pub mod model;
pub mod ports;
+/// Compute resources for a sandbox size.
+pub mod sandbox;
/// The harness orchestrator: containers, announcements, and trigger commands.
pub mod service;
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 74a4294891..3cb7c96657 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -1,7 +1,7 @@
//! Commands and values used by the harness domain.
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
-use agent_session::domain::model::{AgentSessionId, MessageId};
+use agent_session::domain::model::{AgentSessionId, MessageId, SandboxSize};
use agent_session::domain::ports::ControlEvent;
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
@@ -90,6 +90,8 @@ pub enum HarnessCommand {
Open(OpenSession),
/// Act on a session that already exists.
Deliver(DeliverAction),
+ /// Change the session's sandbox size and the owner's default.
+ SetSandboxSize(SandboxSize),
/// Release a session's live resources and delete it.
Delete,
}
@@ -169,6 +171,8 @@ pub struct SpawnContainer {
pub session_id: AgentSessionId,
/// Repository cloned into the container workspace.
pub repo_url: String,
+ /// Compute tier to request from the provider.
+ pub size: SandboxSize,
}
/// Session-row values that remain deployment configuration for now.
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index fa1355640d..2d9db0fed6 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -1,12 +1,13 @@
//! Outbound capabilities required by the harness domain.
use agent_session::domain::connection::RuntimeAttachment;
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentSessionId, SandboxSize};
use agent_session::domain::ports::AgentConnector;
use bot_id::BotId;
use super::error::Result;
use super::model::{SessionAnnouncement, SpawnContainer};
+use super::sandbox::SandboxResizeEffect;
#[cfg(test)]
mod test;
@@ -56,6 +57,25 @@ pub trait ContainerManager: Send + Sync + 'static {
command: SpawnContainer,
) -> impl Future<Output = Result<Self::Transport>> + Send;
+ /// How this manager applies a change from `from` to `to`.
+ ///
+ /// Domain uses this to decide whether to close the session before
+ /// [`Self::resize`]. Named size → CPU/RAM mapping is harness policy;
+ /// whether a running container can take that change is a manager
+ /// capability.
+ fn resize_effect(&self, from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect;
+
+ /// Change a live sandbox's compute to `size`.
+ ///
+ /// Domain has already closed the session when [`Self::resize_effect`]
+ /// returned [`SandboxResizeEffect::Restart`]. [`SandboxResizeEffect::InPlace`]
+ /// must not stop the sandbox. Disk is never changed.
+ fn resize(
+ &self,
+ session: AgentSessionId,
+ size: SandboxSize,
+ ) -> impl Future<Output = Result<()>> + Send;
+
/// Reattach to a session's existing container, starting it if stopped.
fn resume(
&self,
diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rs
index 127bb42356..fd1d31effc 100644
--- a/crates/agent_harness/src/domain/ports/test.rs
+++ b/crates/agent_harness/src/domain/ports/test.rs
@@ -34,6 +34,7 @@ fn params(id: AgentSessionId) -> CreateAgentSessionParams {
harness: "opencode".to_owned(),
repo_url: Some("https://github.com/macro/macro".to_owned()),
workspace: "/workspace".to_owned(),
+ sandbox_size: agent_session::domain::model::SandboxSize::Default,
}
}
@@ -63,6 +64,7 @@ async fn container_session_runs_and_logs_end_to_end() {
.spawn(SpawnContainer {
session_id: id,
repo_url: "https://github.com/macro/macro".to_owned(),
+ size: agent_session::domain::model::SandboxSize::Default,
})
.await
.unwrap();
diff --git a/crates/agent_harness/src/domain/sandbox.rs b/crates/agent_harness/src/domain/sandbox.rs
new file mode 100644
index 0000000000..1c0f75abde
--- /dev/null
+++ b/crates/agent_harness/src/domain/sandbox.rs
@@ -0,0 +1,99 @@
+//! Compute resources for a [`SandboxSize`].
+
+use agent_session::domain::model::SandboxSize;
+
+#[cfg(test)]
+mod test;
+
+/// CPU, RAM, and disk for one sandbox size.
+///
+/// Disk is 96 GiB for every tier so a live session can raise CPU/RAM in place
+/// without a disk migrate. Growing disk requires a stop; shrinking it is not
+/// supported.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SandboxResources {
+ /// vCPU cores.
+ pub cpu: u32,
+ /// RAM in GiB.
+ pub memory_gib: u32,
+ /// Disk in GiB. Constant across tiers.
+ pub disk_gib: u32,
+}
+
+/// How a container manager applies a named size change.
+///
+/// Product sizes live in this module. Whether an existing container can take
+/// that change — in place, after a stop, or not at all — is a
+/// [`crate::domain::ports::ContainerManager`] capability.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SandboxResizeEffect {
+ /// Already at the requested size.
+ NoOp,
+ /// Change compute without stopping the container.
+ InPlace,
+ /// Container must be stopped first. Domain closes the session, then
+ /// [`crate::domain::ports::ContainerManager::resize`], then resume+attach.
+ Restart,
+ /// This manager cannot change size on an existing container.
+ Unsupported,
+}
+
+/// Resources for `size`. Disk is always 96 GiB.
+#[must_use]
+pub fn resources(size: SandboxSize) -> SandboxResources {
+ match size {
+ SandboxSize::Small => SandboxResources {
+ cpu: 2,
+ memory_gib: 4,
+ disk_gib: 96,
+ },
+ SandboxSize::Default => SandboxResources {
+ cpu: 8,
+ memory_gib: 16,
+ disk_gib: 96,
+ },
+ SandboxSize::Large => SandboxResources {
+ cpu: 16,
+ memory_gib: 32,
+ disk_gib: 96,
+ },
+ }
+}
+
+/// CPU/RAM comparison used by managers that can resize a live container.
+///
+/// Disk is ignored: named tiers never change disk, and shrinking it is not
+/// supported. Spawn uses this against a snapshot's live CPU/RAM because
+/// `POST /sandbox` with a snapshot cannot set resources.
+#[must_use]
+pub fn resize_effect(from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect {
+ resize_effect_from_resources(resources(from), resources(to))
+}
+
+/// Size change for managers that can only pick resources at create time.
+#[must_use]
+pub fn create_only_resize_effect(from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect {
+ if from == to {
+ SandboxResizeEffect::NoOp
+ } else {
+ SandboxResizeEffect::Unsupported
+ }
+}
+
+/// CPU/RAM comparison between two resource quotas.
+///
+/// Increases can apply in place. A decrease needs a stop. Equal CPU and RAM
+/// is a no-op.
+#[must_use]
+pub fn resize_effect_from_resources(
+ current: SandboxResources,
+ next: SandboxResources,
+) -> SandboxResizeEffect {
+ if current.cpu == next.cpu && current.memory_gib == next.memory_gib {
+ SandboxResizeEffect::NoOp
+ } else if next.cpu >= current.cpu && next.memory_gib >= current.memory_gib {
+ SandboxResizeEffect::InPlace
+ } else {
+ SandboxResizeEffect::Restart
+ }
+}
diff --git a/crates/agent_harness/src/domain/sandbox/test.rs b/crates/agent_harness/src/domain/sandbox/test.rs
new file mode 100644
index 0000000000..706ad4239f
--- /dev/null
+++ b/crates/agent_harness/src/domain/sandbox/test.rs
@@ -0,0 +1,81 @@
+use super::*;
+
+#[test]
+fn disk_is_96_gib_for_every_tier() {
+ for size in [SandboxSize::Small, SandboxSize::Default, SandboxSize::Large] {
+ assert_eq!(resources(size).disk_gib, 96);
+ }
+}
+
+#[test]
+fn default_is_eight_cpu_sixteen_gib() {
+ assert_eq!(
+ resources(SandboxSize::Default),
+ SandboxResources {
+ cpu: 8,
+ memory_gib: 16,
+ disk_gib: 96,
+ }
+ );
+}
+
+#[test]
+fn cpu_ram_increases_are_in_place_and_decreases_need_a_restart() {
+ assert_eq!(
+ resize_effect(SandboxSize::Small, SandboxSize::Default),
+ SandboxResizeEffect::InPlace
+ );
+ assert_eq!(
+ resize_effect(SandboxSize::Default, SandboxSize::Large),
+ SandboxResizeEffect::InPlace
+ );
+ assert_eq!(
+ resize_effect(SandboxSize::Small, SandboxSize::Large),
+ SandboxResizeEffect::InPlace
+ );
+ assert_eq!(
+ resize_effect(SandboxSize::Large, SandboxSize::Default),
+ SandboxResizeEffect::Restart
+ );
+ assert_eq!(
+ resize_effect(SandboxSize::Default, SandboxSize::Small),
+ SandboxResizeEffect::Restart
+ );
+ assert_eq!(
+ resize_effect(SandboxSize::Default, SandboxSize::Default),
+ SandboxResizeEffect::NoOp
+ );
+}
+
+#[test]
+fn live_quotas_that_are_not_named_tiers_still_pick_in_place_or_restart() {
+ let snapshot = SandboxResources {
+ cpu: 4,
+ memory_gib: 8,
+ disk_gib: 10,
+ };
+ assert_eq!(
+ resize_effect_from_resources(snapshot, resources(SandboxSize::Default)),
+ SandboxResizeEffect::InPlace
+ );
+ assert_eq!(
+ resize_effect_from_resources(resources(SandboxSize::Default), snapshot),
+ SandboxResizeEffect::Restart
+ );
+ assert_eq!(
+ resize_effect_from_resources(snapshot, snapshot),
+ SandboxResizeEffect::NoOp
+ );
+}
+
+#[test]
+fn create_only_managers_cannot_change_size() {
+ assert_eq!(
+ create_only_resize_effect(SandboxSize::Default, SandboxSize::Default),
+ SandboxResizeEffect::NoOp
+ );
+ assert_eq!(
+ create_only_resize_effect(SandboxSize::Default, SandboxSize::Large),
+ SandboxResizeEffect::Unsupported
+ );
+}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 9a39f1be13..9d32d84a55 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -7,7 +7,7 @@ use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::{
- AgentSession, AgentSessionId, AuthorKind, CreateAgentSessionParams, MessageId,
+ AgentSession, AgentSessionId, AuthorKind, CreateAgentSessionParams, MessageId, SandboxSize,
};
use agent_session::domain::ports::{AgentSessionNotificationRecipient, ControlEvent};
use agent_session::domain::service::AgentSessionService;
@@ -23,6 +23,7 @@ use crate::domain::model::{
SessionAnnouncement, SessionDefaults, SpawnContainer, is_managed_bot,
};
use crate::domain::ports::{ContainerManager, RuntimeConnections, SessionAnnouncer};
+use crate::domain::sandbox::SandboxResizeEffect;
type SessionWorkers = DashMap<AgentSessionId, mpsc::UnboundedSender<QueuedCommand>>;
@@ -204,6 +205,16 @@ where
.map_err(into_session_error)?;
Ok(action_id)
}
+
+ async fn set_sandbox_size(
+ &self,
+ id: AgentSessionId,
+ size: SandboxSize,
+ ) -> agent_session::domain::error::Result<()> {
+ self.execute(id, HarnessCommand::SetSandboxSize(size))
+ .await
+ .map_err(into_session_error)
+ }
}
/// External sessions create the row and announce - the magic-chip message
@@ -238,6 +249,7 @@ where
harness: self.inner.defaults.harness.clone(),
repo_url: request.repo_url,
workspace: request.workspace,
+ sandbox_size: SandboxSize::Default,
// The thread linkage is the caller's claim, not an observed
// mention; it must not grant the channel anything.
})
@@ -277,6 +289,11 @@ where
request: agent_session::domain::ports::OpenManagedSession,
) -> agent_session::domain::error::Result<AgentSession> {
let defaults = &self.inner.defaults;
+ let sandbox_size = self
+ .inner
+ .sessions
+ .user_sandbox_size(&request.owner)
+ .await?;
let session = self
.inner
.sessions
@@ -291,6 +308,7 @@ where
repo_url: Some(defaults.repo_url.clone()),
// Managed sandboxes run in the path baked into their image.
workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
+ sandbox_size,
})
.await?;
@@ -300,6 +318,7 @@ where
.spawn(SpawnContainer {
session_id: session.id,
repo_url: defaults.repo_url.clone(),
+ size: sandbox_size,
})
.await
{
@@ -385,6 +404,7 @@ where
match command {
HarnessCommand::Open(command) => self.open(session_id, command).await,
HarnessCommand::Deliver(command) => self.deliver(session_id, command).await,
+ HarnessCommand::SetSandboxSize(size) => self.apply_sandbox_size(session_id, size).await,
HarnessCommand::Delete => self.delete(session_id).await,
}
}
@@ -403,6 +423,37 @@ where
Ok(())
}
+ /// Apply `size` to this session's sandbox and remember it as the owner's default.
+ ///
+ /// The container manager reports whether the change is in-place, needs a
+ /// stop, or is unsupported. Disk is never changed.
+ #[tracing::instrument(err, skip(self), fields(%session_id, %size))]
+ async fn apply_sandbox_size(
+ &self,
+ session_id: AgentSessionId,
+ size: SandboxSize,
+ ) -> Result<()> {
+ let session = self.sessions.get_session(session_id).await?;
+ let effect = self.containers.resize_effect(session.sandbox_size, size);
+ if is_managed_bot(session.bot_id) && effect != SandboxResizeEffect::NoOp {
+ if effect == SandboxResizeEffect::Restart {
+ self.sessions.close_session(session_id).await?;
+ }
+ self.containers.resize(session_id, size).await?;
+ if effect == SandboxResizeEffect::Restart {
+ let container = self.containers.resume(session_id).await?;
+ self.sessions
+ .attach_session(session_id, RuntimeAttachment::solo(container))
+ .await?;
+ }
+ }
+ self.sessions.set_sandbox_size(session_id, size).await?;
+ self.sessions
+ .set_user_sandbox_size(&session.owner_id, size)
+ .await?;
+ Ok(())
+ }
+
#[tracing::instrument(err, skip(self, command), fields(
%session_id,
bot_id = %command.bot_id,
@@ -411,6 +462,7 @@ where
async fn open(&self, session_id: AgentSessionId, command: OpenSession) -> Result<()> {
let OpenSession { bot_id, origin } = command;
let repo_url = self.defaults.repo_url.clone();
+ let sandbox_size = self.sessions.user_sandbox_size(&origin.sender).await?;
self.sessions
.create_session(CreateAgentSessionParams {
@@ -424,6 +476,7 @@ where
repo_url: Some(repo_url.clone()),
// Managed sandboxes run in the path baked into their image.
workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
+ sandbox_size,
// This open came from the trigger pipeline seeing the mention.
})
.await?;
@@ -445,6 +498,7 @@ where
.spawn(SpawnContainer {
session_id,
repo_url,
+ size: sandbox_size,
})
.await
{
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 47d743d0e5..0076bf994c 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -16,7 +16,9 @@ use agent_runtime_protocol::domain::{
schema::v0::{AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage},
};
use agent_session::PROTOCOL_VERSION;
-use agent_session::domain::model::{AgentSessionId, CreateAgentSessionParams, Message};
+use agent_session::domain::model::{
+ AgentSessionId, CreateAgentSessionParams, Message, SandboxSize,
+};
use agent_session::domain::ports::{
AgentSessionLogRepo as _, AgentSessionNotificationRecipient as _, AgentSessionRepo as _,
ControlEvent, NoOpRealtime,
@@ -39,7 +41,9 @@ use crate::testing::helpers::agent::FakeAgent;
use crate::testing::helpers::announcer::AnnouncerMock;
use crate::testing::helpers::containers::{ContainerMock, ContainerSender, MockContainerManager};
use agent_session::domain::error::AgentSessionError;
-use agent_session::domain::ports::{OpenExternalAgentSession, SessionOpener as _};
+use agent_session::domain::ports::{
+ OpenExternalAgentSession, OpenManagedSession, SessionOpener as _,
+};
fn sender() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
@@ -175,6 +179,7 @@ async fn disconnected_session(
harness: "opencode".to_owned(),
repo_url: Some("https://github.com/macro-inc/macro".to_owned()),
workspace: "/workspace".to_owned(),
+ sandbox_size: agent_session::domain::model::SandboxSize::Default,
},
)
.await
@@ -186,6 +191,7 @@ async fn disconnected_session(
.spawn(SpawnContainer {
session_id: id,
repo_url: "https://github.com/macro-inc/macro".to_owned(),
+ size: agent_session::domain::model::SandboxSize::Default,
})
.await
.expect("the original sandbox should exist");
@@ -1137,3 +1143,156 @@ async fn an_announce_whose_bot_does_not_own_the_session_is_dropped() {
assert_eq!(announcer.announced().len(), 0);
}
+
+#[tokio::test]
+async fn open_spawns_at_the_users_default_size() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ repo.set_user_sandbox_size(&sender(), SandboxSize::Small)
+ .await
+ .expect("the user default should persist");
+ let command = open_command();
+ let id = AgentSessionId::new();
+
+ let open = service.execute(id, HarnessCommand::Open(command));
+ let drive = async {
+ loop {
+ if containers.spawned() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let container = containers
+ .container(session_of(&containers))
+ .expect("the spawned container is findable");
+ complete_handshake(&container).await;
+ };
+ let (opened, _) = tokio::join!(open, drive);
+ opened.expect("open should succeed");
+
+ assert_eq!(containers.spawn_sizes(), [SandboxSize::Small]);
+ assert_eq!(
+ repo.get(id)
+ .await
+ .expect("the session row exists")
+ .sandbox_size,
+ SandboxSize::Small
+ );
+}
+
+#[tokio::test]
+async fn open_managed_session_spawns_at_the_users_default_size() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ repo.set_user_sandbox_size(&sender(), SandboxSize::Small)
+ .await
+ .expect("the user default should persist");
+
+ let open = service.open_managed_session(OpenManagedSession {
+ owner: sender(),
+ prompt: None,
+ });
+ let drive = async {
+ loop {
+ if containers.spawned() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let container = containers
+ .container(session_of(&containers))
+ .expect("the spawned container is findable");
+ complete_handshake(&container).await;
+ };
+ let (opened, _) = tokio::join!(open, drive);
+ let session = opened.expect("open should succeed");
+
+ assert_eq!(containers.spawn_sizes(), [SandboxSize::Small]);
+ assert_eq!(session.sandbox_size, SandboxSize::Small);
+ assert_eq!(
+ repo.get(session.id)
+ .await
+ .expect("the session row exists")
+ .sandbox_size,
+ SandboxSize::Small
+ );
+}
+
+#[tokio::test]
+async fn set_sandbox_size_hot_resizes_and_updates_the_user_default() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let id = disconnected_session(&repo, &containers).await;
+
+ service
+ .set_sandbox_size(id, SandboxSize::Large)
+ .await
+ .expect("hot resize should succeed");
+
+ assert_eq!(containers.resizes(), [(id, SandboxSize::Large)]);
+ assert_eq!(
+ repo.get(id).await.expect("session").sandbox_size,
+ SandboxSize::Large
+ );
+ assert_eq!(
+ repo.user_sandbox_size(&sender())
+ .await
+ .expect("user default"),
+ SandboxSize::Large
+ );
+ assert_eq!(containers.resumed(), 0);
+}
+
+#[tokio::test]
+async fn set_sandbox_size_restart_closes_resizes_and_resumes() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let id = disconnected_session(&repo, &containers).await;
+
+ service
+ .set_sandbox_size(id, SandboxSize::Small)
+ .await
+ .expect("restart resize should succeed");
+
+ assert_eq!(containers.resizes(), [(id, SandboxSize::Small)]);
+ assert_eq!(containers.resumed(), 1);
+ assert_eq!(
+ repo.get(id).await.expect("session").sandbox_size,
+ SandboxSize::Small
+ );
+}
+
+#[tokio::test]
+async fn set_sandbox_size_same_tier_does_not_resize() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let id = disconnected_session(&repo, &containers).await;
+
+ service
+ .set_sandbox_size(id, SandboxSize::Default)
+ .await
+ .expect("no-op size should succeed");
+
+ assert!(containers.resizes().is_empty());
+ assert_eq!(containers.resumed(), 0);
+ assert_eq!(
+ repo.get(id).await.expect("session").sandbox_size,
+ SandboxSize::Default
+ );
+}
+
+#[tokio::test]
+async fn set_sandbox_size_unsupported_does_not_persist() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let id = disconnected_session(&repo, &containers).await;
+ containers.refuse_resize();
+
+ let error = service
+ .set_sandbox_size(id, SandboxSize::Large)
+ .await
+ .expect_err("unsupported resize should fail");
+ assert!(
+ error.to_string().contains("cannot resize"),
+ "unexpected error: {error}"
+ );
+ assert_eq!(
+ repo.get(id).await.expect("session").sandbox_size,
+ SandboxSize::Default
+ );
+ assert_eq!(containers.resumed(), 0);
+}
diff --git a/crates/agent_harness/src/outbound/containers.rs b/crates/agent_harness/src/outbound/containers.rs
index 0b688e5757..7a538bf1ab 100644
--- a/crates/agent_harness/src/outbound/containers.rs
+++ b/crates/agent_harness/src/outbound/containers.rs
@@ -11,11 +11,12 @@
use agent_runtime_protocol::domain::ports::Transport;
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentSessionId, SandboxSize};
use crate::domain::error::Result;
use crate::domain::model::SpawnContainer;
use crate::domain::ports::ContainerManager;
+use crate::domain::sandbox::SandboxResizeEffect;
use crate::outbound::daytona::{DaytonaContainer, DaytonaContainerManager};
use crate::outbound::local::LocalContainerManager;
use crate::outbound::sidecar::{SidecarSender, SidecarTransport};
@@ -58,6 +59,20 @@ impl ContainerManager for HarnessContainers {
}
}
+ fn resize_effect(&self, from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect {
+ match self {
+ Self::Daytona(manager) => manager.resize_effect(from, to),
+ Self::Local(manager) => manager.resize_effect(from, to),
+ }
+ }
+
+ async fn resize(&self, session: AgentSessionId, size: SandboxSize) -> Result<()> {
+ match self {
+ Self::Daytona(manager) => manager.resize(session, size).await,
+ Self::Local(manager) => manager.resize(session, size).await,
+ }
+ }
+
async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {
match self {
Self::Daytona(manager) => manager.resume(session).await.map(HarnessContainer::Daytona),
diff --git a/crates/agent_harness/src/outbound/daytona/client.rs b/crates/agent_harness/src/outbound/daytona/client.rs
index 07041ebc21..26e3fafa22 100644
--- a/crates/agent_harness/src/outbound/daytona/client.rs
+++ b/crates/agent_harness/src/outbound/daytona/client.rs
@@ -15,6 +15,8 @@ const POLL_INTERVAL: Duration = Duration::from_millis(250);
#[serde(rename_all = "snake_case")]
enum SandboxState {
Started,
+ Stopped,
+ Resizing,
Error,
BuildFailed,
#[serde(other)]
@@ -27,6 +29,9 @@ struct SandboxDto {
id: String,
state: SandboxState,
error_reason: Option<String>,
+ cpu: Option<u32>,
+ memory: Option<u32>,
+ disk: Option<u32>,
}
#[derive(Debug, Deserialize)]
@@ -67,11 +72,26 @@ struct ExecuteRequest<'a> {
timeout: u64,
}
-fn configuration_parameters(
- snapshot: &Snapshot,
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ResizeSandboxRequest {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ cpu: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ memory: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ disk: Option<u32>,
+}
+
+fn resize_not_enabled(status: reqwest::StatusCode, body: &str) -> bool {
+ status == reqwest::StatusCode::NOT_FOUND && body.contains("Cannot POST")
+}
+
+fn configuration_parameters<'a>(
+ snapshot: &'a Snapshot,
env: Env,
labels: Labels,
-) -> CreateSandboxRequest<'_> {
+) -> CreateSandboxRequest<'a> {
CreateSandboxRequest {
snapshot,
env,
@@ -99,7 +119,11 @@ impl DaytonaClient {
}
}
- /// Create a sandbox and return its Daytona id.
+ /// Create a sandbox from a snapshot and return its Daytona id.
+ ///
+ /// Resource fields must be omitted: Daytona returns 400 ("Cannot specify
+ /// Sandbox resources when using a snapshot") if `cpu` / `memory` / `disk`
+ /// are sent with `snapshot`. Size is applied after start via [`Self::resize`].
#[tracing::instrument(err, skip(self, env))]
pub async fn create(&self, snapshot: &Snapshot, env: Env, labels: Labels) -> Result<String> {
let request = configuration_parameters(snapshot, env, labels);
@@ -115,6 +139,50 @@ impl DaytonaClient {
Ok(sandbox.id)
}
+ /// Current CPU, RAM, and disk quotas for a sandbox, when Daytona reports them.
+ #[tracing::instrument(err, skip(self))]
+ pub async fn resources(
+ &self,
+ sandbox_id: &str,
+ ) -> Result<(Option<u32>, Option<u32>, Option<u32>)> {
+ let sandbox: SandboxDto = self
+ .json(
+ self.http.get(format!("{}/sandbox/{sandbox_id}", self.base)),
+ "get sandbox",
+ )
+ .await?;
+ Ok((sandbox.cpu, sandbox.memory, sandbox.disk))
+ }
+
+ /// Resize CPU, RAM, and/or disk. Omit a field to leave it unchanged.
+ ///
+ /// In-place resize (running sandbox) accepts CPU/RAM increases only. Disk
+ /// changes and CPU/RAM decreases require a stopped sandbox.
+ #[tracing::instrument(err, skip(self))]
+ pub async fn resize(
+ &self,
+ sandbox_id: &str,
+ cpu: Option<u32>,
+ memory: Option<u32>,
+ disk: Option<u32>,
+ ) -> Result<()> {
+ let result = self
+ .json::<serde::de::IgnoredAny>(
+ self.http
+ .post(format!("{}/sandbox/{sandbox_id}/resize", self.base))
+ .json(&ResizeSandboxRequest { cpu, memory, disk }),
+ "resize sandbox",
+ )
+ .await;
+ match result {
+ Ok(_) => Ok(()),
+ Err(DaytonaError::Api { status, body, .. }) if resize_not_enabled(status, &body) => {
+ Err(DaytonaError::ResizeNotEnabled)
+ }
+ Err(error) => Err(error),
+ }
+ }
+
/// Find one sandbox carrying the supplied label.
#[tracing::instrument(err, skip(self))]
pub async fn find_by_label(&self, label: &str, value: &str) -> Result<Option<String>> {
@@ -165,7 +233,81 @@ impl DaytonaClient {
.unwrap_or_else(|| "no reason given".to_owned()),
});
}
- SandboxState::Other => {}
+ SandboxState::Stopped | SandboxState::Resizing | SandboxState::Other => {}
+ }
+
+ if Instant::now() >= deadline {
+ return Err(DaytonaError::SandboxStartTimeout {
+ sandbox_id: sandbox_id.to_owned(),
+ timeout,
+ });
+ }
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+ }
+
+ /// Poll a sandbox until it has stopped or the deadline passes.
+ #[tracing::instrument(err, skip(self))]
+ pub async fn wait_for_stopped(&self, sandbox_id: &str, timeout: Duration) -> Result<()> {
+ let deadline = Instant::now() + timeout;
+ loop {
+ let sandbox: SandboxDto = self
+ .json(
+ self.http.get(format!("{}/sandbox/{sandbox_id}", self.base)),
+ "get sandbox",
+ )
+ .await?;
+
+ match sandbox.state {
+ SandboxState::Stopped => return Ok(()),
+ SandboxState::Error | SandboxState::BuildFailed => {
+ return Err(DaytonaError::SandboxStart {
+ sandbox_id: sandbox_id.to_owned(),
+ state: format!("{:?}", sandbox.state),
+ reason: sandbox
+ .error_reason
+ .unwrap_or_else(|| "no reason given".to_owned()),
+ });
+ }
+ SandboxState::Started | SandboxState::Resizing | SandboxState::Other => {}
+ }
+
+ if Instant::now() >= deadline {
+ return Err(DaytonaError::SandboxStartTimeout {
+ sandbox_id: sandbox_id.to_owned(),
+ timeout,
+ });
+ }
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+ }
+
+ /// Poll until a resize is no longer in progress.
+ #[tracing::instrument(err, skip(self))]
+ pub async fn wait_for_resize(&self, sandbox_id: &str, timeout: Duration) -> Result<()> {
+ let deadline = Instant::now() + timeout;
+ loop {
+ let sandbox: SandboxDto = self
+ .json(
+ self.http.get(format!("{}/sandbox/{sandbox_id}", self.base)),
+ "get sandbox",
+ )
+ .await?;
+
+ match sandbox.state {
+ SandboxState::Resizing => {}
+ SandboxState::Error | SandboxState::BuildFailed => {
+ return Err(DaytonaError::SandboxStart {
+ sandbox_id: sandbox_id.to_owned(),
+ state: format!("{:?}", sandbox.state),
+ reason: sandbox
+ .error_reason
+ .unwrap_or_else(|| "no reason given".to_owned()),
+ });
+ }
+ SandboxState::Started | SandboxState::Stopped | SandboxState::Other => {
+ return Ok(());
+ }
}
if Instant::now() >= deadline {
diff --git a/crates/agent_harness/src/outbound/daytona/client/test.rs b/crates/agent_harness/src/outbound/daytona/client/test.rs
index 072ca985d5..831de53f75 100644
--- a/crates/agent_harness/src/outbound/daytona/client/test.rs
+++ b/crates/agent_harness/src/outbound/daytona/client/test.rs
@@ -1,5 +1,19 @@
use super::*;
+mod live_env {
+ macro_env_var::maybe_env_vars! {
+ pub struct DaytonaApiKey;
+ pub struct DaytonaSnapshot;
+ pub struct DaytonaApiUrl;
+ }
+}
+
+fn optional_env(value: Option<impl AsRef<str>>) -> Option<String> {
+ value
+ .map(|value| value.as_ref().trim().to_owned())
+ .filter(|value| !value.is_empty())
+}
+
#[test]
fn sandbox_list_deserializes_the_paginated_daytona_response() {
let response = serde_json::json!({
@@ -21,3 +35,139 @@ fn sandbox_list_deserializes_the_paginated_daytona_response() {
assert_eq!(response.items[0].id, "sandbox-1");
assert_eq!(response.items[0].state, SandboxState::Started);
}
+
+#[test]
+fn create_request_omits_cpu_memory_and_disk() {
+ let snapshot = Snapshot::new("macro-agent-harness".into());
+ let request = configuration_parameters(
+ &snapshot,
+ Env::from(HashMap::new()),
+ Labels::from(HashMap::new()),
+ );
+ let json = serde_json::to_value(&request).expect("create request should serialize");
+ assert_eq!(json["snapshot"], "macro-agent-harness");
+ assert_eq!(json["autoStopInterval"], 0);
+ assert!(json.get("cpu").is_none());
+ assert!(json.get("memory").is_none());
+ assert!(json.get("disk").is_none());
+}
+
+#[test]
+fn resize_request_omits_unset_fields() {
+ let json = serde_json::to_value(&ResizeSandboxRequest {
+ cpu: Some(16),
+ memory: Some(32),
+ disk: None,
+ })
+ .expect("resize request should serialize");
+ assert_eq!(json["cpu"], 16);
+ assert_eq!(json["memory"], 32);
+ assert!(json.get("disk").is_none());
+}
+
+#[test]
+fn resize_404_cannot_post_means_the_route_is_missing() {
+ assert!(resize_not_enabled(
+ reqwest::StatusCode::NOT_FOUND,
+ r#"{"message":"Cannot POST /api/sandbox/abc/resize"}"#,
+ ));
+ assert!(!resize_not_enabled(
+ reqwest::StatusCode::NOT_FOUND,
+ r#"{"message":"Sandbox with ID or name abc not found"}"#,
+ ));
+}
+
+#[tokio::test]
+async fn live_hot_resize_increases_cpu_and_memory_without_touching_disk() {
+ let Some(api_key) = live_env::DaytonaApiKey::new().and_then(|key| optional_env(key.value()))
+ else {
+ eprintln!("skipping live Daytona hot-resize: DAYTONA_API_KEY is unset");
+ return;
+ };
+ let snapshot = live_env::DaytonaSnapshot::new()
+ .and_then(|snapshot| optional_env(snapshot.value()))
+ .unwrap_or_else(|| "macro-agent-harness".to_owned());
+ let api_url = live_env::DaytonaApiUrl::new()
+ .and_then(|url| optional_env(url.value()))
+ .unwrap_or_else(|| "https://app.daytona.io/api".to_owned());
+ let client = DaytonaClient::new(api_url, DaytonaApiKey::new(api_key));
+ let labels = Labels::from(HashMap::from([(
+ "macro.test".to_owned(),
+ format!("sandbox-size-{}", macro_uuid::generate_uuid_v7()),
+ )]));
+ let id = client
+ .create(&Snapshot::new(snapshot), Env::from(HashMap::new()), labels)
+ .await
+ .expect("create a throwaway sandbox");
+
+ let outcome = async {
+ client
+ .wait_for_started(&id, Duration::from_secs(300))
+ .await?;
+ let (cpu, memory, disk) = client.resources(&id).await?;
+ let cpu = cpu.expect("daytona should report cpu after start");
+ let memory = memory.expect("daytona should report memory after start");
+ eprintln!("snapshot sandbox started at cpu={cpu} memory_gib={memory} disk={disk:?}");
+
+ // Stay inside Daytona's default per-sandbox cap (4 vCPU / 8 GiB).
+ // Create-from-snapshot inherits those quotas, so the only in-quota
+ // hot-up is: stop, shrink, start, then raise CPU/RAM without disk.
+ let (low_cpu, low_memory) = (cpu.min(2), memory.min(4));
+ assert!(
+ low_cpu < cpu || low_memory < memory,
+ "need headroom under the snapshot quota to hot-resize back up"
+ );
+
+ eprintln!("stopping to shrink cpu {cpu}->{low_cpu} memory_gib {memory}->{low_memory}");
+ client.stop(&id).await?;
+ client
+ .wait_for_stopped(&id, Duration::from_secs(60))
+ .await?;
+ match client
+ .resize(&id, Some(low_cpu), Some(low_memory), None)
+ .await
+ {
+ Ok(()) => {}
+ Err(error @ DaytonaError::ResizeNotEnabled) => {
+ eprintln!(
+ "skipping live Daytona hot-resize: create-without-resources worked \
+ (cpu={cpu} memory_gib={memory} disk={disk:?}) but POST /sandbox/{{id}}/resize \
+ 404s Cannot POST. The official Python SDK hits the same 404. A missing \
+ sandbox 404s with not found, so the route exists and this organization \
+ does not get the handler."
+ );
+ return Err(error);
+ }
+ Err(error) => return Err(error),
+ }
+ client
+ .wait_for_resize(&id, Duration::from_secs(300))
+ .await?;
+ client.start(&id).await?;
+ client
+ .wait_for_started(&id, Duration::from_secs(300))
+ .await?;
+
+ eprintln!(
+ "hot-resizing cpu {low_cpu}->{cpu} memory_gib {low_memory}->{memory} without disk"
+ );
+ client.resize(&id, Some(cpu), Some(memory), None).await?;
+ client
+ .wait_for_resize(&id, Duration::from_secs(300))
+ .await?;
+ let (after_cpu, after_memory, after_disk) = client.resources(&id).await?;
+ assert_eq!(after_cpu, Some(cpu), "cpu should hot-resize");
+ assert_eq!(after_memory, Some(memory), "memory should hot-resize");
+ assert_eq!(after_disk, disk, "disk should be unchanged");
+ Ok::<(), DaytonaError>(())
+ }
+ .await;
+ if let Err(error) = client.delete(&id).await {
+ eprintln!("failed to delete throwaway sandbox {id}: {error}");
+ }
+ match outcome {
+ Ok(()) => {}
+ Err(DaytonaError::ResizeNotEnabled) => {}
+ Err(error) => panic!("hot resize should succeed: {error}"),
+ }
+}
diff --git a/crates/agent_harness/src/outbound/daytona/errors.rs b/crates/agent_harness/src/outbound/daytona/errors.rs
index 0b9b1b4bfa..0f4b491ec0 100644
--- a/crates/agent_harness/src/outbound/daytona/errors.rs
+++ b/crates/agent_harness/src/outbound/daytona/errors.rs
@@ -28,6 +28,15 @@ pub enum DaytonaError {
status: reqwest::StatusCode,
body: String,
},
+ /// `POST /sandbox/{id}/resize` is not registered for a real sandbox on this API.
+ ///
+ /// Daytona documents resize as generally available. A missing sandbox 404s
+ /// with "not found" (the route exists). A real sandbox 404s with NestJS
+ /// `Cannot POST .../resize` — the official Python SDK hits the same error.
+ #[error(
+ "daytona POST /sandbox/{{id}}/resize is not available for this organization (404 Cannot POST); documented as generally available"
+ )]
+ ResizeNotEnabled,
/// A successful response did not match Daytona's response schema.
#[error("failed to parse the {operation} response: {source}: {body}")]
Decode {
diff --git a/crates/agent_harness/src/outbound/daytona/manager.rs b/crates/agent_harness/src/outbound/daytona/manager.rs
index fb0d6ff1dc..9609497fab 100644
--- a/crates/agent_harness/src/outbound/daytona/manager.rs
+++ b/crates/agent_harness/src/outbound/daytona/manager.rs
@@ -15,6 +15,9 @@ use super::types::{DaytonaSettings, Env, GithubToken, Labels, PortPreview, Snaps
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::SpawnContainer;
use crate::domain::ports::ContainerManager;
+use crate::domain::sandbox::{
+ SandboxResizeEffect, SandboxResources, resize_effect_from_resources, resources,
+};
use crate::outbound::managed_containers::ManagedContainers;
use crate::outbound::provision::{self, SESSION_LABEL};
use crate::outbound::sidecar::SidecarTransport;
@@ -231,6 +234,103 @@ impl DaytonaContainerManager {
}
}
}
+
+ /// Snapshot creates inherit snapshot quotas. Align CPU/RAM to `size`, then
+ /// run the readiness recipe.
+ async fn align_size_then_bring_up(
+ &self,
+ id: &DaytonaSandboxId,
+ size: agent_session::domain::model::SandboxSize,
+ ) -> Result<DaytonaContainer> {
+ self.client
+ .wait_for_started(id.as_str(), provision::ENSURE_TIMEOUT)
+ .await
+ .map_err(unavailable)?;
+ self.align_size(id, size).await?;
+ self.bring_up(id).await
+ }
+
+ async fn align_size(
+ &self,
+ id: &DaytonaSandboxId,
+ size: agent_session::domain::model::SandboxSize,
+ ) -> Result<()> {
+ let (cpu, memory, _) = self
+ .client
+ .resources(id.as_str())
+ .await
+ .map_err(unavailable)?;
+ let cpu = cpu.ok_or_else(|| {
+ HarnessError::Container("daytona did not report cpu for the new sandbox".to_owned())
+ })?;
+ let memory = memory.ok_or_else(|| {
+ HarnessError::Container("daytona did not report memory for the new sandbox".to_owned())
+ })?;
+ let current = SandboxResources {
+ cpu,
+ memory_gib: memory,
+ disk_gib: 96,
+ };
+ let next = resources(size);
+ let kind = resize_effect_from_resources(current, next);
+ tracing::info!(
+ sandbox_id = %id.as_str(),
+ %size,
+ current_cpu = cpu,
+ current_memory_gib = memory,
+ next_cpu = next.cpu,
+ next_memory_gib = next.memory_gib,
+ ?kind,
+ "aligning sandbox size after snapshot create"
+ );
+ self.apply_resize(id, next, kind).await
+ }
+
+ async fn apply_resize(
+ &self,
+ id: &DaytonaSandboxId,
+ next: SandboxResources,
+ effect: SandboxResizeEffect,
+ ) -> Result<()> {
+ match effect {
+ SandboxResizeEffect::NoOp => Ok(()),
+ SandboxResizeEffect::Unsupported => Err(HarnessError::Container(
+ "daytona reported resize as unsupported".to_owned(),
+ )),
+ SandboxResizeEffect::InPlace => {
+ self.client
+ .resize(id.as_str(), Some(next.cpu), Some(next.memory_gib), None)
+ .await
+ .map_err(unavailable)?;
+ self.client
+ .wait_for_resize(id.as_str(), provision::ENSURE_TIMEOUT)
+ .await
+ .map_err(unavailable)?;
+ Ok(())
+ }
+ SandboxResizeEffect::Restart => {
+ self.client.stop(id.as_str()).await.map_err(unavailable)?;
+ self.client
+ .wait_for_stopped(id.as_str(), STOP_TIMEOUT)
+ .await
+ .map_err(unavailable)?;
+ self.client
+ .resize(id.as_str(), Some(next.cpu), Some(next.memory_gib), None)
+ .await
+ .map_err(unavailable)?;
+ self.client
+ .wait_for_resize(id.as_str(), provision::ENSURE_TIMEOUT)
+ .await
+ .map_err(unavailable)?;
+ self.client.start(id.as_str()).await.map_err(unavailable)?;
+ self.client
+ .wait_for_started(id.as_str(), provision::ENSURE_TIMEOUT)
+ .await
+ .map_err(unavailable)?;
+ Ok(())
+ }
+ }
+ }
}
impl ContainerManager for DaytonaContainerManager {
@@ -241,6 +341,7 @@ impl ContainerManager for DaytonaContainerManager {
let SpawnContainer {
session_id,
repo_url,
+ size,
} = command;
// `GITHUB_TOKEN` is here for `gh auth setup-git` and the github MCP
// server. It is also the env var opencode's `github-copilot` provider
@@ -278,7 +379,7 @@ impl ContainerManager for DaytonaContainerManager {
));
}
- match self.bring_up(&id).await {
+ match self.align_size_then_bring_up(&id, size).await {
Ok(container) => Ok(container),
Err(error) => {
self.managed.containers.remove(&id);
@@ -292,6 +393,52 @@ impl ContainerManager for DaytonaContainerManager {
}
}
+ fn resize_effect(
+ &self,
+ from: agent_session::domain::model::SandboxSize,
+ to: agent_session::domain::model::SandboxSize,
+ ) -> SandboxResizeEffect {
+ crate::domain::sandbox::resize_effect(from, to)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn resize(
+ &self,
+ session: AgentSessionId,
+ size: agent_session::domain::model::SandboxSize,
+ ) -> Result<()> {
+ let Some(id) = self
+ .client
+ .find_by_label(SESSION_LABEL, &session.to_string())
+ .await
+ .map_err(unavailable)?
+ .map(DaytonaSandboxId::new)
+ else {
+ return Err(HarnessError::Container(format!(
+ "session {session} has no sandbox to resize"
+ )));
+ };
+ let (cpu, memory, _) = self
+ .client
+ .resources(id.as_str())
+ .await
+ .map_err(unavailable)?;
+ let cpu = cpu.ok_or_else(|| {
+ HarnessError::Container("daytona did not report cpu for the sandbox".to_owned())
+ })?;
+ let memory = memory.ok_or_else(|| {
+ HarnessError::Container("daytona did not report memory for the sandbox".to_owned())
+ })?;
+ let current = SandboxResources {
+ cpu,
+ memory_gib: memory,
+ disk_gib: 96,
+ };
+ let next = resources(size);
+ self.apply_resize(&id, next, resize_effect_from_resources(current, next))
+ .await
+ }
+
#[tracing::instrument(err, skip(self))]
async fn resume(&self, session: AgentSessionId) -> Result<DaytonaContainer> {
let id = DaytonaSandboxId::new(
diff --git a/crates/agent_harness/src/outbound/local/manager.rs b/crates/agent_harness/src/outbound/local/manager.rs
index a728544fdf..e5c81b1198 100644
--- a/crates/agent_harness/src/outbound/local/manager.rs
+++ b/crates/agent_harness/src/outbound/local/manager.rs
@@ -1,12 +1,13 @@
use std::time::Duration;
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentSessionId, SandboxSize};
use super::docker::{ContainerRef, Docker, RunSpec};
use super::errors::LocalError;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::SpawnContainer;
use crate::domain::ports::ContainerManager;
+use crate::domain::sandbox::{SandboxResizeEffect, create_only_resize_effect};
use crate::outbound::daytona::GithubToken;
use crate::outbound::provision::{self, SESSION_LABEL};
use crate::outbound::sidecar::SidecarTransport;
@@ -195,6 +196,7 @@ impl ContainerManager for LocalContainerManager {
let SpawnContainer {
session_id,
repo_url,
+ size: _,
} = command;
if !self
@@ -239,6 +241,16 @@ impl ContainerManager for LocalContainerManager {
}
}
+ fn resize_effect(&self, from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect {
+ create_only_resize_effect(from, to)
+ }
+
+ async fn resize(&self, _session: AgentSessionId, _size: SandboxSize) -> Result<()> {
+ Err(HarnessError::Container(
+ "Local Docker containers cannot be resized in place".to_owned(),
+ ))
+ }
+
#[tracing::instrument(err, skip(self))]
async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {
let container = self.find(session).await?.ok_or_else(|| {
diff --git a/crates/agent_harness/src/outbound/namespace/client.rs b/crates/agent_harness/src/outbound/namespace/client.rs
index b4c48decbf..62b1477370 100644
--- a/crates/agent_harness/src/outbound/namespace/client.rs
+++ b/crates/agent_harness/src/outbound/namespace/client.rs
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
use super::errors::{NamespaceError, Result};
use super::types::{CommandOutput, ContainerSpec, Instance, InstanceId, NamespaceToken};
+use crate::domain::sandbox::SandboxResources;
const COMPUTE_SERVICE: &str = "namespace.cloud.compute.v1beta.ComputeService";
const COMMAND_SERVICE: &str = "namespace.cloud.compute.v1beta.CommandService";
@@ -127,10 +128,11 @@ struct ExportedPortBackendRequest {
port: u16,
}
-fn configuration_parameters(
- container: &ContainerSpec,
+fn configuration_parameters<'a>(
+ container: &'a ContainerSpec,
deadline: String,
-) -> CreateInstanceRequest<'_> {
+ resources: SandboxResources,
+) -> CreateInstanceRequest<'a> {
let env = container
.env
.iter()
@@ -148,8 +150,8 @@ fn configuration_parameters(
CreateInstanceRequest {
shape: ShapeRequest {
- virtual_cpu: 2,
- memory_megabytes: 4096,
+ virtual_cpu: resources.cpu,
+ memory_megabytes: resources.memory_gib * 1024,
machine_arch: "amd64",
},
documented_purpose: "agent_harness agent session",
@@ -189,10 +191,11 @@ impl NamespaceClient {
&self,
container: &ContainerSpec,
lifetime: Duration,
+ resources: SandboxResources,
) -> Result<Instance> {
let deadline = chrono::Utc::now()
+ chrono::TimeDelta::from_std(lifetime).map_err(NamespaceError::LifetimeOutOfRange)?;
- let request = configuration_parameters(container, deadline.to_rfc3339());
+ let request = configuration_parameters(container, deadline.to_rfc3339(), resources);
let response: CreateInstanceResponse = self
.call(&self.base, COMPUTE_SERVICE, "CreateInstance", &request)
.await?;
diff --git a/crates/agent_harness/src/outbound/namespace/manager.rs b/crates/agent_harness/src/outbound/namespace/manager.rs
index e8097798ac..f6f72ad7e3 100644
--- a/crates/agent_harness/src/outbound/namespace/manager.rs
+++ b/crates/agent_harness/src/outbound/namespace/manager.rs
@@ -2,7 +2,7 @@ use std::sync::Arc;
use agent_runtime_protocol::domain::ports::Transport;
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentSessionId, SandboxSize};
use super::client::NamespaceClient;
use super::errors::NamespaceError;
@@ -10,6 +10,7 @@ use super::types::{ContainerSpec, Instance, NamespaceSettings};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::SpawnContainer;
use crate::domain::ports::ContainerManager;
+use crate::domain::sandbox::{SandboxResizeEffect, create_only_resize_effect, resources};
use crate::outbound::daytona::GithubToken;
use crate::outbound::provision;
use crate::outbound::sidecar::SidecarTransport;
@@ -96,7 +97,7 @@ impl ContainerManager for NamespaceContainerManager {
};
let instance = self
.client
- .create_instance(&container, self.lifetime)
+ .create_instance(&container, self.lifetime, resources(command.size))
.await
.map_err(unavailable)?;
tracing::info!(instance_id = %instance.id, url = %instance.url, "instance created");
@@ -117,6 +118,16 @@ impl ContainerManager for NamespaceContainerManager {
}
}
+ fn resize_effect(&self, from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect {
+ create_only_resize_effect(from, to)
+ }
+
+ async fn resize(&self, _session: AgentSessionId, _size: SandboxSize) -> Result<()> {
+ Err(HarnessError::Container(
+ "Namespace instances cannot be resized in place".to_owned(),
+ ))
+ }
+
async fn resume(&self, _session: AgentSessionId) -> Result<Self::Transport> {
todo!("resuming Namespace instances is not implemented yet")
}
diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rs
index 5a09f6eaec..ebc56bd9b4 100644
--- a/crates/agent_harness/src/testing/helpers/containers.rs
+++ b/crates/agent_harness/src/testing/helpers/containers.rs
@@ -1,7 +1,7 @@
//! In-memory container and provisioner test doubles.
use std::collections::HashMap;
-use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use agent_client_protocol::RawJsonRpcMessage;
@@ -11,12 +11,13 @@ use agent_runtime_protocol::domain::ports::{
use agent_runtime_protocol::domain::schema::v0::{
AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
};
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentSessionId, SandboxSize};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::SpawnContainer;
use crate::domain::ports::ContainerManager;
+use crate::domain::sandbox::{SandboxResizeEffect, create_only_resize_effect, resize_effect};
use crate::testing::helpers::agent::FakeAgent;
/// A container connection driven by hand.
@@ -196,6 +197,9 @@ impl TransportReceiver<ToServerMessage> for ContainerReceiver {
pub struct MockContainerManager {
containers: Arc<Mutex<HashMap<AgentSessionId, ContainerMock>>>,
spawn_error: Arc<Mutex<Option<String>>>,
+ spawn_sizes: Arc<Mutex<Vec<SandboxSize>>>,
+ resizes: Arc<Mutex<Vec<(AgentSessionId, SandboxSize)>>>,
+ resize_unsupported: Arc<AtomicBool>,
resumes: Arc<AtomicUsize>,
teardowns: Arc<AtomicUsize>,
}
@@ -245,6 +249,29 @@ impl MockContainerManager {
self.teardowns.load(Ordering::Relaxed)
}
+ /// Sizes requested at spawn, in order.
+ #[must_use]
+ pub fn spawn_sizes(&self) -> Vec<SandboxSize> {
+ self.spawn_sizes
+ .lock()
+ .expect("spawn sizes lock should not be poisoned")
+ .clone()
+ }
+
+ /// Resize requests, in order.
+ #[must_use]
+ pub fn resizes(&self) -> Vec<(AgentSessionId, SandboxSize)> {
+ self.resizes
+ .lock()
+ .expect("resizes lock should not be poisoned")
+ .clone()
+ }
+
+ /// Report [`SandboxResizeEffect::Unsupported`] for any real size change.
+ pub fn refuse_resize(&self) {
+ self.resize_unsupported.store(true, Ordering::Relaxed);
+ }
+
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<AgentSessionId, ContainerMock>> {
self.containers
.lock()
@@ -264,11 +291,41 @@ impl ContainerManager for MockContainerManager {
{
return Err(HarnessError::Container(message));
}
+ self.spawn_sizes
+ .lock()
+ .expect("spawn sizes lock should not be poisoned")
+ .push(command.size);
let container = ContainerMock::default();
self.lock().insert(command.session_id, container.clone());
Ok(container)
}
+ fn resize_effect(&self, from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect {
+ if self.resize_unsupported.load(Ordering::Relaxed) {
+ create_only_resize_effect(from, to)
+ } else {
+ resize_effect(from, to)
+ }
+ }
+
+ async fn resize(&self, session: AgentSessionId, size: SandboxSize) -> Result<(), HarnessError> {
+ if !self.lock().contains_key(&session) {
+ return Err(HarnessError::Container(format!(
+ "no sandbox was ever spawned for {session}"
+ )));
+ }
+ if self.resize_unsupported.load(Ordering::Relaxed) {
+ return Err(HarnessError::Container(
+ "this container manager cannot resize a live sandbox".to_owned(),
+ ));
+ }
+ self.resizes
+ .lock()
+ .expect("resizes lock should not be poisoned")
+ .push((session, size));
+ Ok(())
+ }
+
async fn resume(&self, session: AgentSessionId) -> Result<ContainerMock, HarnessError> {
self.resumes.fetch_add(1, Ordering::Relaxed);
let mut containers = self.lock();
diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rs
index 9ce6d0d664..5681aa51b4 100644
--- a/crates/agent_session/src/bin/seed_jsonl.rs
+++ b/crates/agent_session/src/bin/seed_jsonl.rs
@@ -248,6 +248,7 @@ async fn seed(args: &Args) -> Result<(), SeedError> {
harness: args.harness.clone(),
repo_url: Some(args.repo_url.clone()),
workspace: args.workspace.clone(),
+ sandbox_size: agent_session::domain::model::SandboxSize::Default,
},
)
.await
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index 94cfda322d..d1592e0b9d 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -2,5 +2,6 @@ pub mod connection;
pub mod error;
pub mod model;
pub mod ports;
+mod sandbox_size;
pub mod service;
pub mod session;
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index 5cc07d7646..12f3e61c95 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -9,6 +9,7 @@ use macro_uuid::Uuid;
// carries - is owned by `agent_fold`, the bottom of the agent session stack,
// so that this crate can depend on the fold (see `agent_fold::domain::log`).
// Re-exported here because this is where callers expect session types.
+pub use super::sandbox_size::SandboxSize;
pub use agent_fold::domain::log::{AgentSessionId, AgentSessionLog, Message};
pub use agent_fold::domain::model::{
Author, AuthorKind, FoldEvent, MessageId, OwnedFoldEvent, TurnId,
@@ -47,6 +48,8 @@ pub struct CreateAgentSessionParams {
pub repo_url: Option<String>,
/// Absolute directory the harness runs in on its runtime.
pub workspace: String,
+ /// Compute tier the managed sandbox was spawned with.
+ pub sandbox_size: SandboxSize,
}
/// A running or historical agent coding session.
@@ -77,6 +80,8 @@ pub struct AgentSession {
/// and load re-enter it - the directory the session actually ran in,
/// not whatever the runtime is configured with today.
pub workspace: String,
+ /// Compute tier of the managed sandbox, snapshotted at spawn.
+ pub sandbox_size: SandboxSize,
/// ACP session if we have one
pub acp_session_id: Option<SessionId>,
pub status: SessionStatus,
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 5cc7c01191..195c4a219c 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -173,6 +173,28 @@ pub trait AgentSessionRepo: Send + Sync + 'static {
fn set_model(&self, id: AgentSessionId, model: &str)
-> impl Future<Output = Result<()>> + Send;
+ /// Persist the sandbox size this session was spawned with, or resized to.
+ fn set_sandbox_size(
+ &self,
+ id: AgentSessionId,
+ size: SandboxSize,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// The user's default sandbox size for new `@coder` sessions.
+ ///
+ /// A missing row is [`SandboxSize::Default`], not an error.
+ fn user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<SandboxSize>> + Send;
+
+ /// Upsert the user's default sandbox size for the next `@coder` mention.
+ fn set_user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ size: SandboxSize,
+ ) -> impl Future<Output = Result<()>> + Send;
+
/// Delete an agent session by id.
fn delete(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
}
@@ -265,4 +287,11 @@ pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {
id: AgentSessionId,
event: ControlEvent,
) -> impl Future<Output = Result<AgentActionId>> + Send;
+
+ /// Resize this session's sandbox and remember `size` as the owner's default.
+ fn set_sandbox_size(
+ &self,
+ id: AgentSessionId,
+ size: SandboxSize,
+ ) -> impl Future<Output = Result<()>> + Send;
}
diff --git a/crates/agent_session/src/domain/sandbox_size.rs b/crates/agent_session/src/domain/sandbox_size.rs
new file mode 100644
index 0000000000..10989c0979
--- /dev/null
+++ b/crates/agent_session/src/domain/sandbox_size.rs
@@ -0,0 +1,66 @@
+//! Named compute tier for a managed coding-agent sandbox.
+
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+#[cfg(test)]
+mod test;
+
+/// Named compute tier for a managed sandbox.
+///
+/// Disk is always 96 GiB; CPU and RAM vary. The API and database store the
+/// name, never raw resource integers.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub enum SandboxSize {
+ /// 2 vCPU / 4 GiB RAM / 96 GiB disk.
+ Small,
+ /// 8 vCPU / 16 GiB RAM / 96 GiB disk.
+ #[default]
+ Default,
+ /// 16 vCPU / 32 GiB RAM / 96 GiB disk.
+ Large,
+}
+
+impl SandboxSize {
+ /// Wire and database form: `small`, `default`, or `large`.
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Small => "small",
+ Self::Default => "default",
+ Self::Large => "large",
+ }
+ }
+}
+
+impl std::fmt::Display for SandboxSize {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+impl std::str::FromStr for SandboxSize {
+ type Err = SandboxSizeParseError;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ match value {
+ "small" => Ok(Self::Small),
+ "default" => Ok(Self::Default),
+ "large" => Ok(Self::Large),
+ _ => Err(SandboxSizeParseError),
+ }
+ }
+}
+
+/// The string is not `small`, `default`, or `large`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SandboxSizeParseError;
+
+impl std::fmt::Display for SandboxSizeParseError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("sandbox size must be small, default, or large")
+ }
+}
+
+impl std::error::Error for SandboxSizeParseError {}
diff --git a/crates/agent_session/src/domain/sandbox_size/test.rs b/crates/agent_session/src/domain/sandbox_size/test.rs
new file mode 100644
index 0000000000..a9fdd9df24
--- /dev/null
+++ b/crates/agent_session/src/domain/sandbox_size/test.rs
@@ -0,0 +1,21 @@
+use super::*;
+
+#[test]
+fn parses_the_three_tiers() {
+ assert_eq!("small".parse(), Ok(SandboxSize::Small));
+ assert_eq!("default".parse(), Ok(SandboxSize::Default));
+ assert_eq!("large".parse(), Ok(SandboxSize::Large));
+ assert!("medium".parse::<SandboxSize>().is_err());
+}
+
+#[test]
+fn round_trips_json_as_camel_case_names() {
+ assert_eq!(
+ serde_json::to_value(SandboxSize::Default).unwrap(),
+ serde_json::json!("default")
+ );
+ assert_eq!(
+ serde_json::from_value::<SandboxSize>(serde_json::json!("large")).unwrap(),
+ SandboxSize::Large
+ );
+}
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 298e9b7877..42a2a7c21b 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -44,7 +44,8 @@ use super::connection::RuntimeAttachment;
use super::error::{AgentSessionError, Result};
use super::model::{
AgentSession, AgentSessionId, AgentSessionLog, AuthorKind, ChannelSession,
- CreateAgentSessionParams, LogAppended, Message, MessageId, SessionLog, StoredAgentSessionLog,
+ CreateAgentSessionParams, LogAppended, Message, MessageId, SandboxSize, SessionLog,
+ StoredAgentSessionLog,
};
use super::ports::{
AgentConnector, AgentSessionLogRepo, AgentSessionLogWriter, AgentSessionRealtime,
@@ -127,6 +128,28 @@ pub trait AgentSessionService: Send + Sync + 'static {
/// and a reloaded one are rendered by one implementation rather than two
/// that have to be kept agreeing. See [`SessionLog`].
fn session_log(&self, id: AgentSessionId) -> impl Future<Output = Result<SessionLog>> + Send;
+
+ /// Persist the sandbox size this session is running at.
+ fn set_sandbox_size(
+ &self,
+ id: AgentSessionId,
+ size: SandboxSize,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// The user's default sandbox size for new `@coder` sessions.
+ ///
+ /// A missing preference is [`SandboxSize::Default`].
+ fn user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<SandboxSize>> + Send;
+
+ /// Upsert the user's default sandbox size for the next `@coder` mention.
+ fn set_user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ size: SandboxSize,
+ ) -> impl Future<Output = Result<()>> + Send;
}
/// Agent session service backed by one durable repository and local actors.
@@ -327,6 +350,22 @@ where
entries,
})
}
+
+ async fn set_sandbox_size(&self, id: AgentSessionId, size: SandboxSize) -> Result<()> {
+ self.repo.set_sandbox_size(id, size).await
+ }
+
+ async fn user_sandbox_size(&self, user_id: &MacroUserIdStr<'static>) -> Result<SandboxSize> {
+ self.repo.user_sandbox_size(user_id).await
+ }
+
+ async fn set_user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ size: SandboxSize,
+ ) -> Result<()> {
+ self.repo.set_user_sandbox_size(user_id, size).await
+ }
}
/// The [`AgentSessionLogRepo`] a session's actor writes through: the durable
@@ -479,6 +518,22 @@ where
self.repo.set_model(id, model).await
}
+ async fn set_sandbox_size(&self, id: AgentSessionId, size: SandboxSize) -> Result<()> {
+ self.repo.set_sandbox_size(id, size).await
+ }
+
+ async fn user_sandbox_size(&self, user_id: &MacroUserIdStr<'static>) -> Result<SandboxSize> {
+ self.repo.user_sandbox_size(user_id).await
+ }
+
+ async fn set_user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ size: SandboxSize,
+ ) -> Result<()> {
+ self.repo.set_user_sandbox_size(user_id, size).await
+ }
+
async fn delete(&self, id: AgentSessionId) -> Result<()> {
self.repo.delete(id).await
}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 3224b1945c..913cd24957 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -24,7 +24,7 @@ use axum::{
extract::{FromRef, Path, State},
http::StatusCode,
response::{IntoResponse, Response},
- routing::{delete, get, post},
+ routing::{delete, get, post, put},
};
use chrono::DateTime;
use chrono::Utc;
@@ -32,8 +32,8 @@ use entity_access::domain::models::{OwnerAccessLevel, ViewAccessLevel};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrBot,
- UserOrBotAuthorization,
+ ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ UserOrBot, UserOrBotAuthorization,
};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -42,7 +42,8 @@ use utoipa::ToSchema;
use crate::domain::error::AgentSessionError;
use crate::domain::model::{
- AgentSession, AgentSessionId, Message, SessionBot, SessionStatus, StoredAgentSessionLog,
+ AgentSession, AgentSessionId, Message, SandboxSize, SessionBot, SessionStatus,
+ StoredAgentSessionLog,
};
use crate::domain::ports::{
AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlEvent,
@@ -201,6 +202,29 @@ where
"/{session_id}/control",
post(control_agent_session_handler::<R, Access, Auth>),
)
+ .route(
+ "/{session_id}/sandbox-size",
+ put(put_agent_session_sandbox_size_handler::<R, Access, Auth>),
+ )
+ .with_state(state)
+}
+
+/// Build the caller-default sandbox size router. Mount at `/agent-sandbox-size`.
+pub fn agent_sandbox_size_router<T, Access, Auth, S>(
+ state: AgentSessionRouterState<T, Access, Auth>,
+) -> Router<S>
+where
+ T: AgentSessionService,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/agent-sandbox-size",
+ get(get_agent_sandbox_size_handler::<T, Access, Auth>)
+ .put(put_agent_sandbox_size_handler::<T, Access, Auth>),
+ )
.with_state(state)
}
@@ -309,6 +333,8 @@ pub struct AgentSessionResponse {
pub repo_url: Option<String>,
/// The directory the session's harness runs in on its runtime.
pub workspace: String,
+ /// Compute tier of the managed sandbox.
+ pub sandbox_size: SandboxSize,
/// The ACP session id, if one exists.
pub acp_session_id: Option<String>,
/// The session's status.
@@ -332,6 +358,7 @@ impl From<AgentSession> for AgentSessionResponse {
harness: session.harness,
repo_url: session.repo_url,
workspace: session.workspace,
+ sandbox_size: session.sandbox_size,
acp_session_id: session.acp_session_id.map(|id| id.to_string()),
status: session.status.into(),
created_at: session.created_at,
@@ -458,6 +485,109 @@ pub async fn delete_agent_session_handler<
Ok(StatusCode::OK)
}
+/// Request or response body for a named sandbox size.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct SandboxSizeBody {
+ /// Named compute tier.
+ pub size: SandboxSize,
+}
+
+#[utoipa::path(
+ put,
+ path = "/agent-sessions/{session_id}/sandbox-size",
+ tag = "agent-sessions",
+ operation_id = "put_agent_session_sandbox_size",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ request_body = SandboxSizeBody,
+ responses(
+ (status = 200, body = SandboxSizeBody),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Resize this session's sandbox and remember the size as the owner's default.
+#[tracing::instrument(skip_all, fields(session_id = %session_id, size = %req.size), err(Debug))]
+pub async fn put_agent_session_sandbox_size_handler<
+ R: AgentSessionNotificationRecipient,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ _access: AgentSessionAccessLevelExtractor<OwnerAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionControlState<R, Access, Auth>>,
+ Path(session_id): Path<Uuid>,
+ Json(req): Json<SandboxSizeBody>,
+) -> Result<Json<SandboxSizeBody>, AgentSessionApiError> {
+ state
+ .recipient
+ .set_sandbox_size(AgentSessionId::new_from_uuid(session_id), req.size)
+ .await?;
+ Ok(Json(req))
+}
+
+#[utoipa::path(
+ get,
+ path = "/agent-sandbox-size",
+ tag = "agent-sessions",
+ operation_id = "get_agent_sandbox_size",
+ responses(
+ (status = 200, body = SandboxSizeBody),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Read the caller's default sandbox size for new `@coder` sessions.
+#[tracing::instrument(skip_all, fields(actor = %caller.acting_entity()), err(Debug))]
+pub async fn get_agent_sandbox_size_handler<
+ T: AgentSessionService,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,
+) -> Result<Json<SandboxSizeBody>, AgentSessionApiError> {
+ let size = state
+ .service
+ .user_sandbox_size(&caller.authorization.user.macro_user_id)
+ .await?;
+ Ok(Json(SandboxSizeBody { size }))
+}
+
+#[utoipa::path(
+ put,
+ path = "/agent-sandbox-size",
+ tag = "agent-sessions",
+ operation_id = "put_agent_sandbox_size",
+ request_body = SandboxSizeBody,
+ responses(
+ (status = 200, body = SandboxSizeBody),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Set the caller's default sandbox size for the next `@coder` mention.
+#[tracing::instrument(
+ skip_all,
+ fields(actor = %caller.acting_entity(), size = %req.size),
+ err(Debug)
+)]
+pub async fn put_agent_sandbox_size_handler<
+ T: AgentSessionService,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,
+ Json(req): Json<SandboxSizeBody>,
+) -> Result<Json<SandboxSizeBody>, AgentSessionApiError> {
+ state
+ .service
+ .set_user_sandbox_size(&caller.authorization.user.macro_user_id, req.size)
+ .await?;
+ Ok(Json(req))
+}
+
/// One entry of a session's protocol log.
///
/// Serializes as `{"userId": ..., "direction": ..., "content": ...}` - the
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 4816ed5d1b..eec23df7fa 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -77,6 +77,7 @@ impl SessionOpener for RecordingOpener {
harness: "opencode".to_owned(),
repo_url: request.repo_url.clone(),
workspace: request.workspace.clone(),
+ sandbox_size: crate::domain::model::SandboxSize::Default,
acp_session_id: None,
status: SessionStatus::NoMessages,
created_at: Utc::now(),
@@ -101,6 +102,7 @@ impl SessionOpener for RecordingOpener {
harness: "opencode".to_owned(),
repo_url: Some("https://github.com/macro-inc/macro".to_owned()),
workspace: crate::MANAGED_CONTAINER_WORKSPACE.to_owned(),
+ sandbox_size: crate::domain::model::SandboxSize::Default,
acp_session_id: None,
status: SessionStatus::NoMessages,
created_at: Utc::now(),
diff --git a/crates/agent_session/src/inbound/mod.rs b/crates/agent_session/src/inbound/mod.rs
index 856622ff63..ceb250cb88 100644
--- a/crates/agent_session/src/inbound/mod.rs
+++ b/crates/agent_session/src/inbound/mod.rs
@@ -3,6 +3,6 @@
pub mod axum_router;
pub use axum_router::{
- AgentSessionControlState, AgentSessionRouterState, agent_session_control_router,
- agent_session_read_router,
+ AgentSessionControlState, AgentSessionRouterState, agent_sandbox_size_router,
+ agent_session_control_router, agent_session_read_router,
};
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 9ccb9b815c..95ea40ff80 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -8,7 +8,7 @@ mod test;
use crate::domain::error::{AgentSessionError, Result};
use crate::domain::model::{
AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, CreateAgentSessionParams,
- Message, SessionBot, SessionStatus, StoredAgentSessionLog,
+ Message, SandboxSize, SessionBot, SessionStatus, StoredAgentSessionLog,
};
use crate::domain::ports::{AgentSessionLogRepo, AgentSessionRepo};
use crate::outbound::connection_gateway_realtime::SessionAudience;
@@ -66,6 +66,12 @@ fn parse_status(status: &str, event_name: Option<String>) -> anyhow::Result<Sess
}
}
+fn parse_sandbox_size(value: &str) -> anyhow::Result<SandboxSize> {
+ value
+ .parse()
+ .map_err(|_| anyhow::anyhow!("unknown agent_session sandbox_size {value:?}"))
+}
+
/// The wire direction and JSON payload for a [`Message`].
fn message_columns(message: &Message) -> anyhow::Result<(&'static str, serde_json::Value)> {
match message {
@@ -98,6 +104,7 @@ struct AgentSessionRow {
harness: String,
repo_url: Option<String>,
workspace: String,
+ sandbox_size: String,
acp_session_id: Option<String>,
status: String,
status_event_name: Option<String>,
@@ -122,6 +129,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {
harness: row.harness,
repo_url: row.repo_url,
workspace: row.workspace,
+ sandbox_size: parse_sandbox_size(&row.sandbox_size)?,
acp_session_id: row.acp_session_id.map(Into::into),
status,
created_at: row.created_at,
@@ -142,6 +150,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
harness,
repo_url,
workspace,
+ sandbox_size,
} = params;
// The session row and its access grants land together: a crash between
@@ -159,13 +168,13 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
INSERT INTO agent_session (
id, owner_id, thread_id, originating_message_id, bot_id, model,
- harness, repo_url, workspace, acp_session_id, status,
+ harness, repo_url, workspace, sandbox_size, acp_session_id, status,
status_event_name
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
RETURNING
id, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?"
@@ -179,6 +188,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
harness,
repo_url,
workspace,
+ sandbox_size.as_str(),
None::<String>,
status,
status_event_name,
@@ -249,7 +259,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?"
@@ -282,7 +292,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?"
@@ -375,6 +385,65 @@ impl AgentSessionRepo for PgAgentSessionRepo {
Ok(())
}
+ async fn set_sandbox_size(&self, id: AgentSessionId, size: SandboxSize) -> Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE agent_session
+ SET sandbox_size = $2,
+ modified_at = NOW()
+ WHERE id = $1
+ AND sandbox_size IS DISTINCT FROM $2
+ "#,
+ id.as_uuid(),
+ size.as_str(),
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to persist agent session sandbox size")?;
+ Ok(())
+ }
+
+ async fn user_sandbox_size(&self, user_id: &MacroUserIdStr<'static>) -> Result<SandboxSize> {
+ let size = sqlx::query_scalar!(
+ r#"
+ SELECT sandbox_size
+ FROM user_agent_sandbox_size
+ WHERE user_id = $1
+ "#,
+ user_id.as_ref(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("failed to read user sandbox size")?;
+
+ match size {
+ Some(value) => Ok(parse_sandbox_size(&value)?),
+ None => Ok(SandboxSize::Default),
+ }
+ }
+
+ async fn set_user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ size: SandboxSize,
+ ) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO user_agent_sandbox_size (user_id, sandbox_size, modified_at)
+ VALUES ($1, $2, NOW())
+ ON CONFLICT (user_id) DO UPDATE
+ SET sandbox_size = EXCLUDED.sandbox_size,
+ modified_at = NOW()
+ "#,
+ user_id.as_ref(),
+ size.as_str(),
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to persist user sandbox size")?;
+ Ok(())
+ }
+
async fn delete(&self, id: AgentSessionId) -> Result<()> {
let mut transaction = self
.pool
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 859d083d4d..dc0d913986 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -90,6 +90,7 @@ fn new_session(
harness: "claude-code".to_string(),
repo_url: Some("https://github.com/example/example".to_string()),
workspace: "/workspace".to_string(),
+ sandbox_size: SandboxSize::Default,
}
}
@@ -183,6 +184,7 @@ async fn create_and_get_round_trips(pool: PgPool) {
);
assert_eq!(session.thread_id, None);
+ assert_eq!(session.sandbox_size, SandboxSize::Default);
assert!(matches!(session.status, SessionStatus::NoMessages));
}
@@ -230,6 +232,49 @@ async fn set_model_updates_only_the_model(pool: PgPool) {
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn sandbox_size_round_trips_and_user_default_falls_back(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot_id = create_test_bot(&pool).await;
+ let owner = user_id(OWNER);
+ let id = create_session(&repo, new_session(bot_id, None, None))
+ .await
+ .id;
+
+ assert_eq!(
+ repo.user_sandbox_size(&owner)
+ .await
+ .expect("missing default"),
+ SandboxSize::Default
+ );
+
+ repo.set_sandbox_size(id, SandboxSize::Large)
+ .await
+ .expect("persist session size");
+ assert_eq!(
+ repo.get(id).await.expect("get session").sandbox_size,
+ SandboxSize::Large
+ );
+
+ repo.set_user_sandbox_size(&owner, SandboxSize::Small)
+ .await
+ .expect("persist user default");
+ assert_eq!(
+ repo.user_sandbox_size(&owner).await.expect("user default"),
+ SandboxSize::Small
+ );
+
+ repo.set_user_sandbox_size(&owner, SandboxSize::Large)
+ .await
+ .expect("upsert user default");
+ assert_eq!(
+ repo.user_sandbox_size(&owner)
+ .await
+ .expect("upserted default"),
+ SandboxSize::Large
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn get_missing_session_errors(pool: PgPool) {
let repo = PgAgentSessionRepo::new(pool);
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index e611eb490e..6810a3666d 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -7,12 +7,13 @@
use crate::domain::error::{AgentSessionError, Result};
use crate::domain::model::{
AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, CreateAgentSessionParams,
- LogAppended, SessionBot, SessionStatus, StoredAgentSessionLog,
+ LogAppended, SandboxSize, SessionBot, SessionStatus, StoredAgentSessionLog,
};
use crate::domain::ports::{AgentSessionLogRepo, AgentSessionRealtime, AgentSessionRepo};
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::schema::v0::ToServerMessage;
use bots::domain::models::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -28,6 +29,7 @@ use std::sync::{Arc, Mutex};
pub struct InMemoryAgentSessionRepo {
sessions: Arc<Mutex<HashMap<AgentSessionId, AgentSession>>>,
logs: Arc<Mutex<HashMap<AgentSessionId, Vec<StoredAgentSessionLog>>>>,
+ user_sizes: Arc<Mutex<HashMap<String, SandboxSize>>>,
log_reads: Arc<AtomicUsize>,
session_reads: Arc<AtomicUsize>,
}
@@ -110,6 +112,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
harness: params.harness,
repo_url: params.repo_url,
workspace: params.workspace,
+ sandbox_size: params.sandbox_size,
acp_session_id: None,
status: SessionStatus::default(),
created_at: now,
@@ -190,6 +193,41 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
Ok(())
}
+ async fn set_sandbox_size(&self, id: AgentSessionId, size: SandboxSize) -> Result<()> {
+ let mut sessions = self
+ .sessions
+ .lock()
+ .expect("in-memory session store is not poisoned");
+ let session = sessions.get_mut(&id).ok_or_else(|| {
+ AgentSessionError::Unknown(anyhow::anyhow!("no agent session {}", id.as_uuid()))
+ })?;
+ session.sandbox_size = size;
+ session.modified_at = chrono::Utc::now();
+ Ok(())
+ }
+
+ async fn user_sandbox_size(&self, user_id: &MacroUserIdStr<'static>) -> Result<SandboxSize> {
+ Ok(self
+ .user_sizes
+ .lock()
+ .expect("in-memory session store is not poisoned")
+ .get(user_id.as_ref())
+ .copied()
+ .unwrap_or_default())
+ }
+
+ async fn set_user_sandbox_size(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ size: SandboxSize,
+ ) -> Result<()> {
+ self.user_sizes
+ .lock()
+ .expect("in-memory session store is not poisoned")
+ .insert(user_id.as_ref().to_owned(), size);
+ Ok(())
+ }
+
async fn delete(&self, id: AgentSessionId) -> Result<()> {
self.sessions
.lock()
@@ -300,6 +338,7 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {
harness: "claude-code".to_string(),
repo_url: Some("https://github.com/example/example".to_string()),
workspace: "/workspace".to_string(),
+ sandbox_size: SandboxSize::Default,
acp_session_id: None,
status: SessionStatus::NoMessages,
created_at: now,
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index 808d1bca3b..4461d930aa 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -54,6 +54,7 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {
harness: "harness".to_owned(),
repo_url: Some("https://example.com/repo".to_owned()),
workspace: "/workspace".to_owned(),
+ sandbox_size: agent_session::domain::model::SandboxSize::Default,
acp_session_id: None,
status: SessionStatus::NoMessages,
created_at: Utc::now(),
diff --git a/crates/macro_db_client/migrations/20260821164408_agent_session_sandbox_size.down.sql b/crates/macro_db_client/migrations/20260821164408_agent_session_sandbox_size.down.sql
new file mode 100644
index 0000000000..ea166e1ca5
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260821164408_agent_session_sandbox_size.down.sql
@@ -0,0 +1,4 @@
+DROP TABLE user_agent_sandbox_size;
+
+ALTER TABLE agent_session
+ DROP COLUMN sandbox_size;
diff --git a/crates/macro_db_client/migrations/20260821164408_agent_session_sandbox_size.up.sql b/crates/macro_db_client/migrations/20260821164408_agent_session_sandbox_size.up.sql
new file mode 100644
index 0000000000..d342bd91ea
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260821164408_agent_session_sandbox_size.up.sql
@@ -0,0 +1,13 @@
+-- Named compute tier for a managed coding-agent sandbox. Disk is always
+-- 96 GiB; CPU and RAM vary. Existing sessions keep the product default.
+ALTER TABLE agent_session
+ ADD COLUMN sandbox_size TEXT NOT NULL DEFAULT 'default'
+ CHECK (sandbox_size IN ('small', 'default', 'large'));
+
+-- Per-user default applied when @coder opens a new session.
+CREATE TABLE user_agent_sandbox_size (
+ user_id TEXT PRIMARY KEY REFERENCES "User"("id") ON DELETE CASCADE,
+ sandbox_size TEXT NOT NULL
+ CHECK (sandbox_size IN ('small', 'default', 'large')),
+ modified_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/docs/AGENT_SANDBOX_SIZE_PLAN.md b/docs/AGENT_SANDBOX_SIZE_PLAN.md
new file mode 100644
index 0000000000..a97c705eb7
--- /dev/null
+++ b/docs/AGENT_SANDBOX_SIZE_PLAN.md
@@ -0,0 +1,304 @@
+# Agent Sandbox Sizes (small / default / large)
+
+## Status
+
+Implemented. Named tiers, user default, in-place Daytona resize (hot up / cold down), and a size picker on the agent composer.
+
+Disk is 96 GiB on every tier so a live session can hot-resize CPU/RAM without a disk migrate. Changing the picker resizes **this** sandbox and updates the user default for the next `@coder`.
+
+## Problem
+
+Macro Coder sessions always get one Daytona size, and that size is not chosen in product code. It is baked into the snapshot:
+
+- `crates/agent_harness/justfile` `ensure-daytona` used to create `macro-agent-harness` with `--cpu 4 --memory 8 --disk 10`.
+- The justfile still comments that 10GB disk was the account ceiling. That quota is now raised.
+- `POST /sandbox` in `crates/agent_harness/src/outbound/daytona/client.rs` sends only `snapshot`, `env`, `labels`, and `autoStopInterval`. It does not send CPU, RAM, or disk.
+- The Namespace provider hardcodes 2 vCPU / 4GB RAM and has no disk field.
+- `SpawnContainer` carries `session_id` and `repo_url` only.
+- `agent_session` stores model, harness, repo, and workspace, not sandbox size.
+- Macro Coder sessions are opened by the mention trigger. `POST /agent-sessions` rejects managed bots. There is no UI or API for a user to pick a size.
+
+The wanted product is three named tiers (`small`, `default`, `large`), with `default` being 8 vCPU / 16 GiB RAM / 96 GiB disk, and a way for a user to choose a tier that future `@coder` sessions actually use.
+
+## Decisions
+
+1. **Named tiers, not raw integers.** The domain type is `SandboxSize::{Small, Default, Large}`. UI and API never send `cpu` / `memory` / `disk`. Those numbers are a provider mapping owned by the harness domain.
+2. **`default` is 8 / 16 / 96.** That is the new Macro Coder size. `small` and `large` are scaled off it (numbers below; confirm `large` against the live Daytona quota before shipping it).
+3. **One snapshot, size after create.** Do not build three snapshots. Rebuild `macro-agent-harness` at the default resource profile (`--cpu 8 --memory 16 --disk 96`). Daytona returns 400 if `cpu` / `memory` / `disk` are sent on `POST /sandbox` with a snapshot, so spawn creates from the snapshot, waits for start, and applies the named tier with `POST /sandbox/{id}/resize` (hot if CPU/RAM only increase, cold if either decreases). Disk is never sent on resize. Namespace maps the same tier onto `virtual_cpu` / `memory_megabytes` at create time.
+4. **Size is snapshotted onto the session at spawn and can be changed in place when the manager allows it.** CPU/RAM upgrades are in-place on a running Daytona sandbox. Downgrades stop, resize, and start it again. Disk never changes. Local Docker and Namespace report `Unsupported` (no in-place resize).
+5. **User default drives mention spawn.** `@coder` has no settings chrome. The harness reads the mentioning user's default size (falling back to `default`) and writes it onto the new session before `spawn`.
+6. **Sandbox size is not an `AgentAction`.** `AgentAction` is ACP (`prompt`, `set_model`, `compact`, `stop`). Size is harness/container policy. Do not send it to the agent. Use a dedicated settings endpoint for the user default, and a field on the session response for the size this session was spawned with.
+7. **Every authenticated user may pick any tier.** No plan gating, no locks, no team-admin override, no extra receipts. `GET`/`PUT` the caller's own default; mention spawn already knows the sender. Handlers do not branch on who may use `large`.
+8. **Policy lives in the harness domain; resize capability lives on the container-manager port.** Inbound parses the tier. Domain validates the name, resolves the user default, and puts it on `SpawnContainer`. Named size → CPU/RAM/disk is harness mapping. Whether an existing container can take that change (`NoOp` / `InPlace` / `Restart` / `Unsupported`) is `ContainerManager::resize_effect`. Domain closes/resumes from that effect and calls `resize(session, size)` with no kind argument. Adapters implement the effect and the resize. Hexagonal boundary: no Daytona/Namespace types in domain, no size policy in axum handlers or the web picker.
+
+## Goals
+
+- Every new Macro Coder sandbox is 8 vCPU / 16 GiB / 96 GiB unless the user picked `small` or `large`.
+- `GET` session includes `sandboxSize`.
+- A user can set their default size; the next `@coder` mention uses it.
+- Unknown or raw resource payloads are rejected at the API boundary.
+- Daytona and Namespace both honor the same three tiers.
+- Existing sessions keep working: a NULL/missing size on old rows means `default` at the new resource mapping only for *new* spawns. Already-running sandboxes stay at whatever Daytona already gave them.
+
+## Non-goals (v1)
+
+- Recreating a sandbox to change size (Daytona CPU/RAM resize in place instead).
+- Per-team or per-org size caps, plan gating, or paywalled `large`.
+- Extra authorization beyond "the caller sets their own default."
+- Billing, metering, or showing remaining Daytona quota in the UI.
+- GPU tiers.
+- Letting external (non-managed) agent runtimes declare a size. They bring their own machine.
+- Putting a size picker in the `@` mention typeahead.
+- Recreating a live sandbox when the user changes their default.
+
+## Resource mapping
+
+Units match Daytona: CPU cores, memory GiB, disk GiB.
+
+| Tier | vCPU | RAM | Disk | Notes |
+| --------- | ---- | --- | ---- | ------------------------------------------ |
+| `small` | 2 | 4 | 96 | Cheap / short tasks |
+| `default` | 8 | 16 | 96 | The new Macro Coder size |
+| `large` | 16 | 32 | 96 | Same disk so live sessions can hot-resize |
+
+Namespace create gets the same tier, mapped onto its shape (`virtual_cpu`, `memory_megabytes` = RAM GiB × 1024). It has no disk field today, so disk is Daytona-only until Namespace exposes one.
+
+If the live Daytona quota cannot place `large`, ship `small` + `default` only and keep `Large` out of the public enum until it can.
+
+## Product behavior
+
+### New `@coder` mention
+
+1. Trigger pipeline opens a managed session as it does today.
+2. Harness loads the sender's default `SandboxSize`, or `Default`.
+3. Session row is created with that size.
+4. `spawn` passes the size to the container manager.
+5. Daytona create omits resource fields. After the sandbox starts, spawn resizes CPU/RAM to the session tier (in-place if the snapshot is smaller, restart if it is larger). Disk stays at the snapshot's disk.
+
+### User default
+
+- Stored server-side in `user_agent_sandbox_size`, not in `localStorage` — mention spawn is backend-only and would ignore a browser preference.
+- Any signed-in user can read and write **their own** row. All three sizes are available. No extra authz layer.
+- New endpoint, not `POST /agent-sessions` (that route still rejects managed bots) and not `/control` (that route is ACP).
+- Suggested shape:
+ - `GET /agent-sandbox-size` → `{ size: "small" | "default" | "large" }`
+ - `PUT /agent-sandbox-size` `{ size }` → same
+- First-time users have no row; reads return `default`.
+
+### Resume / idle stop
+
+- Idle reaper still stops the sandbox; resume starts the same Daytona id.
+- Do not re-apply size on resume. The box already has a size.
+- Teardown + a brand-new session is the only v1 way to get a different size.
+
+## Domain design
+
+### `SandboxSize`
+
+New domain enum in `crates/agent_harness` (owned there, not in `agent_session` ACP types):
+
+```rust
+pub enum SandboxSize {
+ Small,
+ Default,
+ Large,
+}
+```
+
+- Serde/API: `"small" | "default" | "large"`.
+- `Default` for `#[default]` and for missing DB values.
+- `resources(self) -> SandboxResources { cpu, memory_gib, disk_gib }` is domain data, not an outbound DTO.
+
+`agent_session` may store the enum as text on the row and echo it on `AgentSessionResponse`. It should not know Daytona field names.
+
+### `SpawnContainer`
+
+Add `size: SandboxSize`. Both Daytona and Namespace managers read it. Fakes in harness tests must too.
+
+### Session row
+
+Migration on `agent_session`:
+
+```sql
+ALTER TABLE agent_session
+ ADD COLUMN sandbox_size TEXT NOT NULL DEFAULT 'default'
+ CHECK (sandbox_size IN ('small', 'default', 'large'));
+```
+
+Existing rows become `default`. That label does **not** resize already-created Daytona sandboxes.
+
+### User default row
+
+New table, not a column on `"User"`:
+
+```sql
+CREATE TABLE user_agent_sandbox_size (
+ user_id TEXT PRIMARY KEY REFERENCES "User"("id") ON DELETE CASCADE,
+ sandbox_size TEXT NOT NULL
+ CHECK (sandbox_size IN ('small', 'default', 'large')),
+ modified_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+```
+
+Port: `AgentSandboxSizePreference` with `get(user) -> SandboxSize` and `set(user, size)`. Missing row → `Default`. The authenticated user is the `user_id`; do not add role checks, receipts, or per-tier permission.
+
+### Authorization
+
+None beyond the existing session view extractor and "this is my user id." Every user can pick `small`, `default`, or `large`. Spawn uses the observed mention sender; it must not take a size from the message body.
+
+## Provider mapping
+
+### Daytona
+
+`CreateSandboxRequest` gains:
+
+```rust
+cpu: u32,
+memory: u32, // GiB
+disk: u32, // GiB
+```
+
+`configuration_parameters` sends `snapshot`, `env`, `labels`, and `auto_stop_interval: 0` only. Daytona rejects `cpu` / `memory` / `disk` on snapshot creates (HTTP 400: "Cannot specify Sandbox resources when using a snapshot"). Size is applied after start via `POST /sandbox/{id}/resize` with `cpu` and `memory` only.
+
+Snapshot create in `justfile` / `ensure-daytona` is `--cpu 8 --memory 16 --disk 96` so a `default` spawn is a no-op after create, `large` is an in-place resize, and `small` is a restart resize. Rebuild the snapshot (delete + create); `snapshot create` will not replace an existing name.
+
+Verify with a throwaway sandbox: create from the snapshot with no resource fields, wait until started, stay inside the org per-sandbox cap, shrink while stopped, then raise CPU/RAM in place without sending `disk`, and confirm disk is unchanged. Always delete the sandbox.
+
+### Namespace
+
+Same idea as Daytona: create-time resources from the tier, not a hardcoded shape.
+
+Replace
+
+```rust
+virtual_cpu: 2,
+memory_megabytes: 4096,
+```
+
+with the mapped `virtual_cpu` and `memory_megabytes` for `SpawnContainer.size`. Namespace's `ShapeRequest` has no disk field, so do not invent one. If Namespace adds disk later, thread `disk_gib` through the same mapping.
+
+### coding-agent-worker
+
+Out of scope unless it is still used to boot Macro Coder. Production harness is `crates/agent_harness`. Do not silently fork a second size table there.
+
+## API / SDK
+
+- `AgentSessionResponse.sandboxSize`: `"small" | "default" | "large"`.
+- New user-default routes on the agent harness service (same service that already owns managed sessions).
+- OpenAPI in `agent_session` / `agent_harness_service` swagger, then `just coverage` / add-sdk-endpoint skill so `packages/sdk` and the web generated client pick it up.
+- Do **not** add `sandboxSize` to `CreateAgentSessionRequest` in v1. That route is for external runtimes and rejects managed bots. Mention spawn is not that route.
+
+## UI
+
+Small composer control, same family as Macro AI's `ModelSelector` — not a header setting, not in the `@` mention typeahead.
+
+`AgentInput` today is a `Surface` with the editor and a send/stop button in the bottom-right. Add a ghost `Dropdown` to the left of send, mirroring `ChatInput`'s right-controls cluster.
+
+### Closed
+
+```
+┌──────────────────────────────────────────────────────┐
+│ Message the agent │
+│ [Default ▾] (send) │
+└──────────────────────────────────────────────────────┘
+```
+
+Trigger: `Dropdown.Trigger` `variant="ghost"` `size="sm"`, `text-xs`, caret, no CPU icon required. Label is the **user default** (`Small` / `Default` / `Large`), not raw resources.
+
+When the editor wraps past one line, the chip stays bottom-right with send, same as ChatInput.
+
+### Open
+
+```
+ ┌──────────────────────────┐
+ │ Small │
+ │ 2 vCPU · 4 GB · 20 GB │
+ │ ✓ Default │
+ │ 8 vCPU · 16 GB · 96 GB │
+ │ Large │
+ │ 16 vCPU · 32 GB · 200 GB │
+ │ │
+ │ Applies to new @coder │
+ │ sessions │
+ └──────────────────────────┘
+┌──────────────────────────────────────────────────────┐
+│ Message the agent │
+│ [Default ▾] (send) │
+└──────────────────────────────────────────────────────┘
+```
+
+All three rows are always enabled. No lock icons, no paywall, no "unavailable." Checkmark on the current user default.
+
+Footer copy is required: picking a size does not resize the open sandbox. `PUT /agent-sandbox-size`, toast on success ("New @coder sessions will use Large").
+
+If this session's snapshotted size differs from the user default, the trigger can stay as the default (what you will get next) rather than the current session. Optional muted line under the footer: `This session: Default`. Skip that if it feels noisy; the session response still has `sandboxSize` for later.
+
+### Component split
+
+- `apps/web/src/features/block-agent/ui/SandboxSizeSelector.tsx` — pure: `size`, `onSelect`, options hardcoded. Reuse `@ui` `Dropdown` like `ModelSelector`.
+- `AgentInput` grows an optional `size` / `onSizeSelect` slot in the right-controls cluster. Keep the ui/ component free of queries.
+- `AgentComposer` loads `GET /agent-sandbox-size` (fallback `default`) and `PUT`s on select.
+
+No picker on `AgentSplitHeader`. No mention-typeahead control.
+
+## Phasing
+
+### 1. Default size bump (can ship alone)
+
+- Snapshot flags → 8 / 16 / 96.
+- Daytona create omits `cpu`/`memory`/`disk`.
+- Tests: Daytona create JSON omits resource fields; resize omits `disk`; snapshot justfile comment about the 10GB ceiling is removed.
+- No UI. Every new sandbox is `default`.
+
+### 2. Domain + persistence + API
+
+- `SandboxSize` enum, `SpawnContainer.size`, session column, user-default table.
+- Mention `open` reads the user default.
+- `GET`/`PUT /agent-sandbox-size`, session response field.
+- Domain tests: missing preference → `Default`; `PUT` then mention uses the new size; unknown size → 422; outbound mapping for all three tiers on both providers.
+
+### 3. UI picker
+
+- `SandboxSizeSelector` on `AgentInput`, wired from `AgentComposer`.
+- Generated client from phase 2.
+- Footer copy + toast that this session does not resize.
+
+### 4. Later (not this plan)
+
+- Daytona `resize` for CPU/RAM on a live session (disk grow-only).
+- Team default.
+- "Restart this session at a new size" (teardown + new sandbox; loses the live workspace unless we snapshot first).
+
+## Testing
+
+- `cargo test -p agent_harness` for spawn mapping, preference fallback, and Daytona request body.
+- `cargo test -p agent_session` for the new column on create/get fixtures.
+- SQLX: `just prepare_db` after the migration, from the repo root, with `SQLX_OFFLINE` unset.
+- Web: `SandboxSizeSelector` test that every tier is enabled; composer test that select calls `PUT` and does not call session `/control`.
+- Manual: one real Daytona create per tier against the quota (phase 1 spike for override; phase 2 for `small` vs `default`).
+
+## Risks
+
+- **Snapshot create rejects resource fields (HTTP 400).** Mitigated by inheriting snapshot quotas on create and applying the named tier with resize.
+- **`POST /sandbox/{id}/resize` 404s with `Cannot POST` when the route is not registered on this API.** Daytona documents resize as available to all organizations. The client maps that 404 to `ResizeNotEnabled`. A missing sandbox 404s with "not found" instead.
+- **Live per-sandbox cap is 4 vCPU / 8 GiB / 10 GiB.** `POST /snapshots` with `--cpu 8 --memory 16 --disk 96` returns 400: "CPU request 8 exceeds maximum allowed per sandbox (4)". Ask Daytona to raise per-sandbox limits to at least 16 / 32 / 96 (`large`) before rebuilding `macro-agent-harness`. Do not delete the live 4/8/10 snapshot until that create would succeed.
+- **`large` exceeds quota.** Keep it out of the public enum until a create succeeds.
+- **Users think the picker resizes the open session.** Header copy + toast. Size on the session response is the spawned size, not the pending default.
+- **Mention already spawned before the UI is visible.** That is why the picker edits the *next* session's default, not the current sandbox.
+- **Namespace disk.** Document that `small`/`large` on Namespace only change CPU/RAM.
+
+## Files (expected)
+
+- `crates/agent_harness/justfile` — snapshot resources
+- `crates/agent_harness/src/domain/ports.rs` — `ContainerManager::resize_effect` + `resize` without a kind argument
+- `crates/agent_harness/src/domain/sandbox.rs` — named size → CPU/RAM/disk; in-place vs restart comparison
+- `crates/agent_harness/src/domain/service.rs` — resolve user default on `open`
+- `crates/agent_harness/src/outbound/daytona/client.rs` — create omits resources; resize sends `cpu`/`memory`
+- `crates/agent_harness/src/outbound/namespace/client.rs` — shape from tier
+- `crates/agent_session/src/domain/model.rs` + postgres outbound — `sandbox_size` column
+- `crates/macro_db_client/migrations/` — session column + `user_agent_sandbox_size`
+- `crates/agent_session/src/inbound/axum_router.rs` — response field; new default-size handlers (or a small harness inbound module)
+- `apps/web/src/features/block-agent/ui/SandboxSizeSelector.tsx` — dropdown
+- `apps/web/src/features/block-agent/ui/AgentInput.tsx` — right-controls slot next to send
+- `apps/web/src/features/block-agent/component/AgentComposer.tsx` — GET/PUT default size
+- Generated OpenAPI / SDK clients after the new routes
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index 7c0556cff1..d62a3cd0d0 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -10,7 +10,8 @@ use agent_session::domain::ports::{
use agent_session::domain::service::AgentSessionService;
use agent_session::inbound::axum_router::{
AgentSessionControlState, AgentSessionRouterState, CreateSessionState,
- agent_session_control_router, agent_session_create_router, agent_session_read_router,
+ agent_sandbox_size_router, agent_session_control_router, agent_session_create_router,
+ agent_session_read_router,
};
use anyhow::Context;
use axum::Router;
@@ -69,12 +70,13 @@ where
Access: EntityAccessService,
Auth: MacroAuthorizationService,
{
- let agent_sessions = agent_session_read_router(read_state)
+ let agent_sessions = agent_session_read_router(read_state.clone())
.merge(agent_session_control_router(control_state))
.merge(agent_session_create_router(create_state));
Router::new()
.route("/health", get(health))
.nest("/agent-sessions", agent_sessions)
+ .merge(agent_sandbox_size_router(read_state))
.nest("/runtime", runtime_gateway_router(gateway_state))
}
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index a92c581b6c..54abb63ae9 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -1,11 +1,11 @@
//! OpenAPI document for the agent harness service's session routes.
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
-use agent_session::domain::model::SessionBot;
+use agent_session::domain::model::{SandboxSize, SessionBot};
use agent_session::inbound::axum_router::{
self, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionResponse, ControlRequest,
CreateAgentSessionRequest, CreateAgentSessionResponse, CreateSessionThread, LogDirectionDto,
- LogFrameDto, SessionStatusDto,
+ LogFrameDto, SandboxSizeBody, SessionStatusDto,
};
use utoipa::OpenApi;
@@ -18,6 +18,9 @@ use utoipa::OpenApi;
axum_router::get_agent_session_log_handler,
axum_router::control_agent_session_handler,
axum_router::delete_agent_session_handler,
+ axum_router::put_agent_session_sandbox_size_handler,
+ axum_router::get_agent_sandbox_size_handler,
+ axum_router::put_agent_sandbox_size_handler,
),
components(schemas(
CreateAgentSessionRequest,
@@ -33,6 +36,8 @@ use utoipa::OpenApi;
SessionBot,
LogFrameDto,
LogDirectionDto,
+ SandboxSize,
+ SandboxSizeBody,
)),
tags((name = "agent-sessions", description = "Agent sessions"))
)]
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot.rs
index 93d35d82f1..3d73d69740 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot.rs
@@ -87,10 +87,14 @@ fn ensure_snapshot() -> Job {
exit 1
fi
daytona login --api-key "$DAYTONA_API_KEY"
+ echo "ensuring Daytona snapshot at --cpu ${DAYTONA_SNAPSHOT_CPU} --memory ${DAYTONA_SNAPSHOT_MEMORY} --disk ${DAYTONA_SNAPSHOT_DISK}"
just --justfile crates/agent_harness/justfile ensure-daytona
"#})
.shell("bash")
- .add_env(("DAYTONA_API_KEY", vars::DAYTONA_API_KEY)),
+ .add_env(("DAYTONA_API_KEY", vars::DAYTONA_API_KEY))
+ .add_env(("DAYTONA_SNAPSHOT_CPU", "8"))
+ .add_env(("DAYTONA_SNAPSHOT_MEMORY", "16"))
+ .add_env(("DAYTONA_SNAPSHOT_DISK", "96")),
)
}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot/test.rs
index 188bd0d415..0f9dd33ec3 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot/test.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/ensure_daytona_snapshot/test.rs
@@ -65,6 +65,18 @@ fn daytona_job_stays_on_the_small_runner_and_skips_prs() {
);
}
+#[test]
+fn daytona_job_requests_the_default_snapshot_size() {
+ let yaml = rendered();
+ assert!(yaml.contains("DAYTONA_SNAPSHOT_CPU: '8'"), "{yaml}");
+ assert!(yaml.contains("DAYTONA_SNAPSHOT_MEMORY: '16'"), "{yaml}");
+ assert!(yaml.contains("DAYTONA_SNAPSHOT_DISK: '96'"), "{yaml}");
+ assert!(
+ yaml.contains("--cpu ${DAYTONA_SNAPSHOT_CPU} --memory ${DAYTONA_SNAPSHOT_MEMORY} --disk ${DAYTONA_SNAPSHOT_DISK}"),
+ "{yaml}"
+ );
+}
+
#[test]
fn publish_runs_on_same_repo_pull_requests() {
let yaml = rendered();