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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ All notable changes to Agent Relay will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
## [Unreleased - Patch]

### Fixed

- `agent-relay fleet spawn --sandbox` reports provider capacity and confirms no sandbox was created when Cloud rejects before allocation, without misleading leak-check guidance.

## [13.1.3] - 2026-10-07

Expand Down
71 changes: 71 additions & 0 deletions packages/cli/src/cli/commands/fleet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3893,6 +3893,77 @@ describe('fleet command support', () => {
expect(warnings.join('\n')).toContain(`--sandbox-id '${REPLAY_SANDBOX_ID}'`);
});

it('prints definitive capacity detail without cleanup or unknown-outcome guidance', async () => {
const warnings: string[] = [];
const deleteCloudFleetSandbox = vi.fn(async () => undefined);
const capacityMessage =
'Sandbox capacity is exhausted before allocation (agent37: 14 current / 10 limit). No sandbox was created; retry when capacity is available.';
const program = new Command();
program.exitOverride();
registerFleetCommands(program, {
resolveSandboxRepository: () => undefined,
sdk: {
createAgentRelay: vi.fn() as never,
createWorkspaceRelay: vi.fn(() => ({
workspace: { info: vi.fn(async () => ({ id: 'rw_abc' })) },
})) as never,
createWorkspace: vi.fn() as never,
log: vi.fn(),
error: vi.fn(),
exit: (() => {
throw new Error('__exit__');
}) as never,
},
ensureCloudFleetSandbox: vi.fn(async () => {
throw new CloudFleetSandboxProvisionError(capacityMessage, {
cloudWorkspaceId: '50587328-441d-4acb-b8f3-dbe1b3c5de99',
nodeName: REPLAY_SANDBOX_NAME,
providerId: 'agent37',
code: 'sandbox_capacity_exhausted',
noSandboxCreated: true,
retryable: true,
capacity: [{ provider: 'agent37', current: 14, limit: 10 }],
});
}),
deleteCloudFleetSandbox,
createFleetWorkspaceClient: vi.fn() as never,
log: () => undefined,
warn: (...args: unknown[]) => warnings.push(args.join(' ')),
error: () => undefined,
});

await expect(
program.parseAsync(
[
'fleet',
'spawn',
'codex',
'--sandbox',
'--sandbox-id',
REPLAY_SANDBOX_ID,
'--sandbox-name',
REPLAY_SANDBOX_NAME,
'--workspace-id',
'rw_abc',
'--name',
'sandbox-worker',
'--task',
'Work',
'--workspace-key',
'rk_live_test',
'--token',
'at_live_lead',
],
{ from: 'user' }
)
).rejects.toThrow('__exit__');

expect(deleteCloudFleetSandbox).not.toHaveBeenCalled();
expect(warnings).toEqual([capacityMessage]);
expect(warnings.join('\n')).not.toContain('outcome is unknown');
expect(warnings.join('\n')).not.toContain('check Cloud Fleet');
});

it('preserves the caller Daytona ID after a matched malformed provisioned response', async () => {
const warnings: string[] = [];
const deleteCloudFleetSandbox = vi.fn(async () => undefined);
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/cli/commands/fleet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ function mergeFleetNodeListOptions(
return merged;
}

/** Register fleet lifecycle and sandbox commands on the root CLI program. */
export function registerFleetCommands(
program: Command,
overrides: Partial<FleetCommandDependencies> = {}
Expand Down Expand Up @@ -829,6 +830,8 @@ export function registerFleetCommands(
}`
);
});
} else if (error instanceof CloudFleetSandboxProvisionError && error.noSandboxCreated) {
deps.warn(error.message);
} else if (error instanceof CloudFleetSandboxProvisionError && error.outcomeUnknown) {
deps.warn(
`Cloud did not return a complete provisioning response. The outcome is unknown; check Cloud Fleet for node '${
Expand Down
93 changes: 93 additions & 0 deletions packages/cloud/src/fleet-sandbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,99 @@ describe('Cloud fleet sandbox client', () => {
}
);

it('classifies a capacity 503 as a definitive pre-allocation rejection', async () => {
mocks.authorizedApiFetch
.mockResolvedValueOnce({
response: Response.json({ cloudWorkspaceId: CLOUD_WORKSPACE_ID }),
auth,
})
.mockResolvedValueOnce({
response: Response.json(
{
error: 'Sandbox capacity is exhausted before allocation; no sandbox was created',
code: 'sandbox_capacity_exhausted',
capacity: [{ provider: 'agent37', current: 14, limit: 10 }],
retryable: true,
no_sandbox_created: true,
},
{ status: 503 }
),
auth,
});

const error = await ensureCloudFleetSandbox({
workspaceId: 'rw_abc',
requiredCapability: 'spawn:codex',
sandboxId: SANDBOX_ID,
name: SANDBOX_NAME,
forceProvision: true,
providerId: 'agent37',
workloadProfile: 'long-running-agent',
}).catch((caught: unknown) => caught);

expect(error).toBeInstanceOf(CloudFleetSandboxProvisionError);
expect(error).toMatchObject({
code: 'sandbox_capacity_exhausted',
providerId: 'agent37',
sandboxId: undefined,
confirmedProvisioned: false,
outcomeUnknown: false,
noSandboxCreated: true,
retryable: true,
capacity: [{ provider: 'agent37', current: 14, limit: 10 }],
});
expect(String(error)).toContain('agent37: 14 current / 10 limit');
expect(String(error)).toContain('No sandbox was created');
});

it.each([
['current', 14.5, 10],
['limit', 14, 10.5],
])(
'keeps a capacity 503 with fractional %s on the conservative unknown path',
async (_field, current, limit) => {
mocks.authorizedApiFetch
.mockResolvedValueOnce({
response: Response.json({ cloudWorkspaceId: CLOUD_WORKSPACE_ID }),
auth,
})
.mockResolvedValueOnce({
response: Response.json(
{
error: 'Sandbox capacity is exhausted before allocation; no sandbox was created',
code: 'sandbox_capacity_exhausted',
capacity: [{ provider: 'agent37', current, limit }],
retryable: true,
no_sandbox_created: true,
},
{ status: 503 }
),
auth,
});

const error = await ensureCloudFleetSandbox({
workspaceId: 'rw_abc',
requiredCapability: 'spawn:codex',
sandboxId: SANDBOX_ID,
name: SANDBOX_NAME,
forceProvision: true,
providerId: 'agent37',
workloadProfile: 'long-running-agent',
}).catch((caught: unknown) => caught);

expect(error).toBeInstanceOf(CloudFleetSandboxProvisionError);
expect(error).toMatchObject({
code: undefined,
sandboxId: SANDBOX_ID,
confirmedProvisioned: false,
outcomeUnknown: true,
noSandboxCreated: false,
retryable: false,
capacity: [],
});
}
);

it.each(['provisioned', 'provisioning_timeout'] as const)(
'requires a valid Daytona providerSandboxId for %s responses',
async (outcome) => {
Expand Down
91 changes: 87 additions & 4 deletions packages/cloud/src/fleet-sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,18 +68,31 @@ export type CloudFleetSandboxProviderId =
| 'agent37'
| 'microsandbox';

/**
* Carries every safe identifier Cloud returned when provisioning failed after
* the request may have created a billable sandbox.
*/
/** Safe aggregate provider-capacity detail returned before allocation. */
export type CloudFleetSandboxCapacityExhaustion = {
readonly provider: CloudFleetSandboxProviderId;
readonly current: number;
readonly limit: number;
};

/** Describes provisioning failure without granting unproven cleanup authority. */
export class CloudFleetSandboxProvisionError extends Error {
readonly cloudWorkspaceId?: string;
readonly sandboxId?: string;
readonly nodeName?: string;
readonly providerId?: CloudFleetSandboxProviderId;
/** A 2xx response proved this exact caller-owned sandbox was provisioned. */
readonly confirmedProvisioned: boolean;
/** Cloud may have accepted the request without returning a complete outcome. */
readonly outcomeUnknown: boolean;
/** Stable Cloud error code for a validated pre-allocation capacity rejection. */
readonly code?: 'sandbox_capacity_exhausted';
/** Cloud affirmatively proved the rejected request allocated no sandbox. */
readonly noSandboxCreated: boolean;
/** The same request can be retried after provider capacity becomes available. */
readonly retryable: boolean;
/** Safe aggregate counts for each provider that blocked allocation. */
readonly capacity: readonly CloudFleetSandboxCapacityExhaustion[];

constructor(
message: string,
Expand All @@ -90,6 +103,10 @@ export class CloudFleetSandboxProvisionError extends Error {
providerId?: CloudFleetSandboxProviderId;
confirmedProvisioned?: boolean;
outcomeUnknown?: boolean;
code?: 'sandbox_capacity_exhausted';
noSandboxCreated?: boolean;
retryable?: boolean;
capacity?: readonly CloudFleetSandboxCapacityExhaustion[];
cause?: unknown;
} = {}
) {
Expand All @@ -101,6 +118,10 @@ export class CloudFleetSandboxProvisionError extends Error {
this.providerId = identity.providerId;
this.confirmedProvisioned = identity.confirmedProvisioned === true;
this.outcomeUnknown = !this.confirmedProvisioned && identity.outcomeUnknown === true;
this.code = identity.code;
this.noSandboxCreated = !this.confirmedProvisioned && identity.noSandboxCreated === true;
this.retryable = identity.retryable === true;
this.capacity = identity.capacity?.map((entry) => ({ ...entry })) ?? [];
}
}

Expand Down Expand Up @@ -636,6 +657,55 @@ function readProviderId(
return undefined;
}

/** Parse only the complete, affirmative pre-allocation capacity contract. */
function readCapacityExhaustion(
payload: unknown
): readonly CloudFleetSandboxCapacityExhaustion[] | undefined {
if (
!isObject(payload) ||
readString(payload, 'code') !== 'sandbox_capacity_exhausted' ||
payload.no_sandbox_created !== true ||
payload.retryable !== true ||
!Array.isArray(payload.capacity) ||
payload.capacity.length === 0
) {
return undefined;
}
const capacity: CloudFleetSandboxCapacityExhaustion[] = [];
for (const value of payload.capacity) {
if (!isObject(value)) return undefined;
const provider = readString(value, 'provider');
const current = readNumber(value, 'current');
const limit = readNumber(value, 'limit');
if (
provider === undefined ||
!CLOUD_FLEET_SANDBOX_PROVIDER_IDS.includes(provider as CloudFleetSandboxProviderId) ||
current === undefined ||
current < 0 ||
!Number.isInteger(current) ||
limit === undefined ||
limit < 0 ||
!Number.isInteger(limit)
) {
return undefined;
}
capacity.push({
provider: provider as CloudFleetSandboxProviderId,
current,
limit,
});
}
return capacity;
}

/** Render safe aggregate provider counts for a definitive capacity rejection. */
function capacityExhaustionMessage(capacity: readonly CloudFleetSandboxCapacityExhaustion[]): string {
const detail = capacity
.map(({ provider, current, limit }) => `${provider}: ${current} current / ${limit} limit`)
.join('; ');
return `Sandbox capacity is exhausted before allocation (${detail}). No sandbox was created; retry when capacity is available.`;
}

function assertExpectedSandboxIdentity(payload: JsonRecord, expectedSandboxId: string): void {
const sandboxId = requiredString(payload, 'sandboxId', 'Cloud fleet sandbox');
if (sandboxId !== expectedSandboxId) {
Expand Down Expand Up @@ -1022,6 +1092,19 @@ export async function ensureCloudFleetSandbox(
});
}
const error = endpointError('provision the fleet sandbox', response, payload);
const capacity = response.status === 503 ? readCapacityExhaustion(payload) : undefined;
if (capacity !== undefined) {
throw new CloudFleetSandboxProvisionError(capacityExhaustionMessage(capacity), {
cloudWorkspaceId: resolved.cloudWorkspaceId,
...(sandboxIdentity.name === undefined ? {} : { nodeName: sandboxIdentity.name }),
providerId: capacity.length === 1 ? capacity[0].provider : input.providerId,
code: 'sandbox_capacity_exhausted',
noSandboxCreated: true,
retryable: true,
capacity,
cause: error,
});
}
// Gateway/server failures can arrive after Cloud accepted the ensure
// request but before it could return an identity. Keep every 5xx failure
// replayable as an unknown outcome, even for legacy custom-name callers;
Expand Down
1 change: 1 addition & 0 deletions packages/cloud/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export {
type CloudFleetSandboxReused,
type CloudFleetSandboxProvisioningTimeout,
type CloudFleetSandboxProviderId,
type CloudFleetSandboxCapacityExhaustion,
type CloudFleetSandboxWorkloadProfile,
type DeleteCloudFleetSandboxInput,
type CloudFleetSandboxRequestOptions,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"version": 1,
"id": "1916-sandbox-capacity-rejection",
"kind": "bugfix",
"title": "Classify a pre-allocation sandbox capacity rejection as definitive",
"runner": {
"command": ["node", "tests/relayflows/cases/1916-sandbox-capacity-rejection/run.mjs"]
},
"requirements": [],
"timeoutSeconds": 900,
"expected": {
"base": {
"outcome": "bug",
"signature": "capacity_503_reported_as_unknown"
},
"head": {
"outcome": "fixed",
"signature": "capacity_503_definitive_no_sandbox_created"
}
}
}
Loading
Loading