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.

fix(agent): pin sandbox models to Anthropic and surface model-change failures (#5900)

Eric Hayesd707a2a6e7b4
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index bd075307d0..151f87ccc4 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -24,6 +24,7 @@ import {
type ParentProps,
useContext,
} from 'solid-js';
+import { controlOutcome } from '../state/control-message';
import { createAgentSessionFeed } from './create-agent-session-feed';
import {
type ComposerController,
@@ -107,6 +108,7 @@ export function AgentSessionProvider(
sessionId,
working,
model: () => feed.metadata()?.model,
+ controlOutcome: (requestId) => controlOutcome(feed.messages(), requestId),
});
// Anything the service can only deliver over a live transport: a prompt on
diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
index 31dd7ef661..3204290e84 100644
--- a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
+++ b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
@@ -9,6 +9,7 @@
import { createRoot, createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ControlOutcome } from '../state/control-message';
import {
createComposerController,
TURN_OBSERVE_TIMEOUT_MS,
@@ -25,7 +26,12 @@ vi.mock('@service-agent-harness/client', () => ({
control: vi.fn(async (sessionId: string, action: unknown) => {
control.calls.push({ sessionId, action });
if (control.outcome === 'reject') throw new Error('network');
- return { isErr: () => control.outcome === 'err' };
+ return {
+ isErr: () => control.outcome === 'err',
+ // The action id the endpoint returns — the fold's `requestId` for
+ // the folded message this action derives. One per call, in order.
+ value: `action-${control.calls.length - 1}`,
+ };
}),
},
}));
@@ -52,11 +58,29 @@ function setup(options?: {
'sessionId' in (options ?? {}) ? options?.sessionId : 'session-1'
);
const [model, setModel] = createSignal<string | null>(options?.model ?? null);
+ // The fold's per-action outcomes, keyed by the id `control` returned.
+ const [outcomes, setOutcomes] = createSignal<Record<string, ControlOutcome>>(
+ {}
+ );
+ const resolveControl = (requestId: string, outcome: ControlOutcome) =>
+ setOutcomes((current) => ({ ...current, [requestId]: outcome }));
const { controller, dispose } = createRoot((dispose) => ({
- controller: createComposerController({ sessionId, working, model }),
+ controller: createComposerController({
+ sessionId,
+ working,
+ model,
+ controlOutcome: (requestId) => outcomes()[requestId],
+ }),
dispose,
}));
- return { controller, setWorking, setSessionId, setModel, dispose };
+ return {
+ controller,
+ setWorking,
+ setSessionId,
+ setModel,
+ resolveControl,
+ dispose,
+ };
}
beforeEach(() => {
@@ -331,6 +355,68 @@ describe('a model change in flight', () => {
expect(controller.changingModel()).toBeUndefined();
dispose();
});
+
+ it('clears when the runtime rejects the change', async () => {
+ const { controller, resolveControl, dispose } = setup({
+ model: 'old-model',
+ });
+ controller.setModel('new-model');
+ await flush();
+ expect(controller.changingModel()).toBe('new-model');
+
+ // The runtime refuses: the fold resolves this action's control outcome,
+ // the model never moves. The pending state must release on it alone.
+ resolveControl('action-0', {
+ kind: 'rejected',
+ message: 'no provider serves it',
+ });
+ await flush();
+
+ expect(controller.changingModel()).toBeUndefined();
+ dispose();
+ });
+
+ it("ignores another action's rejection", async () => {
+ const { controller, resolveControl, dispose } = setup({
+ model: 'old-model',
+ });
+ // An earlier change was refused before this request.
+ controller.setModel('new-model');
+ await flush();
+ controller.setModel('new-model');
+ await flush();
+
+ // The first action's rejection must not answer the second request…
+ resolveControl('action-0', { kind: 'rejected', message: 'refused' });
+ await flush();
+ expect(controller.changingModel()).toBe('new-model');
+
+ // …but its own does.
+ resolveControl('action-1', { kind: 'rejected', message: 'refused again' });
+ await flush();
+
+ expect(controller.changingModel()).toBeUndefined();
+ dispose();
+ });
+
+ it('keeps waiting while its own action is pending or accepted', async () => {
+ const { controller, resolveControl, dispose } = setup({
+ model: 'old-model',
+ });
+ controller.setModel('new-model');
+ await flush();
+
+ resolveControl('action-0', { kind: 'pending' });
+ await flush();
+ expect(controller.changingModel()).toBe('new-model');
+
+ // Accepted alone is not the end of the wait — the fold's `model` moving
+ // is (the accepted response carries it) — so the pending state holds.
+ resolveControl('action-0', { kind: 'accepted' });
+ await flush();
+ expect(controller.changingModel()).toBe('new-model');
+ dispose();
+ });
});
describe('session switch', () => {
diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.ts b/apps/web/src/features/block-agent/context/create-composer-controller.ts
index 8e159ed870..94da1ba8d1 100644
--- a/apps/web/src/features/block-agent/context/create-composer-controller.ts
+++ b/apps/web/src/features/block-agent/context/create-composer-controller.ts
@@ -24,6 +24,7 @@ import {
type PostPhase,
type QueuedPrompt,
} from '../state/composer-state';
+import type { ControlOutcome } from '../state/control-message';
export type ComposerController = {
/** Prompts waiting to be sent, oldest first. The head sends next. */
@@ -75,16 +76,31 @@ export function createComposerController(options: {
sessionId: Accessor<string | undefined>;
/** The block's one working signal — see `AgentSessionContext`. */
working: Accessor<boolean>;
+ /**
+ * The fold's outcome for the control action `requestId` — the id the
+ * control POST returned, which the fold stamps on the folded message the
+ * action derives. A rejection is the other way a pending model change
+ * resolves — the fold's `model` never moves for one — so without this a
+ * refused switch would shimmer forever.
+ */
+ controlOutcome?: (requestId: string) => ControlOutcome | undefined;
}): ComposerController {
const [state, setState] = createStore<{
queue: QueuedPrompt[];
post: PostPhase;
/** The model a `setModel` is currently asking for. */
requestedModel: string | undefined;
+ /**
+ * The id the control POST returned for the in-flight change — the exact
+ * handle for its outcome in the fold, so no other action's rejection
+ * (nor an older refusal of the same model) can answer this request.
+ */
+ requestedActionId: string | undefined;
}>({
queue: [],
post: { type: 'idle' },
requestedModel: undefined,
+ requestedActionId: undefined,
});
const postHead = async (sessionId: string, prompt: QueuedPrompt) => {
@@ -112,13 +128,21 @@ export function createComposerController(options: {
.control(sessionId, { type: 'setModel', model })
.catch(() => undefined);
if (result === undefined || result.isErr()) {
- setState('requestedModel', undefined);
+ batch(() => {
+ setState('requestedModel', undefined);
+ setState('requestedActionId', undefined);
+ });
toast.failure('The model could not be changed');
+ return;
+ }
+ // The POST returning only means the service accepted it; resolution is
+ // observed through the fold. The returned action id is the fold's
+ // `requestId` for this change: an accepted change moves the metadata's
+ // `model`, a rejected one resolves this id's control outcome, and the
+ // effects below watch for whichever comes.
+ if (state.requestedModel === model) {
+ setState('requestedActionId', result.value);
}
- // Success is observed through the fold: the runtime acks the config
- // change and the session metadata's `model` moves. The POST returning is
- // not the end of the wait — it only means the service accepted it — so
- // `requestedModel` is cleared by the effect below, not here.
};
const postStop = async (sessionId: string) => {
@@ -158,7 +182,30 @@ export function createComposerController(options: {
if (requested === undefined) return;
const current = options.model?.();
if (current == null) return;
- if (current === requested) setState('requestedModel', undefined);
+ if (current === requested) {
+ batch(() => {
+ setState('requestedModel', undefined);
+ setState('requestedActionId', undefined);
+ });
+ }
+ });
+
+ // The other resolution: the runtime refused the change. The fold resolves
+ // this exact action's control outcome (`ControlOutcome::Rejected`) on the
+ // message carrying its id, and the transcript renders the refusal; here it
+ // just has to release the pending state, and say so — a refused switch
+ // otherwise looks like one that never registered.
+ createEffect(() => {
+ const requested = state.requestedModel;
+ const actionId = state.requestedActionId;
+ if (requested === undefined || actionId === undefined) return;
+ const outcome = options.controlOutcome?.(actionId);
+ if (outcome?.kind !== 'rejected') return;
+ batch(() => {
+ setState('requestedModel', undefined);
+ setState('requestedActionId', undefined);
+ });
+ toast.failure(`Couldn't switch to ${requested}`);
});
// `awaiting_turn` resolves on whichever comes first: the fold reports the
@@ -198,6 +245,7 @@ export function createComposerController(options: {
queue: [],
post: { type: 'idle' },
requestedModel: undefined,
+ requestedActionId: undefined,
});
});
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 e3139ece93..6d7ed1bffd 100644
--- a/apps/web/src/features/block-agent/debug/replay/driver.ts
+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts
@@ -167,8 +167,10 @@ export function createReplayDriver(options: ReplayDriverOptions): ReplayDriver {
}, PROMPT_ECHO_DELAY_MS);
}
// Every other action — stop, permissions — acks and does nothing:
- // their observable effects come from frames, which playback owns.
- return ok(undefined);
+ // their observable effects come from frames, which playback owns. The
+ // id is what the real endpoint returns; replay frames never carry it,
+ // so nothing correlates against it.
+ return ok(`replay-action-${cursor()}`);
},
};
diff --git a/apps/web/src/features/block-agent/state/control-message.ts b/apps/web/src/features/block-agent/state/control-message.ts
index cb217cff77..3f54cc1eaa 100644
--- a/apps/web/src/features/block-agent/state/control-message.ts
+++ b/apps/web/src/features/block-agent/state/control-message.ts
@@ -32,3 +32,33 @@ export function lastTurnMessage(
}
return undefined;
}
+
+/** How the runtime disposed of one control, read off its folded message. */
+export type ControlOutcome = Extract<
+ FoldedMessage['parts'][number],
+ { kind: 'control' }
+>['outcome'];
+
+/**
+ * The outcome of the control action `requestId`, once the fold has folded it.
+ *
+ * The control endpoint returns each accepted action's id, and the fold
+ * stamps that same id as `requestId` on the folded message the action
+ * derives — so this is exact correlation, not a newest-wins scan. The
+ * composer uses it to resolve a pending model switch: the fold's `model`
+ * only moves for an accepted change, so a rejection is only visible here.
+ * `undefined` until the fold has seen the action's frame.
+ */
+export function controlOutcome(
+ messages: readonly FoldedMessage[],
+ requestId: string
+): ControlOutcome | undefined {
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index]!;
+ if (message.requestId !== requestId) continue;
+ for (const part of message.parts) {
+ if (part.kind === 'control') return part.outcome;
+ }
+ }
+ return undefined;
+}
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 3eb866d33a..9324106452 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
@@ -1,6 +1,7 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import type {
+ AgentActionId,
AgentSessionLogResponse,
AgentSessionResponse,
ControlRequest,
@@ -52,7 +53,15 @@ export const agentHarnessServiceClient = {
).then((result) => result.map(() => undefined));
},
+ /**
+ * Returns the accepted action's id, which the fold stamps as `requestId`
+ * on the folded message the action derives — the correlation handle for
+ * watching that action's outcome.
+ */
control(sessionId: string, request: ControlRequest) {
+ // The endpoint answers with a bare JSON string (`AgentActionId`), which
+ // `fetchWithToken`'s object-or-bytes constraint cannot name; the cast is
+ // the whole accommodation.
return fetchWithToken<Record<string, never>>(
`${agentHarnessHost}/agent-sessions/${sessionId}/control`,
{
@@ -60,7 +69,7 @@ export const agentHarnessServiceClient = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
}
- ).then((result) => result.map(() => undefined));
+ ).then((result) => result.map((id) => id as unknown as AgentActionId));
},
delete(sessionId: string) {
diff --git a/crates/agent_harness/container/opencode.json b/crates/agent_harness/container/opencode.json
index 9ee0a2e5a1..20f7216465 100644
--- a/crates/agent_harness/container/opencode.json
+++ b/crates/agent_harness/container/opencode.json
@@ -1,9 +1,9 @@
{
"$schema": "https://opencode.ai/config.json",
"enabled_providers": [
- "opencode"
+ "anthropic"
],
- "model": "opencode/big-pickle",
+ "model": "anthropic/claude-sonnet-5",
"instructions": [
"/etc/macro-agent/SYSTEM.md"
],
diff --git a/crates/agent_harness/src/outbound/daytona/client.rs b/crates/agent_harness/src/outbound/daytona/client.rs
index 04b138a387..4e6ad3facb 100644
--- a/crates/agent_harness/src/outbound/daytona/client.rs
+++ b/crates/agent_harness/src/outbound/daytona/client.rs
@@ -347,6 +347,11 @@ impl DaytonaClient {
}
/// Stop a running sandbox without deleting it.
+ ///
+ /// A sandbox Daytona no longer knows (404) counts as stopped: it is
+ /// already in the state the caller asked for, and treating it as a
+ /// failure puts the idle reaper into an endless retry loop against a
+ /// sandbox that was deleted out from under it.
#[tracing::instrument(err, skip(self))]
pub async fn stop(&self, sandbox_id: &str) -> Result<()> {
let operation = "stop sandbox";
@@ -358,7 +363,7 @@ impl DaytonaClient {
.await
.map_err(|source| DaytonaError::Request { operation, source })?;
let status = response.status();
- if status.is_success() {
+ if status.is_success() || status == reqwest::StatusCode::NOT_FOUND {
return Ok(());
}
let body = response
@@ -438,16 +443,34 @@ impl DaytonaClient {
}
/// Destroy a sandbox.
+ ///
+ /// A sandbox Daytona no longer knows (404) counts as deleted — already
+ /// the state the caller asked for — so a repeated delete (or one racing
+ /// Daytona's own cleanup) cannot park the sandbox in the failed-stop
+ /// retry queue forever.
#[tracing::instrument(err, skip(self))]
pub async fn delete(&self, sandbox_id: &str) -> Result<()> {
- let _: serde::de::IgnoredAny = self
- .json(
- self.http
- .delete(format!("{}/sandbox/{sandbox_id}", self.base)),
- "delete sandbox",
- )
- .await?;
- Ok(())
+ let operation = "delete sandbox";
+ let response = self
+ .http
+ .delete(format!("{}/sandbox/{sandbox_id}", self.base))
+ .bearer_auth(self.api_key.expose())
+ .send()
+ .await
+ .map_err(|source| DaytonaError::Request { operation, source })?;
+ let status = response.status();
+ if status.is_success() || status == reqwest::StatusCode::NOT_FOUND {
+ return Ok(());
+ }
+ let body = response
+ .text()
+ .await
+ .map_err(|source| DaytonaError::ReadResponse { operation, source })?;
+ Err(DaytonaError::Api {
+ operation,
+ status,
+ body,
+ })
}
/// Poll the sidecar readiness endpoint until it succeeds.
diff --git a/crates/agent_harness/src/outbound/daytona/manager.rs b/crates/agent_harness/src/outbound/daytona/manager.rs
index 9daf3f0c6b..5cf4fac64b 100644
--- a/crates/agent_harness/src/outbound/daytona/manager.rs
+++ b/crates/agent_harness/src/outbound/daytona/manager.rs
@@ -12,7 +12,9 @@ use tracing::Instrument as _;
use super::client::DaytonaClient;
use super::errors::DaytonaError;
-use super::types::{DaytonaSettings, Env, GithubToken, Labels, PortPreview, Snapshot};
+use super::types::{
+ AnthropicApiKey, DaytonaSettings, Env, GithubToken, Labels, PortPreview, Snapshot,
+};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::SpawnContainer;
use crate::domain::ports::ContainerManager;
@@ -85,6 +87,7 @@ pub struct DaytonaContainerManager {
client: DaytonaClient,
snapshot: Snapshot,
github_token: GithubToken,
+ anthropic_api_key: AnthropicApiKey,
managed: Arc<DaytonaContainerManagerState>,
}
@@ -97,6 +100,7 @@ impl DaytonaContainerManager {
api_key,
snapshot,
github_token,
+ anthropic_api_key,
} = settings;
let client = DaytonaClient::new(api_url, api_key);
let managed = Arc::new(DaytonaContainerManagerState::new());
@@ -107,6 +111,7 @@ impl DaytonaContainerManager {
client,
snapshot,
github_token,
+ anthropic_api_key,
managed,
}
}
@@ -366,12 +371,19 @@ impl ContainerManager for DaytonaContainerManager {
// one fails at prompt time with "Authorization header is badly
// formatted". `container/opencode.json` pins `enabled_providers` to
// keep that list honest; do not drop that pin while this var is set.
+ // `ANTHROPIC_API_KEY` is what activates opencode's `anthropic`
+ // provider — with `enabled_providers` pinned in
+ // `container/opencode.json`, it is the sandbox's only model source.
let env = Env::from(HashMap::from([
("REPO_URL".to_owned(), repo_url),
(
"GITHUB_TOKEN".to_owned(),
self.github_token.expose().to_owned(),
),
+ (
+ "ANTHROPIC_API_KEY".to_owned(),
+ self.anthropic_api_key.expose().to_owned(),
+ ),
]));
let labels = Labels::from(HashMap::from([(
SESSION_LABEL.to_owned(),
diff --git a/crates/agent_harness/src/outbound/daytona/mod.rs b/crates/agent_harness/src/outbound/daytona/mod.rs
index e12d3d7841..be18314b12 100644
--- a/crates/agent_harness/src/outbound/daytona/mod.rs
+++ b/crates/agent_harness/src/outbound/daytona/mod.rs
@@ -8,4 +8,7 @@ mod types;
pub use client::DaytonaClient;
pub use errors::DaytonaError;
pub use manager::{DaytonaContainer, DaytonaContainerManager};
-pub use types::{DaytonaApiKey, DaytonaSettings, Env, GithubToken, Labels, PortPreview, Snapshot};
+pub use types::{
+ AnthropicApiKey, DaytonaApiKey, DaytonaSettings, Env, GithubToken, Labels, PortPreview,
+ Snapshot,
+};
diff --git a/crates/agent_harness/src/outbound/daytona/types.rs b/crates/agent_harness/src/outbound/daytona/types.rs
index 42e30afc4c..341fad61ce 100644
--- a/crates/agent_harness/src/outbound/daytona/types.rs
+++ b/crates/agent_harness/src/outbound/daytona/types.rs
@@ -77,6 +77,28 @@ impl GithubToken {
}
}
+/// API key sandboxes use to run Anthropic models.
+///
+/// opencode activates its `anthropic` provider on this variable's value —
+/// empty behaves like absent — so, like [`GithubToken`], it wraps a possibly
+/// empty string and is always injected. Empty means the sandbox has no model
+/// provider at all (`container/opencode.json` enables only `anthropic`), so
+/// managed sessions advertise no models and cannot prompt.
+#[derive(Clone)]
+pub struct AnthropicApiKey(String);
+
+impl AnthropicApiKey {
+ /// Wrap an Anthropic API credential.
+ #[must_use]
+ pub fn new(value: String) -> Self {
+ Self(value)
+ }
+
+ pub(crate) fn expose(&self) -> &str {
+ &self.0
+ }
+}
+
/// Settings required to create Daytona-backed containers.
pub struct DaytonaSettings {
/// Base URL of the Daytona REST API.
@@ -87,4 +109,6 @@ pub struct DaytonaSettings {
pub snapshot: Snapshot,
/// Token with read access to the repository cloned into sandboxes.
pub github_token: GithubToken,
+ /// Key sandboxes run Anthropic models with.
+ pub anthropic_api_key: AnthropicApiKey,
}
diff --git a/crates/agent_harness/src/outbound/local/manager.rs b/crates/agent_harness/src/outbound/local/manager.rs
index e5c81b1198..07c054134a 100644
--- a/crates/agent_harness/src/outbound/local/manager.rs
+++ b/crates/agent_harness/src/outbound/local/manager.rs
@@ -8,7 +8,7 @@ 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::daytona::{AnthropicApiKey, GithubToken};
use crate::outbound::provision::{self, SESSION_LABEL};
use crate::outbound::sidecar::SidecarTransport;
@@ -28,6 +28,8 @@ pub struct LocalSettings {
pub network: String,
/// Token with read access to the repository cloned into sandboxes.
pub github_token: GithubToken,
+ /// Key sandboxes run Anthropic models with.
+ pub anthropic_api_key: AnthropicApiKey,
}
/// Hands out containers on the local Docker daemon.
@@ -46,6 +48,7 @@ pub struct LocalContainerManager {
image: String,
network: String,
github_token: GithubToken,
+ anthropic_api_key: AnthropicApiKey,
}
impl LocalContainerManager {
@@ -57,12 +60,14 @@ impl LocalContainerManager {
image,
network,
github_token,
+ anthropic_api_key,
} = settings;
Self {
docker: Docker::new(docker_binary),
image,
network,
github_token,
+ anthropic_api_key,
}
}
@@ -226,7 +231,7 @@ impl ContainerManager for LocalContainerManager {
image: self.image.clone(),
name: container_name(session_id),
labels: vec![(SESSION_LABEL.to_owned(), session_id.to_string())],
- env: sandbox_env(repo_url, &self.github_token),
+ env: sandbox_env(repo_url, &self.github_token, &self.anthropic_api_key),
network: self.network.clone(),
};
let container = self.docker.run(&spec).await.map_err(unavailable)?;
@@ -290,10 +295,18 @@ fn sidecar_address(container: &ContainerRef) -> String {
format!("{}:{}", container.name, provision::SIDECAR_PORT)
}
-fn sandbox_env(repo_url: String, github_token: &GithubToken) -> Vec<(String, String)> {
+fn sandbox_env(
+ repo_url: String,
+ github_token: &GithubToken,
+ anthropic_api_key: &AnthropicApiKey,
+) -> Vec<(String, String)> {
vec![
("REPO_URL".to_owned(), repo_url),
("GITHUB_TOKEN".to_owned(), github_token.expose().to_owned()),
+ (
+ "ANTHROPIC_API_KEY".to_owned(),
+ anthropic_api_key.expose().to_owned(),
+ ),
]
}
diff --git a/crates/agent_harness/src/outbound/local/manager/test.rs b/crates/agent_harness/src/outbound/local/manager/test.rs
index 36ef342eca..78b151c53f 100644
--- a/crates/agent_harness/src/outbound/local/manager/test.rs
+++ b/crates/agent_harness/src/outbound/local/manager/test.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::outbound::daytona::GithubToken;
+use crate::outbound::daytona::{AnthropicApiKey, GithubToken};
/// One container per session, so a resume finds exactly one and `docker ps`
/// says which session it belongs to.
@@ -22,13 +22,16 @@ fn a_sidecar_is_dialed_by_container_name() {
);
}
-/// Same clone credentials Daytona injects, so the readiness recipe is
-/// exercised against the same environment a deployed sandbox sees.
+/// Same credentials Daytona injects, so the readiness recipe is exercised
+/// against the same environment a deployed sandbox sees. The Anthropic key
+/// is what activates the one model provider `container/opencode.json`
+/// enables.
#[test]
-fn sandbox_env_carries_the_repo_and_github_token() {
+fn sandbox_env_carries_the_repo_and_credentials() {
let env = sandbox_env(
"https://github.com/macro-inc/macro".to_owned(),
&GithubToken::new("test-token".to_owned()),
+ &AnthropicApiKey::new("test-anthropic-key".to_owned()),
);
assert!(env.contains(&(
@@ -36,4 +39,8 @@ fn sandbox_env_carries_the_repo_and_github_token() {
"https://github.com/macro-inc/macro".to_owned()
)));
assert!(env.contains(&("GITHUB_TOKEN".to_owned(), "test-token".to_owned())));
+ assert!(env.contains(&(
+ "ANTHROPIC_API_KEY".to_owned(),
+ "test-anthropic-key".to_owned()
+ )));
}
diff --git a/crates/agent_harness/src/outbound/namespace/manager.rs b/crates/agent_harness/src/outbound/namespace/manager.rs
index 249fbfc113..874c13e460 100644
--- a/crates/agent_harness/src/outbound/namespace/manager.rs
+++ b/crates/agent_harness/src/outbound/namespace/manager.rs
@@ -12,7 +12,7 @@ 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::daytona::{AnthropicApiKey, GithubToken};
use crate::outbound::provision;
use crate::outbound::sidecar::SidecarTransport;
@@ -22,6 +22,7 @@ pub struct NamespaceContainerManager {
image_ref: super::types::ImageRef,
lifetime: std::time::Duration,
github_token: GithubToken,
+ anthropic_api_key: AnthropicApiKey,
}
impl NamespaceContainerManager {
@@ -34,12 +35,14 @@ impl NamespaceContainerManager {
image_ref,
lifetime,
github_token,
+ anthropic_api_key,
} = settings;
Self {
client: NamespaceClient::new(api_url, token),
image_ref,
lifetime,
github_token,
+ anthropic_api_key,
}
}
@@ -108,6 +111,10 @@ impl ContainerManager for NamespaceContainerManager {
"GITHUB_TOKEN".to_owned(),
self.github_token.expose().to_owned(),
),
+ (
+ "ANTHROPIC_API_KEY".to_owned(),
+ self.anthropic_api_key.expose().to_owned(),
+ ),
],
exported_ports: vec![provision::SIDECAR_PORT],
};
diff --git a/crates/agent_harness/src/outbound/namespace/types.rs b/crates/agent_harness/src/outbound/namespace/types.rs
index 8f5e54fe52..63ae81c6e3 100644
--- a/crates/agent_harness/src/outbound/namespace/types.rs
+++ b/crates/agent_harness/src/outbound/namespace/types.rs
@@ -1,6 +1,6 @@
use std::time::Duration;
-use crate::outbound::daytona::GithubToken;
+use crate::outbound::daytona::{AnthropicApiKey, GithubToken};
/// Namespace instance identifier.
#[derive(Debug, Clone)]
@@ -99,4 +99,6 @@ pub struct NamespaceSettings {
pub lifetime: Duration,
/// Token with read access to the repository cloned into instances.
pub github_token: GithubToken,
+ /// Key instances run Anthropic models with.
+ pub anthropic_api_key: AnthropicApiKey,
}
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index ed22ba1124..90ae38b965 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -41,6 +41,13 @@ pub struct Config {
/// unaffected.
#[macro_config_default(String::new())]
pub github_token: String,
+ /// API key sandboxes run Anthropic models with. Injected into the
+ /// sandbox environment at creation, where it activates opencode's
+ /// `anthropic` provider — the only provider
+ /// `crates/agent_harness/container/opencode.json` enables. Empty means
+ /// sandboxes advertise no models and managed sessions cannot prompt.
+ #[macro_config_default(String::new())]
+ pub anthropic_api_key: String,
/// Run sandboxes on the local Docker daemon instead of Daytona.
///
/// Default off: a deployed harness must keep using Daytona even if this
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 09104d0d54..e923492140 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -21,8 +21,8 @@ use agent_harness::inbound::runtime_gateway::RuntimeGatewayState;
use agent_harness::outbound::channel_announcer::ChannelAnnouncer;
use agent_harness::outbound::containers::HarnessContainers;
use agent_harness::outbound::daytona::{
- DaytonaApiKey as DaytonaApiKeySecret, DaytonaContainerManager, DaytonaSettings,
- GithubToken as GithubTokenSecret, Snapshot,
+ AnthropicApiKey as AnthropicApiKeySecret, DaytonaApiKey as DaytonaApiKeySecret,
+ DaytonaContainerManager, DaytonaSettings, GithubToken as GithubTokenSecret, Snapshot,
};
use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};
use agent_harness::outbound::runtime_registry::RuntimeRegistry;
@@ -144,6 +144,16 @@ async fn run() -> anyhow::Result<()> {
)));
// Containers: local Docker when a developer has opted in, Daytona otherwise.
+ // The key rides into every sandbox's environment; without it the runtime
+ // has no model provider at all (`container/opencode.json` enables only
+ // `anthropic`), so managed sessions would advertise no models and fail
+ // every prompt.
+ if config.anthropic_api_key.trim().is_empty() {
+ tracing::warn!(
+ "ANTHROPIC_API_KEY is unset: managed sandboxes have no model provider; external agent sessions are unaffected"
+ );
+ }
+ let anthropic_api_key = AnthropicApiKeySecret::new(config.anthropic_api_key.clone());
let containers = if config.dev_dangerous_local_containers {
if !matches!(config.environment, Environment::Local) {
anyhow::bail!("DEV_DANGEROUS_LOCAL_CONTAINERS is only allowed when ENVIRONMENT=local");
@@ -164,6 +174,7 @@ async fn run() -> anyhow::Result<()> {
image: config.local_container_image.clone(),
network: network.to_owned(),
github_token: GithubTokenSecret::new(config.github_token.clone()),
+ anthropic_api_key: anthropic_api_key.clone(),
}))
} else {
// Credential-less boot is deliberate: external sessions need neither.
@@ -178,6 +189,7 @@ async fn run() -> anyhow::Result<()> {
api_key: DaytonaApiKeySecret::new(config.daytona_api_key.clone()),
snapshot: Snapshot::new(config.daytona_snapshot.clone()),
github_token: GithubTokenSecret::new(config.github_token.clone()),
+ anthropic_api_key,
}))
};
let container_shutdown = containers.clone();