Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents)!: remove the Claude Cloud harness and @claude agent (#8474)
Eric Hayes75818b477513
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex d9cf70fd5a..47e1319ec2 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -468,7 +468,6 @@"crates/call","crates/channel_sender","crates/channels",- "crates/claude_cloud_agents","crates/codex_cloud_agents","crates/codex_connection","crates/comms_db_client",@@ -622,7 +621,6 @@"crates/channel_sender","crates/channels","crates/chat",- "crates/claude_cloud_agents","crates/code_execution","crates/codex_cloud_agents","crates/codex_connection",@@ -3250,26 +3248,6 @@"crates/share_permission_db_utils","crates/workspace-hack"],- "claude_cloud_agents": [- "crates/agent_runtime_protocol",- "crates/bot_id",- "crates/bot_token",- "crates/claude_cloud_agents",- "crates/cowlike",- "crates/cursor_api_key",- "crates/harness_id",- "crates/harness_token",- "crates/macro_auth",- "crates/macro_authorization",- "crates/macro_env",- "crates/macro_env_var",- "crates/macro_user_id",- "crates/macro_uuid",- "crates/model-error-response",- "crates/model_user",- "crates/remote_env_var",- "crates/workspace-hack"- ],"claude_fold": ["crates/agent_runtime_protocol","crates/cowlike",diff --git a/.gitignore b/.gitignoreindex 7fbc7d0d78..3a5c3d81f0 100644--- a/.gitignore+++ b/.gitignore@@ -53,7 +53,6 @@ infra/local/generated//macrod.webhook-state.json# Owner-bound subscription OAuth credentials for the internal Claude demo.-/.claude-cloud/# Marketing site prerender bundle (dist/ is covered by **/dist)./apps/marketing/dist-prerender/diff --git a/.sqlx/query-0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75.json b/.sqlx/query-0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75.jsondeleted file mode 100644index f7978a9aaa..0000000000--- a/.sqlx/query-0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 2) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 2, updated_at = now()",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Bytea",- "Text"- ]- },- "nullable": []- },- "hash": "0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75"-}diff --git a/.sqlx/query-60c4b70fca2877d4725e9d8ffdf61f434e090e77ce7c0d273cd2bdd242e1a30f.json b/.sqlx/query-60c4b70fca2877d4725e9d8ffdf61f434e090e77ce7c0d273cd2bdd242e1a30f.jsondeleted file mode 100644index 74b9ac3715..0000000000--- a/.sqlx/query-60c4b70fca2877d4725e9d8ffdf61f434e090e77ce7c0d273cd2bdd242e1a30f.json+++ /dev/null@@ -1,34 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT grant_ciphertext, kms_key_id, encryption_version FROM claude_oauth_grants WHERE user_id = $1",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "grant_ciphertext",- "type_info": "Bytea"- },- {- "ordinal": 1,- "name": "kms_key_id",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "encryption_version",- "type_info": "Int2"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- false- ]- },- "hash": "60c4b70fca2877d4725e9d8ffdf61f434e090e77ce7c0d273cd2bdd242e1a30f"-}diff --git a/.sqlx/query-82f5f0bbdc50b48174baa0d5b1e2020d3ccf13300604c8b0e0af6610decc7fa5.json b/.sqlx/query-82f5f0bbdc50b48174baa0d5b1e2020d3ccf13300604c8b0e0af6610decc7fa5.jsondeleted file mode 100644index 66cf24728d..0000000000--- a/.sqlx/query-82f5f0bbdc50b48174baa0d5b1e2020d3ccf13300604c8b0e0af6610decc7fa5.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "DELETE FROM claude_oauth_grants WHERE user_id = $1",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "82f5f0bbdc50b48174baa0d5b1e2020d3ccf13300604c8b0e0af6610decc7fa5"-}diff --git a/Cargo.lock b/Cargo.lockindex 0e49334e0e..1b94f90849 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -411,7 +411,6 @@ dependencies = ["channel_sender","channels","chrono",- "claude_cloud_agents","codex_cloud_agents","codex_connection","cursor_api_key",@@ -517,7 +516,6 @@ dependencies = ["chat","chrono","chrono-tz",- "claude_cloud_agents","code_execution","codex_cloud_agents","codex_connection",@@ -4353,37 +4351,6 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"-[[package]]-name = "claude_cloud_agents"-version = "0.1.0"-dependencies = [- "agent-client-protocol",- "agent_runtime_protocol",- "async-trait",- "axum",- "base64 0.22.1",- "clap",- "cursor_api_key",- "futures",- "macro_authorization",- "macro_db_migrator",- "rand 0.9.4",- "reqwest 0.13.4",- "serde",- "serde_json",- "sha2 0.10.9",- "sqlx",- "sse-core",- "subtle",- "tempfile",- "thiserror 2.0.18",- "tokio",- "utoipa",- "uuid",- "workspace-hack",- "zeroize",-]-[[package]]name = "claude_fold"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 444d3a9d32..a982d2756a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -40,7 +40,6 @@ members = ["crates/cursor_api_key","crates/cursor_cloud_agents","crates/jev",- "crates/claude_cloud_agents","crates/database_sql","crates/database_webhooks","crates/databases",diff --git a/apps/docs/AI/mcp/tools/configure-agent.mdx b/apps/docs/AI/mcp/tools/configure-agent.mdxindex b5bcbf545b..357b77ec82 100644--- a/apps/docs/AI/mcp/tools/configure-agent.mdx+++ b/apps/docs/AI/mcp/tools/configure-agent.mdx@@ -15,7 +15,7 @@ Update the instructions or settings of an AI agent the current user can manage.| --- | --- | --- | --- || `botId` | string | Yes | The agent's bot id: `bot.botId` from ListAgents. || `instructions` | string | No | The complete new instructions in markdown. Replaces the current instructions entirely; omit to keep them. |-| `harness` | `"in-memory"` \| `"cursor"` \| `"claude-cloud"` \| `"macrod"` | No | Runtime to move the agent onto. `macrod` also needs harnessId; the other runtimes must not have one. The current model may not exist on the new runtime, so usually pass defaultModel with it. Omit to keep the current runtime. |+| `harness` | `"in-memory"` \| `"cursor"` \| `"macrod"` | No | Runtime to move the agent onto. `macrod` also needs harnessId; the other runtimes must not have one. The current model may not exist on the new runtime, so usually pass defaultModel with it. Omit to keep the current runtime. || `harnessId` | string | No | Id of the registered self-hosted harness, required when harness is `macrod` and forbidden otherwise. || `defaultModel` | string | No | Model id the agent's new sessions should use, as the runtime names it (e.g. `claude-sonnet-4-5`). Valid ids depend on the runtime. Omit to keep the current model. || `channelScope` | `"all"` \| `"selected"` | No | `all` makes the agent mentionable in every channel its owner can use; `selected` limits it to channelIds. Omit to keep the current scope, or omit it and pass channelIds alone to switch to `selected`. |diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsxindex 6841d80352..9b64a12b9e 100644--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx@@ -182,8 +182,6 @@ function SessionContent(props: {{label: () => {const provider = session()?.external?.provider;- if (provider === 'claude-cloud')- return 'Open in Claude';return provider? `Open in ${provider.charAt(0).toUpperCase()}${provider.slice(1)}`: 'Open externally';diff --git a/apps/web/src/features/agents-view/core/roster.test.ts b/apps/web/src/features/agents-view/core/roster.test.tsindex 8a0ece3a9e..f3f3b78827 100644--- a/apps/web/src/features/agents-view/core/roster.test.ts+++ b/apps/web/src/features/agents-view/core/roster.test.ts@@ -126,7 +126,6 @@ describe('rosterForAgentPicker and kindForBot', () => {persisted({ harness: 'cursor' }),persisted({ harness: 'macrod' }),persisted({ harness: 'sandbox' }),- persisted({ harness: 'claude-cloud' }),persisted({ harness: 'codex-cloud' }),persisted({ harness: 'future-runtime' }),persisted({@@ -155,14 +154,13 @@ describe('rosterForAgentPicker and kindForBot', () => {'bot-cursor','bot-macrod','bot-sandbox',- 'bot-claude-cloud','bot-codex-cloud','bot-future-runtime','saved-macro-name',]);});- it.each(['claude-cloud', 'codex-cloud', 'future-runtime'])(+ it.each(['codex-cloud', 'future-runtime'])('does not block an agent just because its runtime is %s',(harness) => {const agent = roster.find((entry) => entry.harness === harness);diff --git a/apps/web/src/features/agents-view/core/roster.ts b/apps/web/src/features/agents-view/core/roster.tsindex 1da4feb786..aee19ae97f 100644--- a/apps/web/src/features/agents-view/core/roster.ts+++ b/apps/web/src/features/agents-view/core/roster.ts@@ -94,8 +94,6 @@ export function runtimeLabel(return MACRO_HARNESS_NAME;case 'cursor':return 'Cursor';- case 'claude-cloud':- return 'Claude Cloud';case 'macrod':return (runtimes.find((runtime) => runtime.id === harnessId)?.name ??diff --git a/apps/web/src/features/agents-view/queries/composer-models.test.ts b/apps/web/src/features/agents-view/queries/composer-models.test.tsindex af7bab5c43..c7a4dc8552 100644--- a/apps/web/src/features/agents-view/queries/composer-models.test.ts+++ b/apps/web/src/features/agents-view/queries/composer-models.test.ts@@ -30,8 +30,8 @@ describe('composer model discovery', () => {).toEqual({ harness: 'macrod', harnessId: 'paired-runtime' });expect(composerModelTarget({ harness: 'macrod' })).toBeUndefined();expect(composerModelTarget({ harness: 'sandbox' })).toBeUndefined();- expect(composerModelTarget({ harness: 'claude-cloud' })).toEqual({- harness: 'claude-cloud',+ expect(composerModelTarget({ harness: 'macro-inmem' })).toEqual({+ harness: 'in-memory',});});@@ -49,8 +49,8 @@ describe('composer model discovery', () => {createComposerModels(agent);expect(discovery.enabled?.()).toBe(true);expect(discovery.target?.()).toEqual({ harness: 'cursor' });- setAgent({ ...agent(), harness: 'claude-cloud' });- expect(discovery.target?.()).toEqual({ harness: 'claude-cloud' });+ setAgent({ ...agent(), harness: 'in-memory' });+ expect(discovery.target?.()).toEqual({ harness: 'in-memory' });setAgent({ ...agent(), harness: 'macrod', harnessId: 'paired-runtime' });expect(discovery.target?.()).toEqual({harness: 'macrod',diff --git a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx b/apps/web/src/features/agents-view/views/NewChatPage.test.tsxindex 8b187ff886..46788d8c10 100644--- a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx+++ b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx@@ -690,7 +690,7 @@ describe('agent-led new conversation', () => {modelOverride: 'google/gemini-3.8-flash',});});- it.each(['claude-cloud', 'codex-cloud', 'future-runtime'])(+ it.each(['codex-cloud', 'future-runtime'])('shows the drawer for a saved %s coding agent without forwarding unsupported repository overrides',async (harness) => {const send = page(diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsxindex 79ce850e7e..097fcb6950 100644--- a/apps/web/src/features/block-agent/agent-session-provider.tsx+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx@@ -220,9 +220,7 @@ function CloudExternalUrlPoll(props: {const id = props.sessionId();const session = props.session();if (!id || !session || session.external?.url) return undefined;- return isCursorBotId(session.botId) ||- isCodexBotId(session.botId) ||- session.harness === 'claude-cloud'+ return isCursorBotId(session.botId) || isCodexBotId(session.botId)? id: undefined;});diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxindex 48361c4ef9..302b52c4fb 100644--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -149,7 +149,6 @@ export function AgentSplitHeader(props: {{label: () => {const provider = props.session?.external?.provider;- if (provider === 'claude-cloud') return 'Open in Claude';if (!provider) return 'Open externally';return `Open in ${provider.charAt(0).toUpperCase()}${provider.slice(1)}`;},diff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.test.tsindex 9de680da0e..5464f5a237 100644--- a/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.test.ts@@ -1,4 +1,3 @@-import { CLAUDE_BOT_ID } from '@core/constant/claudeAgent';import { CODEX_BOT_ID } from '@core/constant/codexAgent';import { CURSOR_BOT_ID } from '@core/constant/cursorAgent';import { describe, expect, it } from 'vitest';@@ -69,7 +68,6 @@ describe('sessionHarnessTitle', () => {it.each([[CURSOR_BOT_ID, 'Cursor'],[CODEX_BOT_ID, 'Codex Cloud'],- [CLAUDE_BOT_ID, 'Claude Cloud'],] as const)('names a %s session from the bot even when the row says opencode',(botId, title) => {@@ -78,9 +76,7 @@ describe('sessionHarnessTitle', () => {);it('title-cases other sessions from their stored slug', () => {- expect(sessionHarnessTitle({ harness: 'claude-cloud' })).toBe(- 'Claude Cloud'- );+ expect(sessionHarnessTitle({ harness: 'claude-code' })).toBe('Claude Code');});it('uses the product name for Macro slugs', () => {@@ -98,7 +94,7 @@ describe('showsSessionHarness', () => {it('keeps the Details row for coding runtimes', () => {expect(showsSessionHarness({ harness: 'cursor' })).toBe(true);- expect(showsSessionHarness({ harness: 'claude-cloud' })).toBe(true);+ expect(showsSessionHarness({ harness: 'codex-cloud' })).toBe(true);expect(showsSessionHarness({ harness: 'sandbox' })).toBe(true);expect(showsSessionHarness({ harness: 'my-laptop' })).toBe(true);});diff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.tsindex b30f971ff3..5e38342702 100644--- a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.ts@@ -1,6 +1,5 @@import { isCoderHarness } from '@app/features/agents-view/core/agent-kind';import { modelLabel } from '@core/component/AI/constant/model-label';-import { isClaudeBotId } from '@core/constant/claudeAgent';import { isCodexBotId } from '@core/constant/codexAgent';import { isCursorBotId } from '@core/constant/cursorAgent';import { MACRO_HARNESS_NAME } from '@core/constant/macroAgent';@@ -45,7 +44,7 @@ export function harnessTitle(harness: string | undefined): string {/*** The harness slug a session should be labeled with. First-party cloud bots- * own a fixed slug (Cursor / Codex / Claude Cloud), even when an older row+ * own a fixed slug (Cursor / Codex), even when an older row* was stamped with the sandboxed-coder default (`opencode`).*/export function sessionHarnessSlug(session: {@@ -55,7 +54,6 @@ export function sessionHarnessSlug(session: {const botId = session.botId;if (botId && isCursorBotId(botId)) return 'cursor';if (botId && isCodexBotId(botId)) return 'codex-cloud';- if (botId && isClaudeBotId(botId)) return 'claude-cloud';return session.harness;}@@ -81,8 +79,6 @@ export function harnessDisplayName(harness: string): string {return 'Cursor';case 'codex-cloud':return 'Codex';- case 'claude-cloud':- return 'Claude Cloud';default:return harness;}diff --git a/apps/web/src/features/block-pr/data/pr-origin.test.ts b/apps/web/src/features/block-pr/data/pr-origin.test.tsindex 6118f37697..ec7926c99e 100644--- a/apps/web/src/features/block-pr/data/pr-origin.test.ts+++ b/apps/web/src/features/block-pr/data/pr-origin.test.ts@@ -93,7 +93,6 @@ describe('detectPrOrigin', () => {describe('toolForHarness', () => {it.each([['claude-code', 'claude'],- ['claude-cloud', 'claude'],['codex-cloud', 'codex'],['cursor', 'cursor'],['macrod', 'macro'],diff --git a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx b/apps/web/src/features/channel/Input/tests/input-slots.test.tsxindex 43c3fcb8b0..8563911dee 100644--- a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx+++ b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx@@ -17,7 +17,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const editorMocks = vi.hoisted(() => ({agentsEnabled: false,- claudeEnabled: false,codexEnabled: false,cursorEnabled: false,clear: vi.fn(),@@ -126,9 +125,6 @@ vi.mock('@core/codex/flag', () => ({vi.mock('@core/cursor/flag', () => ({useCursorAgentsAccess: () => () => editorMocks.cursorEnabled,}));-vi.mock('@core/claude/flag', () => ({- useClaudeAgentsAccess: () => () => editorMocks.claudeEnabled,-}));vi.mock('../../use-chat-v3-agents-flag', () => ({useChatV3AgentsFlag: () => () => editorMocks.agentsEnabled,}));@@ -374,11 +370,7 @@ vi.mock('@queries/messages/typing', () => ({import { MACRO_AGENT_PRINCIPAL_ID } from '@core/constant/macroAgent';import { MACRO_NEW_PRINCIPAL_ID } from '@core/constant/macroNew';-import {- claudeMentionUser,- codexMentionUser,- cursorMentionUser,-} from '../../macroAi';+import { codexMentionUser, cursorMentionUser } from '../../macroAi';import { ThreadReplyChannelInput } from '../../Thread/ThreadReplyChannelInput';import { createInputAttachmentTracker } from '../attachment-tracker';import { ChannelInput } from '../ChannelInput';@@ -410,7 +402,6 @@ function render(ui: () => JSX.Element) {describe('Input slots', () => {beforeEach(() => {editorMocks.agentsEnabled = false;- editorMocks.claudeEnabled = false;editorMocks.codexEnabled = false;editorMocks.cursorEnabled = false;editorMocks.clear.mockClear();@@ -497,13 +488,12 @@ describe('Input slots', () => {expect(screen.queryByRole('group', { name: 'Dictation' })).toBeNull();});- it('offers Cursor, Claude, and Codex within their rollouts before account setup', () => {+ it('offers Cursor and Codex within their rollouts before account setup', () => {editorMocks.cursorEnabled = true;- editorMocks.claudeEnabled = true;editorMocks.codexEnabled = true;render(() => <ChannelInput input={baseInput} />);expect(editorMocks.mentionUsers?.().map((user) => user.name)).toEqual(- expect.arrayContaining(['Cursor', 'Claude', 'Codex'])+ expect.arrayContaining(['Cursor', 'Codex']));});@@ -556,18 +546,13 @@ describe('Input slots', () => {]);});- it('hides Cursor, Claude, and Codex outside their rollouts, including supplied bot entries', () => {- const builtIns = () => [- cursorMentionUser(),- claudeMentionUser(),- codexMentionUser(),- ];+ it('hides Cursor and Codex outside their rollouts, including supplied bot entries', () => {+ const builtIns = () => [cursorMentionUser(), codexMentionUser()];render(() => (<ChannelInput input={baseInput} participants={builtIns} bots={builtIns} />));const names = editorMocks.mentionUsers?.().map((user) => user.name);expect(names).not.toContain('Cursor');- expect(names).not.toContain('Claude');expect(names).not.toContain('Codex');});diff --git a/apps/web/src/features/channel/macroAi.ts b/apps/web/src/features/channel/macroAi.tsindex 7b325c1202..3fece3b3bc 100644--- a/apps/web/src/features/channel/macroAi.ts+++ b/apps/web/src/features/channel/macroAi.ts@@ -1,7 +1,3 @@-import {- CLAUDE_BOT_NAME,- CLAUDE_BOT_PRINCIPAL_ID,-} from '@core/constant/claudeAgent';import {CODEX_BOT_NAME,CODEX_BOT_PRINCIPAL_ID,@@ -69,12 +65,3 @@ export function codexMentionUser(): IUser {email: CODEX_BOT_NAME,};}--/** Claude as a bot mention, using the canonical principal identifier. */-export function claudeMentionUser(): IUser {- return {- id: CLAUDE_BOT_PRINCIPAL_ID,- name: CLAUDE_BOT_NAME,- email: CLAUDE_BOT_NAME,- };-}diff --git a/apps/web/src/features/channel/use-agent-mention-users.test.ts b/apps/web/src/features/channel/use-agent-mention-users.test.tsindex 7e537aabb5..860d705255 100644--- a/apps/web/src/features/channel/use-agent-mention-users.test.ts+++ b/apps/web/src/features/channel/use-agent-mention-users.test.ts@@ -1,4 +1,3 @@-import { CLAUDE_BOT_PRINCIPAL_ID } from '@core/constant/claudeAgent';import { CODEX_BOT_PRINCIPAL_ID } from '@core/constant/codexAgent';import {MACRO_AGENT_NAME,@@ -13,17 +12,15 @@ import { MACRO_NEW_PRINCIPAL_ID } from '@core/constant/macroNew';import type { IUser } from '@core/user/types';import { createRoot, createSignal } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { claudeMentionUser, codexMentionUser } from './macroAi';+import { codexMentionUser } from './macroAi';import { useAgentMentionUsers } from './use-agent-mention-users';const flags = vi.hoisted(() => ({agents: (): boolean => false,- claude: (): boolean => false,codex: (): boolean => false,cursor: (): boolean => false,}));vi.mock('@core/constant/featureFlags', () => ({- claudeCloud: { key: 'claude-cloud' },enableChatV3Agents: { key: 'enable-chat-v3-agents' },enableCodexAgents: { key: 'enable-codex-agents' },enableCursorAgents: { key: 'enable-cursor-agents' },@@ -33,11 +30,9 @@ vi.mock('@app/lib/analytics/posthog', () => ({enabled:flag.key === 'enable-chat-v3-agents'? flags.agents()- : flag.key === 'claude-cloud'- ? flags.claude()- : flag.key === 'enable-codex-agents'- ? flags.codex()- : flags.cursor(),+ : flag.key === 'enable-codex-agents'+ ? flags.codex()+ : flags.cursor(),}),}));@@ -48,7 +43,6 @@ function macroEntries(users: IUser[]): IUser[] {describe('useAgentMentionUsers', () => {beforeEach(() => {flags.agents = () => false;- flags.claude = () => false;flags.codex = () => false;flags.cursor = () => false;});@@ -72,22 +66,6 @@ describe('useAgentMentionUsers', () => {});});- it('offers Claude only within its rollout, even when it is a participant', () => {- createRoot((dispose) => {- const [enabled, setEnabled] = createSignal(false);- flags.claude = enabled;- const users = useAgentMentionUsers(() => [claudeMentionUser()]);- const claudeIds = () =>- users()- .map((user) => user.id)- .filter((id) => id === CLAUDE_BOT_PRINCIPAL_ID);- expect(claudeIds()).toEqual([]);- setEnabled(true);- expect(claudeIds()).toEqual([CLAUDE_BOT_PRINCIPAL_ID]);- dispose();- });- });-it('offers the classic Macro bot as the only Macro entry without the rollout', () => {createRoot((dispose) => {const users = useAgentMentionUsers(() => []);diff --git a/apps/web/src/features/channel/use-agent-mention-users.ts b/apps/web/src/features/channel/use-agent-mention-users.tsindex 58e05dcb7b..d79f83876c 100644--- a/apps/web/src/features/channel/use-agent-mention-users.ts+++ b/apps/web/src/features/channel/use-agent-mention-users.ts@@ -1,6 +1,4 @@-import { useClaudeAgentsAccess } from '@core/claude/flag';import { useCodexAgentsAccess } from '@core/codex/flag';-import { isClaudeBotId } from '@core/constant/claudeAgent';import { isCodexBotId } from '@core/constant/codexAgent';import { isCursorBotId } from '@core/constant/cursorAgent';import { useCursorAgentsAccess } from '@core/cursor/flag';@@ -8,7 +6,6 @@ import type { IUser } from '@core/user/types';import { uniqueByKey } from '@core/util/compareUtils';import type { Accessor } from 'solid-js';import {- claudeMentionUser,codexMentionUser,cursorMentionUser,isMacroAiId,@@ -22,7 +19,7 @@ import { useChatV3AgentsFlag } from './use-chat-v3-agents-flag';* Built-in agent entries shared by every message composer. Account setup does* not hide a mention: the harness answers with a connection prompt in the* thread when setup is needed, so replies link to Settings → Harness rather- * than the entry disappearing. The built-in Cursor, Codex, and Claude entries+ * than the entry disappearing. The built-in Cursor and Codex entries* follow their rollout flags. Mentions are re-tagged as bot mentions at send* time.*@@ -37,7 +34,6 @@ export function useAgentMentionUsers(): Accessor<IUser[]> {const canUseCursor = useCursorAgentsAccess();const canUseCodex = useCodexAgentsAccess();- const canUseClaude = useClaudeAgentsAccess();const canUseAgents = useChatV3AgentsFlag();return () => {@@ -48,7 +44,6 @@ export function useAgentMentionUsers((user) =>(canUseCursor() || !isCursorBotId(user.id)) &&(canUseCodex() || !isCodexBotId(user.id)) &&- (canUseClaude() || !isClaudeBotId(user.id)) &&!isMacroAiId(user.id) &&!isMacroNewId(user.id));@@ -58,9 +53,6 @@ export function useAgentMentionUsers(if (canUseCodex() && !base.some((user) => isCodexBotId(user.id))) {base.unshift(codexMentionUser());}- if (canUseClaude() && !base.some((user) => isClaudeBotId(user.id))) {- base.unshift(claudeMentionUser());- }base.unshift(macroMentionUser(canUseAgents()));return uniqueByKey(base, (user) => user.id);};diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.test.tsindex e25076176f..cfd009e9f5 100644--- a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts@@ -96,19 +96,13 @@ describe('availableBotMentionUsers', () => {'cursor');const codex = agent('codex', 'Codex', 'all', 'codex-cloud');- const claude = agent('claude', 'Claude', 'all', 'claude-cloud');expect(availableBotMentionUsers([bot(CURSOR_BOT_ID, 'Cursor'), installed.bot],- [global, installed, codex, claude],+ [global, installed, codex],false).map((user) => user.id)- ).toEqual([- 'bot|installed-cursor',- 'bot|global-cursor',- 'bot|codex',- 'bot|claude',- ]);+ ).toEqual(['bot|installed-cursor', 'bot|global-cursor', 'bot|codex']);});it('hides the built-in Cursor bot before agent metadata is available', () => {expect(@@ -130,7 +124,7 @@ describe('availableBotMentionUsers', () => {dispose();});});- it.each(['cursor', 'codex-cloud', 'claude-cloud'])(+ it.each(['cursor', 'codex-cloud'])('offers global and installed %s agents before connection',(harness) => {const global = agent('global', 'Global', 'all', harness);diff --git a/apps/web/src/features/claude-connection/claude-connection.tsx b/apps/web/src/features/claude-connection/claude-connection.tsxdeleted file mode 100644index 7a4bbd18fd..0000000000--- a/apps/web/src/features/claude-connection/claude-connection.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { useUserId } from '@core/context/user';-import { fireAndForget } from '@core/util/fireAndForget';-import { useClaudeConnectionSource } from '@queries/claude-auth/connection';-import { Suspense } from 'solid-js';-import { ConnectionCard } from './components/connection-card';-import { openClaudeSignIn } from './open-sign-in';-import { createClaudeConnection } from './primitives/connection';--function ConnectedCard() {- const connection = createClaudeConnection(- useClaudeConnectionSource(useUserId()),- openClaudeSignIn- );- return (- <ConnectionCard- status={connection.status()}- failed={connection.failed()}- login={connection.login()}- code={connection.code()}- busy={connection.busy()}- error={connection.error()}- onCode={connection.setCode}- onBegin={() => fireAndForget(connection.begin(), 'claude-connection')}- onComplete={() =>- fireAndForget(connection.complete(), 'claude-connection')- }- onDisconnect={() =>- fireAndForget(connection.disconnect(), 'claude-connection')- }- onRefresh={() => fireAndForget(connection.refresh(), 'claude-connection')}- />- );-}--/** Production composition, isolated from the parent Settings suspense boundary. */-export function ClaudeConnection() {- return (- <Suspense- fallback={- <p class="text-sm text-ink-muted">Loading Claude connection…</p>- }- >- <ConnectedCard />- </Suspense>- );-}diff --git a/apps/web/src/features/claude-connection/components/connection-card.test.tsx b/apps/web/src/features/claude-connection/components/connection-card.test.tsxdeleted file mode 100644index 1968c1ee83..0000000000--- a/apps/web/src/features/claude-connection/components/connection-card.test.tsx+++ /dev/null@@ -1,74 +0,0 @@-// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { afterEach, expect, it, vi } from 'vitest';-import { ConnectionCard, type ConnectionCardProps } from './connection-card';--vi.mock('@ui', () => ({- confirmDialog: vi.fn(),- Button: (- props: import('solid-js').JSX.ButtonHTMLAttributes<HTMLButtonElement>- ) => <button {...props} />,-}));-afterEach(cleanup);-function props(): ConnectionCardProps {- return {- status: { enabled: true, connected: false, ephemeral: true },- failed: false,- code: '',- busy: false,- error: '',- onCode: vi.fn(),- onBegin: vi.fn(),- onComplete: vi.fn(),- onDisconnect: vi.fn(),- onRefresh: vi.fn(),- };-}-it('shows Claude before connection without adding setup details', () => {- const value = props();- render(() => <ConnectionCard {...value} />);- expect(screen.getByText('Claude Cloud')).toBeTruthy();- expect(screen.queryByText(/Macro never asks/)).toBeNull();- fireEvent.click(screen.getByRole('button', { name: 'Connect Claude' }));- expect(value.onBegin).toHaveBeenCalledOnce();-});-it('renders consent link and masked code entry without tokens', () => {- const value = {- ...props(),- login: {- attemptId: 'attempt',- authorizationUrl: 'https://claude.com/consent',- expiresIn: 600,- },- code: 'code#state',- };- render(() => <ConnectionCard {...value} />);- expect(screen.getByText(/This connection is temporary/)).toBeTruthy();- expect(screen.getByRole('link').getAttribute('rel')).toBe(- 'noopener noreferrer'- );- expect(screen.getByLabelText(/Paste the complete/).getAttribute('type')).toBe(- 'password'- );- fireEvent.click(screen.getByRole('button', { name: 'Finish connecting' }));- expect(value.onComplete).toHaveBeenCalledOnce();- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- expect(value.onDisconnect).toHaveBeenCalledOnce();-});-it('shows disabled and failed states instead of silently disappearing', () => {- render(() => (- <ConnectionCard- {...props()}- status={{ enabled: false, connected: false, ephemeral: false }}- />- ));- expect(- screen.getByText(/sign-in is not configured on this deployment/)- ).toBeTruthy();- expect(screen.queryByRole('button', { name: 'Connect Claude' })).toBeNull();- cleanup();- render(() => <ConnectionCard {...props()} status={undefined} failed />);- expect(- screen.getByRole('button', { name: 'Retry connection status' })- ).toBeTruthy();-});diff --git a/apps/web/src/features/claude-connection/components/connection-card.tsx b/apps/web/src/features/claude-connection/components/connection-card.tsxdeleted file mode 100644index 10064c8862..0000000000--- a/apps/web/src/features/claude-connection/components/connection-card.tsx+++ /dev/null@@ -1,178 +0,0 @@-import AnthropicIcon from '@core/component/AI/assets/anthropic.svg';-import { fireAndForget } from '@core/util/fireAndForget';-import { Button, confirmDialog } from '@ui';-import { createUniqueId, Show } from 'solid-js';-import type { ClaudeConnectionStatus, ClaudeLogin } from '../core/connection';--export type ConnectionCardProps = {- status?: ClaudeConnectionStatus;- failed: boolean;- login?: ClaudeLogin;- code: string;- busy: boolean;- error: string;- onCode: (code: string) => void;- onBegin: () => void;- onComplete: () => void;- onDisconnect: () => void;- onRefresh: () => void;-};--export function ConnectionCard(props: ConnectionCardProps) {- const inputId = createUniqueId();- const disconnect = async () => {- if (props.busy) return;- const confirmed = await confirmDialog({- title: 'Disconnect Claude?',- body: 'Remove your Claude connection from Macro? Existing cloud sessions keep running. You can reconnect at any time.',- confirmLabel: 'Disconnect',- tone: 'danger',- });- if (confirmed && !props.busy) props.onDisconnect();- };- return (- <section aria-label="Claude Cloud connection" class="flex gap-4 px-6 py-5">- <div class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-ink/4 text-ink-muted">- <AnthropicIcon class="size-5" aria-label="Anthropic" />- </div>- <div class="min-w-0 flex-1">- <div class="flex min-h-5 items-start justify-between gap-3">- <h2 class="min-w-0 text-sm/5 font-medium text-ink">Claude Cloud</h2>- <span- class="inline-flex h-5 shrink-0 items-center whitespace-nowrap rounded-md px-2 text-[11px]/none font-medium"- classList={{- 'bg-success-bg text-success': !!props.status?.connected,- 'bg-ink/5 text-ink-muted': !props.status?.connected,- }}- >- {props.failed- ? 'Unavailable'- : !props.status- ? 'Loading…'- : props.status.connected- ? 'Connected'- : 'Not connected'}- </span>- </div>- <p class="mt-1 text-sm text-ink-muted">- Run Claude Code in the cloud using your own Claude subscription. No- macrod required.- </p>- <div class="mt-3">- <Show- when={!props.status || props.status.enabled}- fallback={- <p class="text-xs text-ink-muted">- Claude sign-in is not configured on this deployment.- </p>- }- >- <Show- when={props.login}- keyed- fallback={- <div>- <Button- size="sm"- disabled={props.busy || (!props.status && !props.failed)}- onClick={- props.failed- ? props.onRefresh- : props.status?.connected- ? () =>- fireAndForget(disconnect(), 'claude-connection')- : props.onBegin- }- >- {props.failed- ? 'Retry connection status'- : props.busy- ? 'Working…'- : props.status?.connected- ? 'Disconnect Claude'- : 'Connect Claude'}- </Button>- </div>- }- >- {(login) => (- <form- class="flex max-w-lg flex-col gap-3"- onSubmit={(event) => {- event.preventDefault();- props.onComplete();- }}- >- <p class="text-xs text-ink-muted">- {props.status?.ephemeral- ? 'This connection is temporary. You may need to reconnect later.'- : 'Your connection is saved securely.'}{' '}- Macro never asks for your Claude password.- </p>- <a- class="text-sm text-accent underline"- href={login.authorizationUrl}- target="_blank"- rel="noopener noreferrer"- referrerPolicy="no-referrer"- >- Didn't open? Open Claude sign-in ↗- </a>- <label for={inputId} class="text-sm text-ink">- Paste the complete one-time code from Claude- </label>- <input- id={inputId}- type="password"- class="settings-input w-full"- value={props.code}- onInput={(event) => props.onCode(event.currentTarget.value)}- placeholder="code#state"- autocomplete="off"- spellcheck={false}- disabled={props.busy}- />- <p class="text-xs text-ink-muted">- Approve access on Claude, then copy the entire code shown- there. This attempt expires in{' '}- {Math.round(login.expiresIn / 60)} minutes.- </p>- <div class="flex gap-2">- <Button- type="submit"- size="sm"- disabled={props.busy || !props.code.trim()}- >- {props.busy ? 'Connecting…' : 'Finish connecting'}- </Button>- <Button- variant="ghost"- type="button"- size="sm"- disabled={props.busy}- onClick={props.onDisconnect}- >- Cancel- </Button>- </div>- </form>- )}- </Show>- </Show>- </div>- <Show when={props.error}>- <p role="alert" class="mt-3 text-sm text-failure">- {props.error}- </p>- </Show>- <Show when={props.failed}>- <div>- <p role="alert" class="mt-3 text-xs text-ink-muted">- Could not load Claude connection. Try again.- </p>- </div>- </Show>- </div>- </section>- );-}diff --git a/apps/web/src/features/claude-connection/core/connection.ts b/apps/web/src/features/claude-connection/core/connection.tsdeleted file mode 100644index 7d998229ca..0000000000--- a/apps/web/src/features/claude-connection/core/connection.ts+++ /dev/null@@ -1,28 +0,0 @@-/** Safe connection metadata. Provider tokens are never sent to the browser. */-export type ClaudeConnectionStatus = {- enabled: boolean;- connected: boolean;- ephemeral: boolean;-};--export type ClaudeLogin = {- attemptId: string;- authorizationUrl: string;- expiresIn: number;-};--/** Host-owned sign-in navigation, reserved synchronously during the click. */-export type ClaudeSignIn = {- navigate: (url: string) => void;- close: () => void;-};--/** Narrow source contract; the controller does not know the query or transport library. */-export type ClaudeConnectionSource = {- status: () => ClaudeConnectionStatus | undefined;- failed: () => boolean;- begin: () => Promise<ClaudeLogin>;- complete: (attemptId: string, code: string) => Promise<void>;- disconnect: () => Promise<void>;- refresh: () => Promise<void>;-};diff --git a/apps/web/src/features/claude-connection/open-sign-in.test.ts b/apps/web/src/features/claude-connection/open-sign-in.test.tsdeleted file mode 100644index 0f4100e643..0000000000--- a/apps/web/src/features/claude-connection/open-sign-in.test.ts+++ /dev/null@@ -1,51 +0,0 @@-// @vitest-environment jsdom--import { isTauri } from '@core/util/platform';-import { openExternalUrl } from '@core/util/url';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { openClaudeSignIn } from './open-sign-in';--vi.mock('@core/util/platform', () => ({ isTauri: vi.fn(() => false) }));-vi.mock('@core/util/url', () => ({ openExternalUrl: vi.fn() }));-afterEach(() => vi.restoreAllMocks());--describe('Claude sign-in navigation', () => {- it('reserves an isolated tab with no referrer and navigates it once ready', () => {- const popup = {- opener: window,- document: document.implementation.createHTMLDocument(),- closed: false,- location: { replace: vi.fn() },- close: vi.fn(),- };- const open = vi- .spyOn(window, 'open')- .mockReturnValue(popup as unknown as Window);- const signIn = openClaudeSignIn();- expect(open).toHaveBeenCalledWith('about:blank', '_blank');- expect(popup.opener).toBeNull();- expect(- popup.document- .querySelector('meta[name="referrer"]')- ?.getAttribute('content')- ).toBe('no-referrer');- signIn?.navigate('https://claude.com/consent');- expect(popup.location.replace).toHaveBeenCalledWith(- 'https://claude.com/consent'- );- signIn?.close();- expect(popup.close).toHaveBeenCalledOnce();- });- it('returns no reserved tab when blocked', () => {- vi.spyOn(window, 'open').mockReturnValue(null);- expect(openClaudeSignIn()).toBeUndefined();- });- it('uses the native external browser without opening a blank tab', () => {- vi.mocked(isTauri).mockReturnValueOnce(true);- const open = vi.spyOn(window, 'open');- const signIn = openClaudeSignIn();- expect(open).not.toHaveBeenCalled();- signIn?.navigate('https://claude.com/consent');- expect(openExternalUrl).toHaveBeenCalledWith('https://claude.com/consent');- });-});diff --git a/apps/web/src/features/claude-connection/open-sign-in.ts b/apps/web/src/features/claude-connection/open-sign-in.tsdeleted file mode 100644index 39b0b32a37..0000000000--- a/apps/web/src/features/claude-connection/open-sign-in.ts+++ /dev/null@@ -1,32 +0,0 @@-import { isTauri } from '@core/util/platform';-import { openExternalUrl } from '@core/util/url';-import type { ClaudeSignIn } from './core/connection';--/** Reserve a browser tab before awaiting auth; native shells use the system browser. */-export function openClaudeSignIn(): ClaudeSignIn | undefined {- if (isTauri()) return { navigate: openExternalUrl, close: () => {} };-- let popup: Window | null = null;- try {- popup = window.open('about:blank', '_blank');- if (!popup) return;- popup.opener = null;- const referrer = popup.document.createElement('meta');- referrer.name = 'referrer';- referrer.content = 'no-referrer';- popup.document.head.append(referrer);- popup.document.title = 'Connecting to Claude…';- popup.document.body.textContent = 'Preparing Claude sign-in…';- const tab = popup;- return {- navigate: (url) => {- if (!tab.closed) tab.location.replace(url);- },- close: () => tab.close(),- };- } catch {- popup?.close();- // The settings form retains a normal link when opening a tab is blocked.- return;- }-}diff --git a/apps/web/src/features/claude-connection/primitives/connection.test.ts b/apps/web/src/features/claude-connection/primitives/connection.test.tsdeleted file mode 100644index c0c935b643..0000000000--- a/apps/web/src/features/claude-connection/primitives/connection.test.ts+++ /dev/null@@ -1,147 +0,0 @@-// @vitest-environment jsdom-import { createRoot, createSignal } from 'solid-js';-import { describe, expect, it, vi } from 'vitest';-import type {- ClaudeConnectionSource,- ClaudeConnectionStatus,-} from '../core/connection';-import { createClaudeConnection } from './connection';--function setup() {- return createRoot((dispose) => {- const [status, setStatus] = createSignal<ClaudeConnectionStatus>({- enabled: true,- connected: false,- ephemeral: true,- });- const source: ClaudeConnectionSource = {- status,- failed: () => false,- begin: vi.fn(async () => ({- attemptId: 'attempt',- authorizationUrl: 'https://claude.com/consent',- expiresIn: 600,- })),- complete: vi.fn(async () => {- setStatus({ ...status(), connected: true });- }),- disconnect: vi.fn(async () => {- setStatus({ ...status(), connected: false });- }),- refresh: vi.fn(async () => {}),- };- const signIn = { navigate: vi.fn(), close: vi.fn() };- const openSignIn = vi.fn(() => signIn as typeof signIn | undefined);- return {- state: createClaudeConnection(source, openSignIn),- source,- dispose,- signIn,- openSignIn,- };- });-}-describe('Claude connection controller', () => {- it('reserves a tab synchronously and navigates after authorization starts', async () => {- const { state, source, dispose, signIn, openSignIn } = setup();- const pending = state.begin();- expect(openSignIn).toHaveBeenCalledOnce();- expect(openSignIn.mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(source.begin).mock.invocationCallOrder[0]- );- expect(signIn.navigate).not.toHaveBeenCalled();- await state.begin();- await pending;- expect(openSignIn).toHaveBeenCalledOnce();- expect(signIn.navigate).toHaveBeenCalledWith('https://claude.com/consent');- dispose();- expect(signIn.close).not.toHaveBeenCalled();- });- it('keeps the sign-in link available when a popup is blocked', async () => {- const { state, dispose, openSignIn } = setup();- openSignIn.mockReturnValue(undefined);- await state.begin();- expect(state.login()?.authorizationUrl).toBe('https://claude.com/consent');- expect(state.error()).toBe('');- dispose();- });- it('closes the reserved tab when authorization setup fails', async () => {- const { state, source, dispose, signIn } = setup();- vi.mocked(source.begin).mockRejectedValueOnce(- new Error('Could not start sign-in')- );- await state.begin();- expect(signIn.close).toHaveBeenCalledOnce();- expect(signIn.navigate).not.toHaveBeenCalled();- expect(state.error()).toBe('Could not start sign-in');- expect(state.busy()).toBe(false);- dispose();- });- it('closes a pending tab on unmount and ignores a late authorization URL', async () => {- const { state, source, dispose, signIn } = setup();- let resolve!: (- login: Awaited<ReturnType<ClaudeConnectionSource['begin']>>- ) => void;- vi.mocked(source.begin).mockReturnValueOnce(- new Promise((done) => {- resolve = done;- })- );- const pending = state.begin();- dispose();- expect(signIn.close).toHaveBeenCalledOnce();- resolve({- attemptId: 'late',- authorizationUrl: 'https://claude.com/consent',- expiresIn: 600,- });- await pending;- expect(signIn.navigate).not.toHaveBeenCalled();- });- it('connects and immediately clears the one-time code, then disconnects', async () => {- const { state, source, dispose } = setup();- await state.begin();- expect(state.login()?.attemptId).toBe('attempt');- state.setCode('one-time#state');- const done = state.complete();- expect(state.code()).toBe('');- expect(state.busy()).toBe(true);- await done;- expect(source.complete).toHaveBeenCalledWith('attempt', 'one-time#state');- expect(state.status()?.connected).toBe(true);- expect(state.login()).toBeUndefined();- await state.disconnect();- expect(state.status()?.connected).toBe(false);- dispose();- });- it('shows an exchange error and requires a fresh attempt instead of replaying', async () => {- const { state, source, dispose } = setup();- vi.mocked(source.complete).mockRejectedValueOnce(new Error('Expired code'));- await state.begin();- state.setCode('expired#state');- await state.complete();- expect(state.error()).toBe('Expired code');- expect(state.code()).toBe('');- expect(state.login()).toBeUndefined();- expect(state.busy()).toBe(false);- await state.complete();- expect(source.complete).toHaveBeenCalledTimes(1);- dispose();- });- it('expires an unfinished attempt and cancels explicitly', async () => {- vi.useFakeTimers();- const { state, source, dispose } = setup();- await state.begin();- state.setCode('private#state');- vi.advanceTimersByTime(600_000);- expect(state.login()).toBeUndefined();- expect(state.code()).toBe('');- expect(state.error()).toContain('expired');- await state.begin();- await state.disconnect();- expect(source.disconnect).toHaveBeenCalledTimes(1);- expect(state.login()).toBeUndefined();- dispose();- vi.useRealTimers();- });-});diff --git a/apps/web/src/features/claude-connection/primitives/connection.ts b/apps/web/src/features/claude-connection/primitives/connection.tsdeleted file mode 100644index 50238603cf..0000000000--- a/apps/web/src/features/claude-connection/primitives/connection.ts+++ /dev/null@@ -1,117 +0,0 @@-import { createSignal, onCleanup } from 'solid-js';-import type {- ClaudeConnectionSource,- ClaudeLogin,- ClaudeSignIn,-} from '../core/connection';--/** Owns consent UI state; the source owns transport and cache invalidation. */-export function createClaudeConnection(- source: ClaudeConnectionSource,- openSignIn: () => ClaudeSignIn | undefined-) {- const [login, setLogin] = createSignal<ClaudeLogin>();- const [code, setCode] = createSignal('');- const [busy, setBusy] = createSignal(false);- const [error, setError] = createSignal('');- let disposed = false;- let pendingSignIn: ClaudeSignIn | undefined;- let expiry: ReturnType<typeof setTimeout> | undefined;- const clear = () => {- clearTimeout(expiry);- setLogin(undefined);- setCode('');- };- onCleanup(() => {- disposed = true;- pendingSignIn?.close();- pendingSignIn = undefined;- clearTimeout(expiry);- setCode('');- });- const report = (error: unknown) =>- setError(- error instanceof Error- ? error.message- : 'Claude connection failed. Please try again.'- );-- async function begin() {- if (busy()) return;- clear();- setBusy(true);- setError('');- try {- // Reserve the tab before the first await to retain the user's click activation.- pendingSignIn = openSignIn();- const next = await source.begin();- if (disposed) return;- setLogin(next);- expiry = setTimeout(() => {- clear();- setError('Sign-in expired. Start Connect Claude again.');- }, next.expiresIn * 1000);- pendingSignIn?.navigate(next.authorizationUrl);- pendingSignIn = undefined;- } catch (error) {- pendingSignIn?.close();- pendingSignIn = undefined;- if (!disposed) report(error);- } finally {- if (!disposed) setBusy(false);- }- }- async function complete() {- const current = login();- const pasted = code().trim();- if (busy() || !current || !pasted) return;- setCode('');- setBusy(true);- setError('');- try {- await source.complete(current.attemptId, pasted);- if (!disposed) clear();- } catch (error) {- if (!disposed) {- clear();- report(error);- }- } finally {- if (!disposed) setBusy(false);- }- }- async function disconnect() {- if (busy()) return;- clear();- setBusy(true);- setError('');- try {- await source.disconnect();- } catch (error) {- if (!disposed) report(error);- } finally {- if (!disposed) setBusy(false);- }- }- async function refresh() {- setError('');- try {- await source.refresh();- } catch (error) {- if (!disposed) report(error);- }- }- return {- status: source.status,- failed: source.failed,- login,- code,- setCode,- busy,- error,- begin,- complete,- disconnect,- refresh,- };-}diff --git a/apps/web/src/features/property/queries/agent-assignees.test.ts b/apps/web/src/features/property/queries/agent-assignees.test.tsindex 89a285e1af..a6f65bd121 100644--- a/apps/web/src/features/property/queries/agent-assignees.test.ts+++ b/apps/web/src/features/property/queries/agent-assignees.test.ts@@ -1,4 +1,3 @@-import { CLAUDE_BOT_PRINCIPAL_ID } from '@core/constant/claudeAgent';import { CODEX_BOT_PRINCIPAL_ID } from '@core/constant/codexAgent';import { CURSOR_BOT_PRINCIPAL_ID } from '@core/constant/cursorAgent';import { MACRO_AGENT_PRINCIPAL_ID } from '@core/constant/macroAgent';@@ -14,13 +13,11 @@ const fixture = vi.hoisted(() => ({bots: [] as Bot[],pending: false,agentRollout: false,- claudeRollout: false,codexRollout: false,cursorRollout: false,}));vi.mock('@core/constant/featureFlags', () => ({- claudeCloud: { key: 'claude-cloud' },enableChatV3Agents: { key: 'enable-chat-v3-agents' },enableCodexAgents: { key: 'enable-codex-agents' },enableCursorAgents: { key: 'enable-cursor-agents' },@@ -30,11 +27,9 @@ vi.mock('@app/lib/analytics/posthog', () => ({enabled:flag.key === 'enable-chat-v3-agents'? fixture.agentRollout- : flag.key === 'claude-cloud'- ? fixture.claudeRollout- : flag.key === 'enable-codex-agents'- ? fixture.codexRollout- : fixture.cursorRollout,+ : flag.key === 'enable-codex-agents'+ ? fixture.codexRollout+ : fixture.cursorRollout,}),}));@@ -88,7 +83,6 @@ beforeEach(() => {fixture.bots = [];fixture.pending = false;fixture.agentRollout = false;- fixture.claudeRollout = false;fixture.codexRollout = false;fixture.cursorRollout = false;});@@ -119,10 +113,10 @@ describe('task agent assignees', () => {it('does not suspend people selection while agents are pending, or expose agents to other properties', () => {fixture.pending = true;- fixture.claudeRollout = true;+ fixture.cursorRollout = true;createRoot((dispose) => {expect(useAgentAssignees(() => true)().map(({ id }) => id)).toEqual([- CLAUDE_BOT_PRINCIPAL_ID,+ CURSOR_BOT_PRINCIPAL_ID,]);expect(useAgentAssignees(() => false)()).toEqual([]);dispose();@@ -131,14 +125,12 @@ describe('task agent assignees', () => {it('reuses system session-agent rollout and excludes classic Macro', () => {fixture.agentRollout = true;- fixture.claudeRollout = true;fixture.codexRollout = true;fixture.cursorRollout = true;createRoot((dispose) => {const ids = useAgentAssignees(() => true)().map(({ id }) => id);expect(ids).toEqual([MACRO_NEW_PRINCIPAL_ID,- CLAUDE_BOT_PRINCIPAL_ID,CODEX_BOT_PRINCIPAL_ID,CURSOR_BOT_PRINCIPAL_ID,]);diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxindex 0ee5b2e41f..c96d433fd3 100644--- a/apps/web/src/features/settings/Agents.test.tsx+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -52,25 +52,6 @@ vi.mock('./components/coding-preferences-setting', () => ({CodingPreferencesSetting: () => null,}));-const claudeFlag = vi.hoisted(() => ({ enabled: true }));-vi.mock('@app/lib/analytics/posthog', () => ({- useFeatureFlag: (flag: { key: string }) => {- expect(flag.key).toBe('claude-cloud');- return () => ({ enabled: claudeFlag.enabled });- },-}));--vi.mock('@queries/claude-auth/connection', () => ({- useClaudeConnectionSource: () => ({- status: () => ({ enabled: true, connected: false, ephemeral: true }),- failed: () => false,- begin: vi.fn(),- complete: vi.fn(),- disconnect: vi.fn(),- refresh: vi.fn(),- }),-}));-const [searchParams, updateSearchParams] = createStore<{createAgent?: string;}>({});@@ -349,31 +330,6 @@ const MACROD_HARNESS = {} satisfies Harness;describe('Agents', () => {- it.each([false, true])(- 'gates Claude harness selection and discovery when enabled=%s',- (enabled) => {- claudeFlag.enabled = enabled;- modelMocks.queries['claude-cloud:'] = successfulModels([- { id: 'claude-default', name: 'Subscription default' },- ]);- try {- render(() => <Agents {...agentsPageProps} />);- fireEvent.click(screen.getByRole('button', { name: 'Add agent' }));- const dialog = screen.getByRole('region', { name: 'New agent' });- const option = within(dialog).queryByRole('radio', {- name: 'In Claude Code',- });- expect(Boolean(option)).toBe(enabled);- const targets = vi.mocked(useAgentModelsQueries).mock.lastCall?.[0]();- expect(- targets?.some((target) => target.harness === 'claude-cloud')- ).toBe(enabled);- } finally {- claudeFlag.enabled = true;- }- }- );-it('opens the new-agent form from a link and clears the action on cancel', () => {updateSearchParams({ createAgent: 'true' });render(() => <Agents {...agentsPageProps} />);@@ -466,94 +422,6 @@ describe('Agents', () => {});- it('keeps a saved Claude harness selected while discovery loads and scopes Fable to it', async () => {- agentMocks.query.data = [- {- bot: {- id: 'agent-1',- kind: 'owned',- owner: { type: 'user', user_id: 'macro|[email protected]' },- name: 'Bug fixer',- handle: 'bug-fixer',- has_agent: true,- created_at: '2026-08-27T12:00:00Z',- updated_at: '2026-08-27T12:00:00Z',- },- instructions: 'Fix the root cause.',- harness: 'claude-cloud',- default_model: 'claude-fable-5-1',- channel_scope: 'all',- channel_ids: [],- },- ];- let resolveModels!: (models: LoadAgentModelsResponse) => void;- const response = new Promise<LoadAgentModelsResponse>((resolve) => {- resolveModels = resolve;- });- const client = new QueryClient({- defaultOptions: { queries: { retry: false } },- });- vi.mocked(useAgentModelsQueries).mockImplementationOnce((targets) =>- targets().map((target) =>- useQuery(() => ({- queryKey: ['pending-models', target.harness],- queryFn: () =>- target.harness === 'claude-cloud'- ? response- : Promise.resolve(modelMocks.queries['in-memory:'].data!),- }))- )- );- const view = render(() => (- <QueryClientProvider client={client}>- <Suspense fallback={<p>Settings suspended</p>}>- <Agents {...agentsPageProps} />- </Suspense>- </QueryClientProvider>- ));- try {- fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));- const claude = screen.getByRole('radio', { name: 'In Claude Code' });- expect(claude).toHaveProperty('checked', true);- expect(screen.getByText('Loading models…')).toBeTruthy();- resolveModels({- status: 'available',- currentModel: 'claude-fable-5-1',- models: [{ id: 'claude-fable-5-1', name: 'Fable 5.1' }],- });- await waitFor(() => expect(screen.getByText('Fable 5.1')).toBeTruthy());- expect(- screen.getByRole('radio', { name: 'In Claude Code' })- ).toHaveProperty('checked', true);- fireEvent.click(screen.getByRole('radio', { name: 'In Macro' }));- await waitFor(() =>- expect(screen.getByLabelText('Default model')).toHaveProperty(- 'textContent',- 'Claude Sonnet 4.5'- )- );- expect(- selectOptions(screen.getByLabelText('Default model')).queryByRole(- 'option',- { name: /Fable/i }- )- ).toBeNull();- fireEvent.click(screen.getByRole('button', { name: 'Save changes' }));- await waitFor(() =>- expect(agentMocks.update).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- harness: 'in-memory',- defaultModel: Model.sonnet55,- })- )- );- } finally {- view.unmount();- client.clear();- }- });-it('lists the built-in global Macro agent as a team agent', () => {render(() => <Agents {...agentsPageProps} />);@@ -727,21 +595,6 @@ describe('Agents', () => {channel_scope: 'all',channel_ids: [],},- {- bot: {- id: 'agent-claude',- kind: 'owned',- owner,- name: 'Claude helper',- handle: 'claude-helper',- has_agent: true,- },- instructions: '',- harness: 'claude-cloud',- default_model: 'claude-default',- channel_scope: 'all',- channel_ids: [],- },{bot: {id: 'agent-macrod',@@ -782,9 +635,6 @@ describe('Agents', () => {expect(within(list).getByText('In Cursor · cursor-small · All channels')).toBeTruthy();- expect(- within(list).getByText('In Claude Code · claude-default · All channels')- ).toBeTruthy();expect(within(list).getByText('In your harness · Dev box · codex · All channels')).toBeTruthy();@@ -1186,9 +1036,6 @@ describe('Agents', () => {expect(within(dialog).getByRole('radio', { name: 'In Macro' })).toHaveProperty('checked', true);- expect(- within(dialog).queryByRole('radio', { name: 'In Claude Code' })- ).toBeNull();expect(within(dialog).getByRole('radio', { name: 'In Cursor' })).toHaveProperty('disabled', true);@@ -1734,56 +1581,6 @@ describe('Agents', () => {).toBeTruthy();});- it('keeps a saved Claude harness visible when model discovery fails', async () => {- modelMocks.queries['claude-cloud:'] = {- isPending: false,- isError: true,- isSuccess: false,- refetch: vi.fn(),- };- agentMocks.query.data = [- {- bot: {- id: 'agent-1',- kind: 'owned',- owner: { type: 'user', user_id: 'macro|[email protected]' },- name: 'Bug fixer',- handle: 'bug-fixer',- has_agent: true,- created_at: '2026-08-27T12:00:00Z',- updated_at: '2026-08-27T12:00:00Z',- },- instructions: 'Fix the root cause.',- harness: 'claude-cloud',- default_model: 'saved-claude-model',- channel_scope: 'all',- channel_ids: [],- },- ];-- render(() => <Agents {...agentsPageProps} />);- fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));-- const dialog = screen.getByRole('region', { name: /^(New|Edit) agent$/ });- expect(- within(dialog).getByRole('radio', { name: 'In Claude Code' })- ).toHaveProperty('checked', true);- expect(- within(dialog).getByText(/Could not load models for Claude Cloud/)- ).toBeTruthy();- fireEvent.click(- within(dialog).getByRole('button', { name: 'Save changes' })- );- await waitFor(() => {- expect(agentMocks.update).toHaveBeenCalledWith(- expect.objectContaining({- harness: 'claude-cloud',- defaultModel: 'saved-claude-model',- })- );- });- });-it('preselects the bound macrod harness when editing', () => {harnessMocks.query.data = [MACROD_HARNESS];modelMocks.queries[`macrod:${MACROD_HARNESS.id}`] = successfulModels([@@ -2057,7 +1854,7 @@ it('offers bypass only after harness consent and resets the choice on harness chexpect(within(dialog).queryByLabelText('Always bypass')).toBeNull();});-it.each(['in-memory', 'cursor', 'claude-cloud'])(+it.each(['in-memory', 'cursor'])('hides permission choices and saves bypass for built-in %s',async (harness) => {cursorMocks.status.data.registered = true;@@ -2076,7 +1873,6 @@ it.each(['in-memory', 'cursor', 'claude-cloud'])(name: {'in-memory': 'In Macro',cursor: 'In Cursor',- 'claude-cloud': 'In Claude Code',}[harness]!,}));diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxindex 9d2fe64f95..c2a2d85a1d 100644--- a/apps/web/src/features/settings/Agents.tsx+++ b/apps/web/src/features/settings/Agents.tsx@@ -1,13 +1,11 @@import { useOpenAgentDm } from '@app/features/agent-dms/open-agent-dm';import { isCoderHarness } from '@app/features/agents-view/core/agent-kind';import { AGENTS_TOUR } from '@app/features/agents-view/tour';-import { useFeatureFlag } from '@app/lib/analytics/posthog';-import AnthropicIcon from '@core/component/AI/assets/anthropic.svg';import { ModelCatalogPicker } from '@core/component/AI/component/input/ModelCatalogPicker';import { isLargeModelCatalog } from '@core/component/AI/component/input/modelCatalog';import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';import { toast } from '@core/component/Toast/Toast';-import { claudeCloud, ENABLE_AGENT_DMS } from '@core/constant/featureFlags';+import { ENABLE_AGENT_DMS } from '@core/constant/featureFlags';import {MACRO_AGENT_BOT_ID,MACRO_HARNESS_NAME,@@ -136,7 +134,6 @@ export function Agents(props: {const messageAgent = (id: string) =>agentDm?.open(id === MACRO_AGENT_BOT_ID ? MACRO_NEW_BOT_ID : id);const agentList = tourTarget(AGENTS_TOUR.agentList);- const claudeCloudFlag = useFeatureFlag(claudeCloud);const [creating, setCreating] = createSignal(false);const [searchParams, setSearchParams] = useSearchParams();const creatingFromLink = () => searchParams.createAgent === 'true';@@ -162,46 +159,35 @@ export function Agents(props: {const harnessesQuery = useHarnessesQuery();const connectedHarnesses = (): readonly ConnectedHarness[] => {const harnesses = harnessesQuery.isSuccess ? harnessesQuery.data : [];- return buildAgentModelTargets(- cursorConnected(),- harnesses,- claudeCloudFlag().enabled- ).map((target) => {- if (target.harness === 'in-memory') return IN_MEMORY_HARNESS;- if (target.harness === 'claude-cloud') {- return {- id: 'claude-cloud',- name: 'Claude Cloud',- kind: 'builtin',- allowPermissionBypass: true,- target,- };- }- if (target.harness === 'cursor') {+ return buildAgentModelTargets(cursorConnected(), harnesses).map(+ (target) => {+ if (target.harness === 'in-memory') return IN_MEMORY_HARNESS;+ if (target.harness === 'cursor') {+ return {+ id: 'cursor',+ name: 'Cursor',+ kind: 'builtin',+ allowPermissionBypass: true,+ target,+ };+ }++ const harness = harnesses.find(+ (candidate) => candidate.id === target.harnessId+ );return {- id: 'cursor',- name: 'Cursor',- kind: 'builtin',- allowPermissionBypass: true,+ id: target.harnessId ?? '',+ name:+ harness?.owner.type === 'team'+ ? `${harness.name} · Team`+ : (harness?.name ?? 'macrod'),+ kind: 'macrod',+ allowPermissionBypass: harness?.allow_permission_bypass ?? false,target,+ connected: harness?.connected,};}-- const harness = harnesses.find(- (candidate) => candidate.id === target.harnessId- );- return {- id: target.harnessId ?? '',- name:- harness?.owner.type === 'team'- ? `${harness.name} · Team`- : (harness?.name ?? 'macrod'),- kind: 'macrod',- allowPermissionBypass: harness?.allow_permission_bypass ?? false,- target,- connected: harness?.connected,- };- });+ );};const channelOptions = createMemo(() =>botAssignableChannelOptions(channelsContext.channels())@@ -431,7 +417,6 @@ function summarizeAgent(function whereItRunsLabel(id: string, harness?: ConnectedHarness): string {if (id === 'in-memory') return 'In Macro';if (id === 'cursor') return 'In Cursor';- if (id === 'claude-cloud') return 'In Claude Code';// Any other id is a registered macrod harness uuid; if it is not in the// connected list any more, the harness has been removed.return harness ? `In your harness · ${harness.name}` : 'Disconnected runtime';@@ -745,14 +730,6 @@ function AgentEditorPage(props: {props.connectedHarnesses.find((harness) => harness.id === 'cursor');const macrodHarnesses = () =>props.connectedHarnesses.filter((harness) => harness.kind === 'macrod');- // Claude Cloud stays behind its flag and only once it can list models.- const claudeCloudOption = () =>- props.connectedHarnesses.find(- (harness) =>- harness.id === 'claude-cloud' &&- (harness.id === harnessId() ||- modelDataForHarness(harness.id)?.status === 'available')- );// Back from a setup guide, land on what was just set up.const finishSetup = () => {const finished = setup();@@ -1094,20 +1071,6 @@ function AgentEditorPage(props: {>{modelField()}</WhereItRunsOption>- <Show when={claudeCloudOption()}>- {(claude) => (- <WhereItRunsOption- value="claude-cloud"- title="In Claude Code"- description="Runs Claude Code in the cloud on your Claude plan."- icon={<AnthropicIcon />}- checked={harnessId() === claude().id}- onSelect={() => handleHarnessChange(claude().id)}- >- {modelField()}- </WhereItRunsOption>- )}- </Show><WhereItRunsOptionvalue="cursor"title="In Cursor"diff --git a/apps/web/src/features/settings/Harness.test.tsx b/apps/web/src/features/settings/Harness.test.tsxindex b689cf5878..ecc7f8a76a 100644--- a/apps/web/src/features/settings/Harness.test.tsx+++ b/apps/web/src/features/settings/Harness.test.tsx@@ -35,31 +35,6 @@ vi.mock('./codex/views/CodexHarness', () => ({CodexHarness: () => <div data-testid="codex-harness" />,}));-const claudeFlag = vi.hoisted(() => ({ enabled: true, source: vi.fn() }));-vi.mock('@app/lib/analytics/posthog', () => ({- useFeatureFlag: (flag: { key: string }) => {- expect(flag.key).toBe('claude-cloud');- return () => ({ enabled: claudeFlag.enabled });- },-}));--vi.mock('@core/context/user', () => ({- useUserId: () => () => 'macro|[email protected]',-}));-vi.mock('@queries/claude-auth/connection', () => ({- useClaudeConnectionSource: () => {- claudeFlag.source();- return {- status: () => ({ enabled: true, connected: false, ephemeral: true }),- failed: () => false,- begin: vi.fn(),- complete: vi.fn(),- disconnect: vi.fn(),- refresh: vi.fn(),- };- },-}));-const mocks = vi.hoisted(() => ({status: {isSuccess: true,@@ -233,21 +208,6 @@ describe('Harness', () => {});- it('hides the Claude connection outside its rollout', () => {- claudeFlag.enabled = false;- claudeFlag.source.mockClear();- try {- render(() => <Harness />);- expect(- screen.queryByRole('region', { name: 'Claude Cloud connection' })- ).toBeNull();- expect(claudeFlag.source).not.toHaveBeenCalled();- expect(screen.getByRole('heading', { name: 'Cursor' })).toBeTruthy();- } finally {- claudeFlag.enabled = true;- }- });-it.each(['success', 'error'] as const)('keeps settings visible while Cursor models load and after %s',async (outcome) => {@@ -314,17 +274,11 @@ describe('Harness', () => {});- it('shows Claude with the Anthropic logo above Cursor in the harness list', () => {+ it('lists Macro Agent and Cursor in the harness list', () => {render(() => <Harness />);expect(screen.getByRole('heading', { name: 'Macro Agent' })).toBeTruthy();expect(screen.getByRole('heading', { name: 'Cursor' })).toBeTruthy();- const claude = screen.getByRole('heading', { name: 'Claude Cloud' });- const cursor = screen.getByRole('heading', { name: 'Cursor' });- expect(- claude.compareDocumentPosition(cursor) & Node.DOCUMENT_POSITION_FOLLOWING- ).toBeTruthy();- expect(screen.getByLabelText('Anthropic')).toBeTruthy();expect(screen.getByText(/Uses official Macro tools and MCPs to get the job done/)).toBeTruthy();diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsxindex 1c45a0349f..91fccc59ea 100644--- a/apps/web/src/features/settings/Harness.tsx+++ b/apps/web/src/features/settings/Harness.tsx@@ -1,4 +1,3 @@-import { useClaudeAgentsAccess } from '@core/claude/flag';import { useCodexAgentsAccess } from '@core/codex/flag';import { toast } from '@core/component/Toast/Toast';import { MACRO_HARNESS_NAME } from '@core/constant/macroAgent';@@ -20,7 +19,6 @@ import type { Harness as RegisteredHarness } from '@service-storage/client';import { useSearchParams } from '@solidjs/router';import { Button, confirmDialog, Dialog, Panel } from '@ui';import { createSignal, For, onMount, Show } from 'solid-js';-import { ClaudeConnection } from '../claude-connection/claude-connection';import { CodexHarness } from './codex/views/CodexHarness';import { CursorDefaultModel } from './components/cursor-default-model';import { LocalRuntimeCard } from './components/local-runtime-card';@@ -47,7 +45,6 @@ function lastConnectedText(harness: RegisteredHarness): string {export function Harness(props: { onBack?: () => void; backLabel?: string } = {}) {- const canUseClaude = useClaudeAgentsAccess();const canUseCodex = useCodexAgentsAccess();const [cursorApiKey, setCursorApiKey] = createSignal('');const cursorStatus = useCursorApiKeyStatusQuery();@@ -172,10 +169,6 @@ export function Harness(</div></section>- <Show when={canUseClaude()}>- <ClaudeConnection />- </Show>-<section class="flex gap-4 px-6 py-5"><HarnessIcon><CursorIcon />diff --git a/apps/web/src/lib/core/claude/flag.ts b/apps/web/src/lib/core/claude/flag.tsdeleted file mode 100644index 0fcf94cbf2..0000000000--- a/apps/web/src/lib/core/claude/flag.ts+++ /dev/null@@ -1,9 +0,0 @@-import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { claudeCloud } from '@core/constant/featureFlags';-import type { Accessor } from 'solid-js';--/** Whether the built-in Claude agent is included in this user's rollout. */-export function useClaudeAgentsAccess(): Accessor<boolean> {- const flag = useFeatureFlag(claudeCloud);- return () => flag().enabled;-}diff --git a/apps/web/src/lib/core/component/AI/component/tool/Agents.tsx b/apps/web/src/lib/core/component/AI/component/tool/Agents.tsxindex c74c7df2e2..d0ac71661b 100644--- a/apps/web/src/lib/core/component/AI/component/tool/Agents.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/Agents.tsx@@ -11,7 +11,6 @@ import { createToolRenderer } from './ToolRenderer';const HARNESS_NAMES: Record<string, string> = {'in-memory': 'Macro',cursor: 'Cursor',- 'claude-cloud': 'Claude Cloud',macrod: 'Self-hosted harness',};diff --git a/apps/web/src/lib/core/component/HarnessIcon.tsx b/apps/web/src/lib/core/component/HarnessIcon.tsxindex 247e604028..b6784496eb 100644--- a/apps/web/src/lib/core/component/HarnessIcon.tsx+++ b/apps/web/src/lib/core/component/HarnessIcon.tsx@@ -1,4 +1,3 @@-import ClaudeIcon from '@icon/wide-claude.svg';import CodexIcon from '@icon/wide-codex-ide.svg';import CursorIcon from '@icon/wide-cursor-ide.svg';import PlugsIcon from '@phosphor/plugs.svg';@@ -10,7 +9,6 @@ export function HarnessIcon(props: { harness: string; class?: string }) {const icon = () =>match(props.harness).with('cursor', () => CursorIcon)- .with('claude-cloud', () => ClaudeIcon).with('codex-cloud', () => CodexIcon).otherwise(() => PlugsIcon);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsxindex 0bc9b5f999..19646a7761 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx@@ -22,13 +22,6 @@ const mocks = vi.hoisted(() => ({},data: { connected: false, environmentId: null as string | null },},- claude: {- isLoading: false,- get isPending(): boolean {- return this.isLoading;- },- data: { connected: false },- },}));vi.mock('@app/features/agents-view/primitives/open-page', () => ({openAgentsPage: mocks.openAgentsPage,@@ -36,15 +29,9 @@ vi.mock('@app/features/agents-view/primitives/open-page', () => ({vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({}),}));-vi.mock('@core/context/user', () => ({- useUserId: () => () => 'macro|[email protected]',-}));vi.mock('@queries/auth/codex', () => ({useCodexStatusQuery: vi.fn(() => mocks.codex),}));-vi.mock('@queries/claude-auth/connection', () => ({- useClaudeConnectionStatusQuery: vi.fn(() => mocks.claude),-}));vi.mock('@core/constant/SettingsState', () => ({useSettingsState: () => ({ openSettings: mocks.openSettings }),}));@@ -76,8 +63,6 @@ beforeEach(() => {mocks.cursor.isLoading = false;mocks.codex.isLoading = false;mocks.codex.data = { connected: false, environmentId: null };- mocks.claude.isLoading = false;- mocks.claude.data = { connected: false };mocks.cursor.data = { registered: false };});@@ -208,10 +193,7 @@ describe('connect-app chip', () => {expect(screen.getByRole('button', { name: 'Connect Cursor' })).toBeTruthy();});- it.each([- ['codex-cloud', 'Codex'],- ['claude-cloud', 'Claude'],- ])(+ it.each([['codex-cloud', 'Codex']])('opens Harness settings for an unconnected %s account',(appSlug, name) => {render(() => (@@ -229,24 +211,25 @@ describe('connect-app chip', () => {});- it.each([- ['codex-cloud', 'Codex'],- ['claude-cloud', 'Claude'],- ])('recognizes the reader’s connected %s account', (appSlug, name) => {- mocks.codex.data = { connected: true, environmentId: 'env-selected' };- mocks.claude.data = { connected: true };- render(() => (- <ConnectApp- appSlug={appSlug}- name={name}- target="harness"- key="node"- theme={{}}- />- ));- fireEvent.click(screen.getByRole('button', { name: `${name} connected` }));- expect(mocks.openSettings).not.toHaveBeenCalled();- });+ it.each([['codex-cloud', 'Codex']])(+ 'recognizes the reader’s connected %s account',+ (appSlug, name) => {+ mocks.codex.data = { connected: true, environmentId: 'env-selected' };+ render(() => (+ <ConnectApp+ appSlug={appSlug}+ name={name}+ target="harness"+ key="node"+ theme={{}}+ />+ ));+ fireEvent.click(+ screen.getByRole('button', { name: `${name} connected` })+ );+ expect(mocks.openSettings).not.toHaveBeenCalled();+ }+ );it('keeps Codex setup available until an environment is selected', () => {mocks.codex.data = { connected: true, environmentId: null };diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsxindex b14d9cb414..d801327d9b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx@@ -2,7 +2,6 @@ import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';import { useSplitLayout } from '@components/app/split-layout/layout';import { HarnessIcon } from '@core/component/HarnessIcon';import { useSettingsState } from '@core/constant/SettingsState';-import { useUserId } from '@core/context/user';import { PipedreamConnectorIcon } from '@core/pipedream/ConnectorIcon';import { AppConnectionContext } from '@core/pipedream/connection-context';import { requestConnectApp } from '@core/pipedream/pendingConnect';@@ -60,10 +59,7 @@ function ConnectPipedreamApp(props: ConnectAppDecoratorProps) {function ConnectHarness(props: ConnectAppDecoratorProps) {const { openSettings } = useSettingsState();- const connected = useHarnessConnectionStatus(- () => props.appSlug,- useUserId()- );+ const connected = useHarnessConnectionStatus(() => props.appSlug);return (<ConnectChip{...props}diff --git a/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx b/apps/web/src/lib/core/component/firstPartyBotMark.test.tsxindex ad2f4572e9..525a00cfd1 100644--- a/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx+++ b/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx@@ -1,4 +1,3 @@-import { CLAUDE_BOT_PRINCIPAL_ID } from '@core/constant/claudeAgent';import { CODEX_BOT_PRINCIPAL_ID } from '@core/constant/codexAgent';import {CURSOR_BOT_ID,@@ -8,7 +7,6 @@ import { MACRO_AGENT_PRINCIPAL_ID } from '@core/constant/macroAgent';import { MACRO_CODER_PRINCIPAL_ID } from '@core/constant/macroCoder';import { MACRO_NEW_PRINCIPAL_ID } from '@core/constant/macroNew';import MacroLogo from '@icon/macro-logo.svg';-import ClaudeIcon from '@icon/wide-claude.svg';import CodexIcon from '@icon/wide-codex-ide.svg';import CursorIcon from '@icon/wide-cursor-ide.svg';import { cleanup, render } from '@solidjs/testing-library';@@ -53,7 +51,6 @@ describe('firstPartyBotMark', () => {it('gives the partner agents their own marks', () => {expect(firstPartyBotMark(CURSOR_BOT_PRINCIPAL_ID)?.Icon).toBe(CursorIcon);expect(firstPartyBotMark(CURSOR_BOT_ID)?.Icon).toBe(CursorIcon);- expect(firstPartyBotMark(CLAUDE_BOT_PRINCIPAL_ID)?.Icon).toBe(ClaudeIcon);expect(firstPartyBotMark(CODEX_BOT_PRINCIPAL_ID)?.Icon).toBe(CodexIcon);});diff --git a/apps/web/src/lib/core/component/firstPartyBotMark.ts b/apps/web/src/lib/core/component/firstPartyBotMark.tsindex 6afa946a86..51bcfa1e60 100644--- a/apps/web/src/lib/core/component/firstPartyBotMark.ts+++ b/apps/web/src/lib/core/component/firstPartyBotMark.ts@@ -1,4 +1,3 @@-import { isClaudeBotId } from '@core/constant/claudeAgent';import { isCodexBotId } from '@core/constant/codexAgent';import { isCursorBotId } from '@core/constant/cursorAgent';import { isMacroAgentId } from '@core/constant/macroAgent';@@ -6,7 +5,6 @@ import { isMacroCoderId } from '@core/constant/macroCoder';import { isMacroNewId } from '@core/constant/macroNew';import { isMacroSystemId } from '@core/constant/macroSystem';import MacroLogo from '@icon/macro-logo.svg';-import ClaudeIcon from '@icon/wide-claude.svg';import CodexIcon from '@icon/wide-codex-ide.svg';import CursorIcon from '@icon/wide-cursor-ide.svg';import type { Component, ComponentProps } from 'solid-js';@@ -20,7 +18,6 @@ export type FirstPartyBotMark = {const MACRO_MARK: FirstPartyBotMark = { Icon: MacroLogo, tone: 'accent' };const CURSOR_MARK: FirstPartyBotMark = { Icon: CursorIcon, tone: 'ink' };-const CLAUDE_MARK: FirstPartyBotMark = { Icon: ClaudeIcon, tone: 'ink' };const CODEX_MARK: FirstPartyBotMark = { Icon: CodexIcon, tone: 'ink' };/**@@ -43,7 +40,6 @@ export function firstPartyBotMark(return MACRO_MARK;}if (isCursorBotId(id)) return CURSOR_MARK;- if (isClaudeBotId(id)) return CLAUDE_MARK;if (isCodexBotId(id)) return CODEX_MARK;return undefined;}diff --git a/apps/web/src/lib/core/constant/claudeAgent.ts b/apps/web/src/lib/core/constant/claudeAgent.tsdeleted file mode 100644index d6f556ffca..0000000000--- a/apps/web/src/lib/core/constant/claudeAgent.ts+++ /dev/null@@ -1,8 +0,0 @@-/** First-party Claude identity, matching the backend bot_id registry. */-export const CLAUDE_BOT_ID = '00000000-0000-0000-0000-00000000c1a0';-export const CLAUDE_BOT_PRINCIPAL_ID = `bot|${CLAUDE_BOT_ID}`;-export const CLAUDE_BOT_NAME = 'Claude';-export const CLAUDE_BOT_HANDLE = 'claude';-export function isClaudeBotId(id: string): boolean {- return id === CLAUDE_BOT_ID || id === CLAUDE_BOT_PRINCIPAL_ID;-}diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 396ff5e2ac..977d859cbb 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -177,14 +177,6 @@ export const enableGantt = defineFlag({env: 'ENABLE_GANTT',});-// Claude Cloud: the built-in @claude mention and agent assignee, its Runtimes-// connection card, and harness/model discovery. Off until PostHog enables it,-// including in dev; override locally with VITE_CLAUDE_CLOUD.-export const claudeCloud = defineFlag({- key: 'claude-cloud',- env: 'CLAUDE_CLOUD',-});-export const ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE = defineFlag({env: 'ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE',default: true,diff --git a/apps/web/src/lib/queries/agents/models.test.tsx b/apps/web/src/lib/queries/agents/models.test.tsxindex 862728fef1..d37d927d40 100644--- a/apps/web/src/lib/queries/agents/models.test.tsx+++ b/apps/web/src/lib/queries/agents/models.test.tsx@@ -48,11 +48,10 @@ afterEach(() => {describe('agent model discovery', () => {it('constructs every available target in parallel without waiting for another target', async () => {- const targets = buildAgentModelTargets(- true,- [{ id: 'harness-a' }, { id: 'harness-b' }],- true- );+ const targets = buildAgentModelTargets(true, [+ { id: 'harness-a' },+ { id: 'harness-b' },+ ]);const pending = new Promise<never>(() => {});vi.mocked(agentHarnessServiceClient.loadAgentModels).mockReturnValue(pending@@ -62,7 +61,7 @@ describe('agent model discovery', () => {await vi.waitFor(() => {expect(agentHarnessServiceClient.loadAgentModels).toHaveBeenCalledTimes(- 5+ 4);});expect(@@ -71,7 +70,6 @@ describe('agent model discovery', () => {.mock.calls.map(([request]) => request)).toEqual([{ harness: 'in-memory' },- { harness: 'claude-cloud' },{ harness: 'cursor' },{ harness: 'macrod', harnessId: 'harness-a' },{ harness: 'macrod', harnessId: 'harness-b' },@@ -79,9 +77,8 @@ describe('agent model discovery', () => {});it('omits Cursor when it is not registered', () => {- expect(buildAgentModelTargets(false, [{ id: 'harness-a' }], true)).toEqual([+ expect(buildAgentModelTargets(false, [{ id: 'harness-a' }])).toEqual([{ harness: 'in-memory' },- { harness: 'claude-cloud' },{ harness: 'macrod', harnessId: 'harness-a' },]);});@@ -129,21 +126,4 @@ describe('agent model discovery', () => {});expect(agentHarnessServiceClient.loadAgentModels).toHaveBeenCalledTimes(2);});-- it('does not query Claude when its feature flag is off', async () => {- vi.mocked(agentHarnessServiceClient.loadAgentModels).mockReturnValue(- new Promise<never>(() => {})- );- renderHook(() =>- useAgentModelsQueries(() => buildAgentModelTargets(true, [], false))- );- await vi.waitFor(() =>- expect(agentHarnessServiceClient.loadAgentModels).toHaveBeenCalledTimes(2)- );- expect(- vi- .mocked(agentHarnessServiceClient.loadAgentModels)- .mock.calls.map(([request]) => request)- ).toEqual([{ harness: 'in-memory' }, { harness: 'cursor' }]);- });});diff --git a/apps/web/src/lib/queries/agents/models.ts b/apps/web/src/lib/queries/agents/models.tsindex 92f128ca81..0a97285c7c 100644--- a/apps/web/src/lib/queries/agents/models.ts+++ b/apps/web/src/lib/queries/agents/models.ts@@ -12,11 +12,9 @@ export type AgentModelTarget = LoadAgentModelsRequest;/** Every model provider available to the agent dialog, in display order. */export function buildAgentModelTargets(cursorRegistered: boolean,- harnesses: readonly Pick<Harness, 'id'>[],- claudeCloudEnabled: boolean+ harnesses: readonly Pick<Harness, 'id'>[]): AgentModelTarget[] {const targets: AgentModelTarget[] = [{ harness: 'in-memory' }];- if (claudeCloudEnabled) targets.push({ harness: 'claude-cloud' });if (cursorRegistered) targets.push({ harness: 'cursor' });targets.push(...harnesses.map(diff --git a/apps/web/src/lib/queries/claude-auth/connection.ts b/apps/web/src/lib/queries/claude-auth/connection.tsdeleted file mode 100644index 48074eb022..0000000000--- a/apps/web/src/lib/queries/claude-auth/connection.ts+++ /dev/null@@ -1,61 +0,0 @@-import { throwOnErr } from '@core/util/result';-import { claudeAuthClient } from '@service-agent-harness/claude-auth';-import { queryOptions, useQuery, useQueryClient } from '@tanstack/solid-query';-import type { ClaudeConnectionSource } from '../../../features/claude-connection/core/connection';-import { claudeAuthKeys } from './keys';--/** Safe per-owner Claude status, shared by settings and connection prompts. */-export function useClaudeConnectionStatusQuery(- owner: () => string | undefined,- enabled: () => boolean = () => true-) {- return useQuery(() => claudeConnectionStatusQueryOptions(owner(), enabled()));-}--function fetchClaudeConnectionStatus({ signal }: { signal: AbortSignal }) {- return throwOnErr(() => claudeAuthClient.status(signal));-}--function claudeConnectionStatusQueryOptions(- owner: string | undefined,- enabled: boolean-) {- return queryOptions({- queryKey: claudeAuthKeys.status(owner).queryKey,- queryFn: fetchClaudeConnectionStatus,- enabled: !!owner && enabled,- staleTime: 0,- gcTime: 0,- retry: false,- });-}--/** Only safe status is cached. One-time codes never enter a mutation cache. */-export function useClaudeConnectionSource(- owner: () => string | undefined-): ClaudeConnectionSource {- const client = useQueryClient();- const query = useClaudeConnectionStatusQuery(owner);- const refresh = async () => {- await Promise.all([- client.invalidateQueries({ queryKey: claudeAuthKeys._def }),- client.invalidateQueries({- queryKey: ['agent-models', 'load', 'claude-cloud'],- }),- ]);- };- return {- status: () => (query.isSuccess ? query.data : undefined),- failed: () => query.isError,- begin: () => throwOnErr(() => claudeAuthClient.begin()),- complete: async (attemptId, code) => {- await throwOnErr(() => claudeAuthClient.complete(attemptId, code));- await refresh();- },- disconnect: async () => {- await throwOnErr(() => claudeAuthClient.disconnect());- await refresh();- },- refresh,- };-}diff --git a/apps/web/src/lib/queries/claude-auth/keys.ts b/apps/web/src/lib/queries/claude-auth/keys.tsdeleted file mode 100644index 18cfc28adb..0000000000--- a/apps/web/src/lib/queries/claude-auth/keys.ts+++ /dev/null@@ -1,4 +0,0 @@-import { createQueryKeys } from '@lukemorales/query-key-factory';-export const claudeAuthKeys = createQueryKeys('claude-auth', {- status: (owner: string | undefined) => [owner],-});diff --git a/apps/web/src/lib/queries/harnesses/connections.ts b/apps/web/src/lib/queries/harnesses/connections.tsindex 6b5798dc82..4ff9cb94ff 100644--- a/apps/web/src/lib/queries/harnesses/connections.ts+++ b/apps/web/src/lib/queries/harnesses/connections.ts@@ -2,20 +2,14 @@ import type { Accessor } from 'solid-js';import { match } from 'ts-pattern';import { useCodexStatusQuery } from '../auth/codex';import { useCursorApiKeyStatusQuery } from '../auth/cursor-api-key';-import { useClaudeConnectionStatusQuery } from '../claude-auth/connection';import { queryReadyGate } from '../gate';/** Connection status for a named harness; unsupported providers stay disconnected. */export function useHarnessConnectionStatus(- harness: Accessor<string>,- owner: Accessor<string | undefined>+ harness: Accessor<string>): Accessor<boolean> {const cursor = useCursorApiKeyStatusQuery(() => harness() === 'cursor');const codex = useCodexStatusQuery(() => harness() === 'codex-cloud');- const claude = useClaudeConnectionStatusQuery(- owner,- () => harness() === 'claude-cloud'- );return () =>match(harness())@@ -27,9 +21,5 @@ export function useHarnessConnectionStatus(codex.data.connected &&!!codex.data.environmentId?.trim())- .with(- 'claude-cloud',- () => queryReadyGate(claude) && claude.data.connected- ).otherwise(() => false);}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/claude-auth.ts b/apps/web/src/lib/service-clients/service-agent-harness/claude-auth.tsdeleted file mode 100644index 0b5822a622..0000000000--- a/apps/web/src/lib/service-clients/service-agent-harness/claude-auth.ts+++ /dev/null@@ -1,66 +0,0 @@-import { SERVER_HOSTS } from '@core/constant/servers';-import { fetchWithToken } from '@core/util/fetchWithToken';-import type { ErrorResponseHandler } from '@core/util/safeFetch';--// Mirrors the Rust /claude-auth DTOs. Neither response can contain provider credentials.-export type ClaudeAuthStatus = {- enabled: boolean;- connected: boolean;- ephemeral: boolean;-};-export type ClaudeAuthStart = {- attemptId: string;- authorizationUrl: string;- expiresIn: number;-};-const host = `${SERVER_HOSTS['agent-harness']}/claude-auth`;--const authError: ErrorResponseHandler<never> = async (response) => {- const data: unknown = await response.json();- return {- code: response.status === 401 ? 'UNAUTHORIZED' : 'HTTP_ERROR',- message:- typeof data === 'object' &&- data !== null &&- 'message' in data &&- typeof data.message === 'string'- ? data.message- : 'Claude connection request failed. Start Connect Claude again.',- };-};-const writeOptions = {- headers: { 'Content-Type': 'application/json' },- cache: 'no-store' as const,- errorResponseHandler: authError,-};--export const claudeAuthClient = {- status(signal?: AbortSignal) {- return fetchWithToken<ClaudeAuthStatus>(host, {- method: 'GET',- cache: 'no-store',- signal,- });- },- begin() {- return fetchWithToken<ClaudeAuthStart>(`${host}/start`, {- ...writeOptions,- method: 'POST',- body: '{}',- });- },- complete(attemptId: string, code: string) {- return fetchWithToken<Record<string, never>>(`${host}/complete`, {- ...writeOptions,- method: 'POST',- body: JSON.stringify({ attemptId, code }),- });- },- disconnect() {- return fetchWithToken<Record<string, never>>(host, {- ...writeOptions,- method: 'DELETE',- body: '{}',- });- },-};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.tsindex e71e70967f..861b8dcc9d 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@@ -18,7 +18,6 @@ import type {AnswerToolApprovalRequest,AnswerToolApprovalResponse,CodingPreferencesBody,- CompleteRequest,ControlRequest,ControlResponse,CreateAgentSessionRequest,@@ -27,7 +26,6 @@ import type {DiscoverAgentCapabilitiesRequest,DiscoverAgentCapabilitiesResponse,EditQueuedActionRequest,- EmptyRequest,ExecutionRecord,ListAgentRepositoryBranchesParams,LoadAgentModelsRequest,@@ -47,8 +45,6 @@ import type {SetAgentSessionArchivedRequest,SharePermissionV2,StartFreshAgentConversationRequest,- StartResponse,- StatusResponse,UnlinkAgentSessionPullRequestParams,UpdateSharePermissionRequestV2,WarmAgentSessionRequest,@@ -2963,197 +2959,3 @@ export const answerAgentSessionToolApproval = async (headers: res.headers,} as answerAgentSessionToolApprovalResponse;};--/**- * @summary Read connection status for the authenticated user only.- */-export type statusResponse200 = {- data: StatusResponse;- status: 200;-};--export type statusResponse401 = {- data: void;- status: 401;-};--export type statusResponseSuccess = statusResponse200 & {- headers: Headers;-};-export type statusResponseError = statusResponse401 & {- headers: Headers;-};--export type statusResponse = statusResponseSuccess | statusResponseError;--export const getStatusUrl = () => {- return `/claude-auth`;-};--export const status = async (- options?: RequestInit-): Promise<statusResponse> => {- const res = await fetch(getStatusUrl(), {- ...options,- method: 'GET',- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: statusResponse['data'] = body ? JSON.parse(body) : {};- return { data, status: res.status, headers: res.headers } as statusResponse;-};--/**- * @summary Forget only the authenticated user's grant and cancel pending consent.- */-export type disconnectResponse204 = {- data: void;- status: 204;-};--export type disconnectResponse403 = {- data: void;- status: 403;-};--export type disconnectResponseSuccess = disconnectResponse204 & {- headers: Headers;-};-export type disconnectResponseError = disconnectResponse403 & {- headers: Headers;-};--export type disconnectResponse =- | disconnectResponseSuccess- | disconnectResponseError;--export const getDisconnectUrl = () => {- return `/claude-auth`;-};--export const disconnect = async (- emptyRequest: EmptyRequest,- options?: RequestInit-): Promise<disconnectResponse> => {- const res = await fetch(getDisconnectUrl(), {- ...options,- method: 'DELETE',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(emptyRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: disconnectResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as disconnectResponse;-};--/**- * @summary Exchange one code; never return access or refresh tokens.- */-export type completeResponse204 = {- data: void;- status: 204;-};--export type completeResponse400 = {- data: void;- status: 400;-};--export type completeResponse409 = {- data: void;- status: 409;-};--export type completeResponse502 = {- data: void;- status: 502;-};--export type completeResponseSuccess = completeResponse204 & {- headers: Headers;-};-export type completeResponseError = (- | completeResponse400- | completeResponse409- | completeResponse502-) & {- headers: Headers;-};--export type completeResponse = completeResponseSuccess | completeResponseError;--export const getCompleteUrl = () => {- return `/claude-auth/complete`;-};--export const complete = async (- completeRequest: CompleteRequest,- options?: RequestInit-): Promise<completeResponse> => {- const res = await fetch(getCompleteUrl(), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(completeRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: completeResponse['data'] = body ? JSON.parse(body) : {};- return { data, status: res.status, headers: res.headers } as completeResponse;-};--/**- * @summary Create an expiring PKCE challenge for the authenticated user.- */-export type startResponse200 = {- data: StartResponse;- status: 200;-};--export type startResponse403 = {- data: void;- status: 403;-};--export type startResponse429 = {- data: void;- status: 429;-};--export type startResponseSuccess = startResponse200 & {- headers: Headers;-};-export type startResponseError = (startResponse403 | startResponse429) & {- headers: Headers;-};--export type startResponse = startResponseSuccess | startResponseError;--export const getStartUrl = () => {- return `/claude-auth/start`;-};--export const start = async (- emptyRequest: EmptyRequest,- options?: RequestInit-): Promise<startResponse> => {- const res = await fetch(getStartUrl(), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(emptyRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: startResponse['data'] = body ? JSON.parse(body) : {};- return { data, status: res.status, headers: res.headers } as startResponse;-};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/completeRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/completeRequest.tsdeleted file mode 100644index 9e1e141d0e..0000000000--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/completeRequest.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * agent_harness_service- * OpenAPI spec version: 0.1.0- */--/**- * One-time manual code. Deliberately does not implement Debug.- */-export interface CompleteRequest {- /** Server-issued handle; never an owner selected by the caller. */- attemptId: string;- /** Claude's complete code#state string, not an access token. */- code: string;-}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/emptyRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/emptyRequest.tsdeleted file mode 100644index 722dd6e174..0000000000--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/emptyRequest.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * agent_harness_service- * OpenAPI spec version: 0.1.0- */--/**- * A JSON body is required on writes, including start/disconnect (no form-based CSRF).- */-export interface EmptyRequest {- [key: string]: unknown;-}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.tsindex fab8ef7b32..7eca76e479 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@@ -111,7 +111,6 @@ export * from './changesetDtoRepository';export * from './changesetSourceDto';export * from './channelSharePermission';export * from './codingPreferencesBody';-export * from './completeRequest';export * from './controlRequest';export * from './controlRequestAllOf';export * from './controlRequestAllOfActionId';@@ -156,7 +155,6 @@ export * from './elicitationAnswerOneOfSeven';export * from './elicitationAnswerOneOfSevenAction';export * from './elicitationContentValue';export * from './elicitationRequestId';-export * from './emptyRequest';export * from './executionActivity';export * from './executionId';export * from './executionRecord';@@ -257,8 +255,6 @@ export * from './sharePermissionV2LinkShare';export * from './sharePermissionV2LinkShareAccessLevel';export * from './sharePermissionV2TeamShareAccessLevel';export * from './startFreshAgentConversationRequest';-export * from './startResponse';-export * from './statusResponse';export * from './toolApprovalAnswerDto';export * from './toolApprovalStatusDto';export * from './unlinkAgentSessionPullRequestParams';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/modelHarnessDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/modelHarnessDto.tsindex 0b1b76195e..15d05b1db3 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/modelHarnessDto.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/modelHarnessDto.ts@@ -15,6 +15,5 @@ export type ModelHarnessDto =export const ModelHarnessDto = {'in-memory': 'in-memory',cursor: 'cursor',- 'claude-cloud': 'claude-cloud',macrod: 'macrod',} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/startResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/startResponse.tsdeleted file mode 100644index 3548c268b0..0000000000--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/startResponse.ts+++ /dev/null@@ -1,21 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * agent_harness_service- * OpenAPI spec version: 0.1.0- */--/**- * Public PKCE challenge and attempt handle; contains no verifier or provider tokens.- */-export interface StartResponse {- /** Opaque owner-bound attempt handle. */- attemptId: string;- /** Claude-hosted consent page. */- authorizationUrl: string;- /**- * Attempt lifetime in seconds.- * @minimum 0- */- expiresIn: number;-}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/statusResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/statusResponse.tsdeleted file mode 100644index 19a9af1c85..0000000000--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/statusResponse.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * agent_harness_service- * OpenAPI spec version: 0.1.0- */--/**- * Safe connection metadata.- */-export interface StatusResponse {- /** Whether the authenticated Macro user has connected. */- connected: boolean;- /** Whether this deployment supports browser connection. */- enabled: boolean;- /** Whether reconnecting after service restart is required. */- ephemeral: boolean;-}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.jsonindex cbdb19d225..c0296f16c0 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@@ -2596,137 +2596,6 @@}}}- },- "/claude-auth": {- "get": {- "tags": ["claude-auth"],- "summary": "Read connection status for the authenticated user only.",- "operationId": "status",- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StatusResponse"- }- }- }- },- "401": {- "description": "Unauthenticated"- }- },- "security": [- {- "bearerAuth": []- }- ]- },- "delete": {- "tags": ["claude-auth"],- "summary": "Forget only the authenticated user's grant and cancel pending consent.",- "operationId": "disconnect",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyRequest"- }- }- },- "required": true- },- "responses": {- "204": {- "description": "Disconnected"- },- "403": {- "description": "Disabled"- }- },- "security": [- {- "bearerAuth": []- }- ]- }- },- "/claude-auth/complete": {- "post": {- "tags": ["claude-auth"],- "summary": "Exchange one code; never return access or refresh tokens.",- "operationId": "complete",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/CompleteRequest"- }- }- },- "required": true- },- "responses": {- "204": {- "description": "Connected"- },- "400": {- "description": "Invalid code"- },- "409": {- "description": "Expired or replayed"- },- "502": {- "description": "Provider failed"- }- },- "security": [- {- "bearerAuth": []- }- ]- }- },- "/claude-auth/start": {- "post": {- "tags": ["claude-auth"],- "summary": "Create an expiring PKCE challenge for the authenticated user.",- "operationId": "start",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StartResponse"- }- }- }- },- "403": {- "description": "Disabled"- },- "429": {- "description": "Too many attempts"- }- },- "security": [- {- "bearerAuth": []- }- ]- }}},"components": {@@ -3861,22 +3730,6 @@}}},- "CompleteRequest": {- "type": "object",- "description": "One-time manual code. Deliberately does not implement Debug.",- "required": ["attemptId", "code"],- "properties": {- "attemptId": {- "type": "string",- "description": "Server-issued handle; never an owner selected by the caller."- },- "code": {- "type": "string",- "description": "Claude's complete code#state string, not an access token."- }- },- "additionalProperties": false- },"ControlRequest": {"allOf": [{@@ -4224,11 +4077,6 @@],"description": "The JSON-RPC id of an agent's `elicitation/create` request, carried whole\nso the answer echoes exactly what the agent sent.\n\nAgents pick these, not us: Claude Code counts from `0`, others use\nstrings. `null` is not a legal id for a request that expects a response,\nso it is not representable here."},- "EmptyRequest": {- "type": "object",- "description": "A JSON body is required on writes, including start/disconnect (no form-based CSRF).",- "additionalProperties": false- },"ExecutionActivity": {"type": "object","description": "A bounded SDK operation observed during execution; not an authorization or write receipt.",@@ -4508,7 +4356,7 @@"ModelHarnessDto": {"type": "string","description": "Harness names accepted by the model discovery endpoint.",- "enum": ["in-memory", "cursor", "claude-cloud", "macrod"]+ "enum": ["in-memory", "cursor", "macrod"]},"PermissionAnswer": {"oneOf": [@@ -5229,46 +5077,6 @@}}},- "StartResponse": {- "type": "object",- "description": "Public PKCE challenge and attempt handle; contains no verifier or provider tokens.",- "required": ["attemptId", "authorizationUrl", "expiresIn"],- "properties": {- "attemptId": {- "type": "string",- "description": "Opaque owner-bound attempt handle."- },- "authorizationUrl": {- "type": "string",- "description": "Claude-hosted consent page."- },- "expiresIn": {- "type": "integer",- "format": "int64",- "description": "Attempt lifetime in seconds.",- "minimum": 0- }- }- },- "StatusResponse": {- "type": "object",- "description": "Safe connection metadata.",- "required": ["enabled", "connected", "ephemeral"],- "properties": {- "connected": {- "type": "boolean",- "description": "Whether the authenticated Macro user has connected."- },- "enabled": {- "type": "boolean",- "description": "Whether this deployment supports browser connection."- },- "ephemeral": {- "type": "boolean",- "description": "Whether reconnecting after service restart is required."- }- }- },"ToolApprovalAnswerDto": {"type": "string","description": "How a person answers a held tool call.",diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 79ef738e52..70df29afc5 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -991,7 +991,6 @@ export const ConfigureAgent = z.object({const schemas = [z.literal('in-memory'),z.literal('cursor'),- z.literal('claude-cloud'),z.literal('macrod'),];const errors = schemas.reduce<z.ZodError[]>(diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex edc2edeb11..61b70f39fb 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -220,11 +220,7 @@ export type DiscussionParentType =/*** The runtimes an agent can be moved onto.*/-export type AgentHarnessOption =- | 'in-memory'- | 'cursor'- | 'claude-cloud'- | 'macrod';+export type AgentHarnessOption = 'in-memory' | 'cursor' | 'macrod';/*** Where an agent can be mentioned.*/@@ -5725,7 +5721,7 @@ export interface AgentSummary {*/instructions: string;/**- * Harness slug: `in-memory`, `cursor`, `claude-cloud`, or `macrod`.+ * Harness slug: `in-memory`, `cursor`, or `macrod`.*/harness: string;/**diff --git a/crates/agent_changes/src/domain/pull_request/test.rs b/crates/agent_changes/src/domain/pull_request/test.rsindex c0f4c485ad..38cb90bb90 100644--- a/crates/agent_changes/src/domain/pull_request/test.rs+++ b/crates/agent_changes/src/domain/pull_request/test.rs@@ -73,14 +73,7 @@ fn linked_session() -> AgentSession {#[tokio::test]async fn every_harness_reads_the_linked_pr_with_the_session_owners_access() {let extractor = PullRequestChanges::new(Changesets::default());- for harness in [- "cursor",- "macrod",- "opencode",- "codex-cloud",- "claude-cloud",- "macro-inmem",- ] {+ for harness in ["cursor", "macrod", "opencode", "codex-cloud", "macro-inmem"] {let mut session = test_agent_session(AgentSessionId::TEST_A);session.harness = harness.to_owned();session.pull_request_url = Some("https://github.com/upstream/repo/pull/42".to_owned());diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex d67632339e..edca805283 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -41,10 +41,6 @@"agent-harness.decideSessionReview": "Decide Session Review","agent-harness.putAgentSessionSandboxSize": "Put Agent Session Sandbox Size","agent-harness.answerAgentSessionToolApproval": "Answer Agent Session Tool Approval",- "agent-harness.disconnect": "Disconnect",- "agent-harness.status": "Status",- "agent-harness.complete": "Complete",- "agent-harness.start": "Start","auth.updateAiBillingAutoReload": "Update Ai Billing Auto Reload","auth.createAiCreditCheckout": "Create Ai Credit Checkout","auth.updateAiBillingOverage": "Update Ai Billing Overage",diff --git a/crates/agent_harness/AGENTS.md b/crates/agent_harness/AGENTS.mdindex 46280bdd14..a7e20fe7e7 100644--- a/crates/agent_harness/AGENTS.md+++ b/crates/agent_harness/AGENTS.md@@ -4,14 +4,14 @@Part of agent sessions: orchestrates sandboxed coding-agent sessions end toend — provisioning containers, speaking to each coding-agent runtime-(Claude, Codex), routing triggers to a session, and relaying ACP traffic+(Cursor, Codex), routing triggers to a session, and relaying ACP trafficbetween the sandbox and the rest of the product.## Start here- `src/domain/service.rs` + `src/domain/ports.rs`: the harness service andthe ports every runtime/container provider implements.-- `src/domain/claude.rs` / `src/domain/codex.rs`: per-runtime session setup.+- `src/domain/codex.rs`: per-runtime session setup.- `src/outbound/sidecar.rs` + `sidecar_pump.rs`: the container sidecartransport that speaks `agent_runtime_protocol`.- `src/outbound/containers.rs` / `managed_containers.rs`: containerdiff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.tomlindex ee28e0a835..fe8355dd49 100644--- a/crates/agent_harness/Cargo.toml+++ b/crates/agent_harness/Cargo.toml@@ -7,7 +7,6 @@ version = "0.1.0"[dependencies]genai_telemetry = { path = "../genai_telemetry" }ai_billing = { path = "../ai_billing" }-claude_cloud_agents = { path = "../claude_cloud_agents" }async-trait = { workspace = true }codex_cloud_agents = { path = "../codex_cloud_agents", features = ["postgres"] }codex_connection = { path = "../codex_connection" }diff --git a/crates/agent_harness/src/domain/claude.rs b/crates/agent_harness/src/domain/claude.rsdeleted file mode 100644index 453df5a2e5..0000000000--- a/crates/agent_harness/src/domain/claude.rs+++ /dev/null@@ -1,173 +0,0 @@-//! Claude conversation lifecycle through owner-bound provider and session ports.-use crate::domain::error::{HarnessError, Result};-use crate::domain::model::SessionBlocker;-use agent_session::domain::{- model::{AgentSessionId, ExternalSession},- ports::{AgentSessionRepo, ExternalSessionRepo},-};-use claude_cloud_agents::domain::{- model::{Error, SessionId},- ports::{CloudLifecycle, CloudProvider},- service::Session,-};-use macro_user_id::user_id::MacroUserIdStr;-use std::sync::Arc;--/// Provider identity in the shared external-session store.-pub const PROVIDER: &str = "claude-cloud";-const PENDING: &str = "claude-cloud-create-pending";--fn cloud_error(error: Error) -> HarnessError {- HarnessError::Container(error.to_string())-}--/// Lifecycle policy shared by every agent configured with the Claude harness.-pub struct ClaudeSessions<P, Repo, External> {- provider: Arc<P>,- repo: Repo,- external: External,- mcp_gateway_host: String,- creation: tokio::sync::Mutex<()>,-}--impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>- ClaudeSessions<P, Repo, External>-{- /// Check the owner's connection before a mention creates any session resources.- pub async fn preflight(&self, owner: &MacroUserIdStr<'_>) -> Result<Option<SessionBlocker>> {- match self.provider.connect(owner.as_ref()).await {- Ok(_) => Ok(None),- Err(Error::NotConnected) => Ok(Some(SessionBlocker::ClaudeNotConnected)),- Err(error) => Err(cloud_error(error)),- }- }-- /// Mint a fresh egress credential on reattach; persist only its hash, as for- /// other external runtimes. The saved agent selection remains authoritative.- pub async fn refresh_egress(- &self,- id: AgentSessionId,- provisioner: &impl crate::domain::ports::SandboxEgressProvisioner,- ) -> Result<String> {- let row = self.repo.get(id).await?;- let egress = provisioner- .provision(id, row.owner_user()?, &row.mcp_servers)- .await?;- self.repo- .set_egress_token_hash(id, &egress.session_token_hash)- .await?;- Ok(egress.sandbox.session_token)- }-- /// Wire the provider and the owning session repository at the composition root.- pub fn new(provider: Arc<P>, repo: Repo, external: External, mcp_gateway_host: String) -> Self {- Self {- provider,- repo,- external,- mcp_gateway_host,- creation: tokio::sync::Mutex::new(()),- }- }-- /// Archive the owner's remote conversation before removing its mapping.- pub async fn archive(&self, id: AgentSessionId) -> Result<()> {- let _creation = self.creation.lock().await;- let Some(external) = ExternalSessionRepo::get(&self.external, id).await? else {- return Ok(());- };- if external.provider != PROVIDER {- return Err(cloud_error(Error::UncertainCreate));- }- let row = AgentSessionRepo::get(&self.repo, id).await?;- self.provider- .connect(row.owner_user()?.as_ref())- .await- .map_err(cloud_error)?- .archive(&SessionId::parse(&external.external_id).map_err(cloud_error)?)- .await- .map_err(cloud_error)?;- ExternalSessionRepo::delete(&self.external, id).await?;- Ok(())- }- /// Resolve or create a durable conversation for the session owner.- pub async fn attach(&self, id: AgentSessionId) -> Result<Arc<Session<P::Client>>> {- let _creation = self.creation.lock().await;- let row = AgentSessionRepo::get(&self.repo, id).await?;- let model =- claude_cloud_agents::domain::models::Model::parse(&row.model).map_err(cloud_error)?;- let client = self- .provider- .connect(row.owner_user()?.as_ref())- .await- .map_err(cloud_error)?;- let external = ExternalSessionRepo::get(&self.external, id).await?;- let cloud_id = match external {- Some(mut external) if external.provider == PROVIDER => {- let cloud_id = SessionId::parse(&external.external_id).map_err(cloud_error)?;- if external.external_url.is_none() {- external.external_url = Some(cloud_id.web_url());- self.external.upsert(id, external).await?;- }- cloud_id- }- Some(_) => return Err(cloud_error(Error::UncertainCreate)),- None => {- // Network settings are captured when Claude creates its container.- // Prepare before the durable create intent: a setup failure can- // safely be retried and must not strand the session as pending.- client- .prepare_mcp_access(&self.mcp_gateway_host)- .await- .map_err(cloud_error)?;- // Write a durable intent before the non-idempotent POST. A crash or- // timeout stays visibly pending rather than minting a duplicate VM.- self.external- .upsert(- id,- ExternalSession {- provider: PENDING.into(),- external_id: id.to_string(),- external_name: None,- external_url: None,- last_run_id: None,- },- )- .await?;- let cloud_id = match client- .create(row.instructions.as_deref().unwrap_or_default(), &model)- .await- {- Ok(id) => id,- Err(error) => {- // Only a definite client rejection is safe to retry as a new create.- if matches!(- error,- Error::Authorization | Error::NotConnected | Error::Http(400..=499)- ) {- ExternalSessionRepo::delete(&self.external, id).await?;- }- return Err(cloud_error(error));- }- };- self.external- .upsert(- id,- ExternalSession {- provider: PROVIDER.into(),- external_id: cloud_id.as_str().to_owned(),- external_name: Some("Claude Cloud".into()),- external_url: Some(cloud_id.web_url()),- last_run_id: None,- },- )- .await?;- cloud_id- }- };- Ok(Session::with_model(client, cloud_id, model))- }-}--#[cfg(test)]-mod test;diff --git a/crates/agent_harness/src/domain/claude/test.rs b/crates/agent_harness/src/domain/claude/test.rsdeleted file mode 100644index 4eaafa22fc..0000000000--- a/crates/agent_harness/src/domain/claude/test.rs+++ /dev/null@@ -1,338 +0,0 @@-use super::*;-use agent_session::domain::{- model::{AgentMcpServers, CreateAgentSessionParams, SandboxSize},- ports::MockExternalSessionRepo,-};-use agent_session::testing::InMemoryAgentSessionRepo;-use claude_cloud_agents::domain::{- model::Event,- ports::{Cloud, Events},-};-use std::collections::HashMap;-use std::sync::Mutex;--#[derive(Default)]-struct Provider {- connection_error: Mutex<Option<Error>>,- calls: Arc<Mutex<Vec<(String, String)>>>,- models: Arc<Mutex<Vec<String>>>,- uncertain: bool,- preparations: Arc<Mutex<Vec<(String, String)>>>,- preparation_fails: bool,-}-#[derive(Clone)]-struct Client {- owner: String,- calls: Arc<Mutex<Vec<(String, String)>>>,- models: Arc<Mutex<Vec<String>>>,- uncertain: bool,- preparations: Arc<Mutex<Vec<(String, String)>>>,- preparation_fails: bool,-}-impl CloudProvider for Provider {- type Client = Client;- async fn connect(&self, owner: &str) -> claude_cloud_agents::domain::model::Result<Client> {- if let Some(error) = self.connection_error.lock().unwrap().take() {- return Err(error);- }- Ok(Client {- owner: owner.into(),- calls: self.calls.clone(),- models: self.models.clone(),- uncertain: self.uncertain,- preparations: self.preparations.clone(),- preparation_fails: self.preparation_fails,- })- }-}-impl CloudLifecycle for Client {- async fn prepare_mcp_access(- &self,- host: &str,- ) -> claude_cloud_agents::domain::model::Result<()> {- self.preparations- .lock()- .unwrap()- .push((self.owner.clone(), host.into()));- if self.preparation_fails {- return Err(Error::EnvironmentNetwork);- }- Ok(())- }- async fn create(- &self,- instructions: &str,- model: &claude_cloud_agents::domain::models::Model,- ) -> claude_cloud_agents::domain::model::Result<SessionId> {- self.models.lock().unwrap().push(model.id().to_owned());- assert!(- self.preparations- .lock()- .unwrap()- .iter()- .any(|(owner, host)| owner == &self.owner && host == "dev-gateway.macro.com")- );- self.calls- .lock()- .unwrap()- .push((self.owner.clone(), instructions.into()));- if self.uncertain {- return Err(Error::UncertainCreate);- }- SessionId::parse(&format!("cse_{}", self.calls.lock().unwrap().len()))- }- async fn archive(&self, _: &SessionId) -> claude_cloud_agents::domain::model::Result<()> {- Ok(())- }-}-impl Cloud for Client {- async fn models(- &self,- ) -> claude_cloud_agents::domain::model::Result<- Vec<claude_cloud_agents::domain::models::ModelOption>,- > {- Ok(vec![])- }- async fn history(- &self,- _: &SessionId,- ) -> claude_cloud_agents::domain::model::Result<Vec<Event>> {- Ok(vec![])- }- async fn send(- &self,- _: &SessionId,- _: serde_json::Value,- ) -> claude_cloud_agents::domain::model::Result<()> {- unreachable!()- }- async fn send_batch(- &self,- _: &SessionId,- _: Vec<serde_json::Value>,- ) -> claude_cloud_agents::domain::model::Result<()> {- unreachable!()- }- async fn stream(- &self,- _: &SessionId,- _: Option<u64>,- ) -> claude_cloud_agents::domain::model::Result<Events> {- unreachable!()- }-}--fn mappings() -> MockExternalSessionRepo {- let data = Arc::new(Mutex::new(HashMap::<AgentSessionId, ExternalSession>::new()));- let mut repo = MockExternalSessionRepo::new();- let records = data.clone();- repo.expect_get().returning(move |id| {- let found = records.lock().unwrap().get(&id).cloned();- Box::pin(async move { Ok(found) })- });- let records = data.clone();- repo.expect_upsert().returning(move |id, external| {- records.lock().unwrap().insert(id, external);- Box::pin(async { Ok(()) })- });- repo.expect_delete().returning(move |id| {- data.lock().unwrap().remove(&id);- Box::pin(async { Ok(()) })- });- repo-}--async fn seed(- repo: &InMemoryAgentSessionRepo,- bot: bot_id::BotId,- owner: &str,- instructions: &str,-) -> AgentSessionId {- let id = AgentSessionId::new();- repo.create(CreateAgentSessionParams {- purpose: agent_session::domain::model::SessionPurpose::Standalone,- repo_branch: None,- id,- bot_id: bot,- owner_id: model_owner::Owner::User(- macro_user_id::user_id::MacroUserIdStr::try_from(owner.to_owned()).unwrap(),- ),- thread_id: None,- originating_message_id: None,- model: "claude-default".into(),- harness: "claude-cloud".into(),- repo_url: None,- workspace: "/".into(),- sandbox_size: SandboxSize::Default,- instructions: Some(instructions.into()),- mcp_servers: AgentMcpServers::OwnerConnections,- egress_token_hash: None,- })- .await- .unwrap();- id-}--#[tokio::test]-async fn distinct_agents_keep_their_owner_instructions_model_and_remote_session() {- let repo = InMemoryAgentSessionRepo::new();- let first = seed(- &repo,- bot_id::BotId::TEST_A,- "macro|[email protected]",- "Review code",- )- .await;- let second = seed(- &repo,- bot_id::BotId::TEST_B,- "macro|[email protected]",- "Fix tests",- )- .await;- repo.set_model(first, "claude-fable-5-1").await.unwrap();- let provider = Arc::new(Provider::default());- let sessions = ClaudeSessions::new(- provider.clone(),- repo,- mappings(),- "dev-gateway.macro.com".into(),- );- let one = sessions.attach(first).await.unwrap();- let two = sessions.attach(second).await.unwrap();- assert_ne!(one.id(), two.id());- assert_eq!(one.model().await.id(), "claude-fable-5-1");- assert_eq!(- *provider.models.lock().unwrap(),- vec!["claude-fable-5-1", "claude-default"]- );- assert_eq!(sessions.attach(first).await.unwrap().id(), one.id());- assert_eq!(provider.preparations.lock().unwrap().len(), 2);- assert_eq!(- *provider.calls.lock().unwrap(),- vec![- ("macro|[email protected]".into(), "Review code".into()),- ("macro|[email protected]".into(), "Fix tests".into()),- ]- );-}--#[tokio::test]-async fn uncertain_create_remains_pending_and_is_never_retried() {- let repo = InMemoryAgentSessionRepo::new();- let id = seed(- &repo,- bot_id::BotId::TEST_A,- "macro|[email protected]",- "Review code",- )- .await;- let provider = Arc::new(Provider {- uncertain: true,- ..Default::default()- });- let sessions = ClaudeSessions::new(- provider.clone(),- repo,- mappings(),- "dev-gateway.macro.com".into(),- );- assert!(sessions.attach(id).await.is_err());- assert!(sessions.attach(id).await.is_err());- assert_eq!(provider.calls.lock().unwrap().len(), 1);-}--#[tokio::test]-async fn reattach_restores_egress_with_the_saved_agent_selection() {- use crate::testing::helpers::egress::EgressProvisionerMock;- let repo = InMemoryAgentSessionRepo::new();- let id = seed(- &repo,- bot_id::BotId::TEST_A,- "macro|[email protected]",- "Review code",- )- .await;- let sessions = ClaudeSessions::new(- Arc::new(Provider::default()),- repo.clone(),- mappings(),- "dev-gateway.macro.com".into(),- );- let egress = EgressProvisionerMock::default();- let token = sessions.refresh_egress(id, &egress).await.unwrap();- assert_eq!(token, "test-session-token");- assert_eq!(- egress.provisioned(),- vec![(- id,- "macro|[email protected]".into(),- AgentMcpServers::OwnerConnections- )]- );- assert!(- repo.find_by_egress_token_hash("test-token-hash")- .await- .unwrap()- .is_some()- );-}--#[tokio::test]-async fn network_setup_failure_never_creates_or_leaves_a_pending_intent() {- let repo = InMemoryAgentSessionRepo::new();- let id = seed(- &repo,- bot_id::BotId::TEST_A,- "macro|[email protected]",- "Review code",- )- .await;- let provider = Arc::new(Provider {- preparation_fails: true,- ..Default::default()- });- let sessions = ClaudeSessions::new(- provider.clone(),- repo,- mappings(),- "dev-gateway.macro.com".into(),- );- for _ in 0..2 {- let error = sessions.attach(id).await.err().unwrap();- assert!(error.to_string().contains("MCP gateway"));- assert!(- ExternalSessionRepo::get(&sessions.external, id)- .await- .unwrap()- .is_none()- );- }- assert!(provider.calls.lock().unwrap().is_empty());- assert_eq!(provider.preparations.lock().unwrap().len(), 2);-}--#[tokio::test]-async fn preflight_only_requests_connection_for_a_missing_account() {- let provider = Arc::new(Provider::default());- let service = ClaudeSessions::new(- provider.clone(),- InMemoryAgentSessionRepo::default(),- mappings(),- "dev-gateway.macro.com".into(),- );- let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();- *provider.connection_error.lock().unwrap() = Some(Error::NotConnected);- assert_eq!(- service.preflight(&owner).await.unwrap(),- Some(SessionBlocker::ClaudeNotConnected)- );- assert_eq!(service.preflight(&owner).await.unwrap(), None);- *provider.connection_error.lock().unwrap() = Some(Error::Network);- assert!(matches!(- service.preflight(&owner).await,- Err(HarnessError::Container(_))- ));- assert!(provider.calls.lock().unwrap().is_empty());- assert!(provider.preparations.lock().unwrap().is_empty());-}diff --git a/crates/agent_harness/src/domain/mod.rs b/crates/agent_harness/src/domain/mod.rsindex 31a42fc133..099852d95a 100644--- a/crates/agent_harness/src/domain/mod.rs+++ b/crates/agent_harness/src/domain/mod.rs@@ -26,9 +26,6 @@ pub mod trigger_router;/// Per-owner hosted Codex runtime authorization.pub mod codex;-/// Owner-bound Claude conversation lifecycle.-pub mod claude;-/// Compatible agent model discovery.pub mod model_load;/// Admitted model-backed repository choice, with deterministic paths kept free.diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex 851c7f65a9..4f73204a13 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -108,9 +108,8 @@ pub struct OpenSession {/// session so resume and teardown keep routing correctly after a restart.////// A session's instructions are stored on its row whichever kind serves it.-/// [`Self::InMemory`] builds its system prompt from them in this process and-/// [`Self::ClaudeCloud`] passes them to Claude at create; every other kind-/// talks ACP or a prompt-only API, neither of which has a system prompt, so+/// [`Self::InMemory`] builds its system prompt from them in this process; every other+/// kind talks ACP or a prompt-only API, neither of which has a system prompt, so/// they ride in the first prompt's hidden agent-context node instead. See/// [`Self::folds_instructions`].#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]@@ -122,8 +121,6 @@ pub enum AgentKind {Cursor,/// A per-owner Codex cloud conversation served over ACP.CodexCloud,- /// Anthropic-hosted Claude Code using the session owner's subscription.- ClaudeCloud,/// The in-process (in-memory) Macro agent bot, served by `agent_inmem`.InMemory,/// The bot's operator hosts the runtime and dials the gateway; no@@ -141,8 +138,6 @@ impl AgentKind {Self::Cursor} else if bot == bot_id::CODEX_BOT_ID {Self::CodexCloud- } else if bot == bot_id::CLAUDE_BOT_ID {- Self::ClaudeCloud} else if bot == bot_id::MACRO_NEW_BOT_ID {Self::InMemory} else {@@ -156,7 +151,6 @@ impl AgentKind {match harness {"cursor" => Self::Cursor,"codex-cloud" => Self::CodexCloud,- "claude-cloud" => Self::ClaudeCloud,"in-memory" | "macro-inmem" => Self::InMemory,// Registered macrod harnesses are the deliberate external case:// the agent's `harness_id` names whose daemon serves it.@@ -177,7 +171,7 @@ impl AgentKind {/// Fixed harness slug for kinds that map one-to-one onto one.///- /// Inverse of [`Self::from_harness`] for Cursor, Codex, and Claude — a+ /// Inverse of [`Self::from_harness`] for Cursor and Codex — a/// session of those bots is always stored under that slug, even when the/// open path fell through to a deployment default (`opencode`). The/// sandboxed coder's slug is deployment configuration, in-memory accepts@@ -188,7 +182,6 @@ impl AgentKind {match self {Self::Cursor => Some("cursor"),Self::CodexCloud => Some("codex-cloud"),- Self::ClaudeCloud => Some("claude-cloud"),Self::SandboxedCoder | Self::InMemory | Self::External => None,}}@@ -197,7 +190,7 @@ impl AgentKind {/// whose runtime has no system prompt to put them in.#[must_use]pub const fn folds_instructions(self) -> bool {- !matches!(self, Self::InMemory | Self::ClaudeCloud)+ !matches!(self, Self::InMemory)}/// Whether this kind's runtime starts on the session row's model by itself.@@ -205,7 +198,7 @@ impl AgentKind {/// first prompt.#[must_use]pub const fn starts_on_session_model(self) -> bool {- matches!(self, Self::InMemory | Self::Cursor | Self::ClaudeCloud)+ matches!(self, Self::InMemory | Self::Cursor)}/// Whether a deployment provisions this kind's runtimes itself.@@ -255,11 +248,9 @@ impl AgentKind {#[must_use]pub fn default_permission_policy(self) -> PermissionPolicy {match self {- Self::SandboxedCoder- | Self::Cursor- | Self::CodexCloud- | Self::ClaudeCloud- | Self::InMemory => PermissionPolicy::AutoAccept,+ Self::SandboxedCoder | Self::Cursor | Self::CodexCloud | Self::InMemory => {+ PermissionPolicy::AutoAccept+ }Self::External => PermissionPolicy::Prompt,}}@@ -706,8 +697,6 @@ pub enum SessionBlocker {CodexNotConnected,/// Codex is connected, but no cloud environment has been selected.CodexEnvironmentNotConfigured,- /// The mentioner has not connected their Claude account.- ClaudeNotConnected,}/// A mention that opened no session, and why. Posted back into the mention'sdiff --git a/crates/agent_harness/src/domain/model/test.rs b/crates/agent_harness/src/domain/model/test.rsindex ea5503cb01..338d0ac05c 100644--- a/crates/agent_harness/src/domain/model/test.rs+++ b/crates/agent_harness/src/domain/model/test.rs@@ -1,5 +1,5 @@use super::*;-use bot_id::{CLAUDE_BOT_ID, CODEX_BOT_ID, CURSOR_BOT_ID};+use bot_id::{CODEX_BOT_ID, CURSOR_BOT_ID};#[test]fn only_external_runtimes_prompt_by_default() {@@ -11,7 +11,6 @@ fn only_external_runtimes_prompt_by_default() {AgentKind::SandboxedCoder,AgentKind::Cursor,AgentKind::CodexCloud,- AgentKind::ClaudeCloud,AgentKind::InMemory,] {assert_eq!(@@ -42,7 +41,6 @@ fn builtin_runtimes_always_bypass_regardless_of_saved_agent_choice() {AgentKind::InMemory,AgentKind::Cursor,AgentKind::CodexCloud,- AgentKind::ClaudeCloud,AgentKind::SandboxedCoder,] {for auto_accept_permissions in [None, Some(false), Some(true)] {@@ -86,7 +84,6 @@ fn registered_harness_limit_wins_over_runtime_kind_and_persona_choice() {AgentKind::InMemory,AgentKind::Cursor,AgentKind::CodexCloud,- AgentKind::ClaudeCloud,AgentKind::SandboxedCoder,AgentKind::External,] {@@ -106,18 +103,13 @@ fn registered_harness_limit_wins_over_runtime_kind_and_persona_choice() {fn first_party_cloud_kinds_own_a_fixed_harness_slug() {assert_eq!(AgentKind::Cursor.harness_slug(), Some("cursor"));assert_eq!(AgentKind::CodexCloud.harness_slug(), Some("codex-cloud"));- assert_eq!(AgentKind::ClaudeCloud.harness_slug(), Some("claude-cloud"));assert_eq!(AgentKind::SandboxedCoder.harness_slug(), None);assert_eq!(AgentKind::InMemory.harness_slug(), None);assert_eq!(AgentKind::External.harness_slug(), None);// A create-path fallback that stamped the sandboxed-coder default is// corrected from the bot, not from the wrong slug it was handed.- for (bot, slug) in [- (CURSOR_BOT_ID, "cursor"),- (CODEX_BOT_ID, "codex-cloud"),- (CLAUDE_BOT_ID, "claude-cloud"),- ] {+ for (bot, slug) in [(CURSOR_BOT_ID, "cursor"), (CODEX_BOT_ID, "codex-cloud")] {assert_eq!(AgentKind::for_session(bot, "opencode").harness_slug(),Some(slug),@@ -153,7 +145,6 @@ fn only_the_in_memory_runtime_is_not_a_coder() {AgentKind::SandboxedCoder,AgentKind::Cursor,AgentKind::CodexCloud,- AgentKind::ClaudeCloud,AgentKind::External,] {assert!(coder.is_coding(), "{coder:?} has a repository to work in");diff --git a/crates/agent_harness/src/domain/model_load.rs b/crates/agent_harness/src/domain/model_load.rsindex 4959a9ccfb..b323372d56 100644--- a/crates/agent_harness/src/domain/model_load.rs+++ b/crates/agent_harness/src/domain/model_load.rs@@ -19,8 +19,6 @@ pub enum ModelHarness {InMemory,/// The caller's Cursor account.Cursor,- /// The caller's allowlisted Claude subscription demo.- ClaudeCloud,/// A paired macrod runtime.Macrod,}@@ -147,15 +145,6 @@ pub trait CursorModelProbe: Send + Sync + 'static {) -> impl Future<Output = Result<RawModelProbe, ModelProbeError>> + Send;}-/// Optional demo provider; disabled deployments advertise no Claude models.-pub trait ClaudeModelProbe: Send + Sync + 'static {- /// Discover availability for this caller, never another user's subscription.- fn probe<'a>(- &'a self,- caller: &'a MacroUserIdStr<'static>,- ) -> std::pin::Pin<Box<dyn Future<Output = Result<RawModelProbe, ModelProbeError>> + Send + 'a>>;-}-/// Fresh paired-macrod model probe.pub trait MacrodModelProbe: Send + Sync + 'static {/// Probe the live runtime connection for `harness`.@@ -182,7 +171,6 @@ pub struct AgentModelsServiceImpl<Access, InMemory, Cursor, Macrod> {cursor: Cursor,macrod: Macrod,timeout: Duration,- claude: Option<std::sync::Arc<dyn ClaudeModelProbe>>,}impl<Access, InMemory, Cursor, Macrod> AgentModelsServiceImpl<Access, InMemory, Cursor, Macrod> {@@ -200,15 +188,8 @@ impl<Access, InMemory, Cursor, Macrod> AgentModelsServiceImpl<Access, InMemory,cursor,macrod,timeout,- claude: None,}}-- /// Enable owner-scoped discovery for the demo cloud provider.- pub fn with_claude(mut self, probe: std::sync::Arc<dyn ClaudeModelProbe>) -> Self {- self.claude = Some(probe);- self- }}impl<Access, InMemory, Cursor, Macrod> AgentModelsService@@ -225,12 +206,6 @@ whererequest: LoadAgentModels,) -> Result<AgentModels, LoadAgentModelsError> {let probe = match (request.harness, request.harness_id) {- (ModelHarness::ClaudeCloud, None) => match &self.claude {- Some(probe) => tokio::time::timeout(self.timeout, probe.probe(&caller))- .await- .map_err(|_| LoadAgentModelsError::Timeout)?,- None => Ok(RawModelProbe::Unsupported),- },(ModelHarness::InMemory, None) => {tokio::time::timeout(self.timeout, self.in_memory.probe(&caller)).awaitdiff --git a/crates/agent_harness/src/domain/model_load/test.rs b/crates/agent_harness/src/domain/model_load/test.rsindex e076462ec2..71d65b2813 100644--- a/crates/agent_harness/src/domain/model_load/test.rs+++ b/crates/agent_harness/src/domain/model_load/test.rs@@ -11,29 +11,6 @@ fn caller() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from_email("[email protected]").unwrap()}-#[tokio::test]-async fn claude_is_unavailable_unless_explicitly_configured() {- let service = AgentModelsServiceImpl::new(- Access(true),- Probe::new(unsupported),- Probe::new(unsupported),- Probe::new(unsupported),- Duration::from_secs(1),- );- let result = service- .load(- caller(),- LoadAgentModels {- harness: ModelHarness::ClaudeCloud,- harness_id: None,- },- )- .await- .unwrap();- assert_eq!(result.status, AgentModelsStatus::Unsupported);- assert!(result.models.is_empty());-}-fn options() -> Vec<SessionConfigOption> {vec![SessionConfigOption::select("model",@@ -96,64 +73,6 @@ impl CursorModelProbe for Probe {}}-impl ClaudeModelProbe for Probe {- fn probe<'a>(- &'a self,- _caller: &'a MacroUserIdStr<'static>,- ) -> std::pin::Pin<Box<dyn Future<Output = Result<RawModelProbe, ModelProbeError>> + Send + 'a>>- {- Box::pin(async move {- self.calls.fetch_add(1, Ordering::Relaxed);- (self.result)()- })- }-}--#[tokio::test]-async fn claude_models_are_never_returned_for_in_memory() {- let claude = std::sync::Arc::new(Probe::new(|| {- Ok(RawModelProbe::Options(vec![SessionConfigOption::select(- "model",- "Model",- SessionConfigValueId::new("claude-fable-5-1"),- vec![SessionConfigSelectOption::new(- "claude-fable-5-1",- "Fable 5.1",- )],- )]))- }));- let service = AgentModelsServiceImpl::new(- Access(true),- Probe::new(available),- Probe::new(unsupported),- Probe::new(unsupported),- Duration::from_secs(1),- )- .with_claude(claude.clone());-- for (harness, expected) in [- (ModelHarness::ClaudeCloud, "claude-fable-5-1"),- (ModelHarness::InMemory, "fast"),- ] {- let result = service- .load(- caller(),- LoadAgentModels {- harness,- harness_id: None,- },- )- .await- .unwrap();- assert_eq!(result.status, AgentModelsStatus::Available);- assert_eq!(result.models.len(), 1);- assert_eq!(result.models[0].id, expected);- }- assert_eq!(claude.calls(), 1);- assert_eq!(service.in_memory.calls(), 1);- assert_eq!(*service.in_memory.callers.lock().unwrap(), vec![caller()]);-}-impl MacrodModelProbe for Probe {async fn probe(&self, _harness: HarnessId) -> Result<RawModelProbe, ModelProbeError> {self.calls.fetch_add(1, Ordering::Relaxed);diff --git a/crates/agent_harness/src/domain/service/admission.rs b/crates/agent_harness/src/domain/service/admission.rsindex 431a450460..f71a6253b1 100644--- a/crates/agent_harness/src/domain/service/admission.rs+++ b/crates/agent_harness/src/domain/service/admission.rs@@ -189,9 +189,6 @@ fn macro_funded(kind: AgentKind) -> bool {AgentKind::InMemory | AgentKind::SandboxedCoder => true,// Independently billed tools/helpers have their own admission; runtime// execution itself uses the owner's subscription or external provider.- AgentKind::Cursor- | AgentKind::CodexCloud- | AgentKind::ClaudeCloud- | AgentKind::External => false,+ AgentKind::Cursor | AgentKind::CodexCloud | AgentKind::External => false,}}diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rsindex 7435f19896..673fe4e8b7 100644--- a/crates/agent_harness/src/domain/service/queue.rs+++ b/crates/agent_harness/src/domain/service/queue.rs@@ -426,14 +426,6 @@ whereif session.is_archived {return Err(AgentSessionError::Archived(session_id).into());}- if AgentKind::for_session(session.bot_id, &session.harness)- == AgentKind::ClaudeCloud- && !actor- .as_ref()- .is_some_and(|actor| session.owner_id.is_user(actor))- {- return Err(AgentSessionError::Forbidden.into());- }if AgentKind::of(session.bot_id) == AgentKind::SandboxedCoder&& !actor.as_ref().is_some_and(is_macro_staff){diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 3cab8120b5..b346f62a32 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -892,57 +892,6 @@ async fn open_creates_announces_and_delivers_the_mention() {);}-#[tokio::test]-async fn claude_cloud_only_accepts_control_from_the_subscription_owner() {- let (service, _repo, containers, _announcer, _runtimes) = harness();- let mut command = open_command();- command.runtime.kind = AgentKind::ClaudeCloud;- command.runtime.harness = "claude-cloud".into();- let owner = command.origin.actor().clone();- let id = AgentSessionId::new();- let open = service.execute(id, HarnessCommand::Open(command));- let drive = async {- while containers.spawned() == 0 {- tokio::task::yield_now().await;- }- let container = containers.container(id).unwrap();- complete_handshake(&container).await;- };- let (opened, ()) = tokio::join!(open, drive);- opened.unwrap();- for actor in [None, Some(staff_sender())] {- let error = service- .control_event(- id,- ControlEvent {- action: AgentAction::prompt("spend another user's subscription"),- action_id: None,- actor,- context: None,- },- )- .await- .unwrap_err();- assert!(matches!(error, AgentSessionError::Forbidden));- }- // A non-turn control exercises the same owner gate without opening another turn.- let owner_action = service.control_event(- id,- ControlEvent {- action: AgentAction::prompt("owner follow-up"),- action_id: None,- actor: Some(owner),- context: None,- },- );- let drive = async {- let container = containers.container(id).unwrap();- container.agent().completes_prompt().await;- };- let (accepted, ()) = tokio::join!(owner_action, drive);- accepted.unwrap();-}-/// The agent's MCP selection is snapshotted onto the session row at open, so/// the proxy enforces exactly what this attach advertised for as long as the/// session lives, whatever the agent is edited to later.@@ -1153,12 +1102,6 @@ async fn a_mention_its_sender_is_not_set_up_for_is_declined_in_the_thread() {"codex-cloud",SessionBlocker::CodexEnvironmentNotConfigured,),- (- bot_id::CLAUDE_BOT_ID,- AgentKind::ClaudeCloud,- "claude-cloud",- SessionBlocker::ClaudeNotConnected,- ),] {let (service, repo, containers, announcer, _runtimes) = harness();let id = AgentSessionId::new();diff --git a/crates/agent_harness/src/domain/service/test/quota.rs b/crates/agent_harness/src/domain/service/test/quota.rsindex 84c25f8704..c847af427f 100644--- a/crates/agent_harness/src/domain/service/test/quota.rs+++ b/crates/agent_harness/src/domain/service/test/quota.rs@@ -224,7 +224,7 @@ async fn spending_actions_charge_the_persisted_owner_not_the_actor() {#[tokio::test]async fn externally_funded_runtimes_accept_spending_actions_without_quota_io() {- for harness in ["cursor", "codex-cloud", "claude-cloud", "macrod", "custom"] {+ for harness in ["cursor", "codex-cloud", "macrod", "custom"] {let (service, repo, admission) = bench(Some(denied()));let id = session(&repo, BotId::TEST_A, harness, Owner::User(staff_sender())).await;service.inner.busy.admit(id);diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rsindex 1e28a5c512..d7b5fdb740 100644--- a/crates/agent_harness/src/inbound/kafka/test.rs+++ b/crates/agent_harness/src/inbound/kafka/test.rs@@ -41,7 +41,6 @@ fn runtime(kind: AgentKind) -> Option<AgentRuntimeConfig> {harness: match kind {AgentKind::Cursor => "cursor",AgentKind::CodexCloud => "codex-cloud",- AgentKind::ClaudeCloud => "claude-cloud",AgentKind::InMemory => "in-memory",AgentKind::SandboxedCoder => "opencode",AgentKind::External => "byoa",diff --git a/crates/agent_harness/src/inbound/model_load.rs b/crates/agent_harness/src/inbound/model_load.rsindex f6662d2239..85cb050ea1 100644--- a/crates/agent_harness/src/inbound/model_load.rs+++ b/crates/agent_harness/src/inbound/model_load.rs@@ -41,8 +41,6 @@ pub enum ModelHarnessDto {InMemory,/// The caller's Cursor account.Cursor,- /// The caller's allowlisted Claude subscription demo.- ClaudeCloud,/// A paired macrod runtime.Macrod,}@@ -54,7 +52,6 @@ impl TryFrom<LoadAgentModelsRequest> for LoadAgentModels {let harness = match value.harness {ModelHarnessDto::InMemory => ModelHarness::InMemory,ModelHarnessDto::Cursor => ModelHarness::Cursor,- ModelHarnessDto::ClaudeCloud => ModelHarness::ClaudeCloud,ModelHarnessDto::Macrod => ModelHarness::Macrod,};Ok(Self {diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rsindex c98523c70e..86645d1ac3 100644--- a/crates/agent_harness/src/outbound/channel_announcer.rs+++ b/crates/agent_harness/src/outbound/channel_announcer.rs@@ -251,12 +251,6 @@ fn connection_prompt(blocker: SessionBlocker) -> AgentConnectionPrompt {"codex-cloud","Codex",),- SessionBlocker::ClaudeNotConnected => (- "@claude",- "runs on your own Claude account. Connect Claude, then mention me again.",- "claude-cloud",- "Claude",- ),};AgentConnectionPrompt {agent_tag: agent_tag.to_owned(),diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rsindex 97e8792c6f..0e75590912 100644--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs@@ -57,7 +57,6 @@ fn declined_mentions_target_their_harness_settings() {"codex-cloud","Codex",),- (SessionBlocker::ClaudeNotConnected, "claude-cloud", "Claude"),] {let prompt = connection_prompt(blocker);assert_eq!(diff --git a/crates/agent_harness/src/outbound/claude.rs b/crates/agent_harness/src/outbound/claude.rsdeleted file mode 100644index d6e33b3e8e..0000000000--- a/crates/agent_harness/src/outbound/claude.rs+++ /dev/null@@ -1,134 +0,0 @@-//! Claude implementations of the shared container and model-discovery ports.-use crate::domain::{- claude::ClaudeSessions,- error::{HarnessError, Result},- model::{AgentKind, SessionBlocker, SpawnContainer},- model_load::{ClaudeModelProbe, ModelProbeError, RawModelProbe},- ports::{ContainerManager, SandboxEgressProvisioner},- sandbox::SandboxResizeEffect,-};-use agent_runtime_protocol::domain::connection::ServerChannel;-use agent_session::domain::{- connection::RuntimeAttachment,- model::{AgentSessionId, SandboxSize},- ports::{AgentSessionRepo, ExternalSessionRepo},-};-use claude_cloud_agents::domain::{model::Error, ports::CloudProvider, service::Session};-use macro_user_id::user_id::MacroUserIdStr;-use std::sync::Arc;--/// Adapts the Claude lifecycle service to the same provisioning port as other providers.-pub struct ClaudeContainerManager<P, Repo, External, Egress, Attach> {- sessions: ClaudeSessions<P, Repo, External>,- egress: Egress,- attach: Attach,- tokens: tokio::sync::RwLock<std::collections::HashMap<AgentSessionId, String>>,-}--impl<P, Repo, External, Egress, Attach> ClaudeContainerManager<P, Repo, External, Egress, Attach> {- /// Supply the ACP adapter from the composition root, keeping adapter imports local.- pub fn new(- sessions: ClaudeSessions<P, Repo, External>,- egress: Egress,- attach: Attach,- ) -> Self {- Self {- sessions,- egress,- attach,- tokens: Default::default(),- }- }-}--impl<P, Repo, External, Egress, Attach> ContainerManager- for ClaudeContainerManager<P, Repo, External, Egress, Attach>-where- P: CloudProvider,- Repo: AgentSessionRepo,- External: ExternalSessionRepo,- Egress: SandboxEgressProvisioner,- Attach: Fn(Arc<Session<P::Client>>) -> ServerChannel + Send + Sync + 'static,-{- type Transport = ServerChannel;-- async fn preflight(- &self,- _kind: AgentKind,- owner: &MacroUserIdStr<'_>,- ) -> Result<Option<SessionBlocker>> {- self.sessions.preflight(owner).await- }-- async fn spawn(&self, command: SpawnContainer) -> Result<RuntimeAttachment<ServerChannel>> {- let session = self.sessions.attach(command.session_id).await?;- self.tokens- .write()- .await- .insert(command.session_id, command.egress.session_token);- Ok(RuntimeAttachment::solo((self.attach)(session)))- }-- async fn resume(&self, id: AgentSessionId) -> Result<RuntimeAttachment<ServerChannel>> {- let session = self.sessions.attach(id).await?;- let token = self.sessions.refresh_egress(id, &self.egress).await?;- self.tokens.write().await.insert(id, token);- Ok(RuntimeAttachment::solo((self.attach)(session)))- }-- async fn session_token(&self, id: AgentSessionId) -> Result<Option<String>> {- Ok(self.tokens.read().await.get(&id).cloned())- }-- async fn teardown(&self, id: AgentSessionId) -> Result<()> {- self.sessions.archive(id).await?;- self.tokens.write().await.remove(&id);- Ok(())- }-- fn resize_effect(&self, _: SandboxSize, _: SandboxSize) -> SandboxResizeEffect {- SandboxResizeEffect::Unsupported- }-- async fn resize(&self, _: AgentSessionId, _: SandboxSize) -> Result<()> {- Err(HarnessError::Container(- "Claude manages its own cloud compute".into(),- ))- }-}--/// Read-only discovery through the same account-bound provider as execution.-pub struct ClaudeModels<P>(pub Arc<P>);--impl<P: CloudProvider> ClaudeModelProbe for ClaudeModels<P> {- fn probe<'a>(- &'a self,- caller: &'a macro_user_id::user_id::MacroUserIdStr<'static>,- ) -> std::pin::Pin<- Box<- dyn std::future::Future<Output = std::result::Result<RawModelProbe, ModelProbeError>>- + Send- + 'a,- >,- > {- Box::pin(async move {- let client = match self.0.connect(caller.as_ref()).await {- Ok(client) => client,- Err(Error::NotConnected) => return Ok(RawModelProbe::Unsupported),- Err(error) => return Err(ModelProbeError::Failed(error.to_string())),- };- let catalog = claude_cloud_agents::domain::models::discover(&client)- .await- .map_err(|error| ModelProbeError::Failed(error.to_string()))?;- let options: Vec<_> = catalog.options().iter().map(|option| serde_json::json!({- "value": option.model.id(), "name": option.name, "description": option.description- })).collect();- let options = serde_json::from_value(serde_json::json!([{- "id":"model", "name":"Model", "category":"model", "type":"select",- "currentValue":"claude-default", "options": options- }]))- .map_err(|_| ModelProbeError::Failed("Invalid Claude model configuration".into()))?;- Ok(RawModelProbe::Options(options))- })- }-}diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rsindex 7e25d12f75..7c4125903d 100644--- a/crates/agent_harness/src/outbound/mod.rs+++ b/crates/agent_harness/src/outbound/mod.rs@@ -30,6 +30,3 @@ pub mod tool_approvals;pub mod acp_pipe;/// Per-owner Codex cloud runtime.pub mod codex;--/// Claude cloud container and model adapters.-pub mod claude;diff --git a/crates/agent_harness/src/outbound/routing.rs b/crates/agent_harness/src/outbound/routing.rsindex ee90cac047..0e0630c4f0 100644--- a/crates/agent_harness/src/outbound/routing.rs+++ b/crates/agent_harness/src/outbound/routing.rs@@ -29,46 +29,34 @@ mod test;/// Dispatches each session to the provider its bot is served by.#[derive(Clone)]-pub struct RoutedContainerManager<Sandbox, Cursor, Codex, Claude, Sessions> {+pub struct RoutedContainerManager<Sandbox, Cursor, Codex, Sessions> {sandbox: Sandbox,cursor: Cursor,codex: Codex,- claude: Claude,sessions: Sessions,}-impl<Sandbox, Cursor, Codex, Claude, Sessions>- RoutedContainerManager<Sandbox, Cursor, Codex, Claude, Sessions>-{+impl<Sandbox, Cursor, Codex, Sessions> RoutedContainerManager<Sandbox, Cursor, Codex, Sessions> {/// Wire the router over its providers.- pub fn new(- sandbox: Sandbox,- cursor: Cursor,- codex: Codex,- claude: Claude,- sessions: Sessions,- ) -> Self {+ pub fn new(sandbox: Sandbox, cursor: Cursor, codex: Codex, sessions: Sessions) -> Self {Self {sandbox,cursor,codex,- claude,sessions,}}}-impl<Sandbox, Cursor, Codex, Claude, Sessions> ContainerManager- for RoutedContainerManager<Sandbox, Cursor, Codex, Claude, Sessions>+impl<Sandbox, Cursor, Codex, Sessions> ContainerManager+ for RoutedContainerManager<Sandbox, Cursor, Codex, Sessions>whereSandbox: ContainerManager,Cursor: ContainerManager,Codex: ContainerManager,- Claude: ContainerManager,Sessions: AgentSessionRepo + Clone,{- type Transport =- RoutedTransport<Sandbox::Transport, Cursor::Transport, Codex::Transport, Claude::Transport>;+ type Transport = RoutedTransport<Sandbox::Transport, Cursor::Transport, Codex::Transport>;async fn preflight(&self,@@ -77,7 +65,6 @@ where) -> Result<Option<SessionBlocker>> {match kind {AgentKind::CodexCloud => self.codex.preflight(kind, owner).await,- AgentKind::ClaudeCloud => self.claude.preflight(kind, owner).await,AgentKind::Cursor => self.cursor.preflight(kind, owner).await,AgentKind::SandboxedCoder | AgentKind::InMemory => {self.sandbox.preflight(kind, owner).await@@ -96,11 +83,6 @@ where.spawn(command).await?.map_transport(RoutedTransport::Codex)),- AgentKind::ClaudeCloud => Ok(self- .claude- .spawn(command)- .await?- .map_transport(RoutedTransport::Claude)),AgentKind::Cursor => Ok(self.cursor.spawn(command)@@ -126,11 +108,6 @@ where.resume(session).await?.map_transport(RoutedTransport::Codex)),- AgentKind::ClaudeCloud => Ok(self- .claude- .resume(session)- .await?- .map_transport(RoutedTransport::Claude)),AgentKind::Cursor => Ok(self.cursor.resume(session)@@ -149,7 +126,6 @@ wherelet row = self.sessions.get(session).await?;match AgentKind::for_session(row.bot_id, &row.harness) {AgentKind::CodexCloud => self.codex.session_token(session).await,- AgentKind::ClaudeCloud => self.claude.session_token(session).await,AgentKind::Cursor => self.cursor.session_token(session).await,AgentKind::SandboxedCoder | AgentKind::InMemory => {self.sandbox.session_token(session).await@@ -162,7 +138,6 @@ wherelet row = self.sessions.get(session).await?;match AgentKind::for_session(row.bot_id, &row.harness) {AgentKind::CodexCloud => self.codex.teardown(session).await,- AgentKind::ClaudeCloud => self.claude.teardown(session).await,AgentKind::Cursor => self.cursor.teardown(session).await,AgentKind::SandboxedCoder | AgentKind::InMemory => self.sandbox.teardown(session).await,AgentKind::External => Err(external_is_unroutable()),@@ -183,7 +158,6 @@ whereAgentKind::CodexCloud => Err(HarnessError::Container("a codex session has no sandbox to resize".to_owned(),)),- AgentKind::ClaudeCloud => self.claude.resize(session, size).await,AgentKind::Cursor => Err(HarnessError::Container("a cursor session has no sandbox to resize".to_owned(),)),@@ -206,52 +180,44 @@ fn external_is_unroutable() -> HarnessError {}/// A transport that is one provider's or the other's, decided per session.-pub enum RoutedTransport<Sandbox, Cursor, Codex, Claude> {+pub enum RoutedTransport<Sandbox, Cursor, Codex> {/// A sandbox-provider transport.Sandbox(Sandbox),/// A Cursor-provider transport.Cursor(Cursor),/// A Codex cloud provider transport half.Codex(Codex),- /// A Claude cloud provider transport half.- Claude(Claude),}/// The sending half of a [`RoutedTransport`].-pub enum RoutedSender<Sandbox, Cursor, Codex, Claude> {+pub enum RoutedSender<Sandbox, Cursor, Codex> {/// A sandbox-provider sender.Sandbox(Sandbox),/// A Cursor-provider sender.Cursor(Cursor),/// A Codex cloud provider transport half.Codex(Codex),- /// A Claude cloud provider transport half.- Claude(Claude),}/// The receiving half of a [`RoutedTransport`].-pub enum RoutedReceiver<Sandbox, Cursor, Codex, Claude> {+pub enum RoutedReceiver<Sandbox, Cursor, Codex> {/// A sandbox-provider receiver.Sandbox(Sandbox),/// A Cursor-provider receiver.Cursor(Cursor),/// A Codex cloud provider transport half.Codex(Codex),- /// A Claude cloud provider transport half.- Claude(Claude),}-impl<Sandbox, Cursor, Codex, Claude> Transport<ToRuntimeMessage, ToServerMessage>- for RoutedTransport<Sandbox, Cursor, Codex, Claude>+impl<Sandbox, Cursor, Codex> Transport<ToRuntimeMessage, ToServerMessage>+ for RoutedTransport<Sandbox, Cursor, Codex>whereSandbox: Transport<ToRuntimeMessage, ToServerMessage>,Cursor: Transport<ToRuntimeMessage, ToServerMessage>,Codex: Transport<ToRuntimeMessage, ToServerMessage>,- Claude: Transport<ToRuntimeMessage, ToServerMessage>,{- type Sender = RoutedSender<Sandbox::Sender, Cursor::Sender, Codex::Sender, Claude::Sender>;- type Receiver =- RoutedReceiver<Sandbox::Receiver, Cursor::Receiver, Codex::Receiver, Claude::Receiver>;+ type Sender = RoutedSender<Sandbox::Sender, Cursor::Sender, Codex::Sender>;+ type Receiver = RoutedReceiver<Sandbox::Receiver, Cursor::Receiver, Codex::Receiver>;fn split(self) -> (Self::Sender, Self::Receiver) {match self {@@ -266,13 +232,6 @@ wherelet (sender, receiver) = transport.split();(RoutedSender::Codex(sender), RoutedReceiver::Codex(receiver))}- Self::Claude(transport) => {- let (sender, receiver) = transport.split();- (- RoutedSender::Claude(sender),- RoutedReceiver::Claude(receiver),- )- }Self::Cursor(transport) => {let (sender, receiver) = transport.split();(@@ -284,38 +243,34 @@ where}}-impl<Sandbox, Cursor, Codex, Claude> TransportSender<ToRuntimeMessage>- for RoutedSender<Sandbox, Cursor, Codex, Claude>+impl<Sandbox, Cursor, Codex> TransportSender<ToRuntimeMessage>+ for RoutedSender<Sandbox, Cursor, Codex>whereSandbox: TransportSender<ToRuntimeMessage>,Cursor: TransportSender<ToRuntimeMessage>,Codex: TransportSender<ToRuntimeMessage>,- Claude: TransportSender<ToRuntimeMessage>,{async fn send(&self, message: ToRuntimeMessage) -> std::result::Result<(), TransportError> {match self {Self::Sandbox(sender) => sender.send(message).await,Self::Cursor(sender) => sender.send(message).await,Self::Codex(sender) => sender.send(message).await,- Self::Claude(sender) => sender.send(message).await,}}}-impl<Sandbox, Cursor, Codex, Claude> TransportReceiver<ToServerMessage>- for RoutedReceiver<Sandbox, Cursor, Codex, Claude>+impl<Sandbox, Cursor, Codex> TransportReceiver<ToServerMessage>+ for RoutedReceiver<Sandbox, Cursor, Codex>whereSandbox: TransportReceiver<ToServerMessage>,Cursor: TransportReceiver<ToServerMessage>,Codex: TransportReceiver<ToServerMessage>,- Claude: TransportReceiver<ToServerMessage>,{async fn recv(&mut self) -> std::result::Result<Option<ToServerMessage>, TransportError> {match self {Self::Sandbox(receiver) => receiver.recv().await,Self::Cursor(receiver) => receiver.recv().await,Self::Codex(receiver) => receiver.recv().await,- Self::Claude(receiver) => receiver.recv().await,}}}diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rsindex c1d023d79b..4f02d09efb 100644--- a/crates/agent_harness/src/outbound/routing/test.rs+++ b/crates/agent_harness/src/outbound/routing/test.rs@@ -109,13 +109,6 @@ impl ContainerManager for TaggedManager {#[derive(Clone)]struct FixedBotSessions(BotId);-const CLAUDE_TEST_BOT: BotId = BotId::TEST_B;--#[test]-fn first_party_claude_routes_to_the_claude_provider() {- assert_eq!(AgentKind::of(bot_id::CLAUDE_BOT_ID), AgentKind::ClaudeCloud);-}-impl AgentSessionRepo for FixedBotSessions {async fn create(&self, _params: CreateAgentSessionParams) -> SessionResult<AgentSession> {unimplemented!("the router never creates sessions")@@ -155,12 +148,7 @@ impl AgentSessionRepo for FixedBotSessions {originating_message_id: None,bot_id: self.0,model: "auto".to_owned(),- harness: if self.0 == CLAUDE_TEST_BOT {- "claude-cloud"- } else {- "cursor"- }- .to_owned(),+ harness: "cursor".to_owned(),repo_url: None,workspace: "/workspace".to_owned(),name: DEFAULT_AGENT_SESSION_NAME.to_owned(),@@ -329,7 +317,6 @@ async fn the_cursor_bot_routes_to_cursor_and_everything_else_to_the_sandbox() {sandbox.clone(),cursor.clone(),TaggedManager::new("codex"),- TaggedManager::new("claude"),FixedBotSessions(bot_id::CURSOR_BOT_ID),);@@ -354,12 +341,10 @@ async fn preflight_routes_by_kind_before_any_session_exists() {let sandbox = TaggedManager::new("sandbox");let cursor = TaggedManager::new("cursor");let codex = TaggedManager::new("codex");- let claude = TaggedManager::new("claude");let router = RoutedContainerManager::new(sandbox.clone(),cursor.clone(),codex.clone(),- claude.clone(),FixedBotSessions(bot_id::CURSOR_BOT_ID),);let owner = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");@@ -379,18 +364,10 @@ async fn preflight_routes_by_kind_before_any_session_exists() {.unwrap(),None);- assert_eq!(- router- .preflight(AgentKind::ClaudeCloud, &owner)- .await- .unwrap(),- None- );assert!(router.preflight(AgentKind::External, &owner).await.is_err());assert_eq!(cursor.calls(), ["cursor:preflight"]);assert_eq!(sandbox.calls(), ["sandbox:preflight"]);assert_eq!(codex.calls(), ["codex:preflight"]);- assert_eq!(claude.calls(), ["claude:preflight"]);}/// Resume and teardown route by the session row's bot — the repo says cursor@@ -403,7 +380,6 @@ async fn resume_and_teardown_route_by_the_stored_bot() {sandbox.clone(),cursor.clone(),TaggedManager::new("codex"),- TaggedManager::new("claude"),FixedBotSessions(bot_id::CURSOR_BOT_ID),);@@ -422,7 +398,6 @@ async fn a_database_backed_cursor_agent_routes_by_its_stored_harness() {sandbox.clone(),cursor.clone(),TaggedManager::new("codex"),- TaggedManager::new("claude"),FixedBotSessions(BotId::TEST_A),);@@ -446,7 +421,6 @@ async fn codex_routes_all_lifecycle_operations_and_rejects_resize() {sandbox.clone(),cursor.clone(),codex.clone(),- TaggedManager::new("claude"),FixedBotSessions(bot_id::CODEX_BOT_ID),);router@@ -475,39 +449,3 @@ async fn codex_routes_all_lifecycle_operations_and_rejects_resize() {AgentKind::CodexCloud);}--#[tokio::test]-async fn claude_routes_by_harness_through_the_shared_provider_router() {- let sandbox = TaggedManager::new("sandbox");- let cursor = TaggedManager::new("cursor");- let codex = TaggedManager::new("codex");- let claude = TaggedManager::new("claude");- let router = RoutedContainerManager::new(- sandbox.clone(),- cursor.clone(),- codex.clone(),- claude.clone(),- FixedBotSessions(CLAUDE_TEST_BOT),- );- router- .spawn(spawn_for(AgentKind::ClaudeCloud))- .await- .unwrap()- .map_transport(|transport| assert!(matches!(transport, RoutedTransport::Claude(_))));- let session = AgentSessionId::new();- router.resume(session).await.unwrap();- router.session_token(session).await.unwrap();- router.teardown(session).await.unwrap();- assert_eq!(- claude.calls(),- [- "claude:spawn",- "claude:resume",- "claude:session_token",- "claude:teardown"- ]- );- assert!(sandbox.calls().is_empty());- assert!(cursor.calls().is_empty());- assert!(codex.calls().is_empty());-}diff --git a/crates/agent_runtime_protocol/AGENTS.md b/crates/agent_runtime_protocol/AGENTS.mdindex 3561292153..aef8d072af 100644--- a/crates/agent_runtime_protocol/AGENTS.md+++ b/crates/agent_runtime_protocol/AGENTS.md@@ -33,7 +33,7 @@ payloads.- Depends on: nothing crate-specific (foundational protocol crate).- Used by: `agent_session`, `agent_session_realtime`, `agent_harness`,`agent_egress`, `agent_inmem`, `webhook`, `complete_graph`, and the- Cursor/Codex/Claude cloud-agent adapter crates.+ Cursor/Codex cloud-agent adapter crates.## Recipesdiff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 66cf222981..2c4eca6ae3 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -372,25 +372,6 @@ pub struct ExternalSession {pub last_run_id: Option<String>,}-impl ExternalSession {- /// Provider link, including Claude demo mappings created before URLs were saved.- pub fn web_url(&self) -> Option<String> {- self.external_url.clone().or_else(|| {- (self.provider == "claude-cloud"- && self.external_id.starts_with("cse_")- && self.external_id.len() > 4- && self- .external_id- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b == b'_'))- .then(|| format!("https://claude.ai/code/{}", self.external_id))- })- }-}--#[cfg(test)]-mod test;-/// The agent behind a session, as much of it as rendering a message needs.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]diff --git a/crates/agent_session/src/domain/model/test.rs b/crates/agent_session/src/domain/model/test.rsdeleted file mode 100644index 2a9b33d723..0000000000--- a/crates/agent_session/src/domain/model/test.rs+++ /dev/null@@ -1,25 +0,0 @@-use super::*;--#[test]-fn legacy_claude_links_are_derived_without_changing_other_providers() {- let mut external = ExternalSession {- provider: "claude-cloud".into(),- external_id: "cse_demo".into(),- external_name: None,- external_url: None,- last_run_id: None,- };- assert_eq!(- external.web_url().as_deref(),- Some("https://claude.ai/code/cse_demo")- );- external.external_id = "cse_x/../../other".into();- assert!(external.web_url().is_none());- external.provider = "claude-cloud-create-pending".into();- external.external_id = "cse_demo".into();- assert!(external.web_url().is_none());- external.provider = "cursor".into();- assert!(external.web_url().is_none());- external.external_url = Some("https://cursor.com/agents/bc-test".into());- assert_eq!(external.web_url(), external.external_url);-}diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex c36fcc57e6..34f625f05a 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -665,11 +665,10 @@ pub struct ExternalSessionResponse {impl From<ExternalSession> for ExternalSessionResponse {fn from(external: ExternalSession) -> Self {- let url = external.web_url();Self {provider: external.provider,name: external.external_name,- url,+ url: external.external_url,}}}diff --git a/crates/bot_id/src/lib.rs b/crates/bot_id/src/lib.rsindex dbe4f691ba..c65379ed5b 100644--- a/crates/bot_id/src/lib.rs+++ b/crates/bot_id/src/lib.rs@@ -124,13 +124,6 @@ pub const CODEX_HANDLE: &str = "codex";/// Display name for Codex.pub const CODEX_NAME: &str = "Codex";-/// Stable identity for the per-owner Claude cloud agent.-pub const CLAUDE_BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(0xc1a0));-/// Mention handle for Claude.-pub const CLAUDE_HANDLE: &str = "claude";-/// Display name for Claude.-pub const CLAUDE_NAME: &str = "Claude";-/// Stable handle for the autonomous Macro platform principal.pub const MACRO_SYSTEM_HANDLE: &str = "macro-system";@@ -190,12 +183,6 @@ pub const SYSTEM_BOTS: &[SystemBot] = &[handle: CODEX_HANDLE,has_agent: true,},- SystemBot {- id: CLAUDE_BOT_ID,- name: CLAUDE_NAME,- handle: CLAUDE_HANDLE,- has_agent: true,- },// Posts as itself for autonomous platform operations, but nothing mentions// it and it opens no sessions.SystemBot {diff --git a/crates/bot_id/src/test.rs b/crates/bot_id/src/test.rsindex ef2046d0ca..dddc890cac 100644--- a/crates/bot_id/src/test.rs+++ b/crates/bot_id/src/test.rs@@ -69,20 +69,6 @@ fn rejects_non_bot_storage_string() {assert!(BotIdStr::parse_from_str("macro|[email protected]").is_err());}-#[test]-fn claude_is_a_global_system_agent_with_a_distinct_identity() {- let claude = system_bot(CLAUDE_BOT_ID).unwrap();- assert_eq!(claude.handle, "claude");- assert_eq!(claude.name, "Claude");- assert!(claude.has_agent);- assert_eq!(- CLAUDE_BOT_ID.to_string(),- "00000000-0000-0000-0000-00000000c1a0"- );- let ids: std::collections::HashSet<_> = SYSTEM_BOTS.iter().map(|bot| bot.id).collect();- assert_eq!(ids.len(), SYSTEM_BOTS.len());-}-#[test]fn non_system_bot_id_rejects_every_system_bot() {for bot in SYSTEM_BOTS {diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rsindex c59b3e8cc2..70d32f33ec 100644--- a/crates/bots/src/domain/models.rs+++ b/crates/bots/src/domain/models.rs@@ -450,7 +450,7 @@ mod test;/// other is never a valid choice.#[derive(Debug, Clone, PartialEq, Eq)]pub struct AgentHarnessSelection {- /// Harness slug, e.g. `in-memory`, `cursor`, `claude-cloud`, or `macrod`.+ /// Harness slug, e.g. `in-memory`, `cursor`, or `macrod`.pub harness: String,/// Registered harness to run on. Required when `harness` is `macrod`,/// forbidden otherwise.diff --git a/crates/bots/src/inbound/toolset/configure_agent.rs b/crates/bots/src/inbound/toolset/configure_agent.rsindex 19f627a060..f57c0032c4 100644--- a/crates/bots/src/inbound/toolset/configure_agent.rs+++ b/crates/bots/src/inbound/toolset/configure_agent.rs@@ -30,9 +30,6 @@ pub enum AgentHarnessOption {/// A Cursor cloud agent on the session owner's Cursor account.#[serde(rename = "cursor")]Cursor,- /// Claude Code on the session owner's Claude account.- #[serde(rename = "claude-cloud")]- ClaudeCloud,/// A registered self-hosted harness; requires `harnessId`.#[serde(rename = "macrod")]Macrod,@@ -44,7 +41,6 @@ impl AgentHarnessOption {match self {Self::InMemory => "in-memory",Self::Cursor => "cursor",- Self::ClaudeCloud => "claude-cloud",Self::Macrod => harness_id::MACROD_HARNESS_SLUG,}}diff --git a/crates/bots/src/inbound/toolset/types.rs b/crates/bots/src/inbound/toolset/types.rsindex 3e2b4922ea..bc51435780 100644--- a/crates/bots/src/inbound/toolset/types.rs+++ b/crates/bots/src/inbound/toolset/types.rs@@ -139,7 +139,7 @@ pub struct AgentSummary {pub bot: BotSummary,/// Instructions the agent works under, whole. New sessions snapshot them.pub instructions: String,- /// Harness slug: `in-memory`, `cursor`, `claude-cloud`, or `macrod`.+ /// Harness slug: `in-memory`, `cursor`, or `macrod`.pub harness: String,/// Registered harness the agent runs on when `harness` is `macrod`.pub harness_id: Option<Uuid>,diff --git a/crates/claude_cloud_agents/AGENTS.md b/crates/claude_cloud_agents/AGENTS.mddeleted file mode 100644index 383cee2e1a..0000000000--- a/crates/claude_cloud_agents/AGENTS.md+++ /dev/null@@ -1,51 +0,0 @@-# claude_cloud_agents--## What it is--Part of agent sessions: a demo-only Claude Code cloud provider that runs-agent sessions against Anthropic's hosted Claude Code using user-subscription OAuth, via the Agent Client Protocol.--## Start here--- `src/domain/service.rs` + `src/domain/ports.rs`: provider-independent session- behavior and the ports a cloud agent provider must implement.-- `src/domain/auth.rs` + `src/outbound/oauth.rs`: owner-bound interactive OAuth flow.-- `src/inbound/acp.rs`: Agent Client Protocol adapter driving sessions.-- `src/domain/translate.rs`: translating between ACP and the hosted Claude API shape.-- `src/outbound/credentials.rs` + `src/outbound/postgres.rs`: credential storage.-- `examples/smoke.rs`: a runnable end-to-end smoke test of the flow.--## Scope--- Owns: the demo Claude Cloud provider — auth, MCP gateway access, and- ACP session translation for hosted Claude Code.-- Not here: other agent providers or the provider-agnostic harness →- `crates/agent_harness`.--## Boundaries--- Depends on: `agent-client-protocol`, `agent_runtime_protocol`, `cursor_api_key`,- `macro_authorization` (feature `axum`).-- Used by: `agent_harness`.--## Recipes--- Add a session capability: `src/domain/ports.rs` → `src/domain/service.rs` →- `src/inbound/acp.rs` → `src/domain/translate.rs` if the wire shape changes.--## Checks--- `cargo test -p claude_cloud_agents` (`SQLX_OFFLINE` unset).--## Gotchas--- Model discovery goes through the models API, not a hardcoded Fable/Claude- list (#6595) — don't reintroduce a hardcoded model set.-- The MCP gateway and hosted browser sign-in need explicit allowances in the- cloud environment; don't assume the same network access as local agents- (#6550, #6529).--## Related--- Rules: `.agents/rules/rust/architecture.md`diff --git a/crates/claude_cloud_agents/CLAUDE.md b/crates/claude_cloud_agents/CLAUDE.mddeleted file mode 120000index 47dc3e3d86..0000000000--- a/crates/claude_cloud_agents/CLAUDE.md+++ /dev/null@@ -1 +0,0 @@-AGENTS.md\ No newline at end of filediff --git a/crates/claude_cloud_agents/Cargo.toml b/crates/claude_cloud_agents/Cargo.tomldeleted file mode 100644index 9f19bbc806..0000000000--- a/crates/claude_cloud_agents/Cargo.toml+++ /dev/null@@ -1,34 +0,0 @@-[package]-name = "claude_cloud_agents"-version = "0.1.0"-edition = "2024"-publish = false--[dependencies]-agent-client-protocol = { workspace = true }-async-trait = { workspace = true }-sqlx = { workspace = true }-cursor_api_key = { path = "../cursor_api_key" }-axum = { workspace = true }-base64 = { workspace = true }-macro_authorization = { path = "../macro_authorization", features = ["axum"] }-rand = { workspace = true }-sha2 = { workspace = true }-subtle = { workspace = true }-utoipa = { workspace = true }-agent-runtime-protocol = { package = "agent_runtime_protocol", path = "../agent_runtime_protocol", default-features = false, features = ["transport"] }-futures = { workspace = true }-reqwest = { workspace = true, features = ["stream", "query"] }-serde = { workspace = true }-serde_json = { workspace = true }-sse-core = { workspace = true }-thiserror = { workspace = true }-tokio = { workspace = true, features = ["fs", "io-util", "sync", "time", "macros"] }-uuid = { workspace = true }-zeroize = { workspace = true }-workspace-hack = { version = "0.1", path = "../workspace-hack" }--[dev-dependencies]-macro_db_migrator = { path = "../macro_db_migrator" }-tempfile = { workspace = true }-clap = { workspace = true, features = ["derive"] }diff --git a/crates/claude_cloud_agents/examples/smoke.rs b/crates/claude_cloud_agents/examples/smoke.rsdeleted file mode 100644index a04c8d49f6..0000000000--- a/crates/claude_cloud_agents/examples/smoke.rs+++ /dev/null@@ -1,140 +0,0 @@-//! Explicit opt-in live smoke test. Credentials are read privately, never printed.-use agent_runtime_protocol::domain::{- connection::ServerChannel,- schema::v0::{AcpMessage, ToRuntimeMessage, ToServerMessage},-};-use clap::Parser;-use claude_cloud_agents::{- domain::{model::SessionId, models, service::Session},- inbound::acp,- outbound::{credentials::FileCredentials, http::Client},-};-use serde_json::{Value, json};--#[derive(Parser)]-struct Args {- #[arg(long)]- credentials: std::path::PathBuf,- #[arg(long)]- owner: String,- /// Existing cloud conversation. Omitting this creates one new conversation.- #[arg(long)]- session: Option<String>,- /// Discover choices without creating a session or spending inference.- #[arg(long)]- discover_only: bool,- /// Select a discovered model before sending the smoke prompt.- #[arg(long)]- model: Option<String>,-}--fn send(channel: &ServerChannel, value: Value) {- channel- .tx- .send(ToRuntimeMessage::Acp(AcpMessage(- serde_json::from_value(value).unwrap(),- )))- .unwrap();-}--async fn response(channel: &mut ServerChannel, id: u8) -> Value {- loop {- let message = tokio::time::timeout(std::time::Duration::from_secs(180), channel.rx.recv())- .await- .expect("cloud response timeout")- .expect("ACP connection closed");- if let ToServerMessage::Acp(AcpMessage(frame)) = message {- let frame = serde_json::to_value(frame).unwrap();- if frame["id"] == id {- return frame;- }- }- }-}--#[tokio::main(flavor = "current_thread")]-async fn main() -> Result<(), Box<dyn std::error::Error>> {- let args = Args::parse();- let credentials = FileCredentials::open(args.credentials).await?;- let client = Client::new(credentials, args.owner).await?;- if args.discover_only {- for option in models::discover(&client).await?.options() {- println!("{}: {}", option.model.id(), option.name);- }- return Ok(());- }- let id = match args.session {- Some(id) => SessionId::parse(&id)?,- None => {- client- .create(- "",- &models::Model::parse(args.model.as_deref().unwrap_or("default"))?,- )- .await?- }- };- println!("Testing Claude cloud session {}", id.as_str());- let session = Session::new(client, id.clone());- let mut channel = acp::attach(session);- send(- &channel,- json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}),- );- assert!(response(&mut channel, 1).await.get("result").is_some());- send(- &channel,- json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":id.as_str(),"cwd":"/","mcpServers":[]}}),- );- let loaded = response(&mut channel, 2).await;- assert!(- loaded.get("result").is_some(),- "history load failed: {loaded}"- );- if let Some(model) = args.model {- send(- &channel,- json!({"jsonrpc":"2.0","id":4,"method":"session/set_config_option","params":{"sessionId":id.as_str(),"configId":"model","value":model}}),- );- let selected = response(&mut channel, 4).await;- assert!(- selected.get("result").is_some(),- "model selection failed: {selected}"- );- }- send(- &channel,- json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":id.as_str(),"prompt":[{"type":"text","text":"Reply exactly MACRO_CLAUDE_HARNESS_OK. Do not use tools, read files, access the network, or modify anything."}]}}),- );- let mut text = String::new();- let mut chunks = 0;- loop {- let message = tokio::time::timeout(std::time::Duration::from_secs(180), channel.rx.recv())- .await?- .ok_or("ACP closed")?;- let ToServerMessage::Acp(AcpMessage(frame)) = message else {- continue;- };- let frame = serde_json::to_value(frame)?;- if frame["params"]["update"]["sessionUpdate"] == "agent_message_chunk" {- text.push_str(- frame["params"]["update"]["content"]["text"]- .as_str()- .ok_or("missing text")?,- );- chunks += 1;- }- if frame["id"] == 3 {- assert_eq!(- frame["result"]["stopReason"], "end_turn",- "turn failed: {frame}"- );- break;- }- }- assert_eq!(text.trim(), "MACRO_CLAUDE_HARNESS_OK");- println!(- "PASS: ACP initialize + history load + prompt + {chunks} text chunks + successful completion. Cloud transcript retained."- );- Ok(())-}diff --git a/crates/claude_cloud_agents/src/domain/auth.rs b/crates/claude_cloud_agents/src/domain/auth.rsdeleted file mode 100644index f6103d63b7..0000000000--- a/crates/claude_cloud_agents/src/domain/auth.rs+++ /dev/null@@ -1,259 +0,0 @@-//! One-time, owner-bound browser consent. No provider tokens cross the inbound boundary.-use super::credentials::{ConnectionState, GrantTransaction};-use super::model::{Credentials, Error, Secret};-use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};-use std::time::{Duration, SystemTime, UNIX_EPOCH};-use subtle::ConstantTimeEq;--const LOGIN_TTL: Duration = Duration::from_secs(600);--/// Redacted, user-actionable connection errors.-#[derive(Debug, thiserror::Error)]-pub enum AuthError {- /// This deployment has no configured connection store.- #[error("Claude connection is not configured on this deployment")]- Disabled,- /// Attempt expired, was canceled, replayed, or belongs to another user.- #[error("Sign-in expired or was replaced. Start Connect Claude again.")]- InvalidAttempt,- /// Manual callback input must contain Claude's code and matching state.- #[error("Paste the complete one-time code from Claude, including the # suffix.")]- InvalidCode,- /// Repeated starts are bounded per owner.- #[error("Please wait a moment before starting another sign-in.")]- Busy,- /// Provider or storage failures never include response bodies or secrets.- #[error("Claude connection failed: {0}")]- Provider(#[from] Error),-}--/// Browser-safe status; tokens and provider identifiers are never returned.-pub struct ConnectionStatus {- /// Whether connecting is enabled in this deployment.- pub enabled: bool,- /// Whether the authenticated user has a grant.- pub connected: bool,- /// In-memory connections disappear when the service restarts.- pub ephemeral: bool,-}--/// Browser-safe start response.-pub struct Login {- /// Opaque attempt handle bound to the initiating Macro user.- pub attempt_id: String,- /// Fixed-provider consent URL containing only public PKCE information.- pub authorization_url: String,- /// Seconds until this attempt expires.- pub expires_in: u64,-}--/// OAuth protocol capability; implemented outside the domain.-pub trait OAuthProvider: Send + Sync + 'static {- /// Construct the fixed-origin consent URL.- fn authorization_url(&self, state: &str, verifier: &Secret) -> String;- /// Exchange a one-time code and resolve the grant's cloud environment.- fn exchange(- &self,- code: Secret,- state: &str,- verifier: Secret,- ) -> impl Future<Output = Result<Credentials, Error>> + Send;-}--/// Owner-keyed credential storage capability.-pub trait ConnectionStore: Send + Sync + 'static {- /// Lock the owner's complete connection state across replicas.- fn lock(- &self,- owner: &str,- ) -> impl Future<Output = Result<Box<dyn GrantTransaction>, Error>> + Send;- /// Query presence without returning secrets.- fn connected(&self, owner: &str) -> impl Future<Output = bool> + Send;- /// Save a grant for exactly the authenticated owner.- fn save(- &self,- owner: &str,- credentials: Credentials,- ) -> impl Future<Output = Result<(), Error>> + Send;- /// Forget only this owner's grant. Does not revoke unrelated provider sessions.- fn remove(&self, owner: &str) -> impl Future<Output = Result<(), Error>> + Send;-}--/// Use cases exposed to the HTTP adapter.-pub trait ClaudeAuth: Send + Sync + 'static {- /// Return the current user's connection status.- fn status(&self, owner: &str) -> impl Future<Output = ConnectionStatus> + Send;- /// Start a new user-bound PKCE attempt, replacing older attempts.- fn begin(&self, owner: &str) -> impl Future<Output = Result<Login, AuthError>> + Send;- /// Consume a code once and save the resulting grant for its initiator.- fn complete(- &self,- owner: &str,- attempt_id: &str,- code: Secret,- ) -> impl Future<Output = Result<(), AuthError>> + Send;- /// Cancel pending consent and forget this user's connection.- fn disconnect(&self, owner: &str) -> impl Future<Output = Result<(), AuthError>> + Send;-}--/// Encrypted pending consent. No verifier is returned to the browser.-#[derive(Clone, serde::Serialize, serde::Deserialize)]-pub struct Attempt {- /// Opaque handle bound to the owner by storage.- pub id: String,- /// Expected OAuth state.- pub state: String,- /// Consumed durably before token exchange.- pub verifier: Option<Secret>,- /// Unix timestamp used across replicas and restarts.- pub started: u64,-}--fn now() -> Result<u64, Error> {- SystemTime::now()- .duration_since(UNIX_EPOCH)- .map(|time| time.as_secs())- .map_err(|_| Error::Credentials)-}--/// Expiring, one-use browser consent bound to authenticated users.-pub struct AuthService<P, S> {- provider: P,- store: Option<S>,- ephemeral: bool,-}--impl<P, S> AuthService<P, S> {- /// Enable via a store supplied by the composition root; None disables all writes.- pub fn new(provider: P, store: Option<S>, ephemeral: bool) -> Self {- Self {- provider,- store,- ephemeral,- }- }-}--fn random_secret() -> String {- URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>())-}--impl<P: OAuthProvider, S: ConnectionStore> ClaudeAuth for AuthService<P, S> {- async fn status(&self, owner: &str) -> ConnectionStatus {- ConnectionStatus {- enabled: self.store.is_some(),- connected: match &self.store {- Some(store) => store.connected(owner).await,- None => false,- },- ephemeral: self.ephemeral,- }- }-- async fn begin(&self, owner: &str) -> Result<Login, AuthError> {- let store = self.store.as_ref().ok_or(AuthError::Disabled)?;- let mut transaction = store.lock(owner).await?;- let started = now()?;- if transaction- .state()- .attempt- .as_ref()- .is_some_and(|attempt| started.saturating_sub(attempt.started) < 2)- {- return Err(AuthError::Busy);- }- let state = random_secret();- let verifier = Secret::parse(random_secret())?;- let attempt_id = random_secret();- let authorization_url = self.provider.authorization_url(&state, &verifier);- transaction.state().attempt = Some(Attempt {- id: attempt_id.clone(),- state,- verifier: Some(verifier),- started,- });- transaction.commit().await?;- Ok(Login {- attempt_id,- authorization_url,- expires_in: LOGIN_TTL.as_secs(),- })- }-- async fn complete(- &self,- owner: &str,- attempt_id: &str,- input: Secret,- ) -> Result<(), AuthError> {- let store = self.store.as_ref().ok_or(AuthError::Disabled)?;- let raw = input.expose().trim();- if raw.len() > 4096 {- return Err(AuthError::InvalidCode);- }- let (code, state) = raw.split_once('#').ok_or(AuthError::InvalidCode)?;- if code.is_empty()- || !code- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b"-_.~".contains(&b))- {- return Err(AuthError::InvalidCode);- }- let verifier = {- let mut transaction = store.lock(owner).await?;- let attempt = transaction- .state()- .attempt- .as_mut()- .ok_or(AuthError::InvalidAttempt)?;- if attempt.id != attempt_id- || now()?.saturating_sub(attempt.started) >= LOGIN_TTL.as_secs()- {- return Err(AuthError::InvalidAttempt);- }- if !bool::from(attempt.state.as_bytes().ct_eq(state.as_bytes())) {- return Err(AuthError::InvalidCode);- }- // Taking the verifier consumes the attempt before making any network request.- let verifier = attempt.verifier.take().ok_or(AuthError::InvalidAttempt)?;- transaction.commit().await?;- verifier- };- let result = self- .provider- .exchange(Secret::parse(code.to_owned())?, state, verifier)- .await;- let mut transaction = store.lock(owner).await?;- if !transaction.state().attempt.as_ref().is_some_and(|attempt| {- attempt.id == attempt_id- && now()- .is_ok_and(|time| time.saturating_sub(attempt.started) < LOGIN_TTL.as_secs())- }) {- return Err(AuthError::InvalidAttempt);- }- transaction.state().attempt = None;- match result {- Ok(grant) => {- transaction.state().grant = Some(grant);- transaction.state().refresh_id = None;- transaction.commit().await?;- }- Err(error) => {- transaction.commit().await?;- return Err(error.into());- }- }- Ok(())- }-- async fn disconnect(&self, owner: &str) -> Result<(), AuthError> {- let store = self.store.as_ref().ok_or(AuthError::Disabled)?;- let mut transaction = store.lock(owner).await?;- *transaction.state() = ConnectionState::default();- transaction.commit().await?;- Ok(())- }-}--#[cfg(test)]-mod test;diff --git a/crates/claude_cloud_agents/src/domain/auth/test.rs b/crates/claude_cloud_agents/src/domain/auth/test.rsdeleted file mode 100644index 1e245ac79b..0000000000--- a/crates/claude_cloud_agents/src/domain/auth/test.rs+++ /dev/null@@ -1,210 +0,0 @@-use super::*;-use std::sync::atomic::{AtomicUsize, Ordering};--use super::super::credentials::{GrantRepository, test_support::MemoryRepository};-use std::sync::Arc;--#[derive(Clone, Default)]-struct Store(Arc<MemoryRepository>);-impl ConnectionStore for Store {- async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>, Error> {- self.0.lock(owner).await- }- async fn connected(&self, owner: &str) -> bool {- self.0.get(owner).await.unwrap().is_some()- }- async fn save(&self, owner: &str, c: Credentials) -> Result<(), Error> {- self.0.put(owner, &c).await- }- async fn remove(&self, owner: &str) -> Result<(), Error> {- self.0.delete(owner).await- }-}-#[derive(Default)]-struct Provider {- calls: AtomicUsize,- fail: bool,- gate: Option<Arc<tokio::sync::Semaphore>>,-}-fn secret(s: &str) -> Secret {- Secret::parse(s.to_owned()).unwrap()-}-impl OAuthProvider for Provider {- fn authorization_url(&self, state: &str, _: &Secret) -> String {- format!("https://claude.com/consent?state={state}")- }- async fn exchange(&self, _: Secret, _: &str, _: Secret) -> Result<Credentials, Error> {- self.calls.fetch_add(1, Ordering::SeqCst);- if let Some(gate) = &self.gate {- gate.acquire().await.unwrap().forget();- }- if self.fail {- return Err(Error::Authorization);- }- Ok(Credentials {- access_token: secret("access"),- refresh_token: Some(secret("refresh")),- expires_at: u64::MAX,- organization_id: "org".into(),- environment_id: "env_test".into(),- })- }-}-fn code(login: &Login) -> Secret {- secret(&format!(- "one-time-code#{}",- login.authorization_url.split("state=").nth(1).unwrap()- ))-}--#[tokio::test]-async fn owner_bound_single_use_and_disconnect() {- let store = Store::default();- let service = AuthService::new(Provider::default(), Some(store.clone()), true);- let login = service.begin("macro|alice").await.unwrap();- assert!(matches!(- service- .complete("macro|bob", &login.attempt_id, code(&login))- .await,- Err(AuthError::InvalidAttempt)- ));- assert_eq!(service.provider.calls.load(Ordering::SeqCst), 0);- assert!(matches!(- service- .complete("macro|alice", &login.attempt_id, secret("code#wrong-state"))- .await,- Err(AuthError::InvalidCode)- ));- service- .complete("macro|alice", &login.attempt_id, code(&login))- .await- .unwrap();- assert!(service.status("macro|alice").await.connected);- assert!(!service.status("macro|bob").await.connected);- assert!(matches!(- service- .complete("macro|alice", &login.attempt_id, code(&login))- .await,- Err(AuthError::InvalidAttempt)- ));- service.disconnect("macro|bob").await.unwrap();- assert!(service.status("macro|alice").await.connected);- service.disconnect("macro|alice").await.unwrap();- assert!(!service.status("macro|alice").await.connected);-}--#[tokio::test]-async fn expiry_replacement_and_rate_limit() {- let service = AuthService::new(Provider::default(), Some(Store::default()), true);- let old = service.begin("alice").await.unwrap();- assert!(matches!(service.begin("alice").await, Err(AuthError::Busy)));- let mut transaction = service.store.as_ref().unwrap().lock("alice").await.unwrap();- transaction.state().attempt.as_mut().unwrap().started -= LOGIN_TTL.as_secs();- transaction.commit().await.unwrap();- assert!(matches!(- service.complete("alice", &old.attempt_id, code(&old)).await,- Err(AuthError::InvalidAttempt)- ));- let new = service.begin("alice").await.unwrap();- assert_ne!(old.attempt_id, new.attempt_id);- assert!(matches!(- service.complete("alice", &old.attempt_id, code(&old)).await,- Err(AuthError::InvalidAttempt)- ));- service- .complete("alice", &new.attempt_id, code(&new))- .await- .unwrap();-}--#[tokio::test]-async fn failure_consumes_code_and_disabled_never_starts() {- let disabled = AuthService::<_, Store>::new(Provider::default(), None, true);- assert!(!disabled.status("alice").await.enabled);- assert!(matches!(- disabled.begin("alice").await,- Err(AuthError::Disabled)- ));- let service = AuthService::new(- Provider {- fail: true,- ..Default::default()- },- Some(Store::default()),- true,- );- let login = service.begin("alice").await.unwrap();- assert!(matches!(- service- .complete("alice", &login.attempt_id, code(&login))- .await,- Err(AuthError::Provider(_))- ));- assert!(!service.status("alice").await.connected);- assert!(matches!(- service- .complete("alice", &login.attempt_id, code(&login))- .await,- Err(AuthError::InvalidAttempt)- ));- assert_eq!(service.provider.calls.load(Ordering::SeqCst), 1);-}--#[tokio::test]-async fn disconnect_during_exchange_cannot_reconnect() {- let gate = Arc::new(tokio::sync::Semaphore::new(0));- let service = Arc::new(AuthService::new(- Provider {- gate: Some(gate.clone()),- ..Default::default()- },- Some(Store::default()),- true,- ));- let login = service.begin("alice").await.unwrap();- let running = {- let service = service.clone();- tokio::spawn(async move {- service- .complete("alice", &login.attempt_id, code(&login))- .await- })- };- tokio::time::timeout(Duration::from_secs(1), async {- while service.provider.calls.load(Ordering::SeqCst) == 0 {- tokio::task::yield_now().await;- }- })- .await- .unwrap();- service.disconnect("alice").await.unwrap();- gate.add_permits(1);- assert!(matches!(- running.await.unwrap(),- Err(AuthError::InvalidAttempt)- ));- assert!(!service.status("alice").await.connected);-}--#[tokio::test]-async fn consent_survives_replica_changes_and_restart() {- let store = Store::default();- let first = AuthService::new(Provider::default(), Some(store.clone()), false);- let login = first.begin("alice").await.unwrap();- drop(first);- let second = AuthService::new(Provider::default(), Some(store.clone()), false);- second- .complete("alice", &login.attempt_id, code(&login))- .await- .unwrap();- let third = AuthService::new(Provider::default(), Some(store), false);- assert!(third.status("alice").await.connected);- assert!(matches!(- third- .complete("alice", &login.attempt_id, code(&login))- .await,- Err(AuthError::InvalidAttempt)- ));- third.disconnect("alice").await.unwrap();- assert!(!second.status("alice").await.connected);-}diff --git a/crates/claude_cloud_agents/src/domain/credentials.rs b/crates/claude_cloud_agents/src/domain/credentials.rsdeleted file mode 100644index 928a5a6b49..0000000000--- a/crates/claude_cloud_agents/src/domain/credentials.rs+++ /dev/null@@ -1,165 +0,0 @@-//! Owner-scoped grant lifecycle, shared by browser consent and provider calls.-use super::{- auth::ConnectionStore,- model::{Credentials, Error, Result},-};-use std::{- collections::BTreeMap,- sync::Arc,- time::{SystemTime, UNIX_EPOCH},-};-use tokio::sync::Mutex;--#[cfg(test)]-mod test;-#[cfg(test)]-pub(crate) mod test_support;--/// Encrypted connection state shared across service replicas.-#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]-pub struct ConnectionState {- /// The owner's subscription grant, if connected.- pub grant: Option<Credentials>,- /// Pending, owner-bound browser consent.- pub attempt: Option<super::auth::Attempt>,- /// A consumed refresh must never be retried after an uncertain exchange.- pub refresh_id: Option<String>,-}--/// Owner-scoped transaction. Dropping it rolls back uncommitted state.-#[async_trait::async_trait]-pub trait GrantTransaction: Send {- /// Read or update the locked state.- fn state(&mut self) -> &mut ConnectionState;- /// Persist the state and release the owner lock.- async fn commit(self: Box<Self>) -> Result<()>;-}--/// Persistence serializes connection changes across replicas.-#[async_trait::async_trait]-pub trait GrantRepository: Send + Sync {- /// Lock exactly one owner's state, including owners with no existing row.- async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>>;- /// Load one grant without returning pending consent secrets.- async fn get(&self, owner: &str) -> Result<Option<Credentials>> {- Ok(self.lock(owner).await?.state().grant.clone())- }- /// Persist a new connection and invalidate pending consent or refresh.- async fn put(&self, owner: &str, grant: &Credentials) -> Result<()> {- let mut transaction = self.lock(owner).await?;- *transaction.state() = ConnectionState {- grant: Some(grant.clone()),- ..Default::default()- };- transaction.commit().await- }- /// Forget this owner's connection and any pending consent.- async fn delete(&self, owner: &str) -> Result<()> {- let mut transaction = self.lock(owner).await?;- *transaction.state() = ConnectionState::default();- transaction.commit().await- }-}--/// Provider refresh capability; never retries a token exchange automatically.-#[async_trait::async_trait]-pub trait RefreshGrant: Send + Sync {- /// Refresh an expired grant.- async fn refresh(&self, grant: &Credentials) -> Result<Credentials>;-}--/// Owner-scoped credential lifecycle with durable refresh consumption.-#[derive(Clone)]-pub struct AccountCredentials {- repository: Arc<dyn GrantRepository>,- refresher: Arc<dyn RefreshGrant>,- // Keep rotated grants after a persistence failure so we never reuse an old- // refresh token. The next operation retries persistence before using them.- pending: Arc<Mutex<BTreeMap<String, (String, Credentials)>>>,-}--impl AccountCredentials {- /// Wire persistence and refresh ports at the composition root.- pub fn new(repository: Arc<dyn GrantRepository>, refresher: Arc<dyn RefreshGrant>) -> Self {- Self {- repository,- refresher,- pending: Arc::default(),- }- }-- /// Presence for this exact owner, without exposing a grant.- pub async fn contains(&self, owner: &str) -> bool {- self.repository.get(owner).await.ok().flatten().is_some()- }-- /// Resolve and persist a refresh before a provider operation.- pub async fn resolve(&self, owner: &str) -> Result<Credentials> {- let mut pending = self.pending.lock().await;- let mut transaction = self.repository.lock(owner).await?;- if let Some((id, grant)) = pending.remove(owner)- && transaction.state().refresh_id.as_ref() == Some(&id)- {- transaction.state().grant = Some(grant.clone());- transaction.state().refresh_id = None;- if let Err(error) = transaction.commit().await {- pending.insert(owner.to_owned(), (id, grant));- return Err(error);- }- transaction = self.repository.lock(owner).await?;- }- if transaction.state().refresh_id.is_some() {- return Err(Error::Authorization);- }- let grant = transaction- .state()- .grant- .clone()- .ok_or(Error::NotConnected)?;- let now = SystemTime::now()- .duration_since(UNIX_EPOCH)- .map_err(|_| Error::Credentials)?- .as_secs();- if grant.expires_at > now + 120 {- return Ok(grant);- }- // Persist consumption before the external mutation. A crashed process- // cannot cause another replica to reuse a rotating refresh token.- let id = uuid::Uuid::now_v7().to_string();- transaction.state().refresh_id = Some(id.clone());- transaction.commit().await?;- let refreshed = self.refresher.refresh(&grant).await?;- let mut transaction = self.repository.lock(owner).await?;- if transaction.state().refresh_id.as_ref() != Some(&id) {- return Err(Error::NotConnected);- }- transaction.state().grant = Some(refreshed.clone());- transaction.state().refresh_id = None;- if let Err(error) = transaction.commit().await {- pending.insert(owner.to_owned(), (id, refreshed));- return Err(error);- }- Ok(refreshed)- }-}--impl ConnectionStore for AccountCredentials {- async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {- self.repository.lock(owner).await- }- async fn connected(&self, owner: &str) -> bool {- self.contains(owner).await- }- async fn save(&self, owner: &str, grant: Credentials) -> Result<()> {- let mut pending = self.pending.lock().await;- self.repository.put(owner, &grant).await?;- pending.remove(owner);- Ok(())- }- async fn remove(&self, owner: &str) -> Result<()> {- let mut pending = self.pending.lock().await;- self.repository.delete(owner).await?;- pending.remove(owner);- Ok(())- }-}diff --git a/crates/claude_cloud_agents/src/domain/credentials/test.rs b/crates/claude_cloud_agents/src/domain/credentials/test.rsdeleted file mode 100644index 0e4de77a15..0000000000--- a/crates/claude_cloud_agents/src/domain/credentials/test.rs+++ /dev/null@@ -1,97 +0,0 @@-use super::test_support::MemoryRepository as Repo;-use super::*;-use crate::domain::model::Secret;-use std::sync::atomic::{AtomicUsize, Ordering};--#[derive(Default)]-struct Refresh(AtomicUsize);-#[async_trait::async_trait]-impl RefreshGrant for Refresh {- async fn refresh(&self, grant: &Credentials) -> Result<Credentials> {- self.0.fetch_add(1, Ordering::SeqCst);- let mut updated = grant.clone();- updated.expires_at = 4_000_000_000;- updated.refresh_token = Some(Secret::parse("rotated".into()).unwrap());- Ok(updated)- }-}-#[tokio::test]-async fn refresh_rotation_retries_persistence_without_reusing_old_token_and_disconnect_wins() {- let repo = Arc::new(Repo::default());- let refresh = Arc::new(Refresh::default());- let service = AccountCredentials::new(repo.clone(), refresh.clone());- service- .save(- "alice",- Credentials {- access_token: Secret::parse("access".into()).unwrap(),- refresh_token: Some(Secret::parse("old".into()).unwrap()),- expires_at: 0,- organization_id: "org".into(),- environment_id: "env_test".into(),- },- )- .await- .unwrap();- assert!(matches!(- service.resolve("bob").await,- Err(Error::NotConnected)- ));- repo.fail_commit.store(2, Ordering::SeqCst);- assert!(service.resolve("alice").await.is_err());- repo.fail_commit.store(1, Ordering::SeqCst);- assert!(service.resolve("alice").await.is_err());- assert_eq!(refresh.0.load(Ordering::SeqCst), 1);- repo.fail_commit.store(0, Ordering::SeqCst);- assert_eq!(- service- .resolve("alice")- .await- .unwrap()- .refresh_token- .unwrap()- .expose(),- "rotated"- );- service.remove("alice").await.unwrap();- assert!(matches!(- service.resolve("alice").await,- Err(Error::NotConnected)- ));- assert_eq!(refresh.0.load(Ordering::SeqCst), 1);-}--#[tokio::test]-async fn another_replica_cannot_reuse_refresh_or_resurrect_a_disconnected_grant() {- let repo = Arc::new(Repo::default());- let refresh = Arc::new(Refresh::default());- let first = AccountCredentials::new(repo.clone(), refresh.clone());- let second = AccountCredentials::new(repo.clone(), refresh.clone());- first- .save(- "alice",- Credentials {- access_token: Secret::parse("access".into()).unwrap(),- refresh_token: Some(Secret::parse("old".into()).unwrap()),- expires_at: 0,- organization_id: "org".into(),- environment_id: "env_test".into(),- },- )- .await- .unwrap();- repo.fail_commit.store(2, Ordering::SeqCst);- assert!(first.resolve("alice").await.is_err());- assert!(matches!(- second.resolve("alice").await,- Err(Error::Authorization)- ));- assert_eq!(refresh.0.load(Ordering::SeqCst), 1);- second.remove("alice").await.unwrap();- assert!(matches!(- first.resolve("alice").await,- Err(Error::NotConnected)- ));- assert!(!second.contains("alice").await);- assert_eq!(refresh.0.load(Ordering::SeqCst), 1);-}diff --git a/crates/claude_cloud_agents/src/domain/credentials/test_support.rs b/crates/claude_cloud_agents/src/domain/credentials/test_support.rsdeleted file mode 100644index ae142e2ac4..0000000000--- a/crates/claude_cloud_agents/src/domain/credentials/test_support.rs+++ /dev/null@@ -1,47 +0,0 @@-use super::*;-use std::sync::atomic::{AtomicUsize, Ordering};--#[derive(Default)]-pub(crate) struct MemoryRepository {- pub data: Arc<Mutex<BTreeMap<String, ConnectionState>>>,- /// A positive value fails that numbered future commit once.- pub fail_commit: Arc<AtomicUsize>,-}-struct Transaction {- data: tokio::sync::OwnedMutexGuard<BTreeMap<String, ConnectionState>>,- owner: String,- state: ConnectionState,- fail: Arc<AtomicUsize>,-}-#[async_trait::async_trait]-impl GrantRepository for MemoryRepository {- async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {- let data = self.data.clone().lock_owned().await;- let state = data.get(owner).cloned().unwrap_or_default();- Ok(Box::new(Transaction {- data,- owner: owner.to_owned(),- state,- fail: self.fail_commit.clone(),- }))- }-}-#[async_trait::async_trait]-impl GrantTransaction for Transaction {- fn state(&mut self) -> &mut ConnectionState {- &mut self.state- }- async fn commit(mut self: Box<Self>) -> Result<()> {- if self- .fail- .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))- == Ok(1)- {- return Err(Error::Credentials);- }- let owner = self.owner.clone();- let state = self.state.clone();- self.data.insert(owner, state);- Ok(())- }-}diff --git a/crates/claude_cloud_agents/src/domain/environment.rs b/crates/claude_cloud_agents/src/domain/environment.rsdeleted file mode 100644index d563badfda..0000000000--- a/crates/claude_cloud_agents/src/domain/environment.rs+++ /dev/null@@ -1,28 +0,0 @@-//! Minimal network access required by Macro's session-scoped MCP gateway.-use super::model::{Error, Result};-use serde_json::{Value, json};--/// Add the deployment's exact gateway host to a limited environment's allowlist.-/// Omitted fields in Claude's update API retain their values, so the patch never-/// changes package access, connector access, or any other environment setting.-/// Explicitly disabled or unknown policies require the owner to configure them.-pub fn gateway_network_patch(network: &Value, host: &str) -> Result<Option<Value>> {- match network["type"].as_str() {- Some("unrestricted") => return Ok(None),- Some("limited") => {}- _ => return Err(Error::EnvironmentNetwork),- }- let hosts = network["allowed_hosts"]- .as_array()- .filter(|hosts| hosts.iter().all(Value::is_string))- .ok_or(Error::EnvironmentNetwork)?;- if hosts.iter().any(|entry| entry.as_str() == Some(host)) {- return Ok(None);- }- let mut hosts = hosts.clone();- hosts.push(json!(host));- Ok(Some(json!({"type":"limited", "allowed_hosts":hosts})))-}--#[cfg(test)]-mod test;diff --git a/crates/claude_cloud_agents/src/domain/environment/test.rs b/crates/claude_cloud_agents/src/domain/environment/test.rsdeleted file mode 100644index 32245595b6..0000000000--- a/crates/claude_cloud_agents/src/domain/environment/test.rs+++ /dev/null@@ -1,66 +0,0 @@-use super::*;--#[test]-fn adds_only_gateway_and_preserves_existing_hosts_and_other_settings() {- let network = json!({- "type":"limited", "allowed_hosts":["github.com"],- "allow_mcp_servers":true, "allow_package_managers":false,- "future_setting":"preserve"- });- let patch = gateway_network_patch(&network, "dev-gateway.macro.com")- .unwrap()- .unwrap();- assert_eq!(- patch,- json!({"type":"limited", "allowed_hosts":["github.com", "dev-gateway.macro.com"]})- );- let mut merged = network.clone();- merged- .as_object_mut()- .unwrap()- .extend(patch.as_object().unwrap().clone());- assert_eq!(merged["allow_mcp_servers"], true);- assert_eq!(merged["allow_package_managers"], false);- assert_eq!(merged["future_setting"], "preserve");- assert!(- gateway_network_patch(&merged, "dev-gateway.macro.com")- .unwrap()- .is_none()- );-}--#[test]-fn unrestricted_network_needs_no_update() {- assert!(- gateway_network_patch(&json!({"type":"unrestricted"}), "gateway.macro.com")- .unwrap()- .is_none()- );-}--#[test]-fn never_broadens_disabled_unknown_or_malformed_policies() {- for network in [- json!(null),- json!({"type":"none"}),- json!({"type":"future"}),- json!({"type":"limited"}),- json!({"type":"limited", "allowed_hosts":[1]}),- ] {- assert!(matches!(- gateway_network_patch(&network, "gateway.macro.com"),- Err(Error::EnvironmentNetwork)- ));- }-}--#[test]-fn uses_the_deployments_host_without_adding_other_environments() {- let patch = gateway_network_patch(- &json!({"type":"limited", "allowed_hosts":[]}),- "gateway.macro.com",- )- .unwrap()- .unwrap();- assert_eq!(patch["allowed_hosts"], json!(["gateway.macro.com"]));-}diff --git a/crates/claude_cloud_agents/src/domain/mcp.rs b/crates/claude_cloud_agents/src/domain/mcp.rsdeleted file mode 100644index 583c26af3d..0000000000--- a/crates/claude_cloud_agents/src/domain/mcp.rs+++ /dev/null@@ -1,28 +0,0 @@-//! Remote MCP configuration carried by an agent's session handshake.-use serde::Serialize;-use std::collections::BTreeMap;--/// Remote transports supported by the cloud worker.-#[derive(Clone, Serialize)]-#[serde(rename_all = "lowercase")]-pub enum McpTransport {- /// Streamable HTTP.- Http,- /// HTTP with server-sent events.- Sse,-}--/// One server. Deliberately not Debug: headers contain session credentials.-#[derive(Clone, Serialize)]-pub struct McpServer {- /// Remote transport kind.- #[serde(rename = "type")]- pub transport: McpTransport,- /// The URL supplied by the session's egress provisioner.- pub url: String,- /// Session-scoped authorization and other supplied headers.- pub headers: BTreeMap<String, String>,-}--/// Servers keyed by their stable ACP names.-pub type McpServers = BTreeMap<String, McpServer>;diff --git a/crates/claude_cloud_agents/src/domain/mod.rs b/crates/claude_cloud_agents/src/domain/mod.rsdeleted file mode 100644index 8f7a503df5..0000000000--- a/crates/claude_cloud_agents/src/domain/mod.rs+++ /dev/null@@ -1,11 +0,0 @@-//! Provider-independent session behavior and capabilities.-/// Owner-bound interactive OAuth connection use cases.-pub mod auth;-pub mod credentials;-pub mod environment;-pub mod mcp;-pub mod model;-pub mod models;-pub mod ports;-pub mod service;-pub mod translate;diff --git a/crates/claude_cloud_agents/src/domain/model.rs b/crates/claude_cloud_agents/src/domain/model.rsdeleted file mode 100644index d4a00108e3..0000000000--- a/crates/claude_cloud_agents/src/domain/model.rs+++ /dev/null@@ -1,155 +0,0 @@-//! Validated provider identities and safe failures.-use serde::{Deserialize, Serialize};--/// The deliberately bounded failures exposed to Macro. Never includes HTTP bodies.-#[derive(Debug, thiserror::Error)]-pub enum Error {- /// The cloud environment cannot safely allow the deployment's MCP gateway.- #[error(- "Claude's environment cannot reach Macro's MCP gateway. Check its network settings in Claude Code on the web, then start a new session."- )]- EnvironmentNetwork,- /// MCP setup failed or the worker did not acknowledge it before prompting.- #[error(- "Claude could not connect the session's MCP servers; check the harness connection and retry"- )]- McpConfiguration,- /// Invalid choice or a provider-rejected switch; does not expose provider bodies.- #[error(- "Claude could not select that model. Choose another model available on your subscription."- )]- ModelUnavailable,- /// The demo requires one unambiguous active Claude Code cloud environment.- #[error(- "This demo needs exactly one active Claude Code cloud environment. Check Claude Code on the web first."- )]- CloudEnvironment,- /// No configured credentials for this session owner.- #[error("Connect Claude for this Macro user before starting a Claude Cloud session")]- NotConnected,- /// Expired, revoked, or insufficient OAuth grant.- #[error("Claude authorization failed; reconnect Claude")]- Authorization,- /// Provider rejected a request; body is intentionally omitted.- #[error("Claude cloud request failed (HTTP {0})")]- Http(u16),- /// Transport failed, with secrets and response bodies omitted.- #[error("Claude cloud connection interrupted")]- Network,- /// A malformed or unsupported response.- #[error("Unsupported Claude cloud response")]- Protocol,- /// Local credential storage cannot be used safely.- #[error("Claude credential storage is unavailable or invalid; retry or reconnect Claude")]- Credentials,- /// An uncertain create must not be automatically repeated.- #[error(- "Claude session creation outcome is uncertain; inspect the Claude account before retrying"- )]- UncertainCreate,- /// A stream replay cannot be safely reconciled.- #[error("Claude history recovery is required; reconnect the session")]- Recovery,- /// The local or cloud conversation still has an unfinished turn.- #[error(- "Claude still has a turn in progress; stop it or wait and reload before prompting again"- )]- Busy,-}--/// One operation's safe result.-pub type Result<T> = std::result::Result<T, Error>;--/// A validated Claude cloud session identifier.-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-pub struct SessionId(String);-impl SessionId {- /// Validate before interpolation in URLs.- pub fn parse(value: &str) -> Result<Self> {- if !value.starts_with("cse_")- || value.len() <= 4- || !value- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b == b'_')- {- return Err(Error::Protocol);- }- Ok(Self(value.to_owned()))- }- /// Provider's wire identifier.- pub fn as_str(&self) -> &str {- &self.0- }- /// Claude's web UI for this cloud conversation.- pub fn web_url(&self) -> String {- format!("https://claude.ai/code/{}", self.0)- }-}--/// An OAuth credential, redacted in diagnostics and zeroized on drop.-#[derive(Clone)]-pub struct Secret(zeroize::Zeroizing<String>);-impl Secret {- /// Reject empty credentials and header-control characters.- pub fn parse(value: String) -> Result<Self> {- if value.is_empty()- || value.len() > 16_384- || value- .bytes()- .any(|b| b.is_ascii_whitespace() || b.is_ascii_control())- {- return Err(Error::Credentials);- }- Ok(Self(zeroize::Zeroizing::new(value)))- }- /// Plaintext, only for the provider or private persistence.- pub fn expose(&self) -> &str {- &self.0- }-}-impl std::fmt::Debug for Secret {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.write_str("Secret([REDACTED])")- }-}-impl Serialize for Secret {- fn serialize<S: serde::Serializer>(- &self,- serializer: S,- ) -> std::result::Result<S::Ok, S::Error> {- serializer.serialize_str(self.expose())- }-}-impl<'de> Deserialize<'de> for Secret {- fn deserialize<D: serde::Deserializer<'de>>(- deserializer: D,- ) -> std::result::Result<Self, D::Error> {- Self::parse(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)- }-}--/// Owner-bound demo credentials; this structure must never be returned by an API.-#[derive(Clone, Debug, Serialize, Deserialize)]-pub struct Credentials {- /// Short-lived OAuth bearer.- pub access_token: Secret,- /// Refresh grant, when consent provided one.- pub refresh_token: Option<Secret>,- /// Unix timestamp in seconds.- pub expires_at: u64,- /// Claude organization selected at consent.- pub organization_id: String,- /// Environment explicitly selected for this account.- pub environment_id: String,-}--/// A decoded provider SSE event, independent of the HTTP implementation.-#[derive(Debug, Clone)]-pub struct Event {- /// SSE event name.- pub kind: String,- /// Decoded JSON payload.- pub data: serde_json::Value,- /// Durable sequence number, absent on ephemeral deltas.- pub sequence: Option<u64>,-}diff --git a/crates/claude_cloud_agents/src/domain/models.rs b/crates/claude_cloud_agents/src/domain/models.rsdeleted file mode 100644index 890a53eea9..0000000000--- a/crates/claude_cloud_agents/src/domain/models.rs+++ /dev/null@@ -1,153 +0,0 @@-//! Provider-reported catalogs and validated, open-ended model identifiers.-use super::{- model::{Error, Event, Result},- ports::Cloud,-};--/// An open-ended model ID; default retains the original Macro persisted ID.-#[derive(Clone, Debug, PartialEq, Eq)]-pub struct Model(String);-impl Default for Model {- fn default() -> Self {- Self("claude-default".into())- }-}-impl Model {- /// Validate shape, not membership: membership belongs to the session catalog.- pub fn parse(value: &str) -> Result<Self> {- if matches!(value, "default" | "claude-default") {- return Ok(Self::default());- }- if value.is_empty()- || value.len() > 128- || !value- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b"-_.:[]".contains(&b))- {- return Err(Error::ModelUnavailable);- }- Ok(Self(value.into()))- }- /// Stable Macro option ID.- pub fn id(&self) -> &str {- &self.0- }- /// Provider reset uses null, not the Macro-specific default ID.- pub fn provider_value(&self) -> Option<&str> {- (self != &Self::default()).then_some(self.id())- }-}--/// One choice reported by the account catalog or cloud worker.-#[derive(Clone, Debug, PartialEq, Eq)]-pub struct ModelOption {- /// Provider model ID, normalized only for default.- pub model: Model,- /// Provider display name.- pub name: String,- /// Provider description, when present.- pub description: Option<String>,-}--/// No catalog yet is distinct from a reported empty catalog.-#[derive(Clone, Debug, Default, PartialEq, Eq)]-pub enum Catalog {- /// Bootstrap without claiming account-entitled models.- #[default]- Unknown,- /// Ordered choices from the account catalog or successful initialization.- Reported(Vec<ModelOption>),-}-impl Catalog {- /// Invalid events cannot replace the last usable catalog.- pub fn from_event(event: &Event) -> Option<Self> {- if event.kind != "client_event" {- return None;- }- let payload = &event.data["payload"];- let response = &payload["response"];- if payload["type"] != "control_response" || response["subtype"] != "success" {- return None;- }- let models = response["response"]["models"].as_array()?;- if models.len() > 256 {- return None;- }- let mut seen = std::collections::BTreeSet::new();- let mut options = Vec::new();- for value in models {- let model = Model::parse(value["value"].as_str()?).ok()?;- let name = value["displayName"].as_str()?;- if name.trim().is_empty() || name.len() > 512 || !seen.insert(model.id().to_owned()) {- return None;- }- let description = match value.get("description") {- None | Some(serde_json::Value::Null) => None,- Some(value) => Some(value.as_str().filter(|s| s.len() <= 4096)?.to_owned()),- };- options.push(ModelOption {- model,- name: name.into(),- description,- });- }- Some(Self::Reported(options))- }- /// Use the newest valid catalog in ordered durable history.- pub fn from_history(events: &[Event]) -> Self {- events- .iter()- .rev()- .find_map(Self::from_event)- .unwrap_or_default()- }- /// Bootstrap offers only the provider's reset behavior.- pub fn options(&self) -> Vec<ModelOption> {- match self {- Self::Reported(options) => options.clone(),- Self::Unknown => vec![ModelOption {- model: Model::default(), name: "Claude · subscription default".into(),- description: Some("No Claude model catalog reported yet. Start a session with default; choices appear when Claude reports them.".into()),- }],- }- }- /// Add account choices, preserving this session catalog's labels- /// and order for duplicate IDs. Unknown catalogs do not manufacture defaults.- pub fn supplemented_by(self, other: Self) -> Self {- match (self, other) {- (Self::Unknown, catalog) | (catalog, Self::Unknown) => catalog,- (Self::Reported(mut options), Self::Reported(other)) => {- let mut seen: std::collections::BTreeSet<_> = options- .iter()- .map(|option| option.model.id().to_owned())- .collect();- options.extend(- other- .into_iter()- .filter(|option| seen.insert(option.model.id().to_owned())),- );- Self::Reported(options)- }- }- }-- /// Reject choices absent from the provider-reported choices.- pub fn contains(&self, model: &Model) -> bool {- self.options().iter().any(|option| &option.model == model)- }-}--/// Discover from the account catalog without reading transcripts or starting a-/// worker. The provider still validates the selected model when a turn runs.-pub async fn discover<C: Cloud>(cloud: &C) -> Result<Catalog> {- let models = cloud.models().await?;- let default = ModelOption {- model: Model::default(),- name: "Claude · subscription default".into(),- description: Some("Let Claude choose the subscription's default model.".into()),- };- Ok(Catalog::Reported(vec![default]).supplemented_by(Catalog::Reported(models)))-}--#[cfg(test)]-mod test;diff --git a/crates/claude_cloud_agents/src/domain/models/test.rs b/crates/claude_cloud_agents/src/domain/models/test.rsdeleted file mode 100644index af083e7503..0000000000--- a/crates/claude_cloud_agents/src/domain/models/test.rs+++ /dev/null@@ -1,138 +0,0 @@-use super::*;-use serde_json::json;--fn event(models: serde_json::Value) -> Event {- Event {- kind: "client_event".into(),- sequence: Some(1),- data: json!({"payload":{"type":"control_response","response":{"subtype":"success","response":{"models":models}}}}),- }-}--#[test]-fn new_provider_ids_labels_descriptions_and_order_need_no_code_change() {- let catalog = Catalog::from_event(&event(json!([- {"value":"brand-new-model[1m]","displayName":"New model","description":"Provider description"},- {"value":"default","displayName":"Default (recommended)"}- ]))).unwrap();- let options = catalog.options();- assert_eq!(options[0].model.id(), "brand-new-model[1m]");- assert_eq!(options[0].name, "New model");- assert_eq!(- options[0].description.as_deref(),- Some("Provider description")- );- assert_eq!(options[1].model.id(), "claude-default");- assert!(options[1].model.provider_value().is_none());- assert!(!catalog.contains(&Model::parse("opus").unwrap()));-}--#[test]-fn newest_valid_catalog_replaces_instead_of_merging_and_empty_is_authoritative() {- let old = event(json!([{"value":"old","displayName":"Old"}]));- let new = event(json!([{"value":"new","displayName":"New"}]));- let invalid = event(json!([{"value":"bad/id","displayName":"Bad"}]));- let catalog = Catalog::from_history(&[old, new, invalid]);- assert_eq!(catalog.options().len(), 1);- assert_eq!(catalog.options()[0].model.id(), "new");- assert!(- Catalog::from_event(&event(json!([])))- .unwrap()- .options()- .is_empty()- );- assert_eq!(Catalog::Unknown.options().len(), 1);- assert!(Catalog::Unknown.contains(&Model::default()));-}--#[test]-fn rejects_duplicate_aliases_malformed_catalogs_and_unsuccessful_responses() {- for models in [- json!({}),- json!([{"value":"x"}]),- json!([- {"value":"default","displayName":"Default"},{"value":"claude-default","displayName":"Duplicate"}- ]),- ] {- assert!(Catalog::from_event(&event(models)).is_none());- }- let mut rejected = event(json!([{"value":"x","displayName":"X"}]));- rejected.data["payload"]["response"]["subtype"] = json!("error");- assert!(Catalog::from_event(&rejected).is_none());- for id in ["", "../other", "model\nheader", "model with spaces"] {- assert!(Model::parse(id).is_err());- }-}--#[derive(Clone)]-struct AccountCloud {- models: Vec<ModelOption>,- fails: bool,-}-impl Cloud for AccountCloud {- async fn models(&self) -> Result<Vec<ModelOption>> {- if self.fails {- return Err(Error::Http(403));- }- Ok(self.models.clone())- }- async fn history(&self, _: &super::super::model::SessionId) -> Result<Vec<Event>> {- panic!("model discovery must not read any transcript")- }- async fn send(&self, _: &super::super::model::SessionId, _: serde_json::Value) -> Result<()> {- panic!("discovery is read-only")- }- async fn send_batch(- &self,- _: &super::super::model::SessionId,- _: Vec<serde_json::Value>,- ) -> Result<()> {- panic!("discovery is read-only")- }- async fn stream(- &self,- _: &super::super::model::SessionId,- _: Option<u64>,- ) -> Result<super::super::ports::Events> {- panic!("discovery must not wake a worker")- }-}--#[tokio::test]-async fn discovery_returns_account_models_without_any_sessions() {- let first = AccountCloud {- models: vec![ModelOption {- model: Model::parse("claude-fable-5-1").unwrap(),- name: "Claude Fable 5.1".into(),- description: None,- }],- fails: false,- };- let second = AccountCloud {- models: vec![ModelOption {- model: Model::parse("another-account-model").unwrap(),- name: "Another account model".into(),- description: None,- }],- fails: false,- };- let fable = Model::parse("claude-fable-5-1").unwrap();- let catalog = discover(&first).await.unwrap();- assert!(catalog.contains(&Model::default()));- assert!(catalog.contains(&fable));- assert_eq!(catalog.options()[1].name, "Claude Fable 5.1");- assert!(!discover(&second).await.unwrap().contains(&fable));-}--#[tokio::test]-async fn discovery_surfaces_errors_and_does_not_fall_back_to_history() {- let mut cloud = AccountCloud {- models: vec![],- fails: true,- };- assert!(matches!(discover(&cloud).await, Err(Error::Http(403))));- cloud.fails = false;- let catalog = discover(&cloud).await.unwrap();- assert_eq!(catalog.options().len(), 1);- assert!(catalog.contains(&Model::default()));-}diff --git a/crates/claude_cloud_agents/src/domain/ports.rs b/crates/claude_cloud_agents/src/domain/ports.rsdeleted file mode 100644index af82730d10..0000000000--- a/crates/claude_cloud_agents/src/domain/ports.rs+++ /dev/null@@ -1,77 +0,0 @@-//! Capabilities needed by the Claude session adapter.-use super::model::{Event, Result, SessionId};-use super::models::{Model, ModelOption};-use futures::Stream;-use std::{future::Future, pin::Pin};--/// A bounded provider event stream.-pub type Events = Pin<Box<dyn Stream<Item = Result<Event>> + Send>>;--/// Resolve a provider client for exactly one Macro account.-pub trait CloudProvider: Send + Sync + 'static {- /// Owner-bound conversation and lifecycle operations.- type Client: Cloud + CloudLifecycle;- /// A missing connection must never fall back to another account.- fn connect(&self, owner: &str) -> impl Future<Output = Result<Self::Client>> + Send;-}--/// Lifecycle operations kept separate from an attached conversation.-pub trait CloudLifecycle: Cloud {- /// Ensure the owner's selected environment allows this deployment's MCP host.- /// Must finish before creating a container, whose network policy is fixed.- fn prepare_mcp_access(&self, host: &str) -> impl Future<Output = Result<()>> + Send;- /// Create a conversation with this agent's instructions and starting model.- fn create(- &self,- instructions: &str,- model: &Model,- ) -> impl Future<Output = Result<SessionId>> + Send;- /// Archive the owner's conversation reversibly.- fn archive(&self, session: &SessionId) -> impl Future<Output = Result<()>> + Send;-}--/// The host's tool permission policy, exposed by the ACP client in Macro.-pub trait ToolPermissions: Send + Sync {- /// Ask the host whether this specific tool invocation may proceed.- fn allow(- &self,- tool_id: &str,- name: &str,- input: &serde_json::Value,- ) -> impl Future<Output = Result<bool>> + Send;-}--/// Standalone callers without a permission client refuse approval requests.-pub struct DenyToolPermissions;-impl ToolPermissions for DenyToolPermissions {- async fn allow(&self, _: &str, _: &str, _: &serde_json::Value) -> Result<bool> {- Ok(false)- }-}--/// Account-scoped provider operations. Implementors must never choose another user's credential.-pub trait Cloud: Clone + Send + Sync + 'static {- /// Complete model catalog fetched directly with this account's credential.- /// Discovery must not read transcripts, create sessions, or spend inference.- fn models(&self) -> impl Future<Output = Result<Vec<ModelOption>>> + Send;- /// Submit one event. Mutations are not automatically retried.- fn send(- &self,- session: &SessionId,- payload: serde_json::Value,- ) -> impl Future<Output = Result<()>> + Send;- /// Submit ordered events in a single request. Never retry an uncertain batch.- fn send_batch(- &self,- session: &SessionId,- payloads: Vec<serde_json::Value>,- ) -> impl Future<Output = Result<()>> + Send;- /// Resume durable events after `cursor`, with live ephemeral deltas.- fn stream(- &self,- session: &SessionId,- cursor: Option<u64>,- ) -> impl Future<Output = Result<Events>> + Send;- /// Recover durable transcript from the start for an ACP session/load.- fn history(&self, session: &SessionId) -> impl Future<Output = Result<Vec<Event>>> + Send;-}diff --git a/crates/claude_cloud_agents/src/domain/service.rs b/crates/claude_cloud_agents/src/domain/service.rsdeleted file mode 100644index 9a8a5de0f1..0000000000--- a/crates/claude_cloud_agents/src/domain/service.rs+++ /dev/null@@ -1,405 +0,0 @@-//! Session orchestration: single-turn admission, replay, and bounded stream reconnect.-use super::{- mcp::McpServers,- model::{Error, Result, SessionId},- models::{Catalog, Model},- ports::{Cloud, DenyToolPermissions, ToolPermissions},- translate::{Translator, Update},-};-use futures::StreamExt;-use serde_json::json;-use std::sync::Arc;-use tokio::sync::Mutex;--/// One owner-bound cloud conversation.-pub struct Session<C> {- cloud: C,- id: SessionId,- turn: Mutex<()>,- prompt_admission: Mutex<()>,- cursor: Mutex<Option<u64>>,- translator: Mutex<Translator>,- model: Mutex<Model>,- catalog: Mutex<Catalog>,- account_catalog: Mutex<Catalog>,- mcp_servers: Mutex<Option<McpServers>>,-}--#[cfg(test)]-mod test;--impl<C: Cloud> Session<C> {- /// Construct around an already-persisted provider identity.- pub fn new(cloud: C, id: SessionId) -> Arc<Self> {- Self::with_model(cloud, id, Model::default())- }- /// Restore the model projected by Macro's acknowledged config responses.- pub fn with_model(cloud: C, id: SessionId, model: Model) -> Arc<Self> {- Arc::new(Self {- cloud,- id,- turn: Mutex::new(()),- prompt_admission: Mutex::new(()),- cursor: Mutex::new(None),- translator: Mutex::new(Translator::default()),- model: Mutex::new(model),- catalog: Mutex::new(Catalog::Unknown),- account_catalog: Mutex::new(Catalog::Unknown),- mcp_servers: Mutex::new(None),- })- }- /// Saved preference for the next turn, not the worker's current running model.- pub async fn model(&self) -> Model {- self.model.lock().await.clone()- }-- /// Current session aliases supplemented by the direct account catalog.- pub async fn catalog(&self) -> Catalog {- self.catalog- .lock()- .await- .clone()- .supplemented_by(self.account_catalog.lock().await.clone())- }-- /// Read-only discovery; never starts a cloud worker merely to populate a picker.- pub async fn refresh_catalog(&self) -> Result<()> {- let history = self.cloud.history(&self.id).await?;- let account = super::models::discover(&self.cloud).await?;- *self.catalog.lock().await = Catalog::from_history(&history);- *self.account_catalog.lock().await = account;- Ok(())- }-- async fn learn_catalog(- &self,- event: &super::model::Event,- emit: impl Fn(Update) -> Result<()>,- ) -> Result<()> {- if let Some(next) = Catalog::from_event(event) {- let mut catalog = self.catalog.lock().await;- if *catalog != next {- emit(Update::Models {- catalog: next- .clone()- .supplemented_by(self.account_catalog.lock().await.clone()),- current: self.model().await,- })?;- *catalog = next;- }- }- Ok(())- }-- /// Submit a preference without waiting for an idle worker to wake. The next- /// prompt repeats it in the same ordered batch, like the desktop client.- pub async fn set_model(&self, model: Model) -> Result<()> {- let _admission = self.prompt_admission.try_lock().map_err(|_| Error::Busy)?;- let _turn = self.turn.lock().await;- self.refresh_catalog().await?;- if !self.catalog().await.contains(&model) {- return Err(Error::ModelUnavailable);- }- self.cloud- .send(&self.id, model_request(model.clone()).1)- .await?;- *self.model.lock().await = model;- Ok(())- }-- /// Provider identity; also used as the ACP session identity.- pub fn id(&self) -> &SessionId {- &self.id- }-- /// Retain the host's MCP configuration until the next user-requested turn.- /// An empty restore preserves the cloud worker's existing configuration when- /// the host no longer has the original plaintext egress token.- pub async fn configure_mcp(&self, servers: McpServers) -> Result<()> {- let _turn = self.turn.try_lock().map_err(|_| Error::Busy)?;- if !servers.is_empty() {- *self.mcp_servers.lock().await = Some(servers);- }- Ok(())- }-- /// Replay durable transcript for Macro's normal ACP load flow.- pub async fn load(&self) -> Result<Vec<Update>> {- let _turn = self.turn.try_lock().map_err(|_| Error::Busy)?;- let mut translator = Translator::default();- let mut updates = Vec::new();- let mut cursor = None;- for event in self.cloud.history(&self.id).await? {- if let Some(catalog) = Catalog::from_event(&event) {- *self.catalog.lock().await = catalog;- }- updates.extend(translator.accept(&event, true)?);- if let Some(seq) = event.sequence {- cursor = Some(cursor.unwrap_or(0).max(seq));- }- }- *self.cursor.lock().await = cursor;- *self.translator.lock().await = translator;- *self.account_catalog.lock().await = super::models::discover(&self.cloud).await?;- Ok(updates)- }-- /// Mirror cloud-side durable messages while idle. The turn gate prevents- /// interleaving with Macro prompts; cursor and translator are shared with SSE.- pub async fn sync_foreign(&self, emit: impl Fn(Update) -> Result<()> + Send) -> Result<()> {- let Ok(_turn) = self.turn.try_lock() else {- return Ok(());- };- let history = self.cloud.history(&self.id).await?;- let mut cursor = self.cursor.lock().await;- let mut translator = self.translator.lock().await;- for event in history {- let sequence = event.sequence.ok_or(Error::Recovery)?;- if cursor.is_some_and(|last| sequence <= last) {- continue;- }- // A malformed record must not enter the dedup set and disappear on- // the next poll. Commit translation and cursor only after delivery.- let mut next = translator.clone();- self.learn_catalog(&event, &emit).await?;- for update in next.accept(&event, true)? {- emit(update)?;- }- *translator = next;- *cursor = Some(sequence);- }- Ok(())- }-- /// Run a single text prompt, opening the stream first and never retrying the send.- pub async fn prompt(- &self,- text: String,- emit: impl Fn(Update) -> Result<()> + Send,- ) -> Result<()> {- self.prompt_with_permissions(text, emit, &DenyToolPermissions)- .await- }-- /// Run a turn using the host's existing permission policy.- pub async fn prompt_with_permissions(- &self,- text: String,- emit: impl Fn(Update) -> Result<()> + Send,- permissions: &impl ToolPermissions,- ) -> Result<()> {- // Wait behind a short idle poll, but never admit two Macro prompts.- let _admission = self.prompt_admission.try_lock().map_err(|_| Error::Busy)?;- let _turn = self.turn.lock().await;- if text.trim().is_empty() {- return Err(Error::Protocol);- }- let mut cursor = *self.cursor.lock().await;- // An interrupted Macro process does not stop the cloud worker. Do not- // attribute a previous/out-of-band turn's output to this new prompt.- let history = self.cloud.history(&self.id).await?;- if let Some(event) = history- .iter()- .rev()- .find(|event| Catalog::from_event(event).is_some())- {- self.learn_catalog(event, &emit).await?;- }- let mut pending = std::collections::BTreeSet::new();- for event in &history {- let payload = &event.data["payload"];- let content = &payload["message"]["content"];- if payload["type"] == "user"- && (content.is_string()- || content- .as_array()- .is_some_and(|blocks| blocks.iter().any(|block| block["type"] == "text")))- && let Some(id) = payload["uuid"].as_str()- {- pending.insert(id);- }- if payload["type"] == "result" {- if let Some(id) = payload["user_message_uuid"].as_str() {- pending.remove(id);- }- for id in payload["user_message_uuids"]- .as_array()- .into_iter()- .flatten()- .filter_map(|id| id.as_str())- {- pending.remove(id);- }- }- }- if !pending.is_empty() {- return Err(Error::Busy);- }- if !self.catalog().await.contains(&self.model().await) {- self.refresh_catalog().await?;- if !self.catalog().await.contains(&self.model().await) {- return Err(Error::ModelUnavailable);- }- }- let mut translator = self.translator.lock().await;- // Catch completed foreign turns even if a prompt beats the next poll.- for event in &history {- let seq = event.sequence.ok_or(Error::Recovery)?;- if cursor.is_some_and(|last| seq <= last) {- continue;- }- for update in translator.accept(event, true)? {- emit(update)?;- }- cursor = Some(seq);- *self.cursor.lock().await = cursor;- }- let mut stream = self.cloud.stream(&self.id, cursor).await?;- let mcp_request = self.mcp_servers.lock().await.as_ref().map(|servers| {- let id = uuid::Uuid::now_v7().to_string();- let request = json!({"type":"control_request", "request_id":id,- "request":{"subtype":"mcp_set_servers", "servers":servers}});- (id, request)- });- let mcp_request_id = mcp_request.as_ref().map(|(id, _)| id.clone());- let mut mcp_ready = mcp_request_id.is_none();- let message_id = uuid::Uuid::now_v7().to_string();- let (model_request_id, model_event) = model_request(self.model().await);- let mut batch = Vec::new();- if matches!(Catalog::from_history(&history), Catalog::Unknown) {- // Ask the worker for its catalog as part of the user's first turn,- // never by creating or waking a session during settings discovery.- batch.push(json!({"type":"control_request","request_id":uuid::Uuid::now_v7().to_string(),"request":{"subtype":"initialize"}}));- }- // An idle cloud worker wakes for the user event. Configure its tools in- // the same ordered batch before that event, as with the model choice.- if let Some((_, request)) = mcp_request {- batch.push(request);- }- batch.push(model_event);- batch.push(- json!({"type":"user", "uuid":message_id, "session_id":self.id.as_str(),- "parent_tool_use_id":null, "message":{"role":"user","content":text}}),- );- self.cloud.send_batch(&self.id, batch).await?;- let mut retries = 0u8;- let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(600);- loop {- let event = tokio::time::timeout_at(deadline, stream.next())- .await- .map_err(|_| Error::Network)?;- match event {- Some(Ok(event)) => {- if event.kind == "client_event"- && event- .sequence- .is_some_and(|seq| cursor.is_some_and(|last| seq <= last))- {- continue;- }- let payload = &event.data["payload"];- self.learn_catalog(&event, &emit).await?;- if payload["type"] == "control_response"- && mcp_request_id.as_deref().is_some_and(|id| {- payload["response"]["request_id"].as_str() == Some(id)- })- {- let response = &payload["response"];- if response["subtype"] != "success"- || !response["response"]["errors"]- .as_object()- .is_some_and(|errors| errors.is_empty())- {- let _ = self.cancel().await;- return Err(Error::McpConfiguration);- }- mcp_ready = true;- }- if payload["type"] == "control_response"- && payload["response"]["request_id"].as_str() == Some(&model_request_id)- && payload["response"]["subtype"] == "error"- {- // The batch is accepted already; best-effort interrupt- // avoids knowingly continuing with a rejected preference.- let _ = self.cancel().await;- return Err(Error::ModelUnavailable);- }- if payload["type"] == "control_request"- && payload["request"]["subtype"] == "can_use_tool"- {- let request = &payload["request"];- let allowed = mcp_ready- && permissions- .allow(- request["tool_use_id"].as_str().ok_or(Error::Protocol)?,- request["tool_name"].as_str().ok_or(Error::Protocol)?,- &request["input"],- )- .await?;- let decision = if allowed {- json!({"behavior":"allow", "updatedInput":request["input"]})- } else {- json!({"behavior":"deny", "message":"Tool use was declined by the session host"})- };- self.cloud- .send(- &self.id,- json!({"type":"control_response", "response":{- "subtype":"success", "request_id":payload["request_id"],- "response":decision- }}),- )- .await?;- }- let own_result = payload["type"] == "result"- && (payload["user_message_uuid"].as_str() == Some(&message_id)- || payload["user_message_uuids"].as_array().is_some_and(|ids| {- ids.iter().any(|id| id.as_str() == Some(&message_id))- }));- if own_result && !mcp_ready {- let _ = self.cancel().await;- return Err(Error::McpConfiguration);- }- for update in translator.accept(&event, false)? {- if matches!(update, Update::Finished { .. }) && !own_result {- continue;- }- emit(update)?;- }- if event.kind == "client_event"- && let Some(seq) = event.sequence- {- cursor = Some(seq);- *self.cursor.lock().await = cursor;- }- if own_result {- return Ok(());- }- }- Some(Err(error @ (Error::Authorization | Error::Protocol | Error::Recovery))) => {- return Err(error);- }- Some(Err(_)) | None => {- if retries >= 3 {- return Err(Error::Network);- }- retries += 1;- tokio::time::sleep(std::time::Duration::from_secs(u64::from(retries))).await;- stream = self.cloud.stream(&self.id, cursor).await?;- }- }- }- }-- /// Ask the cloud worker to interrupt; closing SSE alone would not stop it.- pub async fn cancel(&self) -> Result<()> {- self.cloud.send(&self.id, json!({"type":"control_request", "request_id":format!("interrupt-{}",uuid::Uuid::now_v7()), "request":{"subtype":"interrupt"}})).await- }-}--fn model_request(model: Model) -> (String, serde_json::Value) {- let id = uuid::Uuid::now_v7().to_string();- let payload = json!({"type":"control_request","request_id":id,- "request":{"subtype":"set_model","model":model.provider_value()}});- (id, payload)-}diff --git a/crates/claude_cloud_agents/src/domain/service/test.rs b/crates/claude_cloud_agents/src/domain/service/test.rsdeleted file mode 100644index cf57ebe9a8..0000000000--- a/crates/claude_cloud_agents/src/domain/service/test.rs+++ /dev/null@@ -1,370 +0,0 @@-use super::*;-use crate::domain::{model::Event, ports::Events};-use std::sync::atomic::{AtomicUsize, Ordering};--#[derive(Clone, Default)]-struct ReconnectingCloud {- sends: Arc<Mutex<Vec<serde_json::Value>>>,- cursors: Arc<Mutex<Vec<Option<u64>>>>,- streams: Arc<AtomicUsize>,- history: Arc<Mutex<Vec<Event>>>,-}-impl Cloud for ReconnectingCloud {- async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {- Ok(Vec::new())- }- async fn send_batch(- &self,- session: &SessionId,- payloads: Vec<serde_json::Value>,- ) -> Result<()> {- assert_eq!(- payloads[payloads.len() - 2]["request"]["subtype"],- "set_model"- );- if payloads.len() == 3 {- assert_eq!(payloads[0]["request"]["subtype"], "initialize");- }- self.send(session, payloads.last().unwrap().clone()).await- }- async fn send(&self, _: &SessionId, payload: serde_json::Value) -> Result<()> {- self.sends.lock().await.push(payload);- Ok(())- }- async fn history(&self, _: &SessionId) -> Result<Vec<Event>> {- Ok(self.history.lock().await.clone())- }- async fn stream(&self, _: &SessionId, cursor: Option<u64>) -> Result<Events> {- self.cursors.lock().await.push(cursor);- let attempt = self.streams.fetch_add(1, Ordering::SeqCst);- let sends = self.sends.clone();- Ok(futures::stream::once(async move {- let sent = loop {- if let Some(sent) = sends.lock().await.first().cloned() { break sent; }- tokio::task::yield_now().await;- };- let durable = Event { kind:"client_event".into(), sequence:Some(1), data:json!({"payload":{- "type":"assistant", "uuid":"a1", "message":{"id":"msg1","content":[{"type":"text","text":"hello"}]}- }}) };- if attempt == 0 { vec![Ok(durable), Err(Error::Network)] }- else { vec![Ok(durable), Ok(Event {kind:"client_event".into(), sequence:Some(2), data:json!({"payload":{- "type":"result","uuid":"r1","subtype":"success","is_error":false,"user_message_uuid":sent["uuid"],"usage":{}- }})})] }- }).flat_map(futures::stream::iter).boxed())- }-}--#[tokio::test]-async fn stream_reconnect_resumes_after_delivery_without_resending_prompt() {- let cloud = ReconnectingCloud::default();- let session = Session::new(cloud.clone(), SessionId::parse("cse_test").unwrap());- let output = std::sync::Mutex::new(Vec::new());- session- .prompt("hello".into(), |update| {- output.lock().unwrap().push(update);- Ok(())- })- .await- .unwrap();- assert_eq!(cloud.sends.lock().await.len(), 1);- assert_eq!(*cloud.cursors.lock().await, vec![None, Some(1)]);- assert_eq!(- output- .lock()- .unwrap()- .iter()- .filter(|u| matches!(u, Update::Text(_)))- .count(),- 1- );-}--#[tokio::test]-async fn cancel_sends_a_cloud_interrupt_not_just_a_local_disconnect() {- let cloud = ReconnectingCloud::default();- let session = Session::new(cloud.clone(), SessionId::parse("cse_test").unwrap());- session.cancel().await.unwrap();- assert_eq!(- cloud.sends.lock().await[0]["request"]["subtype"],- "interrupt"- );-}--fn foreign_turn() -> Vec<Event> {- vec![- Event {- kind: "client_event".into(),- sequence: Some(1),- data: json!({"payload":{"type":"user","uuid":"foreign-user","message":{"content":"sent in Claude"}}}),- },- Event {- kind: "client_event".into(),- sequence: Some(2),- data: json!({"payload":{"type":"assistant","uuid":"foreign-answer","message":{"id":"foreign-msg","content":[{"type":"text","text":"cloud reply"}]}}}),- },- Event {- kind: "client_event".into(),- sequence: Some(3),- data: json!({"payload":{"type":"result","uuid":"foreign-result","subtype":"success","user_message_uuid":"foreign-user","usage":{}}}),- },- ]-}--#[tokio::test]-async fn foreign_updates_are_ordered_deduplicated_and_resume_after_load() {- let cloud = ReconnectingCloud::default();- let session = Session::new(cloud.clone(), SessionId::parse("cse_test").unwrap());- let output = std::sync::Mutex::new(Vec::new());- let emit = |update| {- output.lock().unwrap().push(update);- Ok(())- };- *cloud.history.lock().await = foreign_turn();- session.sync_foreign(emit).await.unwrap();- session.sync_foreign(emit).await.unwrap();- assert_eq!(output.lock().unwrap().len(), 3);- assert_eq!(- output.lock().unwrap()[0],- Update::User("sent in Claude".into())- );- assert_eq!(- output.lock().unwrap()[1],- Update::Text("cloud reply".into())- );- assert!(matches!(output.lock().unwrap()[2], Update::Finished { .. }));- assert!(cloud.sends.lock().await.is_empty());- session.load().await.unwrap();- output.lock().unwrap().clear();- session.sync_foreign(emit).await.unwrap();- assert!(output.lock().unwrap().is_empty());- // A fresh attachment hydrates once, then its poll does not replay history.- let resumed = Session::new(cloud, SessionId::parse("cse_test").unwrap());- assert_eq!(resumed.load().await.unwrap().len(), 3);- resumed.sync_foreign(emit).await.unwrap();- assert!(output.lock().unwrap().is_empty());-}--#[tokio::test]-async fn poll_skips_active_macro_turn_without_contacting_provider() {- let cloud = ReconnectingCloud::default();- *cloud.history.lock().await = foreign_turn();- let session = Session::new(cloud, SessionId::parse("cse_test").unwrap());- let _active = session.turn.lock().await;- session- .sync_foreign(|_| panic!("must not interleave"))- .await- .unwrap();- assert!(session.cursor.lock().await.is_none());-}--#[test]-fn session_link_is_fixed_origin_and_rejects_path_injection() {- assert_eq!(- SessionId::parse("cse_test").unwrap().web_url(),- "https://claude.ai/code/cse_test"- );- assert!(SessionId::parse("cse_x/../../other").is_err());-}--#[derive(Clone, Default)]-struct ModelCloud {- sends: Arc<Mutex<Vec<serde_json::Value>>>,- reject: Arc<std::sync::atomic::AtomicBool>,- reject_model: Arc<std::sync::atomic::AtomicBool>,- account_models: Arc<Mutex<Vec<crate::domain::models::ModelOption>>>,-}-impl Cloud for ModelCloud {- async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {- Ok(self.account_models.lock().await.clone())- }-- async fn send(&self, _: &SessionId, payload: serde_json::Value) -> Result<()> {- if self.reject.load(Ordering::SeqCst) {- return Err(Error::Network);- }- self.sends.lock().await.push(payload);- Ok(())- }- async fn send_batch(&self, _: &SessionId, payloads: Vec<serde_json::Value>) -> Result<()> {- assert_eq!(payloads.len(), 2);- assert_eq!(payloads[0]["request"]["subtype"], "set_model");- assert_eq!(payloads[1]["type"], "user");- self.sends.lock().await.extend(payloads);- Ok(())- }- async fn history(&self, _: &SessionId) -> Result<Vec<Event>> {- Ok(vec![Event {- kind: "client_event".into(),- sequence: Some(0),- data: json!({"payload":{"type":"control_response","response":{"subtype":"success","response":{"models":[- {"value":"default","displayName":"Default"},- {"value":"opus","displayName":"Opus"},- {"value":"sonnet","displayName":"Sonnet"},- {"value":"haiku","displayName":"Haiku"}]}}}}),- }])- }- async fn stream(&self, _: &SessionId, _: Option<u64>) -> Result<Events> {- let before = self.sends.lock().await.len();- let cloud = self.clone();- Ok(futures::stream::once(async move {- let sent = loop {- let sends = cloud.sends.lock().await;- if sends.len() >= before + 2 { break sends[before..].to_vec(); }- drop(sends);- tokio::task::yield_now().await;- };- vec![- Ok(Event { kind:"client_event".into(), sequence:Some(1), data:json!({"payload":{"type":"control_response","response":{"subtype":"error","request_id":"unrelated"}}}) }),- Ok(Event { kind:"client_event".into(), sequence:Some(2), data:json!({"payload":{"type":"control_response","response":{"subtype":if cloud.reject_model.load(Ordering::SeqCst) { "error" } else { "success" },"request_id":sent[0]["request_id"]}}}) }),- Ok(Event { kind:"client_event".into(), sequence:Some(3), data:json!({"payload":{"type":"result","uuid":"result","subtype":"success","user_message_uuid":sent[1]["uuid"],"usage":{}}}) }),- ]- }).flat_map(futures::stream::iter).boxed())- }-}--#[tokio::test]-async fn account_fable_choice_survives_selection_load_poll_and_prompt() {- let cloud = ModelCloud::default();- *cloud.account_models.lock().await = vec![crate::domain::models::ModelOption {- model: Model::parse("claude-fable-5-1").unwrap(),- name: "Fable 5.1".into(),- description: None,- }];- let fable = Model::parse("claude-fable-5-1").unwrap();- let id = SessionId::parse("cse_test").unwrap();- let session = Session::new(cloud.clone(), id.clone());- session.set_model(fable.clone()).await.unwrap();- assert_eq!(cloud.sends.lock().await[0]["request"]["model"], fable.id());- assert!(matches!(- session- .set_model(Model::parse("not-reported").unwrap())- .await,- Err(Error::ModelUnavailable)- ));-- let restored = Session::with_model(cloud.clone(), id, fable.clone());- restored.load().await.unwrap();- assert!(restored.catalog().await.contains(&fable));- let changed = Event {- kind: "client_event".into(),- sequence: Some(1),- data: json!({"payload":{"type":"control_response","response":{"subtype":"success","response":{"models":[- {"value":"sonnet","displayName":"New Sonnet label"}- ]}}}}),- };- restored- .learn_catalog(&changed, |update| {- let Update::Models { catalog, current } = update else {- panic!("expected catalog")- };- assert!(catalog.contains(&fable));- assert_eq!(current, fable);- assert!(!catalog.contains(&Model::parse("opus").unwrap()));- Ok(())- })- .await- .unwrap();- restored.prompt("hello".into(), |_| Ok(())).await.unwrap();- assert_eq!(cloud.sends.lock().await[1]["request"]["model"], fable.id());-- // Claude still has final authority to reject an account-discovered choice.- cloud.reject_model.store(true, Ordering::SeqCst);- let restored = Session::with_model(cloud.clone(), SessionId::parse("cse_test").unwrap(), fable);- restored.load().await.unwrap();- assert!(matches!(- restored.prompt("hello".into(), |_| Ok(())).await,- Err(Error::ModelUnavailable)- ));- assert_eq!(- cloud.sends.lock().await.last().unwrap()["request"]["subtype"],- "interrupt"- );-}--#[tokio::test]-async fn idle_model_preference_does_not_wait_for_worker_and_failed_sends_preserve_it() {- let cloud = ModelCloud::default();- let session = Session::new(cloud.clone(), SessionId::parse("cse_test").unwrap());- session- .set_model(Model::parse("opus").unwrap())- .await- .unwrap();- assert_eq!(session.model().await, Model::parse("opus").unwrap());- assert_eq!(cloud.sends.lock().await[0]["request"]["model"], "opus");- assert!(session.cursor.lock().await.is_none());- cloud.reject.store(true, Ordering::SeqCst);- assert!(matches!(- session.set_model(Model::parse("haiku").unwrap()).await,- Err(Error::Network)- ));- assert_eq!(session.model().await, Model::parse("opus").unwrap());- cloud.reject.store(false, Ordering::SeqCst);- session.set_model(Model::default()).await.unwrap();- assert!(cloud.sends.lock().await.last().unwrap()["request"]["model"].is_null());-}--#[tokio::test]-async fn provider_rejection_of_own_model_request_interrupts_and_fails_the_turn() {- let cloud = ModelCloud::default();- cloud.reject_model.store(true, Ordering::SeqCst);- let session = Session::with_model(- cloud.clone(),- SessionId::parse("cse_test").unwrap(),- Model::parse("opus").unwrap(),- );- assert!(matches!(- session.prompt("hello".into(), |_| Ok(())).await,- Err(Error::ModelUnavailable)- ));- assert_eq!(- cloud.sends.lock().await.last().unwrap()["request"]["subtype"],- "interrupt"- );-}--#[tokio::test]-async fn restored_model_is_batched_before_next_prompt_and_busy_changes_are_rejected() {- let cloud = ModelCloud::default();- let session = Session::with_model(- cloud.clone(),- SessionId::parse("cse_test").unwrap(),- Model::parse("haiku").unwrap(),- );- let admitted = session.prompt_admission.lock().await;- assert!(matches!(- session.set_model(Model::parse("opus").unwrap()).await,- Err(Error::Busy)- ));- drop(admitted);- session.prompt("hello".into(), |_| Ok(())).await.unwrap();- assert_eq!(cloud.sends.lock().await[0]["request"]["model"], "haiku");- assert_eq!(cloud.sends.lock().await[1]["type"], "user");-}--#[tokio::test]-async fn default_is_also_reset_in_the_prompt_batch() {- let cloud = ModelCloud::default();- let session = Session::new(cloud.clone(), SessionId::parse("cse_test").unwrap());- session.prompt("hello".into(), |_| Ok(())).await.unwrap();- assert!(cloud.sends.lock().await[0]["request"]["model"].is_null());-}--#[tokio::test]-async fn malformed_foreign_record_is_not_silently_skipped_on_retry() {- let cloud = ReconnectingCloud::default();- *cloud.history.lock().await = vec![Event {- kind: "client_event".into(),- sequence: Some(1),- data: json!({"payload":{"type":"assistant","uuid":"invalid","message":{}}}),- }];- let session = Session::new(cloud, SessionId::parse("cse_test").unwrap());- for _ in 0..2 {- assert!(- session- .sync_foreign(|_| panic!("invalid record"))- .await- .is_err()- );- assert!(session.cursor.lock().await.is_none());- }-}diff --git a/crates/claude_cloud_agents/src/domain/translate.rs b/crates/claude_cloud_agents/src/domain/translate.rsdeleted file mode 100644index c2e72156f5..0000000000--- a/crates/claude_cloud_agents/src/domain/translate.rs+++ /dev/null@@ -1,185 +0,0 @@-//! Reconcile ephemeral deltas with durable Claude messages before emitting UI updates.-use super::model::{Error, Event, Result};-use serde_json::Value;-use std::collections::{BTreeMap, BTreeSet};--/// A provider-neutral display or lifecycle update.-#[derive(Debug, Clone, PartialEq)]-pub enum Update {- /// Provider-reported models changed while replaying or streaming.- Models {- /// Complete catalog, replacing the previous one.- catalog: super::models::Catalog,- /// Saved next-turn preference; discovery must not reset it.- current: super::models::Model,- },- /// Assistant-visible text delta.- Text(String),- /// Reasoning text explicitly emitted by the provider.- Thought(String),- /// Historical user input, emitted only while loading a transcript.- User(String),- /// A tool invocation with its provider identity and input.- Tool {- /// Stable tool-call id.- id: String,- /// Display/tool name.- name: String,- /// Tool input.- input: Value,- /// Parent call for a delegated agent.- parent: Option<String>,- },- /// Completed tool output.- ToolResult {- /// Corresponding call id.- id: String,- /// Provider output.- output: Value,- /// Whether the tool failed.- failed: bool,- },- /// Final provider result. Usage remains provider-reported, not a Macro API charge.- Finished {- /// Failed rather than completed successfully.- failed: bool,- /// User cancelled the turn.- cancelled: bool,- /// Provider token usage.- usage: Value,- },-}--/// Per-attachment state that deduplicates durable messages and reconciles live text.-#[derive(Clone, Default)]-pub struct Translator {- current_message: Option<String>,- blocks: BTreeMap<(String, u64), String>,- durable: BTreeSet<String>,-}--impl Translator {- /// Process one provider record. History mode includes user messages.- pub fn accept(&mut self, event: &Event, history: bool) -> Result<Vec<Update>> {- if event.kind == "catch_up_truncated" {- return Err(Error::Recovery);- }- let payload = &event.data["payload"];- let mut updates = Vec::new();- if event.kind == "ephemeral_event" && payload["type"] == "stream_event" {- let frame = &payload["event"];- match frame["type"].as_str() {- Some("message_start") => {- self.current_message = frame["message"]["id"].as_str().map(str::to_owned)- }- Some("content_block_delta") => {- if let (Some(message), Some(index)) =- (&self.current_message, frame["index"].as_u64())- {- let (field, thought) = match frame["delta"]["type"].as_str() {- Some("text_delta") => ("text", false),- Some("thinking_delta") => ("thinking", true),- _ => return Ok(updates),- };- if let Some(text) = frame["delta"][field].as_str() {- self.blocks- .entry((message.clone(), index))- .or_default()- .push_str(text);- updates.push(if thought {- Update::Thought(text.to_owned())- } else {- Update::Text(text.to_owned())- });- }- }- }- _ => {}- }- return Ok(updates);- }- if event.kind != "client_event" {- return Ok(updates);- }- if let Some(id) = payload["uuid"].as_str()- && !self.durable.insert(id.to_owned())- {- return Ok(updates);- }- match payload["type"].as_str() {- Some("assistant") => {- let id = payload["message"]["id"].as_str().ok_or(Error::Protocol)?;- for (index, block) in payload["message"]["content"]- .as_array()- .ok_or(Error::Protocol)?- .iter()- .enumerate()- {- match block["type"].as_str() {- Some("text" | "thinking") => {- let thought = block["type"] == "thinking";- let text = block[if thought { "thinking" } else { "text" }]- .as_str()- .ok_or(Error::Protocol)?;- let sent = self- .blocks- .entry((id.to_owned(), index as u64))- .or_default();- let remaining =- text.strip_prefix(sent.as_str()).ok_or(Error::Recovery)?;- if !remaining.is_empty() {- updates.push(if thought {- Update::Thought(remaining.to_owned())- } else {- Update::Text(remaining.to_owned())- });- }- *sent = text.to_owned();- }- Some("tool_use") => updates.push(Update::Tool {- id: block["id"].as_str().ok_or(Error::Protocol)?.to_owned(),- name: block["name"].as_str().ok_or(Error::Protocol)?.to_owned(),- input: block["input"].clone(),- parent: payload["parent_tool_use_id"].as_str().map(str::to_owned),- }),- _ => {}- }- }- }- Some("user") => {- let content = &payload["message"]["content"];- if history && let Some(text) = content.as_str() {- updates.push(Update::User(text.to_owned()));- }- for block in content.as_array().into_iter().flatten() {- if block["type"] == "tool_result" {- updates.push(Update::ToolResult {- id: block["tool_use_id"]- .as_str()- .ok_or(Error::Protocol)?- .to_owned(),- output: block["content"].clone(),- failed: block["is_error"].as_bool().unwrap_or(false),- });- } else if history && block["type"] == "text" {- updates.push(Update::User(- block["text"].as_str().ok_or(Error::Protocol)?.to_owned(),- ));- }- }- }- Some("result") => updates.push(Update::Finished {- failed: payload["is_error"].as_bool().unwrap_or(false)- || payload["subtype"] != "success",- cancelled: payload["stop_reason"] == "interrupt"- || payload["subtype"] == "interrupted",- usage: payload["usage"].clone(),- }),- _ => {}- }- Ok(updates)- }-}--#[cfg(test)]-mod test;diff --git a/crates/claude_cloud_agents/src/domain/translate/test.rs b/crates/claude_cloud_agents/src/domain/translate/test.rsdeleted file mode 100644index 67ec937bf4..0000000000--- a/crates/claude_cloud_agents/src/domain/translate/test.rs+++ /dev/null@@ -1,97 +0,0 @@-use super::*;-use serde_json::json;-fn event(kind: &str, payload: Value) -> Event {- Event {- kind: kind.into(),- data: json!({"payload":payload}),- sequence: None,- }-}--#[test]-fn reconciles_live_deltas_and_durable_message_without_duplication() {- let mut translator = Translator::default();- translator.accept(&event("ephemeral_event", json!({"type":"stream_event","event":{"type":"message_start","message":{"id":"msg1"}}})), false).unwrap();- let delta = event(- "ephemeral_event",- json!({"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hé"}}}),- );- assert_eq!(- translator.accept(&delta, false).unwrap(),- vec![Update::Text("hé".into())]- );- let durable = event(- "client_event",- json!({"type":"assistant","uuid":"a1","message":{"id":"msg1","content":[{"type":"text","text":"héllo"}]}}),- );- assert_eq!(- translator.accept(&durable, false).unwrap(),- vec![Update::Text("llo".into())]- );- assert!(translator.accept(&durable, false).unwrap().is_empty());-}--#[test]-fn durable_only_transcript_replays_full_text() {- let mut translator = Translator::default();- let durable = event(- "client_event",- json!({"type":"assistant","uuid":"a1","message":{"id":"msg1","content":[{"type":"text","text":"hello"}]}}),- );- assert_eq!(- translator.accept(&durable, true).unwrap(),- vec![Update::Text("hello".into())]- );-}--#[test]-fn text_with_no_message_start_waits_for_durable_recovery() {- let mut translator = Translator::default();- let delta = event(- "ephemeral_event",- json!({"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}}),- );- assert!(translator.accept(&delta, false).unwrap().is_empty());-}--#[test]-fn history_includes_user_but_live_echo_does_not_duplicate_prompt() {- let message = event(- "client_event",- json!({"type":"user","uuid":"u1","message":{"content":"hi"}}),- );- assert!(- Translator::default()- .accept(&message, false)- .unwrap()- .is_empty()- );- assert_eq!(- Translator::default().accept(&message, true).unwrap(),- vec![Update::User("hi".into())]- );-}--#[test]-fn tool_output_retains_call_identity_and_failure() {- let message = event(- "client_event",- json!({"type":"user","uuid":"u1","message":{"content":[{"type":"tool_result","tool_use_id":"t1","content":"denied","is_error":true}]}}),- );- assert_eq!(- Translator::default().accept(&message, false).unwrap(),- vec![Update::ToolResult {- id: "t1".into(),- output: json!("denied"),- failed: true- }]- );-}--#[test]-fn truncated_replay_is_not_silently_accepted() {- assert!(matches!(- Translator::default().accept(&event("catch_up_truncated", json!({})), false),- Err(Error::Recovery)- ));-}diff --git a/crates/claude_cloud_agents/src/inbound/acp.rs b/crates/claude_cloud_agents/src/inbound/acp.rsdeleted file mode 100644index 3ef4f8d341..0000000000--- a/crates/claude_cloud_agents/src/inbound/acp.rs+++ /dev/null@@ -1,281 +0,0 @@-//! Thin ACP transport over the account-scoped Claude session service.-use crate::domain::{- model::{Error, Result},- models::{Catalog, Model},- ports::Cloud,- service::Session,- translate::Update,-};-use agent_runtime_protocol::domain::{- connection::ServerChannel,- schema::v0::{AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage},-};-use serde_json::{Value, json};-use std::sync::{Arc, Mutex};-use tokio::sync::mpsc::UnboundedSender;--mod mcp;-mod permissions;--/// Attach a Claude conversation to Macro's existing runtime protocol.-pub fn attach<C: Cloud>(session: Arc<Session<C>>) -> ServerChannel {- let (server, mut runtime) = ServerChannel::duplex();- tokio::spawn(async move {- let tx = runtime.tx;- let permissions =- permissions::Permissions::new(tx.clone(), session.id().as_str().to_owned());- let _ = tx.send(ToServerMessage::Event {- event: SystemEvent::AcpReady,- });- let mut turns = tokio::task::JoinSet::new();- let mut mirrors = tokio::task::JoinSet::new();- let usage_totals = Arc::new(Mutex::new((0u64, 0u64)));- let every = std::time::Duration::from_secs(2);- let mut mirror = tokio::time::interval_at(tokio::time::Instant::now() + every, every);- mirror.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);- let mut ready = false;- let mut retry_after = tokio::time::Instant::now();- loop {- tokio::select! {- _ = tx.closed() => break,- Some(_) = turns.join_next(), if !turns.is_empty() => {},- Some(result) = mirrors.join_next(), if !mirrors.is_empty() => {- if !matches!(result, Ok(Ok(()))) {- retry_after = tokio::time::Instant::now() + std::time::Duration::from_secs(30);- }- }- _ = mirror.tick(), if ready && turns.is_empty() && mirrors.is_empty() => {- if tokio::time::Instant::now() < retry_after { continue; }- let session = session.clone();- let tx = tx.clone();- let usage_totals = usage_totals.clone();- mirrors.spawn(async move {- session.sync_foreign(|update| {- if let Update::Finished { usage, .. } = &update { let _ = cumulative_usage(&usage_totals, usage); }- notification(&tx, session.id().as_str(), update)- }).await- });- }- incoming = runtime.rx.recv() => {- let Some(ToRuntimeMessage::Acp(AcpMessage(raw))) = incoming else { break; };- let Ok(frame) = serde_json::to_value(raw) else { break; };- if frame.get("method").is_none() {- permissions.respond(&frame);- continue;- }- let id = frame.get("id").cloned();- let params = &frame["params"];- let method = frame["method"].as_str().unwrap_or_default();- if method.starts_with("session/") && method != "session/new" && params["sessionId"].as_str() != Some(session.id().as_str()) {- if let Some(id) = id { let _ = failure(&tx, id, "Unknown Claude session"); }- continue;- }- match method {- "initialize" => { if let Some(id) = id { let _ = reply(&tx, id, json!({- "protocolVersion":1, "agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true}},- "agentInfo":{"name":"claude-cloud","title":"Claude Cloud","version":"0.1.0"}, "authMethods":[]- })); } }- "session/new" => {- let setup = match mcp::servers(params) {- Ok(servers) => session.configure_mcp(servers).await,- Err(error) => Err(error),- };- if let Err(error) = setup {- if let Some(id) = id { let _ = failure(&tx, id, &error.to_string()); }- continue;- }- if let Err(error) = session.refresh_catalog().await {- if let Some(id) = id { let _ = failure(&tx, id, &error.to_string()); }- continue;- }- if let Some(id) = id {- let _ = reply(&tx, id, json!({"sessionId":session.id().as_str(), "configOptions":model_options(&session.catalog().await, &session.model().await)}));- ready = true;- }- }- "session/load" => {- let setup = match mcp::servers(params) {- Ok(servers) => session.configure_mcp(servers).await,- Err(error) => Err(error),- };- if let Err(error) = setup {- if let Some(id) = id { let _ = failure(&tx, id, &error.to_string()); }- continue;- }- mirrors.abort_all();- while mirrors.join_next().await.is_some() {}- if let Some(id) = id {- match session.load().await {- Ok(updates) => {- if let Ok(mut totals) = usage_totals.lock() { *totals = (0, 0); }- for update in updates {- if let Update::Finished { usage, .. } = &update { let _ = cumulative_usage(&usage_totals, usage); }- let _ = notification(&tx, session.id().as_str(), update);- }- let _ = reply(&tx, id, json!({"configOptions":model_options(&session.catalog().await, &session.model().await)}));- ready = true;- }- Err(error) => { let _ = failure(&tx, id, &error.to_string()); }- }- }- }- "session/prompt" => {- let Some(id) = id else { continue; };- if !turns.is_empty() { let _ = failure(&tx, id, "Claude still has a turn in progress"); continue; }- let Some(blocks) = params["prompt"].as_array() else { let _ = failure(&tx, id, "A text prompt is required"); continue; };- if blocks.iter().any(|b| b["type"] != "text") { let _ = failure(&tx, id, "The Claude demo currently supports text prompts only"); continue; }- let text = blocks.iter().filter_map(|b| b["text"].as_str()).collect::<Vec<_>>().join("\n");- let session = session.clone();- let tx = tx.clone();- let usage_totals = usage_totals.clone();- let permissions = permissions.clone();- turns.spawn(async move {- let final_result = Arc::new(Mutex::new(None));- let observed = final_result.clone();- let outcome = session.prompt_with_permissions(text, |update| {- if let Update::Finished { failed, cancelled, usage } = update {- *observed.lock().map_err(|_| Error::Protocol)? = Some((failed, cancelled, usage));- Ok(())- } else { notification(&tx, session.id().as_str(), update) }- }, &permissions).await;- match outcome {- Err(error) => { let _ = failure(&tx, id, &error.to_string()); }- Ok(()) => {- let result = final_result.lock().ok().and_then(|r| r.clone());- match result {- Some((false, cancelled, usage)) => { let _ = reply(&tx, id, json!({"stopReason":if cancelled {"cancelled"} else {"end_turn"}, "usage":cumulative_usage(&usage_totals, &usage), "_meta":{"claudeCode":{"usage":usage}}})); }- Some((true, true, _)) => { let _ = reply(&tx, id, json!({"stopReason":"cancelled"})); }- _ => { let _ = failure(&tx, id, "Claude reported an unsuccessful turn"); }- }- }- }- });- }- "session/cancel" => {- let outcome = session.cancel().await;- if let Some(id) = id {- match outcome { Ok(()) => { let _ = reply(&tx, id, json!({})); }, Err(error) => { let _ = failure(&tx, id, &error.to_string()); } }- } else if outcome.is_err() {- let _ = notification(&tx, session.id().as_str(), Update::Text("\nClaude could not confirm cancellation; check the session in Claude.\n".into()));- }- }- "session/set_config_option" if params["configId"] == "model" => {- let Some(id) = id else { continue; };- let model = match Model::parse(params["value"].as_str().unwrap_or_default()) {- Ok(model) => model,- Err(error) => { let _ = failure(&tx, id, &error.to_string()); continue; }- };- let session = session.clone();- let tx = tx.clone();- turns.spawn(async move {- match session.set_model(model.clone()).await {- Ok(()) => { let _ = reply(&tx, id, json!({"configOptions":model_options(&session.catalog().await, &model)})); }- Err(error) => { let _ = failure(&tx, id, &error.to_string()); }- }- });- }- _ => { if let Some(id) = id { let _ = failure(&tx, id, "Unsupported operation in the Claude Cloud demo"); } }- }- }- }- }- // Losing Macro's transport must not leave locally-running adapter tasks behind.- // The provider conversation remains resumable; do not archive on disconnect.- turns.abort_all();- mirrors.abort_all();- });- server-}--/// Map domain discovery to Macro's standard ACP model picker.-pub fn model_options(catalog: &Catalog, model: &Model) -> Value {- let options: Vec<_> = catalog- .options()- .iter()- .map(|m| json!({"value":m.model.id(),"name":m.name,"description":m.description}))- .collect();- json!([{"id":"model","name":"Model","category":"model","type":"select","currentValue":model.id(),"options":options}])-}--fn cumulative_usage(totals: &Mutex<(u64, u64)>, usage: &Value) -> Value {- let Ok(mut totals) = totals.lock() else {- return Value::Null;- };- totals.0 = totals- .0- .saturating_add(usage["input_tokens"].as_u64().unwrap_or(0));- totals.1 = totals- .1- .saturating_add(usage["output_tokens"].as_u64().unwrap_or(0));- json!({"inputTokens":totals.0,"outputTokens":totals.1})-}--fn send(tx: &UnboundedSender<ToServerMessage>, value: Value) -> Result<()> {- let frame = serde_json::from_value(value).map_err(|_| Error::Protocol)?;- tx.send(ToServerMessage::Acp(AcpMessage(frame)))- .map_err(|_| Error::Network)-}-fn reply(tx: &UnboundedSender<ToServerMessage>, id: Value, result: Value) -> Result<()> {- send(tx, json!({"jsonrpc":"2.0","id":id,"result":result}))-}-fn failure(tx: &UnboundedSender<ToServerMessage>, id: Value, message: &str) -> Result<()> {- send(- tx,- json!({"jsonrpc":"2.0","id":id,"error":{"code":-32000,"message":message}}),- )-}--fn notification(- tx: &UnboundedSender<ToServerMessage>,- session: &str,- update: Update,-) -> Result<()> {- let update = match update {- Update::Models { catalog, current } => {- json!({"sessionUpdate":"config_option_update","configOptions":model_options(&catalog, ¤t)})- }- Update::Text(text) => {- json!({"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":text}})- }- Update::Thought(text) => {- json!({"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":text}})- }- Update::User(text) => {- json!({"sessionUpdate":"user_message_chunk","content":{"type":"text","text":text}})- }- Update::Tool {- id,- name,- input,- parent,- } => {- json!({"sessionUpdate":"tool_call","toolCallId":id,"title":name,"kind":"other","status":"in_progress","rawInput":input,- "_meta":{"claudeCode":{"toolName":name,"parentToolUseId":parent}}})- }- Update::ToolResult { id, output, failed } => {- json!({"sessionUpdate":"tool_call_update","toolCallId":id,"status":if failed {"failed"} else {"completed"},"rawOutput":output})- }- Update::Finished {- failed, cancelled, ..- } => {- let outcome = if cancelled {- json!({"kind":"cancelled"})- } else if failed {- json!({"kind":"failed", "message":"Claude reported an unsuccessful turn"})- } else {- json!({"kind":"finished"})- };- return send(- tx,- json!({"jsonrpc":"2.0","method":"_session/turn_complete","params":{"sessionId":session,"outcome":outcome}}),- );- }- };- send(- tx,- json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":session,"update":update}}),- )-}--#[cfg(test)]-mod test;diff --git a/crates/claude_cloud_agents/src/inbound/acp/mcp.rs b/crates/claude_cloud_agents/src/inbound/acp/mcp.rsdeleted file mode 100644index ee4031a0e1..0000000000--- a/crates/claude_cloud_agents/src/inbound/acp/mcp.rs+++ /dev/null@@ -1,46 +0,0 @@-//! Translate the standard ACP server list into the provider's remote server model.-use crate::domain::{- mcp::{McpServer, McpServers, McpTransport},- model::{Error, Result},-};-use agent_client_protocol::schema::v1::McpServer as AcpMcpServer;--pub(super) fn servers(params: &serde_json::Value) -> Result<McpServers> {- let servers: Vec<AcpMcpServer> = serde_json::from_value(- params- .get("mcpServers")- .cloned()- .unwrap_or_else(|| serde_json::json!([])),- )- .map_err(|_| Error::McpConfiguration)?;- let mut result = McpServers::new();- for server in servers {- let (name, transport, url, headers) = match server {- AcpMcpServer::Http(server) => {- (server.name, McpTransport::Http, server.url, server.headers)- }- AcpMcpServer::Sse(server) => {- (server.name, McpTransport::Sse, server.url, server.headers)- }- _ => return Err(Error::McpConfiguration),- };- if name.is_empty() || result.contains_key(&name) {- return Err(Error::McpConfiguration);- }- let mut mapped_headers = std::collections::BTreeMap::new();- for header in headers {- if mapped_headers.insert(header.name, header.value).is_some() {- return Err(Error::McpConfiguration);- }- }- result.insert(- name,- McpServer {- transport,- url,- headers: mapped_headers,- },- );- }- Ok(result)-}diff --git a/crates/claude_cloud_agents/src/inbound/acp/permissions.rs b/crates/claude_cloud_agents/src/inbound/acp/permissions.rsdeleted file mode 100644index b6fc27b8a7..0000000000--- a/crates/claude_cloud_agents/src/inbound/acp/permissions.rs+++ /dev/null@@ -1,77 +0,0 @@-//! Correlates provider permission requests with the existing ACP host policy.-use super::*;-use crate::domain::ports::ToolPermissions;-use std::collections::HashMap;-use tokio::sync::oneshot;--#[derive(Clone)]-pub(super) struct Permissions {- tx: UnboundedSender<ToServerMessage>,- session: String,- pending: Arc<Mutex<HashMap<String, oneshot::Sender<bool>>>>,-}--impl Permissions {- pub(super) fn new(tx: UnboundedSender<ToServerMessage>, session: String) -> Self {- Self {- tx,- session,- pending: Arc::default(),- }- }-- pub(super) fn respond(&self, frame: &Value) {- let Some(id) = frame["id"].as_str() else {- return;- };- let sender = self- .pending- .lock()- .ok()- .and_then(|mut pending| pending.remove(id));- if let Some(sender) = sender {- let outcome = &frame["result"]["outcome"];- let allowed = outcome["outcome"] == "selected" && outcome["optionId"] == "allow_once";- let _ = sender.send(allowed);- }- }-}--impl ToolPermissions for Permissions {- async fn allow(&self, tool_id: &str, name: &str, input: &Value) -> Result<bool> {- let id = format!("claude-permission-{}", uuid::Uuid::now_v7());- let (sender, receiver) = oneshot::channel();- self.pending- .lock()- .map_err(|_| Error::Protocol)?- .insert(id.clone(), sender);- let sent = send(- &self.tx,- json!({- "jsonrpc":"2.0", "id":id, "method":"session/request_permission",- "params":{- "sessionId":self.session,- "toolCall":{"toolCallId":tool_id,"title":name,"status":"pending","rawInput":input},- "options":[- {"optionId":"allow_once","name":"Allow once","kind":"allow_once"},- {"optionId":"reject_once","name":"Reject","kind":"reject_once"}- ]- }- }),- );- let allowed = if sent.is_ok() {- tokio::time::timeout(std::time::Duration::from_secs(60), receiver)- .await- .ok()- .and_then(|result| result.ok())- .unwrap_or(false)- } else {- false- };- self.pending- .lock()- .map_err(|_| Error::Protocol)?- .remove(&id);- Ok(allowed)- }-}diff --git a/crates/claude_cloud_agents/src/inbound/acp/test.rs b/crates/claude_cloud_agents/src/inbound/acp/test.rsdeleted file mode 100644index 07f0970619..0000000000--- a/crates/claude_cloud_agents/src/inbound/acp/test.rs+++ /dev/null@@ -1,233 +0,0 @@-use super::*;-use crate::domain::{- model::{Event, SessionId},- ports::Events,-};-use futures::StreamExt;--#[derive(Clone, Default)]-struct FakeCloud {- submitted: Arc<tokio::sync::Mutex<Vec<Value>>>,- history: Arc<tokio::sync::Mutex<Vec<Event>>>,-}-impl Cloud for FakeCloud {- async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {- Ok(Vec::new())- }- async fn send_batch(&self, session: &SessionId, payloads: Vec<Value>) -> Result<()> {- assert_eq!(- payloads[payloads.len() - 2]["request"]["subtype"],- "set_model"- );- if payloads.len() == 3 {- assert_eq!(payloads[0]["request"]["subtype"], "initialize");- }- self.send(session, payloads.last().unwrap().clone()).await- }- async fn send(&self, _: &SessionId, payload: Value) -> Result<()> {- self.submitted.lock().await.push(payload);- Ok(())- }- async fn history(&self, _: &SessionId) -> Result<Vec<Event>> {- Ok(self.history.lock().await.clone())- }- async fn stream(&self, _: &SessionId, _: Option<u64>) -> Result<Events> {- let submitted = self.submitted.clone();- let before = submitted.lock().await.len();- Ok(futures::stream::once(async move {- let payload = loop {- if let Some(value) = submitted.lock().await.get(before).cloned() { break value; }- tokio::task::yield_now().await;- };- if payload["type"] == "control_request" {- return Ok(Event {kind:"client_event".into(), sequence:Some(1), data:json!({"payload":{- "type":"control_response", "response":{"subtype":"success","request_id":payload["request_id"]}- }})});- }- Ok(Event {kind:"client_event".into(), sequence:Some(1), data:json!({"payload":{- "type":"result", "uuid":"result1", "subtype":"success", "is_error":false,- "user_message_uuid":payload["uuid"], "usage":{"input_tokens":1,"output_tokens":2}- }})})- }).boxed())- }-}--#[tokio::test]-async fn model_catalog_and_submitted_preference_roundtrip() {- let cloud = FakeCloud::default();- *cloud.history.lock().await = vec![Event {- kind: "client_event".into(),- sequence: Some(0),- data: json!({"payload":{"type":"control_response","response":{"subtype":"success","response":{"models":[- {"value":"default","displayName":"Provider Default"},- {"value":"sonnet","displayName":"Provider Sonnet"},- {"value":"new-model-2030","displayName":"New model","description":"New from provider"}]}}}}),- }];- let session = Session::new(cloud.clone(), SessionId::parse("cse_test").unwrap());- let mut channel = attach(session.clone());- channel- .tx- .send(frame(- json!({"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}),- ))- .unwrap();- let response = read(&mut channel).await;- let config = &response["result"]["configOptions"][0];- assert_eq!(config["currentValue"], "claude-default");- assert_eq!(config["options"].as_array().unwrap().len(), 3);- for (id, value) in [(2, "sonnet"), (3, "new-model-2030"), (4, "claude-default")] {- channel.tx.send(frame(json!({"jsonrpc":"2.0","id":id,"method":"session/set_config_option","params":{"sessionId":"cse_test","configId":"model","value":value}}))).unwrap();- let response = read(&mut channel).await;- assert_eq!(response["id"], id);- assert_eq!(- response["result"]["configOptions"][0]["currentValue"],- value- );- assert_eq!(session.model().await.id(), value);- }- channel.tx.send(frame(json!({"jsonrpc":"2.0","id":5,"method":"session/set_config_option","params":{"sessionId":"cse_test","configId":"model","value":"made-up"}}))).unwrap();- assert!(read(&mut channel).await.get("error").is_some());- let submitted = cloud.submitted.lock().await;- assert_eq!(submitted.len(), 3);- assert!(submitted.iter().all(|p| p["type"] == "control_request"));- assert!(submitted[2]["request"]["model"].is_null());-}-fn frame(value: Value) -> ToRuntimeMessage {- ToRuntimeMessage::Acp(AcpMessage(serde_json::from_value(value).unwrap()))-}--#[tokio::test]-async fn polled_catalog_updates_the_picker_without_resetting_the_saved_model() {- let cloud = FakeCloud::default();- let mut channel = attach(Session::with_model(- cloud.clone(),- SessionId::parse("cse_test").unwrap(),- Model::parse("saved-model").unwrap(),- ));- channel- .tx- .send(frame(- json!({"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}),- ))- .unwrap();- let initial = read(&mut channel).await;- assert_eq!(- initial["result"]["configOptions"][0]["options"]- .as_array()- .unwrap()- .len(),- 1- );- *cloud.history.lock().await = vec![Event {- kind: "client_event".into(),- sequence: Some(1),- data: json!({"payload":{"type":"control_response","response":{"subtype":"success","response":{"models":[{"value":"future-model","displayName":"Future model","description":"Fresh catalog"}]}}}}),- }];- let update = read(&mut channel).await;- assert_eq!(- update["params"]["update"]["sessionUpdate"],- "config_option_update"- );- let config = &update["params"]["update"]["configOptions"][0];- assert_eq!(config["currentValue"], "saved-model");- assert_eq!(config["options"][0]["value"], "future-model");- assert_eq!(config["options"][0]["description"], "Fresh catalog");- assert!(cloud.submitted.lock().await.is_empty());-}-async fn read(channel: &mut ServerChannel) -> Value {- loop {- if let ToServerMessage::Acp(AcpMessage(raw)) =- tokio::time::timeout(std::time::Duration::from_secs(5), channel.rx.recv())- .await- .unwrap()- .unwrap()- {- return serde_json::to_value(raw).unwrap();- }- }-}--#[tokio::test]-async fn handshake_prompt_completion_and_usage_roundtrip() {- let cloud = FakeCloud::default();- let mut channel = attach(Session::new(- cloud.clone(),- SessionId::parse("cse_test").unwrap(),- ));- channel- .tx- .send(frame(- json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}),- ))- .unwrap();- assert_eq!(- read(&mut channel).await["result"]["agentCapabilities"]["loadSession"],- true- );- channel.tx.send(frame(json!({"jsonrpc":"2.0","id":2,"method":"session/new","params":{"cwd":"/","mcpServers":[]}}))).unwrap();- assert_eq!(read(&mut channel).await["result"]["sessionId"], "cse_test");- channel.tx.send(frame(json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":"cse_test","prompt":[{"type":"text","text":"hello"}]}}))).unwrap();- let response = read(&mut channel).await;- assert_eq!(response["result"]["stopReason"], "end_turn");- assert_eq!(response["result"]["usage"]["inputTokens"], 1);- assert_eq!(cloud.submitted.lock().await.len(), 1);-}--#[tokio::test]-async fn cannot_address_another_users_cloud_session() {- let cloud = FakeCloud::default();- let mut channel = attach(Session::new(- cloud.clone(),- SessionId::parse("cse_test").unwrap(),- ));- channel.tx.send(frame(json!({"jsonrpc":"2.0","id":1,"method":"session/prompt","params":{"sessionId":"cse_other","prompt":[{"type":"text","text":"hello"}]}}))).unwrap();- assert!(read(&mut channel).await.get("error").is_some());- assert!(cloud.submitted.lock().await.is_empty());-}--#[tokio::test]-async fn idle_cloud_turn_is_polled_into_acp_and_completed_without_a_macro_prompt() {- let cloud = FakeCloud::default();- let mut channel = attach(Session::new(- cloud.clone(),- SessionId::parse("cse_test").unwrap(),- ));- channel.tx.send(frame(json!({"jsonrpc":"2.0","id":1,"method":"session/new","params":{"cwd":"/","mcpServers":[]}}))).unwrap();- assert!(read(&mut channel).await.get("result").is_some());- *cloud.history.lock().await = vec![- Event {- kind: "client_event".into(),- sequence: Some(1),- data: json!({"payload":{"type":"user","uuid":"u","message":{"content":"web prompt"}}}),- },- Event {- kind: "client_event".into(),- sequence: Some(2),- data: json!({"payload":{"type":"assistant","uuid":"a","message":{"id":"msg","content":[{"type":"text","text":"web answer"}]}}}),- },- Event {- kind: "client_event".into(),- sequence: Some(3),- data: json!({"payload":{"type":"result","uuid":"r","subtype":"success","user_message_uuid":"u","usage":{}}}),- },- ];- assert_eq!(- read(&mut channel).await["params"]["update"]["sessionUpdate"],- "user_message_chunk"- );- assert_eq!(- read(&mut channel).await["params"]["update"]["content"]["text"],- "web answer"- );- let completed = read(&mut channel).await;- assert_eq!(completed["method"], "_session/turn_complete");- assert_eq!(completed["params"]["outcome"]["kind"], "finished");- assert!(cloud.submitted.lock().await.is_empty());- assert!(- tokio::time::timeout(std::time::Duration::from_millis(2200), channel.rx.recv())- .await- .is_err()- );-}--mod mcp;diff --git a/crates/claude_cloud_agents/src/inbound/acp/test/mcp.rs b/crates/claude_cloud_agents/src/inbound/acp/test/mcp.rsdeleted file mode 100644index bc9e044635..0000000000--- a/crates/claude_cloud_agents/src/inbound/acp/test/mcp.rs+++ /dev/null@@ -1,233 +0,0 @@-use super::*;--#[derive(Clone, Default)]-struct McpCloud {- submitted: Arc<Mutex<Vec<Value>>>,- events: Arc<Mutex<Option<tokio::sync::mpsc::UnboundedSender<Result<Event>>>>>,- prompt: Arc<Mutex<Value>>,- fail_mcp: bool,- omit_mcp_ack: bool,- require_permission: bool,-}--impl McpCloud {- fn emit(&self, payload: Value) {- self.events- .lock()- .unwrap()- .as_ref()- .unwrap()- .send(Ok(Event {- kind: "client_event".into(),- sequence: None,- data: json!({"payload":payload}),- }))- .unwrap();- }- fn finish(&self) {- self.emit(- json!({"type":"result", "uuid":"result", "subtype":"success", "is_error":false,- "user_message_uuid":self.prompt.lock().unwrap()["uuid"], "usage":{}}),- );- }-}-impl Cloud for McpCloud {- async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {- Ok(vec![])- }- async fn history(&self, _: &SessionId) -> Result<Vec<Event>> {- Ok(vec![])- }- async fn stream(&self, _: &SessionId, _: Option<u64>) -> Result<Events> {- let (tx, rx) = tokio::sync::mpsc::unbounded_channel();- *self.events.lock().unwrap() = Some(tx);- Ok(futures::stream::unfold(rx, |mut rx| async move {- rx.recv().await.map(|event| (event, rx))- })- .boxed())- }- async fn send_batch(&self, id: &SessionId, payloads: Vec<Value>) -> Result<()> {- for payload in payloads {- self.send(id, payload).await?;- }- Ok(())- }- async fn send(&self, _: &SessionId, payload: Value) -> Result<()> {- self.submitted.lock().unwrap().push(payload.clone());- if payload["request"]["subtype"] == "mcp_set_servers" && !self.omit_mcp_ack {- self.emit(json!({"type":"control_response", "response":{- "subtype":"success", "request_id":payload["request_id"],- "response":{"added":["macro"], "removed":[], "errors":if self.fail_mcp {json!({"macro":"unreachable"})} else {json!({})}}- }}));- }- if payload["type"] == "user" {- *self.prompt.lock().unwrap() = payload;- if self.require_permission {- self.emit(json!({"type":"control_request", "request_id":"tool-permission", "request":{- "subtype":"can_use_tool", "tool_use_id":"tool-1", "tool_name":"mcp__macro__search", "input":{"query":"hello"}- }}));- } else {- self.finish();- }- } else if payload["type"] == "control_response" {- self.finish();- }- Ok(())- }-}--fn remote_servers() -> Value {- json!([{"type":"http", "name":"macro", "url":"https://egress.example/mcp-macro",- "headers":[{"name":"Authorization", "value":"Bearer session-test"}]}])-}--async fn open(cloud: McpCloud, method: &str, servers: Value) -> ServerChannel {- let mut channel = attach(Session::new(cloud, SessionId::parse("cse_test").unwrap()));- channel- .tx- .send(frame(json!({"jsonrpc":"2.0", "id":1, "method":method,- "params":{"sessionId":"cse_test", "cwd":"/", "mcpServers":servers}})))- .unwrap();- assert!(read(&mut channel).await.get("result").is_some());- channel-}-fn prompt(channel: &ServerChannel) {- channel- .tx- .send(frame(- json!({"jsonrpc":"2.0", "id":2, "method":"session/prompt",- "params":{"sessionId":"cse_test", "prompt":[{"type":"text", "text":"hello"}]}}),- ))- .unwrap();-}--#[tokio::test]-async fn new_and_resumed_sessions_forward_authenticated_mcp_before_prompt() {- for method in ["session/new", "session/load"] {- let cloud = McpCloud::default();- let mut channel = open(cloud.clone(), method, remote_servers()).await;- assert!(- cloud.submitted.lock().unwrap().is_empty(),- "opening must not wake the worker"- );- prompt(&channel);- let result = read(&mut channel).await;- assert_eq!(result["result"]["stopReason"], "end_turn");- let sent = cloud.submitted.lock().unwrap();- assert_eq!(sent[1]["request"]["subtype"], "mcp_set_servers");- let server = &sent[1]["request"]["servers"]["macro"];- assert_eq!(server["type"], "http");- assert_eq!(server["url"], "https://egress.example/mcp-macro");- assert_eq!(server["headers"]["Authorization"], "Bearer session-test");- assert_eq!(sent.last().unwrap()["type"], "user");- }-}--#[tokio::test]-async fn failed_mcp_setup_fails_the_turn_and_requests_interruption() {- let cloud = McpCloud {- fail_mcp: true,- ..Default::default()- };- let mut channel = open(cloud.clone(), "session/new", remote_servers()).await;- prompt(&channel);- assert!(read(&mut channel).await.get("error").is_some());- assert!(- cloud- .submitted- .lock()- .unwrap()- .iter()- .any(|event| event["request"]["subtype"] == "interrupt")- );-}--#[tokio::test]-async fn tool_permissions_roundtrip_through_the_acp_host() {- for choice in ["allow_once", "reject_once"] {- let cloud = McpCloud {- require_permission: true,- ..Default::default()- };- let mut channel = open(cloud.clone(), "session/new", remote_servers()).await;- prompt(&channel);- let request = read(&mut channel).await;- assert_eq!(request["method"], "session/request_permission");- assert_eq!(request["params"]["toolCall"]["toolCallId"], "tool-1");- channel- .tx- .send(frame(json!({"jsonrpc":"2.0", "id":request["id"],- "result":{"outcome":{"outcome":"selected", "optionId":choice}}})))- .unwrap();- assert_eq!(read(&mut channel).await["result"]["stopReason"], "end_turn");- let sent = cloud.submitted.lock().unwrap();- let response = sent- .iter()- .find(|event| event["type"] == "control_response")- .unwrap();- assert_eq!(response["response"]["request_id"], "tool-permission");- assert_eq!(- response["response"]["response"]["behavior"],- if choice == "allow_once" {- "allow"- } else {- "deny"- }- );- }-}--#[tokio::test]-async fn unsupported_stdio_and_duplicate_names_fail_the_handshake() {- for servers in [- json!([{"name":"local", "command":"sh", "args":[], "env":[]}]),- json!([remote_servers()[0], remote_servers()[0]]),- ] {- let cloud = McpCloud::default();- let mut channel = attach(Session::new(- cloud.clone(),- SessionId::parse("cse_test").unwrap(),- ));- channel- .tx- .send(frame(- json!({"jsonrpc":"2.0", "id":1, "method":"session/new",- "params":{"cwd":"/", "mcpServers":servers}}),- ))- .unwrap();- assert!(read(&mut channel).await.get("error").is_some());- assert!(cloud.submitted.lock().unwrap().is_empty());- }-}--#[tokio::test]-async fn a_missing_mcp_acknowledgment_cannot_report_a_successful_turn() {- let cloud = McpCloud {- omit_mcp_ack: true,- ..Default::default()- };- let mut channel = open(cloud.clone(), "session/new", remote_servers()).await;- prompt(&channel);- assert!(read(&mut channel).await.get("error").is_some());- assert!(- cloud- .submitted- .lock()- .unwrap()- .iter()- .any(|event| event["request"]["subtype"] == "interrupt")- );-}--#[test]-fn sse_servers_preserve_their_transport_and_auth_headers() {- let mut servers = remote_servers();- servers[0]["type"] = json!("sse");- let mapped = super::super::mcp::servers(&json!({"mcpServers":servers})).unwrap();- let wire = serde_json::to_value(mapped).unwrap();- assert_eq!(wire["macro"]["type"], "sse");- assert_eq!(- wire["macro"]["headers"]["Authorization"],- "Bearer session-test"- );-}diff --git a/crates/claude_cloud_agents/src/inbound/auth.rs b/crates/claude_cloud_agents/src/inbound/auth.rsdeleted file mode 100644index 1dbd65a8a7..0000000000--- a/crates/claude_cloud_agents/src/inbound/auth.rs+++ /dev/null@@ -1,199 +0,0 @@-//! Authenticated connection endpoints; ownership and consent policy live in the domain.-use crate::domain::{- auth::{AuthError, ClaudeAuth},- model::Secret,-};-use axum::{- Json, Router,- extract::{DefaultBodyLimit, FromRef, State},- http::{HeaderValue, StatusCode, header},- response::{IntoResponse, Response},- routing::{get, post},-};-use macro_authorization::{- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOnly,-};-use serde::{Deserialize, Serialize};-use std::sync::Arc;-use utoipa::ToSchema;--/// Router dependencies, assembled by the service composition root.-pub struct ClaudeAuthState<S, A> {- service: Arc<S>,- authorization: MacroAuthorizationState<A>,-}-impl<S, A> ClaudeAuthState<S, A> {- /// Bind the domain service and standard Macro authentication.- pub fn new(service: Arc<S>, authorization: MacroAuthorizationState<A>) -> Self {- Self {- service,- authorization,- }- }-}-impl<S, A> Clone for ClaudeAuthState<S, A> {- fn clone(&self) -> Self {- Self {- service: self.service.clone(),- authorization: self.authorization.clone(),- }- }-}-impl<S, A> FromRef<ClaudeAuthState<S, A>> for MacroAuthorizationState<A> {- fn from_ref(state: &ClaudeAuthState<S, A>) -> Self {- state.authorization.clone()- }-}--/// A JSON body is required on writes, including start/disconnect (no form-based CSRF).-#[derive(Deserialize, ToSchema)]-#[serde(deny_unknown_fields)]-pub struct EmptyRequest {}--/// One-time manual code. Deliberately does not implement Debug.-#[derive(Deserialize, ToSchema)]-#[serde(rename_all = "camelCase", deny_unknown_fields)]-pub struct CompleteRequest {- /// Server-issued handle; never an owner selected by the caller.- pub attempt_id: String,- /// Claude's complete code#state string, not an access token.- #[schema(value_type = String)]- pub code: Secret,-}--/// Safe connection metadata.-#[derive(Serialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct StatusResponse {- /// Whether this deployment supports browser connection.- pub enabled: bool,- /// Whether the authenticated Macro user has connected.- pub connected: bool,- /// Whether reconnecting after service restart is required.- pub ephemeral: bool,-}--/// Public PKCE challenge and attempt handle; contains no verifier or provider tokens.-#[derive(Serialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct StartResponse {- /// Opaque owner-bound attempt handle.- pub attempt_id: String,- /// Claude-hosted consent page.- pub authorization_url: String,- /// Attempt lifetime in seconds.- pub expires_in: u64,-}--/// Build `/claude-auth` routes. Bot and harness credentials are rejected by UserOnly.-pub fn router<S: ClaudeAuth, A: MacroAuthorizationService>(state: ClaudeAuthState<S, A>) -> Router {- Router::new()- .route(- "/claude-auth",- get(status::<S, A>).delete(disconnect::<S, A>),- )- .route("/claude-auth/start", post(start::<S, A>))- .route("/claude-auth/complete", post(complete::<S, A>))- .layer(DefaultBodyLimit::max(8192))- .layer(axum::middleware::map_response(- |mut response: Response| async move {- response- .headers_mut()- .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));- response- },- ))- .with_state(state)-}--/// Read connection status for the authenticated user only.-#[utoipa::path(get, path = "/claude-auth", tag = "claude-auth", security(("bearerAuth" = [])), responses((status = 200, body = StatusResponse), (status = 401, description = "Unauthenticated")))]-pub async fn status<S: ClaudeAuth, A: MacroAuthorizationService>(- State(state): State<ClaudeAuthState<S, A>>,- auth: MacroAuthorizationExtractor<A, UserOnly>,-) -> Json<StatusResponse> {- let status = state- .service- .status(auth.authorization.macro_user_id.as_ref())- .await;- Json(StatusResponse {- enabled: status.enabled,- connected: status.connected,- ephemeral: status.ephemeral,- })-}--/// Create an expiring PKCE challenge for the authenticated user.-#[utoipa::path(post, path = "/claude-auth/start", tag = "claude-auth", security(("bearerAuth" = [])), request_body = EmptyRequest, responses((status = 200, body = StartResponse), (status = 403, description = "Disabled"), (status = 429, description = "Too many attempts")))]-pub async fn start<S: ClaudeAuth, A: MacroAuthorizationService>(- State(state): State<ClaudeAuthState<S, A>>,- auth: MacroAuthorizationExtractor<A, UserOnly>,- Json(_input): Json<EmptyRequest>,-) -> Response {- match state- .service- .begin(auth.authorization.macro_user_id.as_ref())- .await- {- Ok(login) => Json(StartResponse {- attempt_id: login.attempt_id,- authorization_url: login.authorization_url,- expires_in: login.expires_in,- })- .into_response(),- Err(error) => failure(error),- }-}--/// Exchange one code; never return access or refresh tokens.-#[utoipa::path(post, path = "/claude-auth/complete", tag = "claude-auth", security(("bearerAuth" = [])), request_body = CompleteRequest, responses((status = 204, description = "Connected"), (status = 400, description = "Invalid code"), (status = 409, description = "Expired or replayed"), (status = 502, description = "Provider failed")))]-pub async fn complete<S: ClaudeAuth, A: MacroAuthorizationService>(- State(state): State<ClaudeAuthState<S, A>>,- auth: MacroAuthorizationExtractor<A, UserOnly>,- Json(input): Json<CompleteRequest>,-) -> Response {- match state- .service- .complete(- auth.authorization.macro_user_id.as_ref(),- &input.attempt_id,- input.code,- )- .await- {- Ok(()) => StatusCode::NO_CONTENT.into_response(),- Err(error) => failure(error),- }-}--/// Forget only the authenticated user's grant and cancel pending consent.-#[utoipa::path(delete, path = "/claude-auth", tag = "claude-auth", security(("bearerAuth" = [])), request_body = EmptyRequest, responses((status = 204, description = "Disconnected"), (status = 403, description = "Disabled")))]-pub async fn disconnect<S: ClaudeAuth, A: MacroAuthorizationService>(- State(state): State<ClaudeAuthState<S, A>>,- auth: MacroAuthorizationExtractor<A, UserOnly>,- Json(_input): Json<EmptyRequest>,-) -> Response {- match state- .service- .disconnect(auth.authorization.macro_user_id.as_ref())- .await- {- Ok(()) => StatusCode::NO_CONTENT.into_response(),- Err(error) => failure(error),- }-}--fn failure(error: AuthError) -> Response {- let status = match error {- AuthError::Disabled => StatusCode::FORBIDDEN,- AuthError::InvalidAttempt => StatusCode::CONFLICT,- AuthError::InvalidCode => StatusCode::BAD_REQUEST,- AuthError::Busy => StatusCode::TOO_MANY_REQUESTS,- AuthError::Provider(_) => StatusCode::BAD_GATEWAY,- };- (- status,- Json(serde_json::json!({"message": error.to_string()})),- )- .into_response()-}diff --git a/crates/claude_cloud_agents/src/inbound/mod.rs b/crates/claude_cloud_agents/src/inbound/mod.rsdeleted file mode 100644index ec91e75caf..0000000000--- a/crates/claude_cloud_agents/src/inbound/mod.rs+++ /dev/null@@ -1,4 +0,0 @@-//! Macro's ACP-facing adapter.-pub mod acp;-/// Authenticated browser connection endpoints.-pub mod auth;diff --git a/crates/claude_cloud_agents/src/lib.rs b/crates/claude_cloud_agents/src/lib.rsdeleted file mode 100644index dcd68a3585..0000000000--- a/crates/claude_cloud_agents/src/lib.rs+++ /dev/null@@ -1,6 +0,0 @@-#![deny(missing_docs)]-//! Demo-only Claude Code cloud provider using user subscription OAuth.--pub mod domain;-pub mod inbound;-pub mod outbound;diff --git a/crates/claude_cloud_agents/src/outbound/credentials.rs b/crates/claude_cloud_agents/src/outbound/credentials.rsdeleted file mode 100644index eed530e47f..0000000000--- a/crates/claude_cloud_agents/src/outbound/credentials.rs+++ /dev/null@@ -1,237 +0,0 @@-//! Legacy private-file and memory adapters for standalone smoke tests.-pub use crate::domain::credentials::AccountCredentials;-use crate::domain::{- credentials::{ConnectionState, GrantRepository, GrantTransaction, RefreshGrant},- model::{Credentials, Error, Result, Secret},-};-use serde::{Deserialize, Serialize};-use std::{- collections::BTreeMap,- path::{Path, PathBuf},- sync::Arc,- time::{SystemTime, UNIX_EPOCH},-};-use tokio::{io::AsyncWriteExt, sync::Mutex};--/// Public OAuth client used by Claude Code Desktop.-pub const CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";-const TOKEN_URL: &str = "https://platform.claude.com/v1/oauth/token";-/// Compatibility name for the standalone smoke runner.-pub type FileCredentials = AccountCredentials;--#[derive(Default, Serialize, Deserialize)]-struct FileData {- users: BTreeMap<String, Credentials>,- #[serde(default)]- connections: BTreeMap<String, ConnectionState>,-}-struct FileRepository {- path: Option<PathBuf>,- data: Arc<Mutex<FileData>>,-}--impl AccountCredentials {- /// Empty process-local store for tests. Reads no existing credentials.- pub fn memory() -> Result<Self> {- Ok(Self::new(- Arc::new(FileRepository {- path: None,- data: Arc::default(),- }),- Arc::new(ClaudeRefresh::new()?),- ))- }- /// Explicit private-file opt-in for standalone experiments only.- pub async fn open(path: PathBuf) -> Result<Self> {- check_private(&path, false).await?;- check_private(path.parent().ok_or(Error::Credentials)?, true).await?;- let bytes = zeroize::Zeroizing::new(- tokio::fs::read(&path)- .await- .map_err(|_| Error::Credentials)?,- );- if bytes.len() > 2_000_000 {- return Err(Error::Credentials);- }- let data: FileData = serde_json::from_slice(&bytes).map_err(|_| Error::Credentials)?;- for owner in data.users.keys().chain(data.connections.keys()) {- if owner.trim() != owner || !owner.starts_with("macro|") || owner.contains('\0') {- return Err(Error::Credentials);- }- }- for grant in data.users.values().chain(- data.connections- .values()- .filter_map(|state| state.grant.as_ref()),- ) {- uuid::Uuid::parse_str(&grant.organization_id).map_err(|_| Error::Credentials)?;- if !grant.environment_id.starts_with("env_")- || !grant- .environment_id- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b == b'_')- {- return Err(Error::Credentials);- }- }- Ok(Self::new(- Arc::new(FileRepository {- path: Some(path),- data: Arc::new(Mutex::new(data)),- }),- Arc::new(ClaudeRefresh::new()?),- ))- }-}--impl FileRepository {- async fn persist(path: &Option<PathBuf>, data: &FileData) -> Result<()> {- let Some(path) = path else {- return Ok(());- };- let bytes =- zeroize::Zeroizing::new(serde_json::to_vec(data).map_err(|_| Error::Credentials)?);- let temp = path.with_extension(format!("{}.tmp", uuid::Uuid::now_v7()));- let mut options = tokio::fs::OpenOptions::new();- options.write(true).create_new(true);- #[cfg(unix)]- options.mode(0o600);- let mut file = options.open(&temp).await.map_err(|_| Error::Credentials)?;- file.write_all(&bytes)- .await- .map_err(|_| Error::Credentials)?;- file.sync_all().await.map_err(|_| Error::Credentials)?;- tokio::fs::rename(&temp, path)- .await- .map_err(|_| Error::Credentials)- }-}-struct FileTransaction {- data: tokio::sync::OwnedMutexGuard<FileData>,- path: Option<PathBuf>,- owner: String,- state: ConnectionState,-}-#[async_trait::async_trait]-impl GrantRepository for FileRepository {- async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {- let data = self.data.clone().lock_owned().await;- let state = data- .connections- .get(owner)- .cloned()- .unwrap_or_else(|| ConnectionState {- grant: data.users.get(owner).cloned(),- ..Default::default()- });- Ok(Box::new(FileTransaction {- data,- path: self.path.clone(),- owner: owner.to_owned(),- state,- }))- }-}-#[async_trait::async_trait]-impl GrantTransaction for FileTransaction {- fn state(&mut self) -> &mut ConnectionState {- &mut self.state- }- async fn commit(self: Box<Self>) -> Result<()> {- let Self {- mut data,- path,- owner,- state,- } = *self;- let previous = data.connections.insert(owner.clone(), state);- let legacy = data.users.remove(&owner);- if let Err(error) = FileRepository::persist(&path, &data).await {- match previous {- Some(value) => {- data.connections.insert(owner.clone(), value);- }- None => {- data.connections.remove(&owner);- }- }- if let Some(value) = legacy {- data.users.insert(owner, value);- }- return Err(error);- }- Ok(())- }-}--/// Fixed-origin token-refresh transport.-pub struct ClaudeRefresh {- http: reqwest::Client,-}-impl ClaudeRefresh {- /// Construct without redirects or automatic retries.- pub fn new() -> Result<Self> {- Ok(Self {- http: reqwest::Client::builder()- .redirect(reqwest::redirect::Policy::none())- .timeout(std::time::Duration::from_secs(30))- .build()- .map_err(|_| Error::Network)?,- })- }-}-#[async_trait::async_trait]-impl RefreshGrant for ClaudeRefresh {- async fn refresh(&self, current: &Credentials) -> Result<Credentials> {- let refresh = current.refresh_token.as_ref().ok_or(Error::Authorization)?;- let response = self.http.post(TOKEN_URL).json(&serde_json::json!({- "grant_type":"refresh_token", "refresh_token":refresh.expose(), "client_id":CLIENT_ID,- "scope":"user:inference user:profile user:sessions:claude_code"- })).send().await.map_err(|_| Error::Network)?;- if !response.status().is_success() {- return Err(Error::Authorization);- }- #[derive(Deserialize)]- struct Refresh {- access_token: Secret,- refresh_token: Option<Secret>,- expires_in: u64,- }- let refreshed: Refresh = response.json().await.map_err(|_| Error::Protocol)?;- if refreshed.expires_in < 1 {- return Err(Error::Authorization);- }- let now = SystemTime::now()- .duration_since(UNIX_EPOCH)- .map_err(|_| Error::Credentials)?- .as_secs();- let mut updated = current.clone();- updated.access_token = refreshed.access_token;- updated.refresh_token = refreshed.refresh_token.or(updated.refresh_token);- updated.expires_at = now.saturating_add(refreshed.expires_in);- Ok(updated)- }-}-async fn check_private(path: &Path, directory: bool) -> Result<()> {- let metadata = tokio::fs::symlink_metadata(path)- .await- .map_err(|_| Error::Credentials)?;- if metadata.file_type().is_symlink()- || (directory && !metadata.is_dir())- || (!directory && !metadata.is_file())- {- return Err(Error::Credentials);- }- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- if metadata.permissions().mode() & 0o077 != 0 {- return Err(Error::Credentials);- }- }- #[cfg(not(unix))]- return Err(Error::Credentials);- Ok(())-}-#[cfg(test)]-mod test;diff --git a/crates/claude_cloud_agents/src/outbound/credentials/test.rs b/crates/claude_cloud_agents/src/outbound/credentials/test.rsdeleted file mode 100644index 564e02ac21..0000000000--- a/crates/claude_cloud_agents/src/outbound/credentials/test.rs+++ /dev/null@@ -1,104 +0,0 @@-use super::*;-use crate::domain::auth::ConnectionStore;-use std::os::unix::fs::PermissionsExt;--async fn fixture() -> (tempfile::TempDir, PathBuf) {- let dir = tempfile::tempdir().unwrap();- std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();- let path = dir.path().join("credentials.json");- let value = serde_json::json!({"users":{"macro|[email protected]":{- "access_token":"fixture-access", "refresh_token":"fixture-refresh", "expires_at":4_000_000_000u64,- "organization_id":"00000000-0000-4000-8000-000000000001", "environment_id":"env_fixture"- }}});- tokio::fs::write(&path, serde_json::to_vec(&value).unwrap())- .await- .unwrap();- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();- (dir, path)-}--#[tokio::test]-async fn exact_owner_only_and_redacted_debug() {- let (_dir, path) = fixture().await;- let store = FileCredentials::open(path).await.unwrap();- assert!(matches!(- store.resolve("macro|[email protected]").await,- Err(Error::NotConnected)- ));- let credentials = store.resolve("macro|[email protected]").await.unwrap();- assert_eq!(credentials.access_token.expose(), "fixture-access");- let debug = format!("{credentials:?}");- assert!(!debug.contains("fixture-access"));- assert!(!debug.contains("fixture-refresh"));-}--#[tokio::test]-async fn refuses_group_readable_credential_file() {- let (_dir, path) = fixture().await;- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();- assert!(matches!(- FileCredentials::open(path).await,- Err(Error::Credentials)- ));-}--#[tokio::test]-async fn refuses_symlink_credential_file() {- let (dir, path) = fixture().await;- let link = dir.path().join("link.json");- std::os::unix::fs::symlink(path, &link).unwrap();- assert!(matches!(- FileCredentials::open(link).await,- Err(Error::Credentials)- ));-}--#[test]-fn rejects_header_injection_and_path_injection() {- assert!(Secret::parse("abc\r\nAuthorization: injected".into()).is_err());- assert!(crate::domain::model::SessionId::parse("cse_x/../../other").is_err());-}--#[tokio::test]-async fn memory_connection_is_owner_scoped_shared_and_forgotten_on_restart() {- let store = AccountCredentials::memory().unwrap();- let credentials = Credentials {- access_token: Secret::parse("memory-access".into()).unwrap(),- refresh_token: Some(Secret::parse("memory-refresh".into()).unwrap()),- expires_at: 4_000_000_000,- organization_id: "00000000-0000-4000-8000-000000000001".into(),- environment_id: "env_fixture".into(),- };- store- .save("macro|[email protected]", credentials)- .await- .unwrap();- assert!(store.clone().connected("macro|[email protected]").await);- assert!(!store.connected("macro|[email protected]").await);- assert!(matches!(- store.resolve("macro|[email protected]").await,- Err(Error::NotConnected)- ));- assert_eq!(- store- .resolve("macro|[email protected]")- .await- .unwrap()- .access_token- .expose(),- "memory-access"- );- assert!(- !AccountCredentials::memory()- .unwrap()- .connected("macro|[email protected]")- .await- );- store.remove("macro|[email protected]").await.unwrap();- assert!(store.connected("macro|[email protected]").await);- store.remove("macro|[email protected]").await.unwrap();- assert!(matches!(- store.resolve("macro|[email protected]").await,- Err(Error::NotConnected)- ));-}diff --git a/crates/claude_cloud_agents/src/outbound/http.rs b/crates/claude_cloud_agents/src/outbound/http.rsdeleted file mode 100644index c79ff3dd01..0000000000--- a/crates/claude_cloud_agents/src/outbound/http.rs+++ /dev/null@@ -1,435 +0,0 @@-//! The experimentally verified OAuth API origin, not the cookie-authenticated web origin.-use crate::domain::{- credentials::AccountCredentials,- environment::gateway_network_patch,- model::{Error, Event, Result, SessionId},- models::{Model, ModelOption},- ports::{Cloud, CloudLifecycle, CloudProvider, Events},-};-use futures::StreamExt;-use serde_json::{Value, json};-use std::collections::VecDeque;--const API: &str = "https://api.anthropic.com";-const BETA: &str = "ccr-byoc-2025-07-29";-const MODEL_PAGE_SIZE: usize = 1000;-const MODEL_PAGE_LIMIT: u8 = 10;--/// HTTP client pinned to one Macro account and the official Anthropic origin.-#[derive(Clone)]-pub struct Client {- credentials: AccountCredentials,- owner: String,- http: reqwest::Client,-}-impl Client {- /// Resolve account allowlisting before attaching a runtime.- pub async fn new(credentials: AccountCredentials, owner: String) -> Result<Self> {- credentials.resolve(&owner).await?;- let http = reqwest::Client::builder()- .redirect(reqwest::redirect::Policy::none())- .connect_timeout(std::time::Duration::from_secs(15))- .build()- .map_err(|_| Error::Network)?;- Ok(Self {- credentials,- owner,- http,- })- }-- async fn request(&self, path: &str, body: Option<Value>) -> Result<reqwest::Response> {- let credentials = self.credentials.resolve(&self.owner).await?;- let url = format!("{API}{path}");- let request = match body {- Some(body) => self.http.post(url).json(&body),- None => self.http.get(url),- };- let response = request- .bearer_auth(credentials.access_token.expose())- .header("anthropic-version", "2023-06-01")- .header("anthropic-beta", BETA)- .header("anthropic-client-feature", "ccr")- .header("x-organization-uuid", &credentials.organization_id)- .header("anthropic-client-platform", "desktop_app")- .header("anthropic-client-app", "com.anthropic.claudefordesktop")- .header("anthropic-client-version", "1.24012.9")- .timeout(std::time::Duration::from_secs(30))- .send()- .await- .map_err(|_| Error::Network)?;- checked(response)- }-- async fn environment_request(&self, path: &str, body: Option<Value>) -> Result<Value> {- let credentials = self.credentials.resolve(&self.owner).await?;- let url = format!("{API}{path}");- let request = match body {- Some(body) => self.http.post(url).json(&body),- None => self.http.get(url),- };- let response = request- .bearer_auth(credentials.access_token.expose())- .header("anthropic-version", "2023-06-01")- .header(- "anthropic-beta",- "environments-2026-03-01,environments-package-support-2025-12-09",- )- .header("x-organization-uuid", &credentials.organization_id)- .timeout(std::time::Duration::from_secs(30))- .send()- .await- .map_err(|_| Error::Network)?;- checked(response)?.json().await.map_err(|_| Error::Protocol)- }-- async fn selected_environment(&self) -> Result<Value> {- let credentials = self.credentials.resolve(&self.owner).await?;- let environments = self.environment_request("/v1/environments", None).await?;- environments["data"]- .as_array()- .and_then(|all| {- all.iter().find(|e| {- e["id"].as_str() == Some(&credentials.environment_id)- && e["config"]["type"] == "cloud"- && e["state"] == "active"- && e["archived_at"].is_null()- })- })- .cloned()- .ok_or(Error::CloudEnvironment)- }-- /// Create only in the explicitly selected, active Anthropic cloud environment.- pub async fn create(&self, instructions: &str, model: &Model) -> Result<SessionId> {- let environment = self.selected_environment().await?;- let mut config = json!({"sources": [], "outcomes": []});- if let Some(model) = model.provider_value() {- config["model"] = json!(model);- }- if !instructions.is_empty() {- config["append_system_prompt"] = json!(instructions);- }- let response = self- .request(- "/v1/code/sessions",- Some(json!({- "title": "Macro Claude Cloud demo", "environment_id": environment["id"],- "config": config, "events": []- })),- )- .await- .map_err(|error| match error {- Error::Network => Error::UncertainCreate,- other => other,- })?;- let data: Value = response.json().await.map_err(|_| Error::UncertainCreate)?;- SessionId::parse(- data["session"]["id"]- .as_str()- .ok_or(Error::UncertainCreate)?,- )- }-- /// Reversible cleanup; never deletes the user's Claude transcript.- pub async fn archive(&self, session: &SessionId) -> Result<()> {- self.request(- &format!("/v1/code/sessions/{}/archive", session.as_str()),- Some(json!({})),- )- .await?;- Ok(())- }-}--/// Factory using the shared account credential service supplied by the host.-pub struct Provider(pub Option<AccountCredentials>);--impl CloudProvider for Provider {- type Client = Client;-- async fn connect(&self, owner: &str) -> Result<Client> {- Client::new(self.0.clone().ok_or(Error::NotConnected)?, owner.to_owned()).await- }-}--impl CloudLifecycle for Client {- async fn prepare_mcp_access(&self, host: &str) -> Result<()> {- let environment = self.selected_environment().await?;- let Some(networking) = gateway_network_patch(&environment["config"]["networking"], host)?- else {- return Ok(());- };- let id = environment["id"].as_str().ok_or(Error::Protocol)?;- self.environment_request(- &format!("/v1/environments/{id}"),- Some(json!({"config":{"type":"cloud", "networking":networking}})),- )- .await?;- // Do not launch a container if the provider failed to apply the policy.- let updated = self.selected_environment().await?;- if updated["id"] != environment["id"]- || gateway_network_patch(&updated["config"]["networking"], host)?.is_some()- {- return Err(Error::EnvironmentNetwork);- }- Ok(())- }-- async fn create(&self, instructions: &str, model: &Model) -> Result<SessionId> {- Client::create(self, instructions, model).await- }-- async fn archive(&self, session: &SessionId) -> Result<()> {- Client::archive(self, session).await- }-}--impl Cloud for Client {- async fn models(&self) -> Result<Vec<ModelOption>> {- let credentials = self.credentials.resolve(&self.owner).await?;- let mut models = Vec::new();- let mut seen = std::collections::BTreeSet::new();- let mut after = None;- for _ in 0..MODEL_PAGE_LIMIT {- let response = models_request(- &self.http,- credentials.access_token.expose(),- &credentials.organization_id,- after.as_ref(),- )- .send()- .await- .map_err(|_| Error::Network)?;- let page = checked(response)?- .json()- .await- .map_err(|_| Error::Protocol)?;- let (options, next) = model_page(page)?;- for option in options {- if !seen.insert(option.model.id().to_owned()) {- return Err(Error::Protocol);- }- models.push(option);- }- match next {- None => return Ok(models),- Some(next) if after.as_ref() != Some(&next) => after = Some(next),- Some(_) => return Err(Error::Protocol),- }- }- // Never advertise a silently truncated catalog.- Err(Error::Protocol)- }- async fn send_batch(&self, session: &SessionId, payloads: Vec<Value>) -> Result<()> {- self.request(- &format!("/v1/code/sessions/{}/events", session.as_str()),- Some(event_batch(payloads)),- )- .await?;- Ok(())- }- async fn send(&self, session: &SessionId, payload: Value) -> Result<()> {- self.request(- &format!("/v1/code/sessions/{}/events", session.as_str()),- Some(json!({"events": [{"payload": payload}]})),- )- .await?;- Ok(())- }-- async fn history(&self, session: &SessionId) -> Result<Vec<Event>> {- let mut events = Vec::new();- let mut next = None::<String>;- // Bound memory and requests; never silently treat a partial history as complete.- for _ in 0..20 {- let mut url = reqwest::Url::parse(&format!(- "{API}/v1/code/sessions/{}/events",- session.as_str()- ))- .map_err(|_| Error::Protocol)?;- url.query_pairs_mut()- .append_pair("limit", "500")- .append_pair("sort_order", "asc");- if let Some(cursor) = &next {- url.query_pairs_mut().append_pair("cursor", cursor);- }- let path = format!("{}?{}", url.path(), url.query().unwrap_or_default());- let response: Value = self- .request(&path, None)- .await?- .json()- .await- .map_err(|_| Error::Protocol)?;- for data in response["data"].as_array().ok_or(Error::Protocol)? {- events.push(Event {- kind: "client_event".into(),- sequence: sequence(&data["sequence_num"]),- data: data.clone(),- });- }- match response["next_cursor"].as_str().filter(|s| !s.is_empty()) {- None => return Ok(events),- Some(cursor) if next.as_deref() != Some(cursor) => next = Some(cursor.to_owned()),- _ => return Err(Error::Recovery),- }- }- Err(Error::Recovery)- }-- async fn stream(&self, session: &SessionId, cursor: Option<u64>) -> Result<Events> {- let credentials = self.credentials.resolve(&self.owner).await?;- let mut request = self- .http- .get(format!(- "{API}/v1/code/sessions/{}/events/stream",- session.as_str()- ))- .bearer_auth(credentials.access_token.expose())- .header("Accept", "text/event-stream")- .header("anthropic-version", "2023-06-01")- .header("anthropic-beta", BETA)- .header("x-organization-uuid", &credentials.organization_id);- if let Some(cursor) = cursor {- request = request- .query(&[("from_sequence_num", cursor)])- .header("last-event-id", cursor.to_string());- }- let response = tokio::time::timeout(std::time::Duration::from_secs(30), request.send())- .await- .map_err(|_| Error::Network)?- .map_err(|_| Error::Network)?;- let response = checked(response)?;- if !response- .headers()- .get("content-type")- .and_then(|h| h.to_str().ok())- .is_some_and(|s| s.starts_with("text/event-stream"))- {- return Err(Error::Protocol);- }- let state = (- response.bytes_stream().boxed(),- sse_core::SseDecoder::with_limit(- std::num::NonZeroUsize::new(4 * 1024 * 1024).expect("nonzero payload bound"),- ),- VecDeque::new(),- );- Ok(- futures::stream::try_unfold(- state,- |(mut bytes, mut decoder, mut pending)| async move {- loop {- if let Some(event) = pending.pop_front() {- return Ok(Some((event, (bytes, decoder, pending))));- }- match tokio::time::timeout(std::time::Duration::from_secs(45), bytes.next())- .await- {- Ok(Some(Ok(mut chunk))) => {- while let Some(record) = decoder.next(&mut chunk) {- let sse_core::SseEvent::Message(message) =- record.map_err(|_| Error::Protocol)?- else {- continue;- };- if message.data.is_empty() {- continue;- }- let data: Value = serde_json::from_str(&message.data)- .map_err(|_| Error::Protocol)?;- let sequence = message- .last_event_id- .as_ref()- .and_then(|s| s.parse().ok())- .or_else(|| sequence(&data["sequence_num"]));- pending.push_back(Event {- kind: message.event.into_owned(),- data,- sequence,- });- }- }- Ok(None) => return Ok(None),- _ => return Err(Error::Network),- }- }- },- )- .boxed(),- )- }-}--// The code-session beta is not accepted by the standard models endpoint.-fn models_request(- http: &reqwest::Client,- token: &str,- organization: &str,- after: Option<&Model>,-) -> reqwest::RequestBuilder {- let request = http- .get(format!("{API}/v1/models"))- .bearer_auth(token)- .header("anthropic-version", "2023-06-01")- .header("x-organization-uuid", organization)- .query(&[("limit", MODEL_PAGE_SIZE)])- .timeout(std::time::Duration::from_secs(30));- match after {- Some(model) => request.query(&[("after_id", model.id())]),- None => request,- }-}--fn model_page(response: Value) -> Result<(Vec<ModelOption>, Option<Model>)> {- let rows = response["data"].as_array().ok_or(Error::Protocol)?;- if rows.len() > MODEL_PAGE_SIZE {- return Err(Error::Protocol);- }- let options = rows- .iter()- .map(|row| {- let model = Model::parse(row["id"].as_str().ok_or(Error::Protocol)?)- .map_err(|_| Error::Protocol)?;- let name = row["display_name"].as_str().ok_or(Error::Protocol)?;- if name.trim().is_empty() || name.len() > 512 {- return Err(Error::Protocol);- }- Ok(ModelOption {- model,- name: name.into(),- description: None,- })- })- .collect::<Result<Vec<_>>>()?;- let next = match response["has_more"].as_bool().ok_or(Error::Protocol)? {- false => None,- true => {- let last = options.last().ok_or(Error::Protocol)?;- if response["last_id"].as_str() != Some(last.model.id()) {- return Err(Error::Protocol);- }- Some(last.model.clone())- }- };- Ok((options, next))-}--fn checked(response: reqwest::Response) -> Result<reqwest::Response> {- match response.status().as_u16() {- 200..=299 => Ok(response),- 401 | 403 => Err(Error::Authorization),- 410 => Err(Error::Recovery),- status => Err(Error::Http(status)),- }-}-fn sequence(value: &Value) -> Option<u64> {- value.as_u64().or_else(|| value.as_str()?.parse().ok())-}--fn event_batch(payloads: Vec<Value>) -> Value {- json!({"events": payloads.into_iter().map(|payload| json!({"payload":payload})).collect::<Vec<_>>()})-}--#[cfg(test)]-mod test;diff --git a/crates/claude_cloud_agents/src/outbound/http/test.rs b/crates/claude_cloud_agents/src/outbound/http/test.rsdeleted file mode 100644index 803e7a98f1..0000000000--- a/crates/claude_cloud_agents/src/outbound/http/test.rs+++ /dev/null@@ -1,77 +0,0 @@-use super::*;--#[test]-fn direct_models_request_uses_oauth_and_pagination_without_session_beta() {- let after = Model::parse("claude-fable-5-1").unwrap();- let request = models_request(- &reqwest::Client::new(),- "test-token",- "test-org",- Some(&after),- )- .build()- .unwrap();- assert_eq!(request.method(), reqwest::Method::GET);- assert_eq!(request.url().origin().ascii_serialization(), API);- assert_eq!(request.url().path(), "/v1/models");- assert_eq!(- request.url().query_pairs().collect::<Vec<_>>(),- vec![- ("limit".into(), "1000".into()),- ("after_id".into(), after.id().into())- ]- );- assert_eq!(request.headers()["authorization"], "Bearer test-token");- assert_eq!(request.headers()["x-organization-uuid"], "test-org");- assert_eq!(request.headers()["anthropic-version"], "2023-06-01");- assert!(!request.headers().contains_key("anthropic-beta"));- assert!(request.body().is_none());-}--#[test]-fn direct_catalog_preserves_api_ids_names_order_and_next_cursor() {- let (models, next) = model_page(json!({- "data": [- {"id":"claude-fable-5-1","display_name":"Claude Fable 5.1"},- {"id":"brand-new-model","display_name":"New model"}- ],- "has_more":true,- "last_id":"brand-new-model"- }))- .unwrap();- assert_eq!(models[0].model.id(), "claude-fable-5-1");- assert_eq!(models[0].name, "Claude Fable 5.1");- assert_eq!(models[1].model.id(), "brand-new-model");- assert_eq!(next.unwrap().id(), "brand-new-model");- let (models, next) = model_page(json!({"data":[],"has_more":false})).unwrap();- assert!(models.is_empty());- assert!(next.is_none());-}--#[test]-fn malformed_catalogs_and_broken_pagination_fail_instead_of_truncating() {- for response in [- json!({}),- json!({"data":[],"has_more":true,"last_id":"missing"}),- json!({"data":[{"id":"model","display_name":"Model"}],"has_more":true}),- json!({"data":[{"id":"model","display_name":"Model"}],"has_more":true,"last_id":"different"}),- json!({"data":[{"id":"../model","display_name":"Model"}],"has_more":false}),- json!({"data":[{"id":"model","display_name":" "}],"has_more":false}),- json!({"data":[{"id":"model"}],"has_more":false}),- json!({"data":[],"has_more":"false"}),- json!({"data":vec![json!({"id":"model","display_name":"Model"}); MODEL_PAGE_SIZE + 1],"has_more":false}),- ] {- assert!(matches!(model_page(response), Err(Error::Protocol)));- }-}--#[test]-fn model_and_prompt_are_serialized_in_one_ordered_batch() {- let batch = event_batch(vec![- json!({"type":"control_request","request":{"subtype":"set_model","model":"sonnet"}}),- json!({"type":"user","message":{"content":"hello"}}),- ]);- assert_eq!(batch["events"].as_array().unwrap().len(), 2);- assert_eq!(batch["events"][0]["payload"]["request"]["model"], "sonnet");- assert_eq!(batch["events"][1]["payload"]["type"], "user");-}diff --git a/crates/claude_cloud_agents/src/outbound/mod.rs b/crates/claude_cloud_agents/src/outbound/mod.rsdeleted file mode 100644index 4b46d63cc8..0000000000--- a/crates/claude_cloud_agents/src/outbound/mod.rs+++ /dev/null@@ -1,6 +0,0 @@-//! Private demo credentials and Anthropic HTTP transport.-pub mod credentials;-pub mod http;-/// Claude's browser-consent OAuth protocol.-pub mod oauth;-pub mod postgres;diff --git a/crates/claude_cloud_agents/src/outbound/oauth.rs b/crates/claude_cloud_agents/src/outbound/oauth.rsdeleted file mode 100644index cc0fa661c9..0000000000--- a/crates/claude_cloud_agents/src/outbound/oauth.rs+++ /dev/null@@ -1,162 +0,0 @@-//! Claude Code's registered manual callback works across host/container boundaries.-use super::credentials::CLIENT_ID;-use crate::domain::{- auth::OAuthProvider,- model::{Credentials, Error, Secret},-};-use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};-use serde::Deserialize;-use sha2::{Digest, Sha256};-use std::time::{Duration, SystemTime, UNIX_EPOCH};--const REDIRECT_URI: &str = "https://platform.claude.com/oauth/code/callback";-const SCOPES: &str = "user:profile user:inference user:sessions:claude_code";--/// HTTP OAuth adapter. Origins, redirect, client and scopes cannot be caller-controlled.-pub struct ClaudeOAuth {- http: reqwest::Client,-}--impl ClaudeOAuth {- /// Construct a bounded client without redirects or automatic mutation retries.- pub fn new() -> Result<Self, Error> {- Ok(Self {- http: reqwest::Client::builder()- .redirect(reqwest::redirect::Policy::none())- .timeout(Duration::from_secs(30))- .build()- .map_err(|_| Error::Network)?,- })- }-}--impl OAuthProvider for ClaudeOAuth {- fn authorization_url(&self, state: &str, verifier: &Secret) -> String {- let mut url = reqwest::Url::parse("https://claude.com/cai/oauth/authorize")- .expect("fixed OAuth origin");- url.query_pairs_mut()- .append_pair("code", "true")- .append_pair("client_id", CLIENT_ID)- .append_pair("response_type", "code")- .append_pair("redirect_uri", REDIRECT_URI)- .append_pair("scope", SCOPES)- .append_pair("state", state)- .append_pair(- "code_challenge",- &URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.expose().as_bytes())),- )- .append_pair("code_challenge_method", "S256");- url.into()- }-- async fn exchange(- &self,- code: Secret,- state: &str,- verifier: Secret,- ) -> Result<Credentials, Error> {- let response = self.http.post("https://platform.claude.com/v1/oauth/token")- .json(&serde_json::json!({ "grant_type": "authorization_code", "code": code.expose(),- "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "state": state, "code_verifier": verifier.expose() }))- .send().await.map_err(|_| Error::Network)?;- #[derive(Deserialize)]- struct Tokens {- access_token: Secret,- refresh_token: Option<Secret>,- expires_in: u64,- scope: String,- }- let tokens: Tokens = checked(response)?- .json()- .await- .map_err(|_| Error::Protocol)?;- if tokens.expires_in == 0- || !SCOPES- .split_whitespace()- .all(|scope| tokens.scope.split_whitespace().any(|s| s == scope))- {- return Err(Error::Authorization);- }- let expires_at = SystemTime::now()- .duration_since(UNIX_EPOCH)- .map_err(|_| Error::Protocol)?- .as_secs()- .saturating_add(tokens.expires_in);- let response = self- .http- .get("https://api.anthropic.com/api/oauth/profile")- .bearer_auth(tokens.access_token.expose())- .header("anthropic-version", "2023-06-01")- .send()- .await- .map_err(|_| Error::Network)?;- #[derive(Deserialize)]- struct Organization {- uuid: uuid::Uuid,- }- #[derive(Deserialize)]- struct Profile {- organization: Organization,- }- let profile: Profile = checked(response)?- .json()- .await- .map_err(|_| Error::Protocol)?;- let organization_id = profile.organization.uuid.to_string();- let response = self- .http- .get("https://api.anthropic.com/v1/environments")- .bearer_auth(tokens.access_token.expose())- .header("anthropic-version", "2023-06-01")- .header("x-organization-uuid", &organization_id)- .header(- "anthropic-beta",- "environments-2026-03-01,environments-package-support-2025-12-09",- )- .send()- .await- .map_err(|_| Error::Network)?;- let environments: serde_json::Value = checked(response)?- .json()- .await- .map_err(|_| Error::Protocol)?;- let mut candidates = environments["data"]- .as_array()- .ok_or(Error::Protocol)?- .iter()- .filter(|e| {- e["config"]["type"] == "cloud"- && e["state"] == "active"- && e["archived_at"].is_null()- });- let environment_id = candidates- .next()- .and_then(|e| e["id"].as_str())- .ok_or(Error::CloudEnvironment)?;- if candidates.next().is_some() {- return Err(Error::CloudEnvironment);- }- if !environment_id.starts_with("env_")- || !environment_id- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b == b'_')- {- return Err(Error::Protocol);- }- Ok(Credentials {- access_token: tokens.access_token,- refresh_token: tokens.refresh_token,- expires_at,- organization_id,- environment_id: environment_id.to_owned(),- })- }-}--fn checked(response: reqwest::Response) -> Result<reqwest::Response, Error> {- match response.status().as_u16() {- 200..=299 => Ok(response),- 400 | 401 | 403 => Err(Error::Authorization),- status => Err(Error::Http(status)),- }-}diff --git a/crates/claude_cloud_agents/src/outbound/postgres.rs b/crates/claude_cloud_agents/src/outbound/postgres.rsdeleted file mode 100644index 3ad9d66d83..0000000000--- a/crates/claude_cloud_agents/src/outbound/postgres.rs+++ /dev/null@@ -1,124 +0,0 @@-//! Encrypted owner-keyed connections with cross-replica transaction locks.-use crate::domain::{- credentials::{ConnectionState, GrantRepository, GrantTransaction},- model::{Error, Result},-};-use cursor_api_key::cipher::KmsCiphertexts;-use std::{collections::HashMap, sync::Arc};--#[cfg(test)]-mod test;--/// PostgreSQL persistence with purpose- and owner-bound KMS ciphertext.-pub struct PgClaudeGrants<K> {- pool: sqlx::PgPool,- cipher: Arc<K>,-}-impl<K> PgClaudeGrants<K> {- /// Supply the deployment's KMS transport at the composition root.- pub fn new(pool: sqlx::PgPool, cipher: K) -> Self {- Self {- pool,- cipher: Arc::new(cipher),- }- }-}-fn context(owner: &str, version: i16) -> HashMap<String, String> {- HashMap::from([- ("purpose".into(), "claude-cloud-oauth".into()),- ("user_id".into(), owner.into()),- ("encryption_version".into(), version.to_string()),- ])-}-struct OwnerTransaction<K> {- transaction: sqlx::Transaction<'static, sqlx::Postgres>,- owner: String,- state: ConnectionState,- cipher: Arc<K>,-}-#[async_trait::async_trait]-impl<K: KmsCiphertexts + 'static> GrantRepository for PgClaudeGrants<K> {- async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {- let mut transaction = self.pool.begin().await.map_err(|_| Error::Credentials)?;- // Transaction-scoped advisory locks also serialize absent/deleted rows.- // The namespace prevents collisions with other services' owner locks.- let lock_name = format!("claude-cloud-oauth:{owner}");- sqlx::query!(- "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",- lock_name- )- .execute(&mut *transaction)- .await- .map_err(|_| Error::Credentials)?;- let row = sqlx::query!("SELECT grant_ciphertext, kms_key_id, encryption_version FROM claude_oauth_grants WHERE user_id = $1", owner)- .fetch_optional(&mut *transaction).await.map_err(|_| Error::Credentials)?;- let state = match row {- None => ConnectionState::default(),- Some(row) => {- if !matches!(row.encryption_version, 1 | 2) {- return Err(Error::Credentials);- }- let bytes = self- .cipher- .decrypt(- &row.kms_key_id,- &row.grant_ciphertext,- context(owner, row.encryption_version),- )- .await- .map_err(|_| Error::Credentials)?;- if row.encryption_version == 1 {- // Existing encrypted grants upgrade when next written.- ConnectionState {- grant: Some(- serde_json::from_slice(&bytes).map_err(|_| Error::Credentials)?,- ),- ..Default::default()- }- } else {- serde_json::from_slice(&bytes).map_err(|_| Error::Credentials)?- }- }- };- Ok(Box::new(OwnerTransaction {- transaction,- owner: owner.to_owned(),- state,- cipher: self.cipher.clone(),- }))- }-}-#[async_trait::async_trait]-impl<K: KmsCiphertexts + 'static> GrantTransaction for OwnerTransaction<K> {- fn state(&mut self) -> &mut ConnectionState {- &mut self.state- }- async fn commit(self: Box<Self>) -> Result<()> {- let Self {- mut transaction,- owner,- state,- cipher,- } = *self;- if state.grant.is_none() && state.attempt.is_none() {- sqlx::query!("DELETE FROM claude_oauth_grants WHERE user_id = $1", owner)- .execute(&mut *transaction)- .await- .map_err(|_| Error::Credentials)?;- } else {- let bytes = zeroize::Zeroizing::new(- serde_json::to_vec(&state).map_err(|_| Error::Credentials)?,- );- if bytes.len() > 4096 {- return Err(Error::Credentials);- }- let (ciphertext, key_id) = cipher- .encrypt(context(&owner, 2), &bytes)- .await- .map_err(|_| Error::Credentials)?;- sqlx::query!("INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 2) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 2, updated_at = now()", owner, ciphertext, key_id)- .execute(&mut *transaction).await.map_err(|_| Error::Credentials)?;- }- transaction.commit().await.map_err(|_| Error::Credentials)- }-}diff --git a/crates/claude_cloud_agents/src/outbound/postgres/test.rs b/crates/claude_cloud_agents/src/outbound/postgres/test.rsdeleted file mode 100644index 5f7265a768..0000000000--- a/crates/claude_cloud_agents/src/outbound/postgres/test.rs+++ /dev/null@@ -1,211 +0,0 @@-use super::*;-use crate::domain::model::{Credentials, Secret};-use cursor_api_key::cipher::KmsCiphertextsError;-use macro_db_migrator::MACRO_DB_MIGRATIONS;-use std::sync::{Arc, Mutex};-use zeroize::Zeroizing;--type CipherRecords = HashMap<Vec<u8>, (HashMap<String, String>, Vec<u8>)>;-#[derive(Clone, Default)]-struct FakeKms(Arc<Mutex<CipherRecords>>);-#[async_trait::async_trait]-impl KmsCiphertexts for FakeKms {- async fn encrypt(- &self,- context: HashMap<String, String>,- plain: &[u8],- ) -> std::result::Result<(Vec<u8>, String), KmsCiphertextsError> {- let ciphertext = uuid::Uuid::now_v7().as_bytes().to_vec();- self.0- .lock()- .unwrap()- .insert(ciphertext.clone(), (context, plain.to_vec()));- Ok((ciphertext, "test-key".into()))- }- async fn decrypt(- &self,- key: &str,- bytes: &[u8],- context: HashMap<String, String>,- ) -> std::result::Result<Zeroizing<Vec<u8>>, KmsCiphertextsError> {- let records = self.0.lock().unwrap();- let (expected, plain) = records.get(bytes).ok_or(KmsCiphertextsError)?;- if key != "test-key" || expected != &context {- return Err(KmsCiphertextsError);- }- Ok(Zeroizing::new(plain.clone()))- }-}--async fn user(pool: &sqlx::PgPool, id: &str) {- let uuid = uuid::Uuid::now_v7();- let email = format!("{id}@example.com");- sqlx::query!(r#"WITH u AS (INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$2) RETURNING id) INSERT INTO "User" ("id", "email", "macro_user_id") SELECT $3,$2,u.id FROM u"#, uuid, email, id).execute(pool).await.unwrap();-}-fn grant() -> Credentials {- Credentials {- access_token: Secret::parse("test-access".into()).unwrap(),- refresh_token: Some(Secret::parse("test-refresh".into()).unwrap()),- expires_at: 4_000_000_000,- organization_id: "00000000-0000-4000-8000-000000000001".into(),- environment_id: "env_test".into(),- }-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn durable_encrypted_grants_are_owner_bound_replaceable_and_removable(pool: sqlx::PgPool) {- user(&pool, "alice").await;- user(&pool, "bob").await;- let kms = FakeKms::default();- let store = PgClaudeGrants::new(pool.clone(), kms.clone());- store.put("alice", &grant()).await.unwrap();- assert!(store.get("bob").await.unwrap().is_none());- let ciphertext = sqlx::query_scalar!(- "SELECT grant_ciphertext FROM claude_oauth_grants WHERE user_id = 'alice'"- )- .fetch_one(&pool)- .await- .unwrap();- assert!(!ciphertext.windows(11).any(|w| w == b"test-access"));- // New adapter instance, same durable DB: no process-local grant cache.- let restarted = PgClaudeGrants::new(pool.clone(), kms);- assert_eq!(- restarted- .get("alice")- .await- .unwrap()- .unwrap()- .access_token- .expose(),- "test-access"- );- let mut rotated = grant();- rotated.refresh_token = Some(Secret::parse("rotated-refresh".into()).unwrap());- restarted.put("alice", &rotated).await.unwrap();- assert_eq!(- store- .get("alice")- .await- .unwrap()- .unwrap()- .refresh_token- .unwrap()- .expose(),- "rotated-refresh"- );- sqlx::query!("INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) SELECT 'bob', grant_ciphertext, kms_key_id, encryption_version FROM claude_oauth_grants WHERE user_id = 'alice'").execute(&pool).await.unwrap();- assert!(matches!(store.get("bob").await, Err(Error::Credentials)));- sqlx::query!("DELETE FROM claude_oauth_grants WHERE user_id = $1", "bob")- .execute(&pool)- .await- .unwrap();- assert!(store.get("alice").await.unwrap().is_some());- restarted.delete("alice").await.unwrap();- assert!(store.get("alice").await.unwrap().is_none());-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn pending_consent_is_encrypted_durable_and_locked_across_replicas(pool: sqlx::PgPool) {- user(&pool, "alice").await;- let kms = FakeKms::default();- let first = Arc::new(PgClaudeGrants::new(pool.clone(), kms.clone()));- let second = Arc::new(PgClaudeGrants::new(pool.clone(), kms));- let mut transaction = first.lock("alice").await.unwrap();- transaction.state().attempt = Some(crate::domain::auth::Attempt {- id: "attempt".into(),- state: "state".into(),- verifier: Some(Secret::parse("private-verifier".into()).unwrap()),- started: 1,- });- let waiting = {- let second = second.clone();- tokio::spawn(async move { second.lock("alice").await.unwrap() })- };- tokio::task::yield_now().await;- assert!(!waiting.is_finished());- transaction.commit().await.unwrap();- let mut resumed = waiting.await.unwrap();- assert_eq!(- resumed- .state()- .attempt- .as_ref()- .unwrap()- .verifier- .as_ref()- .unwrap()- .expose(),- "private-verifier"- );- resumed.state().attempt.as_mut().unwrap().verifier = None;- resumed.commit().await.unwrap();- drop(first);- let mut restarted = second.lock("alice").await.unwrap();- assert!(- restarted- .state()- .attempt- .as_ref()- .unwrap()- .verifier- .is_none()- );- // An uncommitted replacement must not resurrect the consumed verifier.- restarted.state().attempt = None;- drop(restarted);- assert!(- second- .lock("alice")- .await- .unwrap()- .state()- .attempt- .is_some()- );- let ciphertext = sqlx::query_scalar!(- "SELECT grant_ciphertext FROM claude_oauth_grants WHERE user_id = 'alice'"- )- .fetch_one(&pool)- .await- .unwrap();- assert!(- !ciphertext- .windows(16)- .any(|bytes| bytes == b"private-verifier")- );- second.delete("alice").await.unwrap();- assert!(- second- .lock("alice")- .await- .unwrap()- .state()- .attempt- .is_none()- );-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn reads_legacy_grants_and_upgrades_on_write(pool: sqlx::PgPool) {- user(&pool, "alice").await;- let kms = FakeKms::default();- let (ciphertext, key) = kms- .encrypt(context("alice", 1), &serde_json::to_vec(&grant()).unwrap())- .await- .unwrap();- sqlx::query!("INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 1) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 1, updated_at = now()", "alice", ciphertext, key).execute(&pool).await.unwrap();- let repository = PgClaudeGrants::new(pool, kms);- let mut transaction = repository.lock("alice").await.unwrap();- assert_eq!(- transaction- .state()- .grant- .as_ref()- .unwrap()- .access_token- .expose(),- "test-access"- );- transaction.commit().await.unwrap();- assert!(repository.get("alice").await.unwrap().is_some());-}diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex a9bdc65df1..e1cadea230 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -4,7 +4,7 @@ async function bO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=g.pop()??"";for(let r of g){let p=r.split(``),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var O7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Dj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return IO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},IO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Cj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x7(x),X=Object.entries(S).map(([G,L])=>IO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S7=/\{[^{}]+\}/g,Z7=({path:$,url:O})=>{let j=O,x=O.match(S7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Dj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Cj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${IO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},c1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function P0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var u1=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var d1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var l1=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=IO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},r1=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},X7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function p1($){for(let O of $.security??[]){if(X7($,O.name))continue;let j=await u1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var F0=($)=>c1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:l1($.querySerializer),url:$.url}),E0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Mj($.headers,O.headers),j},G7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Mj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _j{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var a1=()=>({error:new _j,request:new _j,response:new _j}),K7=l1({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y7={"Content-Type":"application/json"},aO=($={})=>({...d1,headers:Y7,parseAs:"auto",querySerializer:K7,...$});var w0=($={})=>{let O=E0(aO(),$),j=()=>({...O}),x=(Y)=>{return O=E0(O,Y),j()},S=a1(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Mj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await p1(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=F0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:P0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?r1(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return m1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:P0(T),url:z})};return{buildUrl:(Y)=>F0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var i1=w0(aO());class n1{client;constructor($){this.client=$?.client??i1}}class s1{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Aj extends n1{static __registry=new s1;constructor($){super($);Aj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}disconnect($){return($.client??this.client).delete({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth",...$,headers:{"Content-Type":"application/json",...$.headers}})}status($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth",...$})}complete($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}start($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function t1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var O7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Dj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return IO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},IO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Cj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x7(x),X=Object.entries(S).map(([G,L])=>IO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S7=/\{[^{}]+\}/g,Z7=({path:$,url:O})=>{let j=O,x=O.match(S7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Dj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Cj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${IO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},c1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function P0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var u1=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var d1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var l1=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=IO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},r1=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},X7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function p1($){for(let O of $.security??[]){if(X7($,O.name))continue;let j=await u1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var F0=($)=>c1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:l1($.querySerializer),url:$.url}),E0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Mj($.headers,O.headers),j},G7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Mj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _j{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var a1=()=>({error:new _j,request:new _j,response:new _j}),K7=l1({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y7={"Content-Type":"application/json"},aO=($={})=>({...d1,headers:Y7,parseAs:"auto",querySerializer:K7,...$});var w0=($={})=>{let O=E0(aO(),$),j=()=>({...O}),x=(Y)=>{return O=E0(O,Y),j()},S=a1(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Mj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await p1(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=F0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:P0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?r1(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return m1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:P0(T),url:z})};return{buildUrl:(Y)=>F0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var i1=w0(aO());class n1{client;constructor($){this.client=$?.client??i1}}class s1{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Aj extends n1{static __registry=new s1;constructor($){super($);Aj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function t1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let r of g){let p=r.split(`diff --git a/crates/cursor_api_key/AGENTS.md b/crates/cursor_api_key/AGENTS.mdindex b6d7ec45c8..85c1f6474e 100644--- a/crates/cursor_api_key/AGENTS.md+++ b/crates/cursor_api_key/AGENTS.md@@ -10,8 +10,7 @@ model.## Boundaries- Depends on: AWS KMS (via `aws-sdk-kms`).-- Used by: `claude_cloud_agents`, `agent_harness`, `authentication_service`,- `agent_harness_service`.+- Used by: `agent_harness`, `authentication_service`, `agent_harness_service`.## Recipesdiff --git a/crates/lexical_client/src/parse_markdown/test.rs b/crates/lexical_client/src/parse_markdown/test.rsindex 8994e329f8..b565c69f15 100644--- a/crates/lexical_client/src/parse_markdown/test.rs+++ b/crates/lexical_client/src/parse_markdown/test.rs@@ -3,11 +3,11 @@ use super::*;#[test]fn connection_prompt_matches_the_lexical_service_request() {let prompt = AgentConnectionPrompt {- agent_tag: "@claude".into(),- message: "Connect Claude, then mention me again.".into(),+ agent_tag: "@codex".into(),+ message: "Connect Codex, then mention me again.".into(),chip: AgentConnectionChip {- app_slug: "claude-cloud".into(),- name: "Claude".into(),+ app_slug: "codex-cloud".into(),+ name: "Codex".into(),target: "harness".into(),},};@@ -19,9 +19,9 @@ fn connection_prompt_matches_the_lexical_service_request() {wire,serde_json::json!({"connectionPrompt": {- "agentTag": "@claude",- "message": "Connect Claude, then mention me again.",- "chip": { "appSlug": "claude-cloud", "name": "Claude", "target": "harness" }+ "agentTag": "@codex",+ "message": "Connect Codex, then mention me again.",+ "chip": { "appSlug": "codex-cloud", "name": "Codex", "target": "harness" }}}));diff --git a/crates/macro_db_client/migrations/20261021191028_remove_claude_cloud.sql b/crates/macro_db_client/migrations/20261021191028_remove_claude_cloud.sqlnew file mode 100644index 0000000000..850ea0244f--- /dev/null+++ b/crates/macro_db_client/migrations/20261021191028_remove_claude_cloud.sql@@ -0,0 +1,14 @@+-- The Claude Cloud demo harness is gone. Forget every stored subscription+-- grant, and move agents that ran on it onto Macro's built-in runtime with its+-- default model so they keep answering instead of routing nowhere.+DROP TABLE claude_oauth_grants;++UPDATE agent_configs+SET harness = 'in-memory',+ default_model = 'anthropic/claude-sonnet-5-5',+ updated_at = now()+WHERE harness = 'claude-cloud';++-- The @claude system bot went with it; take it out of every channel it joined.+DELETE FROM comms_channel_participants+WHERE user_id = 'bot|00000000-0000-0000-0000-00000000c1a0';diff --git a/crates/system_skills/src/configure_agent.rs b/crates/system_skills/src/configure_agent.rsindex f617bd960f..f05b38d9e7 100644--- a/crates/system_skills/src/configure_agent.rs+++ b/crates/system_skills/src/configure_agent.rs@@ -28,7 +28,7 @@ Never send a fragment as the new instructions: it would erase the rest.Pass only the fields that should change; `ConfigureAgent` keeps the others.-- **Runtime (`harness`)**: `in-memory` is Macro's built-in chat agent; `cursor` and `claude-cloud` run on the user's connected Cursor or Claude account; `macrod` is a self-hosted harness and needs `harnessId`. Model ids are runtime-specific, so when the runtime changes, ask which model to use unless the user named one, and pass `defaultModel` in the same call.+- **Runtime (`harness`)**: `in-memory` is Macro's built-in chat agent; `cursor` runs on the user's connected Cursor account; `macrod` is a self-hosted harness and needs `harnessId`. Model ids are runtime-specific, so when the runtime changes, ask which model to use unless the user named one, and pass `defaultModel` in the same call.- **Model (`defaultModel`)**: pass the id as the runtime names it. If the user gives a family name ("Sonnet", "Opus"), confirm the exact id before applying.- **Channels**: `channelScope: "all"` makes the agent mentionable everywhere the owner is; `channelIds` limits it to those channels - the complete list, and the user must belong to each. Resolve channel names to ids first.- **Connected apps**: `mcpScope: "owner_connections"` gives sessions whatever apps the person running them has connected; `mcpServers` pins an exact list of Pipedream apps by `appSlug` and `serverName`. `appSlug` must be a real Pipedream app slug, such as `linear` or `google_sheets`. An invented slug is rejected and the agent is left unchanged; if you are not sure of the slug, ask rather than guessing.diff --git a/docs/agent-guide/README.md b/docs/agent-guide/README.mdindex 0a60f89946..074ce501d7 100644--- a/docs/agent-guide/README.md+++ b/docs/agent-guide/README.md@@ -12,7 +12,6 @@ verified live against a local stack (`just run_local`).| [databases.md](databases.md) | Properties, records, kanban boards, saved views, AI questions, live answers || [forms.md](forms.md) | Forms: create doors, builder (drag and drop, gates), respond route, Responses grid, sharing, polls || [ai-chat.md](ai-chat.md) | Standalone and doc-scoped AI chat |-| [claude-cloud-demo.md](../runbooks/claude-cloud-demo.md) | Claude in Harness settings, encrypted saved connection, Open in Claude, and cloud-side transcript polling || [channels.md](channels.md) | Channels: create, invite, message, participants, bots || [tasks.md](tasks.md) | Task list and creation dialog || [view-tours.md](view-tours.md) | Desktop feature flyovers, dismissal, targeting, and embedded videos |diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex 0efe937fac..4e6f38463b 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -293,7 +293,7 @@ the shimmer.Macro that covers that repository; connecting only Cursor does not grant MacroGitHub access. Cloud agents also need a public agent gateway: Docker-only hostnamescannot receive their MCP callbacks. Check the runtime error before retrying, and- start a new Claude session after correcting its gateway network configuration.+ start a new session after correcting its gateway network configuration.- Open **Go to Agents** → `/app/component/agents`. With AI agents enabled(`enable-chat-v3-agents`), the workspace uses one sidebar for Chat and Code.@@ -435,7 +435,7 @@ the shimmer.Unavailable paired agents stay visible with a reason.If Macro is unavailable, its catalog stays visible butmodel choices are disabled in every list. Model discovery uses the- selected runtime, including Claude Cloud. Every coding agent shows repository+ selected runtime. Every coding agent shows repositorycontrols; chat agents hide those controls but keep the mode bar. Repository/branch overrides are currently appliedonly to Cursor sessions by the create-session API.The most recently used supported,@@ -550,8 +550,7 @@ the shimmer.**Add agent**, the setup strips, and Edit replace the list with full pages,not dialogs; Back/Cancel returns to the list. Use **Create → Agent** to open a new composer.The agent editor has Profile, Instructions, **Where it runs** (In Macro, In- Cursor, In your harness; In Claude Code too with the `claude-cloud` flag once- Claude lists models) and **Who can use it** (Private / Team). The selected+ Cursor, In your harness) and **Who can use it** (Private / Team). The selectedplace opens its Model picker inside its card; In your harness adds a Harnesspicker beside it. An unconnected Cursor or unpaired harness is disabled with**Connect** / **Set up**, which open the setup guide in place and return to the@@ -1720,7 +1719,7 @@ must stay hidden; subsequent live messages must still appear.- **Agent permission policy.** Settings → Agents → Runtime shows `Always prompt`and `Always bypass` only for local macrod harnesses. Macrod defaults to prompts;bypass requires both harness consent and the agent's explicit choice. Built-in- Macro, in-memory, Cursor, Codex, and Claude runtimes always bypass and have no+ Macro, in-memory, Cursor, and Codex runtimes always bypass and have nopermission policy selector. The backend enforces these policies.Locally sent user messages in both AI implementations enter with a short upward@@ -1864,7 +1863,7 @@ picker. New and resumed sessions replace an inaccessible saved model with GeminiA direct request to select a paid model is rejected, and each prompt recheckspermissions before inference, including after a plan downgrade. Permissionlookup failures prevent inference. Paid users retain the full supported catalog.-Cursor, Claude Cloud, and paired external runtimes keep their own model rules.+Cursor and paired external runtimes keep their own model rules.To verify, start a Macro conversation as a free user with a previously savedpaid-model preference: the composer should show Gemini and send that model.diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex dd62c6338f..485ebc5f58 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -379,7 +379,7 @@ someone who holds it on their own calendar. The bot's prompt carries the currentown time zone (their primary calendar's), so it resolves relative times ("tomorrow at 4","EOD") without asking; when no calendar is connected the prompt falls back to UTC and thebot asks before scheduling a specific clock time. Within the rollout, `@Macro` — plus-`@cursor` / `@codex` / `@claude` when available — opens+`@cursor` / `@codex` when available — opensan agent session; follow-up`@` mentions of that bot in the same thread route to it.Macro Coding Agent (`@coder`) is unavailable in mention suggestions, including@@ -426,15 +426,14 @@ collapse control. The card never expands in place.Built-in provider agents are offered before account setup, each within its ownrollout: `@cursor` requires the `enable-cursor-agents` flag (local override:-`VITE_ENABLE_CURSOR_AGENTS`), `@claude` requires the `claude-cloud` flag-(local override: `VITE_CLAUDE_CLOUD`), and `@codex` requires both+`VITE_ENABLE_CURSOR_AGENTS`), and `@codex` requires both`enable-chat-v3-agents` and `enable-codex-agents` (local override:`VITE_ENABLE_CODEX_AGENTS`). Outside a rollout the entry is absent fromthe mention menu and from task agent assignees, even when that bot is already achannel participant. Custom agents keep their channel visibility rulesregardless of which harness they use.A mention without a connected account creates no session and replies in the thread-with a **Connect Cursor**, **Connect Codex**, or **Connect Claude** chip. Each chip+with a **Connect Cursor** or **Connect Codex** chip. Each chipopens Settings → Agents → Runtimes, where the connection cards in the reader's rollout are visible. The samechip reads **connected** after setup; mention the bot again to start a session.Codex also prompts for a cloud environment when ChatGPT is connected but nodiff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex 34ea1ea4a1..05f6312723 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -968,31 +968,6 @@ Settings → Agents → Agents ends with **Coding sessions**: per-user **Createtasks** and **Open pull requests** switches, both off by default. Each saves ontoggle and reverts with a toast if the save fails.-With the `claude-cloud` feature flag enabled, Claude Cloud connection setup is in-Settings → Agents → Runtimes (Manage on Bring your own agent), above Cursor, with the-Anthropic logo. The agent editor's Where it runs offers In Claude Code but does not host-Claude's connection form. **Connect Claude** starts authorization and opens sign-in-on the first click; a fallback link remains if the browser blocks the tab.-Approve on Claude's page, copy the complete `code#state`, then use **Finish-connecting**. Hosted and local deployments use the same flow. Grants and pending-sign-in attempts are encrypted in MacroDB and survive restarts or replica changes.-If the card says sign-in is not configured, the deployment is missing its Claude-OAuth KMS key; changing the frontend flag cannot fix that backend configuration.-Claude's model picker uses provider-reported IDs,-names, descriptions, and order. Settings discovers from recent account sessions;-session catalogs update through replay, polling, and streaming. Before any catalog-is available, only subscription default is shown with an explanation. It saves the next-turn preference-without waking an idle worker; provider model rejections surface during the turn.-Claude agents use their saved MCP selection through the shared authenticated-session egress path. Remote HTTP/SSE servers are supported; stdio servers are-rejected. Tool permission requests use Macro's standard session policy. MCP setup-failures surface as turn errors and request interruption; the first prompt also-wakes the cloud worker, so setup failure may occur after submission. Reconnecting-refreshes the session credential and restores the saved selection.-Claude sessions expose **Open in Claude** in the header-toolbar (or its overflow menu). With a live runtime, messages sent in Claude are-polled into Macro about every two seconds; disconnected runtimes must resume first.-Home does not bind Delete or Backspace to deleting list items. These keys remainavailable to the open editor (for example, clearing a selected spreadsheet range).Use the item menu to delete an item from Home.diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex 158d8ad5ce..ab66926479 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -585,7 +585,7 @@ New macrod sessions use the agent's saved model before sending the first prompt.Changing that default applies to new sessions; existing sessions keep their selected model.If the runtime rejects the saved model, the prompt fails instead of using a different model.-The `Runtimes` section shows built-in Macro, Cursor, Claude, and Codex configuration, followed by paired macrod runtimes. Claude's card appears only with the `claude-cloud` flag, and Codex's only within the agents and Codex rollouts. On the desktop app only, a “This computer” card appears above the built-in runtimes: the bundled macrod daemon is set up from here with one click. `Set up` scans the machine for installed agents (Claude Code, Codex, OpenCode, OpenClaw), offers a workspace folder and a Full access checkbox, and `Start running agents here` configures, pairs, and starts the daemon — the pairing is approved automatically, no code is typed. While running the card shows the agent and workspace with a `Stop` action; a set-up-but-stopped runtime offers `Start`. The web app never shows this card. The “Bring your own agent” card sits above the Agents / Runtimes navigation and is visible on both sections. It rotates Claude Code, OpenCode, OpenClaw, and Hermes; reduced motion keeps a static name. Its `New runtime` action opens the full-page pairing flow from either section: enter the code, look up the request, review the machine, name, sharing and permission consent, then Approve and Done. Back/Cancel returns to the runtime list. Destructive removal still requires confirmation. `/settings/runtimes` opens this section; legacy `/settings/harness?pair=…` links remain supported.+The `Runtimes` section shows built-in Macro, Cursor, and Codex configuration, followed by paired macrod runtimes. Codex's card appears only within the agents and Codex rollouts. On the desktop app only, a “This computer” card appears above the built-in runtimes: the bundled macrod daemon is set up from here with one click. `Set up` scans the machine for installed agents (Claude Code, Codex, OpenCode, OpenClaw), offers a workspace folder and a Full access checkbox, and `Start running agents here` configures, pairs, and starts the daemon — the pairing is approved automatically, no code is typed. While running the card shows the agent and workspace with a `Stop` action; a set-up-but-stopped runtime offers `Start`. The web app never shows this card. The “Bring your own agent” card sits above the Agents / Runtimes navigation and is visible on both sections. It rotates Claude Code, OpenCode, OpenClaw, and Hermes; reduced motion keeps a static name. Its `New runtime` action opens the full-page pairing flow from either section: enter the code, look up the request, review the machine, name, sharing and permission consent, then Approve and Done. Back/Cancel returns to the runtime list. Destructive removal still requires confirmation. `/settings/runtimes` opens this section; legacy `/settings/harness?pair=…` links remain supported.Connection chips in agent replies open this page, including before any account is connected. Cursor's default-model picker usesthe same live model discovery and retains its existing save action.diff --git a/docs/architecture/agent-effort.md b/docs/architecture/agent-effort.mdindex bbb6027b11..85f5b08cfd 100644--- a/docs/architecture/agent-effort.md+++ b/docs/architecture/agent-effort.md@@ -49,8 +49,8 @@ Sources checked September 21, 2026:- Preflight capability cache identity includes the harness and model. A selectionfrom another target is discarded. External harnesses expose controls afteropening a session; model-specific preflight is not guessed.-- A model chosen at creation is the session's model from its row. In-memory,- Cursor, and Claude cloud runtimes start on it; the harness selects it over ACP+- A model chosen at creation is the session's model from its row. In-memory+ and Cursor runtimes start on it; the harness selects it over ACPfor the others and holds the first prompt until the runtime accepts it.- An effort chosen at creation waits for the runtime's reported configuration,checks the effort choices, then confirms effort before sending the prompt.diff --git a/docs/runbooks/ai-quota-enforcement.md b/docs/runbooks/ai-quota-enforcement.mdindex 3a2eb43c2b..5e2b3a8be1 100644--- a/docs/runbooks/ai-quota-enforcement.md+++ b/docs/runbooks/ai-quota-enforcement.md@@ -287,7 +287,7 @@ identity, feature exemption, or `count_usage` from a client; never substitute`SYSTEM_USER_ID` for a missing real caller. Non-user session owners remain rejected.Macro-funded in-memory and managed sandbox sessions require AgentSession admission.-Cursor, Codex Cloud, Claude Cloud, and externally paired runtime execution is funded+Cursor, Codex Cloud, and externally paired runtime execution is fundedexternally and skips that gate; independently Macro-funded naming, repositoryselection, and tool calls still have their own gates.diff --git a/docs/runbooks/claude-cloud-demo.md b/docs/runbooks/claude-cloud-demo.mddeleted file mode 100644index d89b07fd11..0000000000--- a/docs/runbooks/claude-cloud-demo.md+++ /dev/null@@ -1,216 +0,0 @@-# Claude Cloud harness — internal demo--`claude-cloud` runs Claude Code on Anthropic's cloud using **the session owner's subscription OAuth grant**. It does not use macrod, a local Claude process, or Macro's Anthropic API key. This uses an unofficial first-party protocol verified experimentally on September 15, 2026, not a supported third-party OAuth registration.--## Connect in the browser--The frontend entry points require the PostHog flag **`claude-cloud`**. It is-off by default everywhere (including dev); for a local demo, set-`VITE_CLAUDE_CLOUD=true` when starting/building the frontend. With the flag off,-the connection card never mounts and agent settings neither offer Claude Cloud-nor request its model catalog. This is a UI rollout flag, not a backend-authorization boundary or a kill switch for existing agents/sessions.--Deploy the backend and infrastructure from this workspace, or rebuild the local-backend (`r` in `just run_local`), then refresh the browser. In **Settings → Harness**, the-**Claude Cloud** row has the Anthropic logo and appears above Cursor,-even before an account is connected. Connection setup is not in Settings → Agents:--1. Click **Connect Claude** to open Claude sign-in in a new tab automatically.- If the browser blocks it, use the **Didn't open? Open Claude sign-in** link.-2. Sign in and approve on Claude's own page. Macro never asks for your password.-3. Copy the entire one-time `code#state` displayed by Claude, paste it into Macro,- and click **Finish connecting**.-4. Create/edit an agent and select **Claude Cloud** as its harness.--This is Claude Code's manual authorization-code + PKCE flow, not an RFC 8628-device-code grant. The registered callback stays on Claude's site, so this works-across Docker/host boundaries without exposing a localhost callback server.-The Macro user comes from authenticated request identity, never an email field.-Attempts expire after ten minutes, are one-use, and are canceled on disconnect.-Starting again invalidates the prior attempt. A failed exchange requires starting again.--**No credential file or mount is needed.** Every configured deployment stores-grants and pending PKCE attempts in MacroDB's `claude_oauth_grants` table. KMS-encryption binds state to its exact Macro owner and the `claude-cloud-oauth`-purpose. Hosted deployments use a dedicated key; the local stack uses its existing-Cursor KMS key with this separate context. PostgreSQL owner locks serialize-sign-in, disconnect, and credential changes across replicas. Starting on one-replica and finishing on another works, including after a restart. Existing-version-1 encrypted grants are read and upgraded on their next write.--A refresh is durably marked consumed before contacting Claude. A failed or-interrupted exchange requires reconnecting instead of reusing a possibly rotated-refresh token. A persistence retry in the same process may recover the refreshed-grant, but cannot overwrite a newer connection or undo a disconnect.-Access/refresh tokens never reach frontend responses, query caches,-local storage, or logs. The one-time code is briefly in the masked input and POST body,-and is cleared on submission/cancel/expiry. Consent URLs are no-store responses.-Local Macro login may be a different email from the Claude account you authorize.--**Disconnect Claude** forgets Macro's grant and pending attempt. It does not revoke-consent at Anthropic or stop a cloud turn already running; stop the turn first if-needed.--## Legacy command-line provisioning (optional)--From this workspace, with Node 22+:--```sh-node tooling/claude-cloud/connect.mjs --owner [email protected]-```--Complete Claude's own browser consent page. This helper uses authorization-code OAuth with PKCE and a loopback callback, not a device-code grant. It requests `user:profile user:inference user:sessions:claude_code`, resolves the selected Claude organization, and selects a single active cloud environment. If there are several, pass `--environment env_...` explicitly. No session is created by connecting.--To reuse a grant obtained by the earlier isolated experiment, supply `--oauth-file /absolute/path/to/private/oauth.json`. Do not paste tokens into commands, chat, frontend storage, or tracked files.--The output defaults to `.claude-cloud/credentials.json` (gitignored). The parent must be `0700` and the file `0600`. The helper refuses to overwrite a connection. The file is **plaintext private demo storage, not encrypted/KMS storage**, and the service must run as its owner. It maps exact `macro|email` identities to grants; there is no shared default credential.--## Enable the service--The service uses `CLAUDE_OAUTH_KMS_KEY_ID` from MacroConfig/Doppler or the ECS-container environment. `infra/stacks/agent-harness-service` provisions the dedicated-key and injects its ARN, with Encrypt/Decrypt permission restricted to the Claude-purpose and an owner encryption context. Deploy this infrastructure together with-the service. Without a configured key, connection status reports disabled with an-explicit setup message. There is no hosted/local auth behavior gate.--LocalStack keeps the existing `alias/macro-local-cursor-api-key` default. The old-`CLAUDE_CLOUD_CREDENTIALS_PATH` service setting is removed; private files remain-supported only by standalone command-line probes.--Browser consent is authorization-code + PKCE with manual code entry. It does not-implement device-code polling. End-to-end provider verification requires approving-Claude's consent page and completing the one-time code exchange.--## Use in Macro--1. Connect through the Claude row in Settings → Harness, then create or edit a private agent in Settings → Agents.-2. Select **Claude Cloud**. It is offered for new selections only when model discovery confirms that your Macro identity has a configured connection. When editing a saved Claude agent, the harness stays visibly selected while discovery loads or fails. Models belong to the selected harness: Fable is available through Claude Cloud only, and switching to Macro Agent replaces the catalog and model preference with that harness's choices.-3. Choose from Claude's model catalog. Settings calls `GET /v1/models` with your connected account's OAuth credential, without the code-session beta header (which this endpoint rejects). Discovery follows pagination and fails visibly on provider errors or an incomplete catalog; it never scans recent sessions, reads transcripts, creates a worker, or spends inference. IDs, names, and ordering come from the API, with **Claude · subscription default** retained as the provider's reset choice. Fable can appear even when you have no previous sessions. New conversations pass the selected model in Claude's creation configuration. Existing conversations retain aliases reported by their own worker alongside the direct account catalog. The first prompt requests initialization alongside the model and user message, and subsequent worker catalogs replace that session's aliases without removing account-listed choices or resetting your saved preference. The Models API is not a guarantee that every cloud worker accepts every listed model: Claude validates the request when the worker runs. Selection saves the next-turn preference after event submission; it does not wait for an idle worker. Each prompt repeats that preference immediately before the user message in one ordered batch, including after a Macro restart. A worker rejection surfaces an error and requests interruption; this cannot guarantee zero inference before the rejection arrives.-4. Start a session with that agent or mention it in a channel. Prompts, follow-ups, text streaming, tool cards, cancellation, and transcript load use Macro's existing session interface.-5. In the session header, use **Open in Claude** (the external-link icon; in the toolbar overflow on narrow screens). Existing demo sessions get the link too.-6. Send a message on that Claude page. While the Macro runtime connection is live,- durable user messages, assistant text, tool results, and turn completion are- mirrored back into Macro on a two-second polling cadence. Polls skip active- Macro turns, share the SSE replay cursor, and back off for 30 seconds on errors.- Polling uses the bounded history endpoint, so long transcripts may take longer- than two seconds; cloud-side text appears as durable messages, not token deltas.--Only the session owner may send/control prompts or edit/remove queued input for this provider. Sharing visibility does not grant permission to spend the owner's subscription. Existing Macro access checks still apply.--## Harness integration--Claude implements the shared `ContainerManager` and `ClaudeModelProbe` ports and-is dispatched by `RoutedContainerManager` alongside Cursor and Codex. The-composition root supplies the account-scoped `CloudProvider`, session repository,-existing egress provisioner, and ACP adapter. Each saved agent retains its own-instructions, model, and MCP selection. Provider lifecycle policy lives in-`agent_harness::domain::claude`; OAuth credentials stay behind the account service.--ACP `session/new` and `session/load` carry Macro's existing authenticated HTTP/SSE-MCP server list. Claude translates that list into the SDK's `mcp_set_servers`-control request, ordered before the model and user message in the same batch.-An idle worker needs the user event to wake, so an acknowledgment cannot be awaited-before submitting that batch. A rejected or missing setup acknowledgment fails the-turn; rejection also requests interruption. As with model selection, this cannot-guarantee zero inference before a rejection arrives. Tool permission requests go-through Macro's standard ACP `session/request_permission` policy. Unsupported-stdio servers and duplicate names fail the handshake instead of being dropped.-On reattach the existing egress provisioner mints a fresh session token, persists-its hash, and reconstructs the saved selection, including after a host restart.--The control request and response match-[Anthropic's Agent SDK types](https://unpkg.com/@anthropic-ai/[email protected]/sdk.d.ts).-Automated tests exercise protocol translation and host permission decisions using-fake provider ports; they do not establish live Claude Cloud MCP connectivity.-The cloud worker must be able to reach the configured egress URL.--## Demo boundary--- Text prompts only; attachments and repository selection are not forwarded yet. Macro and configured Pipedream MCP servers use the shared session egress path. Built-in cloud tools retain provider policy; explicit permission requests are delegated to the Macro host.-- Model discovery reads the account-scoped Models API with a bound of ten pages of 1,000 models each; exceeding that bound fails instead of returning a partial catalog. No catalog is shared across credential owners. New/removed API model IDs require no code change; existing sessions can also select their own worker-reported aliases. Provider errors stay visible rather than silently substituting a fixed list. No local filesystem. Agent instructions are forwarded as `append_system_prompt`.-- Access tokens refresh shortly before expiry; rotated refresh tokens are encrypted and saved before provider use. If saving fails, the process retains the rotated grant and retries persistence rather than reusing the old refresh token. A revoked grant produces a reconnect error. No API-key fallback or quota bypass.-- Prompt sends and session creation are not blindly retried. A durable `claude-cloud-create-pending` mapping prevents duplicate creation after an uncertain request or crash. An operator must inspect the Claude account before clearing a stuck intent.-- SSE reconnect is bounded and resumes durable sequence numbers. Durable assistant text reconciles with already-delivered ephemeral text; an inconsistent/truncated replay fails visibly. Session/load recovers the durable transcript. A result ends a turn, not the conversation.-- Closing the Macro transport closes its adapter tasks, not the provider's ongoing work. Use Stop for interruption. Deleting a Macro session requests reversible archive of the cloud session, not deletion of the user's Claude transcript.-- A process restart during a running cloud turn does not automatically reattach live output. Wait or interrupt, then reload the transcript; the harness refuses to send a new prompt while cloud history has an unfinished user turn.-- Provider token usage is reported into Macro's existing session telemetry. This is subscription usage, not a Macro-paid model invocation.-- Fresh-login/device-attestation requirements may differ across accounts. Only the standard cloud-session path was verified; errors are surfaced rather than bypassed.--Before production: supported auth onboarding, a dedicated hosted KMS key and IAM-policy, distributed refresh locking, stronger lifecycle/recovery tests, remote MCP-validation, repo authorization, permission UI, and explicit shared-session billing policy.--## Verification--Discovery was verified against the connected account and the real session picker:-both returned Claude's four reported choices with provider names/descriptions,-without the old hard-coded standalone Opus entry. No inference was sent, and the-saved selection was restored to default. Regression tests cover new arbitrary-model IDs, catalog replacement/removal, malformed data, account separation,-bounded discovery, and polled ACP config updates preserving the saved model.--Model switching was checked in the existing local Macro session: Sonnet was saved, and the picker restored subscription-default (confirmed in MacroDB). No inference was sent in that UI check. The-ordered model-plus-prompt batch and model-rejection interruption are regression-tested; control-only requests were observed to remain pending when the cloud-worker was disconnected, which is why selection does not await worker execution.--The Rust ACP adapter was exercised against the existing experiment's live cloud session: initialize, full transcript load, one harmless prompt, two streaming text chunks, and a successful result. No tools were used. The earlier harness changes passed 200 agent-harness tests and 49 focused frontend tests. The interactive connection change passed 19 Claude adapter tests, 26 harness-service tests, 45 focused frontend tests, TypeScript checking, and a Linux service build. OAuth domain tests cover wrong-user/state rejection, expiry, replay, and disconnect racing an exchange.--The polish pass verified the Anthropic-logo row above Cursor in Harness settings,-its absence from Agents settings, and start/cancel against the rebuilt local-backend. The masked code input, fixed PKCE consent URL, wrong-state rejection,-caller-supplied owner rejection, and canceled-attempt rejection were exercised.-The real session toolbar opened the expected Claude URL in a new tab using a-controlled read-only session fixture. Tests used `[email protected]`;-no Claude grant or subscription turn was submitted for that identity.--The updated Claude crate has 26 passing tests, including actual PostgreSQL-persistence with a fake KMS boundary, cross-owner ciphertext rejection, refresh-rotation recovery, replay deduplication, and idle polling through the real ACP-channel. The local KMS key is enabled. TypeScript, 45 frontend tests, and the-Linux service build passed. All 214 agent-session tests passed serially (an-existing telemetry test was flaky in parallel), and 26 harness-service tests passed.-Workspace SQLx preparation passed against the named-local database, including test queries; only the six relevant generated cache-files were retained. **A consenting user's reconnect and cloud-page follow-up-are still needed to verify the complete live flow with database-backed grants.**--Repeat the non-provider browser smoke against your local frontend:--```sh-node tooling/claude-cloud/browser-smoke.mjs --origin http://localhost:25510-```--It signs into that disposable local identity and tests start/cancel; it does not authorize Claude or consume a subscription turn. `just check` cannot discover the jj-only workspace's diff because it uses Git; scoped checks were run directly instead.--An explicit live smoke runner is available (one short subscription turn; transcript retained):--```sh-cargo run -p claude_cloud_agents --example smoke -- \- --credentials .claude-cloud/credentials.json \- --owner 'macro|[email protected]' \- --session cse_existing_session-```--Use `--discover-only` to print API-discovered model IDs and names without creating a session or sending a prompt. Add `--model <advertised-id>` to verify selecting that model before the smoke prompt.--Omitting `--session` creates a new cloud conversation. Do not automatically rerun a failed create; inspect the account first. The runner prints only the session identity and outcome, not tokens or private transcript contents.--## MCP gateway networking--Before creating a Claude cloud conversation, the shared Claude harness lifecycle-allows the deployment’s `AgentHarnessEgressUrl` hostname in the connected owner's-selected environment. Limited networking keeps its existing allowed hosts,-package access, and connector settings; only the exact gateway hostname is-added. Unrestricted environments need no update. Disabled or unrecognized-network policies fail before session creation with an environment setup error.-An environment update failure can be retried without creating duplicate sessions.--Claude captures networking when it creates a container. Start a new Macro agent-session after fixing an environment; existing containers keep their old policy.-The earlier MCP HTTP 403 failure was reproduced with an empty allowlist despite-`allow_mcp_servers: true`: adding `dev-gateway.macro.com` let a fresh Claude-session connect `macro`, `macro_internal`, and `linear` and complete a prompt.diff --git a/infra/stacks/agent-harness-service/agent_harness_service.ts b/infra/stacks/agent-harness-service/agent_harness_service.tsindex 895b604806..3d12574669 100644--- a/infra/stacks/agent-harness-service/agent_harness_service.ts+++ b/infra/stacks/agent-harness-service/agent_harness_service.ts@@ -213,49 +213,6 @@ export class AgentHarnessService extends pulumi.ComponentResource {{ parent: this });- const claudeOauthKey = new aws.kms.Key(- `${BASE_NAME}-claude-oauth-key`,- {- description:- 'Encrypt per-user Claude OAuth grants and browser sign-in state',- enableKeyRotation: true,- deletionWindowInDays: 30,- tags,- },- { parent: this }- );- new aws.kms.Alias(- `${BASE_NAME}-claude-oauth-alias`,- {- name: `alias/agent-harness-service-claude-oauth-${stack}`,- targetKeyId: claudeOauthKey.keyId,- },- { parent: this }- );- const claudeOauthPolicy = new aws.iam.RolePolicy(- `${BASE_NAME}-claude-oauth-policy`,- {- role: this.role.name,- policy: pulumi.jsonStringify({- Version: '2012-10-17',- Statement: [- {- Effect: 'Allow',- Action: ['kms:Encrypt', 'kms:Decrypt'],- Resource: claudeOauthKey.arn,- Condition: {- StringEquals: {- 'kms:EncryptionContext:purpose': 'claude-cloud-oauth',- },- Null: { 'kms:EncryptionContext:user_id': 'false' },- },- },- ],- }),- },- { parent: this }- );-// Producer/consumer access to the macro event Kafka cluster: the harness// consumes `macro.channels` and `macro.agent_sessions`, publishes agent// triggers, and publishes channel side effects.@@ -480,7 +437,6 @@ export class AgentHarnessService extends pulumi.ComponentResource {memory: 8192,environment: [...containerEnvVars,- { name: 'CLAUDE_OAUTH_KMS_KEY_ID', value: claudeOauthKey.arn },{name: 'BASE_URL',value: this.domain,@@ -539,7 +495,6 @@ export class AgentHarnessService extends pulumi.ComponentResource {...publicHostRules,...sharedApiRules,egress.listener_rule,- claudeOauthPolicy,],});diff --git a/packages/lexical-core/tests/agent-connection-prompt.test.ts b/packages/lexical-core/tests/agent-connection-prompt.test.tsindex 5d2bd8a1e7..e15b70ab61 100644--- a/packages/lexical-core/tests/agent-connection-prompt.test.ts+++ b/packages/lexical-core/tests/agent-connection-prompt.test.ts@@ -6,7 +6,6 @@ describe('composeAgentConnectionPrompt', () => {it.each([['cursor', 'Cursor', '@cursor'],['codex-cloud', 'Codex', '@codex'],- ['claude-cloud', 'Claude', '@claude'],])('round-trips the %s setup reply through real Lexical nodes',(appSlug, name, agentTag) => {diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.mdindex 1dd03d7b57..9450737a39 100644--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md@@ -59,11 +59,6 @@- [ChannelSharePermission](type-aliases/ChannelSharePermission.md)- [ClientOptions](type-aliases/ClientOptions.md)- [CodingPreferencesBody](type-aliases/CodingPreferencesBody.md)-- [CompleteData](type-aliases/CompleteData.md)-- [CompleteErrors](type-aliases/CompleteErrors.md)-- [CompleteRequest](type-aliases/CompleteRequest.md)-- [CompleteResponse](type-aliases/CompleteResponse.md)-- [CompleteResponses](type-aliases/CompleteResponses.md)- [ControlAgentSessionData](type-aliases/ControlAgentSessionData.md)- [ControlAgentSessionError](type-aliases/ControlAgentSessionError.md)- [ControlAgentSessionErrors](type-aliases/ControlAgentSessionErrors.md)@@ -95,10 +90,6 @@- [DeleteAgentSessionError](type-aliases/DeleteAgentSessionError.md)- [DeleteAgentSessionErrors](type-aliases/DeleteAgentSessionErrors.md)- [DeleteAgentSessionResponses](type-aliases/DeleteAgentSessionResponses.md)-- [DisconnectData](type-aliases/DisconnectData.md)-- [DisconnectErrors](type-aliases/DisconnectErrors.md)-- [DisconnectResponse](type-aliases/DisconnectResponse.md)-- [DisconnectResponses](type-aliases/DisconnectResponses.md)- [DiscoverAgentCapabilitiesHandlerData](type-aliases/DiscoverAgentCapabilitiesHandlerData.md)- [DiscoverAgentCapabilitiesHandlerErrors](type-aliases/DiscoverAgentCapabilitiesHandlerErrors.md)- [DiscoverAgentCapabilitiesHandlerResponse](type-aliases/DiscoverAgentCapabilitiesHandlerResponse.md)@@ -115,7 +106,6 @@- [ElicitationAnswer](type-aliases/ElicitationAnswer.md)- [ElicitationContentValue](type-aliases/ElicitationContentValue.md)- [ElicitationRequestId](type-aliases/ElicitationRequestId.md)-- [EmptyRequest](type-aliases/EmptyRequest.md)- [ExecutionActivity](type-aliases/ExecutionActivity.md)- [ExecutionId](type-aliases/ExecutionId.md)- [ExecutionRecord](type-aliases/ExecutionRecord.md)@@ -288,21 +278,11 @@- [SetAgentSessionArchivedResponse](type-aliases/SetAgentSessionArchivedResponse.md)- [SetAgentSessionArchivedResponses](type-aliases/SetAgentSessionArchivedResponses.md)- [SharePermissionV2](type-aliases/SharePermissionV2.md)-- [StartData](type-aliases/StartData.md)-- [StartErrors](type-aliases/StartErrors.md)- [StartFreshAgentConversationData](type-aliases/StartFreshAgentConversationData.md)- [StartFreshAgentConversationErrors](type-aliases/StartFreshAgentConversationErrors.md)- [StartFreshAgentConversationRequest](type-aliases/StartFreshAgentConversationRequest.md)- [StartFreshAgentConversationResponse](type-aliases/StartFreshAgentConversationResponse.md)- [StartFreshAgentConversationResponses](type-aliases/StartFreshAgentConversationResponses.md)-- [StartResponse](type-aliases/StartResponse.md)-- [StartResponse2](type-aliases/StartResponse2.md)-- [StartResponses](type-aliases/StartResponses.md)-- [StatusData](type-aliases/StatusData.md)-- [StatusErrors](type-aliases/StatusErrors.md)-- [StatusResponse](type-aliases/StatusResponse.md)-- [StatusResponse2](type-aliases/StatusResponse2.md)-- [StatusResponses](type-aliases/StatusResponses.md)- [SteerQueuedActionData](type-aliases/SteerQueuedActionData.md)- [SteerQueuedActionError](type-aliases/SteerQueuedActionError.md)- [SteerQueuedActionErrors](type-aliases/SteerQueuedActionErrors.md)diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteData.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteData.mddeleted file mode 100644index 6688b9a616..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteData.md+++ /dev/null@@ -1,12 +0,0 @@-# Type Alias: CompleteData--> **CompleteData** = \{ `body`: [`CompleteRequest`](CompleteRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/claude-auth/complete"`; \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-body"></a> `body` | [`CompleteRequest`](CompleteRequest.md) |-| <a id="property-path"></a> `path?` | `never` |-| <a id="property-query"></a> `query?` | `never` |-| <a id="property-url"></a> `url` | `"/claude-auth/complete"` |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteErrors.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteErrors.mddeleted file mode 100644index 1e69e827d8..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteErrors.md+++ /dev/null@@ -1,11 +0,0 @@-# Type Alias: CompleteErrors--> **CompleteErrors** = \{ `400`: `unknown`; `409`: `unknown`; `502`: `unknown`; \}--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-400"></a> `400` | `unknown` | Invalid code |-| <a id="property-409"></a> `409` | `unknown` | Expired or replayed |-| <a id="property-502"></a> `502` | `unknown` | Provider failed |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteRequest.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteRequest.mddeleted file mode 100644index 21e3b1afd6..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteRequest.md+++ /dev/null@@ -1,12 +0,0 @@-# Type Alias: CompleteRequest--> **CompleteRequest** = \{ `attemptId`: `string`; `code`: `string`; \}--One-time manual code. Deliberately does not implement Debug.--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-attemptid"></a> `attemptId` | `string` | Server-issued handle; never an owner selected by the caller. |-| <a id="property-code"></a> `code` | `string` | Claude's complete code#state string, not an access token. |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteResponse.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteResponse.mddeleted file mode 100644index 8f7bd0f80f..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteResponse.md+++ /dev/null@@ -1,3 +0,0 @@-# Type Alias: CompleteResponse--> **CompleteResponse** = [`CompleteResponses`](CompleteResponses.md)\[keyof [`CompleteResponses`](CompleteResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteResponses.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteResponses.mddeleted file mode 100644index f057143ed1..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CompleteResponses.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: CompleteResponses--> **CompleteResponses** = \{ `204`: `void`; \}--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-204"></a> `204` | `void` | Connected |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectData.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectData.mddeleted file mode 100644index bd03ad09bb..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectData.md+++ /dev/null@@ -1,12 +0,0 @@-# Type Alias: DisconnectData--> **DisconnectData** = \{ `body`: [`EmptyRequest`](EmptyRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/claude-auth"`; \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-body"></a> `body` | [`EmptyRequest`](EmptyRequest.md) |-| <a id="property-path"></a> `path?` | `never` |-| <a id="property-query"></a> `query?` | `never` |-| <a id="property-url"></a> `url` | `"/claude-auth"` |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectErrors.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectErrors.mddeleted file mode 100644index 4ffca1bc83..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectErrors.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: DisconnectErrors--> **DisconnectErrors** = \{ `403`: `unknown`; \}--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-403"></a> `403` | `unknown` | Disabled |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectResponse.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectResponse.mddeleted file mode 100644index ec23f36207..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectResponse.md+++ /dev/null@@ -1,3 +0,0 @@-# Type Alias: DisconnectResponse--> **DisconnectResponse** = [`DisconnectResponses`](DisconnectResponses.md)\[keyof [`DisconnectResponses`](DisconnectResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectResponses.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectResponses.mddeleted file mode 100644index 7d2236bfcc..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/DisconnectResponses.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: DisconnectResponses--> **DisconnectResponses** = \{ `204`: `void`; \}--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-204"></a> `204` | `void` | Disconnected |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/EmptyRequest.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/EmptyRequest.mddeleted file mode 100644index 9d5da8f576..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/EmptyRequest.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: EmptyRequest--> **EmptyRequest** = \{\[`key`: `string`\]: `never`; \}--A JSON body is required on writes, including start/disconnect (no form-based CSRF).--## Index Signature--\[`key`: `string`\]: `never`diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ModelHarnessDto.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ModelHarnessDto.mdindex b3495b4b51..82cd7c5f5f 100644--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ModelHarnessDto.md+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ModelHarnessDto.md@@ -1,5 +1,5 @@# Type Alias: ModelHarnessDto-> **ModelHarnessDto** = `"in-memory"` \| `"cursor"` \| `"claude-cloud"` \| `"macrod"`+> **ModelHarnessDto** = `"in-memory"` \| `"cursor"` \| `"macrod"`Harness names accepted by the model discovery endpoint.diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartData.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartData.mddeleted file mode 100644index 28f4092ee4..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartData.md+++ /dev/null@@ -1,12 +0,0 @@-# Type Alias: StartData--> **StartData** = \{ `body`: [`EmptyRequest`](EmptyRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/claude-auth/start"`; \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-body"></a> `body` | [`EmptyRequest`](EmptyRequest.md) |-| <a id="property-path"></a> `path?` | `never` |-| <a id="property-query"></a> `query?` | `never` |-| <a id="property-url"></a> `url` | `"/claude-auth/start"` |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartErrors.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartErrors.mddeleted file mode 100644index 17986d1b9f..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartErrors.md+++ /dev/null@@ -1,10 +0,0 @@-# Type Alias: StartErrors--> **StartErrors** = \{ `403`: `unknown`; `429`: `unknown`; \}--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-403"></a> `403` | `unknown` | Disabled |-| <a id="property-429"></a> `429` | `unknown` | Too many attempts |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponse.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponse.mddeleted file mode 100644index 5076020f4d..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponse.md+++ /dev/null@@ -1,13 +0,0 @@-# Type Alias: StartResponse--> **StartResponse** = \{ `attemptId`: `string`; `authorizationUrl`: `string`; `expiresIn`: `number`; \}--Public PKCE challenge and attempt handle; contains no verifier or provider tokens.--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-attemptid"></a> `attemptId` | `string` | Opaque owner-bound attempt handle. |-| <a id="property-authorizationurl"></a> `authorizationUrl` | `string` | Claude-hosted consent page. |-| <a id="property-expiresin"></a> `expiresIn` | `number` | Attempt lifetime in seconds. |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponse2.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponse2.mddeleted file mode 100644index d430399430..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponse2.md+++ /dev/null@@ -1,3 +0,0 @@-# Type Alias: StartResponse2--> **StartResponse2** = [`StartResponses`](StartResponses.md)\[keyof [`StartResponses`](StartResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponses.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponses.mddeleted file mode 100644index a779ee7111..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StartResponses.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: StartResponses--> **StartResponses** = \{ `200`: [`StartResponse`](StartResponse.md); \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-200"></a> `200` | [`StartResponse`](StartResponse.md) |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusData.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusData.mddeleted file mode 100644index 5f74e2cc72..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusData.md+++ /dev/null@@ -1,12 +0,0 @@-# Type Alias: StatusData--> **StatusData** = \{ `body?`: `never`; `path?`: `never`; `query?`: `never`; `url`: `"/claude-auth"`; \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-body"></a> `body?` | `never` |-| <a id="property-path"></a> `path?` | `never` |-| <a id="property-query"></a> `query?` | `never` |-| <a id="property-url"></a> `url` | `"/claude-auth"` |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusErrors.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusErrors.mddeleted file mode 100644index 1e9a5cc303..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusErrors.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: StatusErrors--> **StatusErrors** = \{ `401`: `unknown`; \}--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-401"></a> `401` | `unknown` | Unauthenticated |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponse.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponse.mddeleted file mode 100644index b6399c4487..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponse.md+++ /dev/null@@ -1,13 +0,0 @@-# Type Alias: StatusResponse--> **StatusResponse** = \{ `connected`: `boolean`; `enabled`: `boolean`; `ephemeral`: `boolean`; \}--Safe connection metadata.--## Properties--| Property | Type | Description |-| ------ | ------ | ------ |-| <a id="property-connected"></a> `connected` | `boolean` | Whether the authenticated Macro user has connected. |-| <a id="property-enabled"></a> `enabled` | `boolean` | Whether this deployment supports browser connection. |-| <a id="property-ephemeral"></a> `ephemeral` | `boolean` | Whether reconnecting after service restart is required. |diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponse2.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponse2.mddeleted file mode 100644index d92521a54f..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponse2.md+++ /dev/null@@ -1,3 +0,0 @@-# Type Alias: StatusResponse2--> **StatusResponse2** = [`StatusResponses`](StatusResponses.md)\[keyof [`StatusResponses`](StatusResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponses.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponses.mddeleted file mode 100644index cd363ae411..0000000000--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/StatusResponses.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: StatusResponses--> **StatusResponses** = \{ `200`: [`StatusResponse`](StatusResponse.md); \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-200"></a> `200` | [`StatusResponse`](StatusResponse.md) |diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.tsindex c9df8926c1..81b2d06e18 100644--- a/packages/sdk/generated/agent-harness/index.ts+++ b/packages/sdk/generated/agent-harness/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CodingPreferencesBody, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, FileChangeKindDto, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewItem, ReviewItemStatus, ReviewKind, ReviewRecord, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CodingPreferencesBody, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, FileChangeKindDto, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewItem, ReviewItemStatus, ReviewKind, ReviewRecord, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.tsindex 88373b14e2..12fc6e22fe 100644--- a/packages/sdk/generated/agent-harness/sdk.gen.ts+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';+import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -556,60 +556,4 @@ export class Sdk extends HeyApiClient {}});}-- /**- * Forget only the authenticated user's grant and cancel pending consent.- */- public disconnect<ThrowOnError extends boolean = false>(options: Options<DisconnectData, ThrowOnError>): RequestResult<DisconnectResponses, DisconnectErrors, ThrowOnError> {- return (options.client ?? this.client).delete<DisconnectResponses, DisconnectErrors, ThrowOnError>({- security: [{ scheme: 'bearer', type: 'http' }],- url: '/claude-auth',- ...options,- headers: {- 'Content-Type': 'application/json',- ...options.headers- }- });- }-- /**- * Read connection status for the authenticated user only.- */- public status<ThrowOnError extends boolean = false>(options?: Options<StatusData, ThrowOnError>): RequestResult<StatusResponses, StatusErrors, ThrowOnError> {- return (options?.client ?? this.client).get<StatusResponses, StatusErrors, ThrowOnError>({- security: [{ scheme: 'bearer', type: 'http' }],- url: '/claude-auth',- ...options- });- }-- /**- * Exchange one code; never return access or refresh tokens.- */- public complete<ThrowOnError extends boolean = false>(options: Options<CompleteData, ThrowOnError>): RequestResult<CompleteResponses, CompleteErrors, ThrowOnError> {- return (options.client ?? this.client).post<CompleteResponses, CompleteErrors, ThrowOnError>({- security: [{ scheme: 'bearer', type: 'http' }],- url: '/claude-auth/complete',- ...options,- headers: {- 'Content-Type': 'application/json',- ...options.headers- }- });- }-- /**- * Create an expiring PKCE challenge for the authenticated user.- */- public start<ThrowOnError extends boolean = false>(options: Options<StartData, ThrowOnError>): RequestResult<StartResponses, StartErrors, ThrowOnError> {- return (options.client ?? this.client).post<StartResponses, StartErrors, ThrowOnError>({- security: [{ scheme: 'bearer', type: 'http' }],- url: '/claude-auth/start',- ...options,- headers: {- 'Content-Type': 'application/json',- ...options.headers- }- });- }}diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex e00a7ebc35..7f355a886e 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -815,20 +815,6 @@ export type CodingPreferencesBody = {openPullRequests: boolean;};-/**- * One-time manual code. Deliberately does not implement Debug.- */-export type CompleteRequest = {- /**- * Server-issued handle; never an owner selected by the caller.- */- attemptId: string;- /**- * Claude's complete code#state string, not an access token.- */- code: string;-};-/*** Request body for a control operation on a live session.*@@ -1126,13 +1112,6 @@ export type ElicitationContentValue = string | boolean | number | number | Array*/export type ElicitationRequestId = number | string;-/**- * A JSON body is required on writes, including start/disconnect (no form-based CSRF).- */-export type EmptyRequest = {- [key: string]: never;-};-/*** A bounded SDK operation observed during execution; not an authorization or write receipt.*/@@ -1346,7 +1325,7 @@ export type MessageParent = {/*** Harness names accepted by the model discovery endpoint.*/-export type ModelHarnessDto = 'in-memory' | 'cursor' | 'claude-cloud' | 'macrod';+export type ModelHarnessDto = 'in-memory' | 'cursor' | 'macrod';/*** The decision carried by an [`AgentPermissionAction`].@@ -1870,42 +1849,6 @@ export type StartFreshAgentConversationRequest = {sessionId: string;};-/**- * Public PKCE challenge and attempt handle; contains no verifier or provider tokens.- */-export type StartResponse = {- /**- * Opaque owner-bound attempt handle.- */- attemptId: string;- /**- * Claude-hosted consent page.- */- authorizationUrl: string;- /**- * Attempt lifetime in seconds.- */- expiresIn: number;-};--/**- * Safe connection metadata.- */-export type StatusResponse = {- /**- * Whether the authenticated Macro user has connected.- */- connected: boolean;- /**- * Whether this deployment supports browser connection.- */- enabled: boolean;- /**- * Whether reconnecting after service restart is required.- */- ephemeral: boolean;-};-/*** How a person answers a held tool call.*/@@ -3150,101 +3093,3 @@ export type AnswerAgentSessionToolApprovalResponses = {};export type AnswerAgentSessionToolApprovalResponse = AnswerAgentSessionToolApprovalResponses[keyof AnswerAgentSessionToolApprovalResponses];--export type DisconnectData = {- body: EmptyRequest;- path?: never;- query?: never;- url: '/claude-auth';-};--export type DisconnectErrors = {- /**- * Disabled- */- 403: unknown;-};--export type DisconnectResponses = {- /**- * Disconnected- */- 204: void;-};--export type DisconnectResponse = DisconnectResponses[keyof DisconnectResponses];--export type StatusData = {- body?: never;- path?: never;- query?: never;- url: '/claude-auth';-};--export type StatusErrors = {- /**- * Unauthenticated- */- 401: unknown;-};--export type StatusResponses = {- 200: StatusResponse;-};--export type StatusResponse2 = StatusResponses[keyof StatusResponses];--export type CompleteData = {- body: CompleteRequest;- path?: never;- query?: never;- url: '/claude-auth/complete';-};--export type CompleteErrors = {- /**- * Invalid code- */- 400: unknown;- /**- * Expired or replayed- */- 409: unknown;- /**- * Provider failed- */- 502: unknown;-};--export type CompleteResponses = {- /**- * Connected- */- 204: void;-};--export type CompleteResponse = CompleteResponses[keyof CompleteResponses];--export type StartData = {- body: EmptyRequest;- path?: never;- query?: never;- url: '/claude-auth/start';-};--export type StartErrors = {- /**- * Disabled- */- 403: unknown;- /**- * Too many attempts- */- 429: unknown;-};--export type StartResponses = {- 200: StartResponse;-};--export type StartResponse2 = StartResponses[keyof StartResponses];diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex cbdb19d225..c0296f16c0 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -2596,137 +2596,6 @@}}}- },- "/claude-auth": {- "get": {- "tags": ["claude-auth"],- "summary": "Read connection status for the authenticated user only.",- "operationId": "status",- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StatusResponse"- }- }- }- },- "401": {- "description": "Unauthenticated"- }- },- "security": [- {- "bearerAuth": []- }- ]- },- "delete": {- "tags": ["claude-auth"],- "summary": "Forget only the authenticated user's grant and cancel pending consent.",- "operationId": "disconnect",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyRequest"- }- }- },- "required": true- },- "responses": {- "204": {- "description": "Disconnected"- },- "403": {- "description": "Disabled"- }- },- "security": [- {- "bearerAuth": []- }- ]- }- },- "/claude-auth/complete": {- "post": {- "tags": ["claude-auth"],- "summary": "Exchange one code; never return access or refresh tokens.",- "operationId": "complete",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/CompleteRequest"- }- }- },- "required": true- },- "responses": {- "204": {- "description": "Connected"- },- "400": {- "description": "Invalid code"- },- "409": {- "description": "Expired or replayed"- },- "502": {- "description": "Provider failed"- }- },- "security": [- {- "bearerAuth": []- }- ]- }- },- "/claude-auth/start": {- "post": {- "tags": ["claude-auth"],- "summary": "Create an expiring PKCE challenge for the authenticated user.",- "operationId": "start",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StartResponse"- }- }- }- },- "403": {- "description": "Disabled"- },- "429": {- "description": "Too many attempts"- }- },- "security": [- {- "bearerAuth": []- }- ]- }}},"components": {@@ -3861,22 +3730,6 @@}}},- "CompleteRequest": {- "type": "object",- "description": "One-time manual code. Deliberately does not implement Debug.",- "required": ["attemptId", "code"],- "properties": {- "attemptId": {- "type": "string",- "description": "Server-issued handle; never an owner selected by the caller."- },- "code": {- "type": "string",- "description": "Claude's complete code#state string, not an access token."- }- },- "additionalProperties": false- },"ControlRequest": {"allOf": [{@@ -4224,11 +4077,6 @@],"description": "The JSON-RPC id of an agent's `elicitation/create` request, carried whole\nso the answer echoes exactly what the agent sent.\n\nAgents pick these, not us: Claude Code counts from `0`, others use\nstrings. `null` is not a legal id for a request that expects a response,\nso it is not representable here."},- "EmptyRequest": {- "type": "object",- "description": "A JSON body is required on writes, including start/disconnect (no form-based CSRF).",- "additionalProperties": false- },"ExecutionActivity": {"type": "object","description": "A bounded SDK operation observed during execution; not an authorization or write receipt.",@@ -4508,7 +4356,7 @@"ModelHarnessDto": {"type": "string","description": "Harness names accepted by the model discovery endpoint.",- "enum": ["in-memory", "cursor", "claude-cloud", "macrod"]+ "enum": ["in-memory", "cursor", "macrod"]},"PermissionAnswer": {"oneOf": [@@ -5229,46 +5077,6 @@}}},- "StartResponse": {- "type": "object",- "description": "Public PKCE challenge and attempt handle; contains no verifier or provider tokens.",- "required": ["attemptId", "authorizationUrl", "expiresIn"],- "properties": {- "attemptId": {- "type": "string",- "description": "Opaque owner-bound attempt handle."- },- "authorizationUrl": {- "type": "string",- "description": "Claude-hosted consent page."- },- "expiresIn": {- "type": "integer",- "format": "int64",- "description": "Attempt lifetime in seconds.",- "minimum": 0- }- }- },- "StatusResponse": {- "type": "object",- "description": "Safe connection metadata.",- "required": ["enabled", "connected", "ephemeral"],- "properties": {- "connected": {- "type": "boolean",- "description": "Whether the authenticated Macro user has connected."- },- "enabled": {- "type": "boolean",- "description": "Whether this deployment supports browser connection."- },- "ephemeral": {- "type": "boolean",- "description": "Whether reconnecting after service restart is required."- }- }- },"ToolApprovalAnswerDto": {"type": "string","description": "How a person answers a held tool call.",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 496127933a..2265f747d2 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -25,11 +25,6 @@ import type { Sdk as StorageSdk } from '../../generated/storage/sdk.gen';import type { Sdk as UnfurlSdk } from '../../generated/unfurl/sdk.gen';export const agentHarnessExcluded = [- // Claude Cloud sign-in is an app-internal auth flow, not SDK surface.- 'complete',- 'disconnect',- 'start',- 'status','loadAgentModelsHandler','discoverAgentCapabilitiesHandler','previewAgentSessions',diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.ymlindex b4c1e6ad20..24eab62211 100644--- a/rules/ast-grep/ts-feature-components-presentational.yml+++ b/rules/ast-grep/ts-feature-components-presentational.yml@@ -37,7 +37,6 @@ files:- apps/web/src/features/meetings/components/**- apps/web/src/features/block-spreadsheet/components/**- apps/web/src/features/property/tags/components/**- - apps/web/src/features/claude-connection/components/**- apps/web/src/features/activity/components/**- apps/web/src/features/drive-view/components/**- apps/web/src/features/email-message/components/**diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.ymlindex 078925e9f6..9c3b652ef9 100644--- a/rules/ast-grep/ts-feature-core-pure.yml+++ b/rules/ast-grep/ts-feature-core-pure.yml@@ -36,7 +36,6 @@ files:- apps/web/src/features/meetings/core/**- apps/web/src/features/block-spreadsheet/core/**- apps/web/src/features/property/tags/core/**- - apps/web/src/features/claude-connection/core/**- apps/web/src/features/activity/core/**- apps/web/src/features/drive-view/core/**- apps/web/src/features/email-message/core/**diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.ymlindex 1d4b6320a5..d87689084e 100644--- a/rules/ast-grep/ts-feature-data-no-ui.yml+++ b/rules/ast-grep/ts-feature-data-no-ui.yml@@ -59,7 +59,6 @@ files:- apps/web/src/features/block-spreadsheet/primitives/**- apps/web/src/features/property/tags/queries/**- apps/web/src/features/property/tags/primitives/**- - apps/web/src/features/claude-connection/primitives/**- apps/web/src/features/activity/queries/**- apps/web/src/features/drive-view/queries/**- apps/web/src/features/activity/primitives/**diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.ymlindex 046ab4f3a8..368a72e4d8 100644--- a/rules/ast-grep/ts-feature-layers-use-context.yml+++ b/rules/ast-grep/ts-feature-layers-use-context.yml@@ -115,8 +115,6 @@ files:- apps/web/src/features/property/tags/queries/**- apps/web/src/features/property/tags/primitives/**- apps/web/src/features/property/tags/views/**- - apps/web/src/features/claude-connection/components/**- - apps/web/src/features/claude-connection/primitives/**- apps/web/src/features/activity/components/**- apps/web/src/features/drive-view/components/**- apps/web/src/features/activity/queries/**diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.ymlindex c2880b326f..1b1df55668 100644--- a/rules/ast-grep/tsx-feature-components-presentational.yml+++ b/rules/ast-grep/tsx-feature-components-presentational.yml@@ -37,7 +37,6 @@ files:- apps/web/src/features/meetings/components/**- apps/web/src/features/block-spreadsheet/components/**- apps/web/src/features/property/tags/components/**- - apps/web/src/features/claude-connection/components/**- apps/web/src/features/activity/components/**- apps/web/src/features/drive-view/components/**- apps/web/src/features/email-message/components/**diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.ymlindex 90a9e05024..fdafc8237b 100644--- a/rules/ast-grep/tsx-feature-core-pure.yml+++ b/rules/ast-grep/tsx-feature-core-pure.yml@@ -36,7 +36,6 @@ files:- apps/web/src/features/meetings/core/**- apps/web/src/features/block-spreadsheet/core/**- apps/web/src/features/property/tags/core/**- - apps/web/src/features/claude-connection/core/**- apps/web/src/features/activity/core/**- apps/web/src/features/drive-view/core/**- apps/web/src/features/email-message/core/**diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.ymlindex 30a406943b..76224a64a8 100644--- a/rules/ast-grep/tsx-feature-data-no-ui.yml+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml@@ -59,7 +59,6 @@ files:- apps/web/src/features/block-spreadsheet/primitives/**- apps/web/src/features/property/tags/queries/**- apps/web/src/features/property/tags/primitives/**- - apps/web/src/features/claude-connection/primitives/**- apps/web/src/features/activity/queries/**- apps/web/src/features/drive-view/queries/**- apps/web/src/features/activity/primitives/**diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.ymlindex 4a33d80a07..f7a7a62332 100644--- a/rules/ast-grep/tsx-feature-layers-use-context.yml+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml@@ -115,8 +115,6 @@ files:- apps/web/src/features/property/tags/queries/**- apps/web/src/features/property/tags/primitives/**- apps/web/src/features/property/tags/views/**- - apps/web/src/features/claude-connection/components/**- - apps/web/src/features/claude-connection/primitives/**- apps/web/src/features/activity/components/**- apps/web/src/features/drive-view/components/**- apps/web/src/features/activity/queries/**diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 0e1dc2ccd3..0ef04f6b5b 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -66,7 +66,6 @@ channels = { path = "../../crates/channels", features = ["attachment", "outboundchat = { path = "../../crates/chat", features = ["ai_tools", "attachment", "outbound"] }chrono = { workspace = true }chrono-tz = { workspace = true }-claude_cloud_agents = { path = "../../crates/claude_cloud_agents" }code_execution = { path = "../../crates/code_execution" }codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }codex_connection = { path = "../../crates/codex_connection" }diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rsindex 7ade26b7c8..df82ec05c9 100644--- a/services/agent_harness_service/src/api.rs+++ b/services/agent_harness_service/src/api.rs@@ -74,7 +74,6 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changescognition: Router,scheduling: Router,preview: Router,- claude_auth: Router,sharing: Router,routine_sessions: Router,coding_agents: Router,@@ -112,7 +111,6 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>cognition: Router::new(),scheduling: Router::new(),preview: Router::new(),- claude_auth: Router::new(),sharing: Router::new(),routine_sessions: Router::new(),coding_agents: Router::new(),@@ -180,12 +178,6 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>self}- /// Attach the optional owner-authenticated Claude demo connection routes.- pub fn with_claude_auth(mut self, router: Router) -> Self {- self.claude_auth = router;- self- }-/// Attach internal-only routine routes with their independent domain service.pub fn with_routine_sessions(mut self, router: Router) -> Self {self.routine_sessions = router;@@ -343,7 +335,6 @@ where.merge(agent_coding_preferences_router(states.read)).merge(agent_models_router(states.models)).merge(agent_repositories_router(states.repositories))- .merge(states.claude_auth).merge(states.routine_sessions).merge(states.coding_agents).merge(states.capabilities)diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rsindex 8d44dd53ae..4ab79f1e8a 100644--- a/services/agent_harness_service/src/api/swagger.rs+++ b/services/agent_harness_service/src/api/swagger.rs@@ -35,7 +35,6 @@ use agent_session::inbound::axum_router::{PreviewAgentSessionsResponse, QueuedActionDto, RenameAgentSessionRequest, SandboxSizeBody,SessionStatusDto, SetAgentSessionArchivedRequest, WithAgentSessionId,};-use claude_cloud_agents::inbound::auth as claude_auth;use utoipa::{Modify, OpenApi,openapi::security::{Http, HttpAuthScheme, SecurityScheme},@@ -64,10 +63,6 @@ impl Modify for SecurityAddon {agent_code_mode::inbound::axum_router::get_review,agent_code_mode::inbound::axum_router::list_reviews,agent_code_mode::inbound::axum_router::decide_review,- claude_auth::status,- claude_auth::start,- claude_auth::complete,- claude_auth::disconnect,axum_router::create_agent_session_handler,axum_router::warm_agent_session_handler,axum_router::get_agent_session_handler,@@ -107,10 +102,6 @@ impl Modify for SecurityAddon {tool_approvals::answer_tool_approval_handler,),components(schemas(- claude_auth::StatusResponse,- claude_auth::StartResponse,- claude_auth::CompleteRequest,- claude_auth::EmptyRequest,CreateAgentSessionRequest,CreateAgentSessionResponse,CreateSessionThread,diff --git a/services/agent_harness_service/src/coding_agents.rs b/services/agent_harness_service/src/coding_agents.rsindex 774ff483c2..0e5e298032 100644--- a/services/agent_harness_service/src/coding_agents.rs+++ b/services/agent_harness_service/src/coding_agents.rs@@ -10,7 +10,6 @@ use agent_session::domain::routines::RoutineSessions;use agent_session::inbound::coding_agents::{CodingAgentsState, coding_agents_router};use axum::Router;use bots::domain::ports::BotService;-use claude_cloud_agents::domain::credentials::AccountCredentials;use codex_connection::domain::ConnectionService;use harness_id::HarnessId;use harnesses::domain::ports::HarnessRepo;@@ -27,7 +26,6 @@ pub struct AvailableCodingAgents<Bots, Harnesses> {harnesses: Harnesses,pool: PgPool,codex: Option<Arc<dyn ConnectionService>>,- claude: Option<AccountCredentials>,}impl<Bots, Harnesses> AvailableCodingAgents<Bots, Harnesses> {@@ -37,14 +35,12 @@ impl<Bots, Harnesses> AvailableCodingAgents<Bots, Harnesses> {harnesses: Harnesses,pool: PgPool,codex: Option<Arc<dyn ConnectionService>>,- claude: Option<AccountCredentials>,) -> Self {Self {bots,harnesses,pool,codex,- claude,}}}@@ -92,14 +88,6 @@ impl<Bots: BotService, Harnesses: HarnessRepo> CodingAgentDirectory} else {false};- let claude_connected = if agents.iter().any(|agent| agent.harness == "claude-cloud") {- match &self.claude {- Some(claude) => claude.contains(user_id.as_ref()).await,- None => false,- }- } else {- false- };let mut candidates = vec![CodingAgentCandidate {agent: CodingAgent {id: bot_id::CURSOR_BOT_ID.as_uuid(),@@ -117,7 +105,6 @@ impl<Bots: BotService, Harnesses: HarnessRepo> CodingAgentDirectorylet connections = RuntimeConnections {cursor: cursor.is_some(),codex: codex_connected,- claude: claude_connected,harnesses,};candidates.extend(agents.into_iter().map(|agent| {@@ -165,7 +152,6 @@ fn codex_available(status: &codex_connection::domain::ConnectionStatus) -> boolstruct RuntimeConnections {cursor: bool,codex: bool,- claude: bool,harnesses: HashMap<HarnessId, bool>,}@@ -174,7 +160,6 @@ impl RuntimeConnections {match harness {"cursor" => self.cursor,"codex-cloud" => self.codex,- "claude-cloud" => self.claude,"in-memory" | "macro-inmem" => true,harness_id::MACROD_HARNESS_SLUG => harness_id.and_then(|id| self.harnesses.get(&id))diff --git a/services/agent_harness_service/src/coding_agents/test.rs b/services/agent_harness_service/src/coding_agents/test.rsindex ef30b0b917..8b9b682ff3 100644--- a/services/agent_harness_service/src/coding_agents/test.rs+++ b/services/agent_harness_service/src/coding_agents/test.rs@@ -69,7 +69,6 @@ fn one_provider_connection_does_not_enable_another_provider() {};assert!(connections.available("cursor", None));assert!(!connections.available("codex-cloud", None));- assert!(!connections.available("claude-cloud", None));assert!(!connections.available("unknown-runtime", None));assert!(connections.available("in-memory", None));assert!(connections.available("macro-inmem", None));diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 592691bade..aaddfc6a96 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -48,8 +48,6 @@ macro_env_var::maybe_env_vars!(pub struct PosthogApiKey;/// Regional PostHog ingestion origin; defaults to the US origin.pub struct PosthogHost;- /// KMS key for encrypted per-owner Claude OAuth connections.- pub struct ClaudeOauthKmsKeyId;/// Dedicated KMS key for encrypted per-owner Codex OAuth state.pub struct CodexOauthKmsKeyId;/// Rollout gate for sessions owned by a bot.@@ -129,8 +127,6 @@ pub struct Config {/// Markup on paid AI usage past the allowance, as a whole percent of/// provider cost. Mandatory; set in Doppler.pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,- /// OAuth encryption key; deployments without a key do not advertise sign-in.- pub claude_oauth_kms_key_id: ClaudeOauthKmsKeyId,/// The environment we are in.#[macro_config_default(Environment::new_or_prod())]pub environment: Environment,@@ -278,26 +274,6 @@ impl Config {)}- /// Resolve the deployment-injected encryption key. Local stacks use their- /// existing LocalStack key with a separate Claude encryption context.- pub fn claude_oauth_kms_key_id(&self) -> Option<String> {- self.claude_oauth_kms_key_id- .value()- .filter(|key| !key.trim().is_empty())- .map(str::to_owned)- .or_else(|| {- ClaudeOauthKmsKeyId::new().and_then(|key| {- key.value()- .filter(|key| !key.trim().is_empty())- .map(str::to_owned)- })- })- .or_else(|| {- matches!(self.environment, Environment::Local)- .then(|| "alias/macro-local-cursor-api-key".to_owned())- })- }-/// Resolve the optional key from Doppler or the deployment-injected environment.pub fn codex_oauth_kms_key_id(&self) -> Option<String> {self.codex_oauth_kms_key_iddiff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 24e55737e5..06d71a5f55 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -264,22 +264,6 @@ async fn run() -> anyhow::Result<()> {.await.context("failed to connect to macrodb")?;- // The same encrypted connection store serves browser consent and runtime- // credentials in every deployment. Only the KMS key configuration varies.- let claude_refresh =- Arc::new(claude_cloud_agents::outbound::credentials::ClaudeRefresh::new()?);- let claude_credentials = config.claude_oauth_kms_key_id().map(|key| {- claude_cloud_agents::domain::credentials::AccountCredentials::new(- Arc::new(- claude_cloud_agents::outbound::postgres::PgClaudeGrants::new(- pool.clone(),- AwsKmsCiphertexts::new(aws_sdk_kms::Client::new(&aws_config), key),- ),- ),- claude_refresh.clone(),- )- });-// Built before the sessions rather than beside the other channel plumbing// below: this service owns the live actors, so it is where a session's// frames are streamed from.@@ -940,18 +924,6 @@ async fn run() -> anyhow::Result<()> {},},));- fixed_runtimes.push((- bot_id::CLAUDE_BOT_ID,- AgentRuntimeConfig {- kind: AgentKind::ClaudeCloud,- model: claude_cloud_agents::domain::models::Model::default()- .id()- .to_owned(),- harness: "claude-cloud".into(),- instructions: String::new(),- mcp_servers: AgentMcpServers::OwnerConnections,- },- ));let runtime_directory =PgAgentRuntimeDirectory::new(PgBotsRepo::new(pool.clone()), fixed_runtimes.clone());// Logged because the failure mode this replaced was silent: a harness that@@ -964,31 +936,10 @@ async fn run() -> anyhow::Result<()> {environment = %config.environment,"agent harness serving bots");- let claude_provider = Arc::new(claude_cloud_agents::outbound::http::Provider(- claude_credentials.clone(),- ));- let claude_manager = agent_harness::outbound::claude::ClaudeContainerManager::new(- agent_harness::domain::claude::ClaudeSessions::new(- claude_provider.clone(),- session_repo.clone(),- session_repo.clone(),- url::Url::parse(&egress_base_url)?- .host_str()- .context("egress URL needs a host")?- .to_owned(),- ),- EgressProvisioner::new(- Arc::clone(&mcp_connections),- Arc::clone(&mcp_servers),- egress_base_url.clone(),- ),- claude_cloud_agents::inbound::acp::attach,- );let containers = RoutedContainerManager::new(sandbox_and_inmem,cursor_manager,codex_manager,- claude_manager,session_repo.clone(),);@@ -1132,17 +1083,6 @@ async fn run() -> anyhow::Result<()> {repo_url: None,},)- .with_bot(- bot_id::CLAUDE_BOT_ID,- SessionDefaults {- bot_id: bot_id::CLAUDE_BOT_ID,- model: claude_cloud_agents::domain::models::Model::default()- .id()- .to_owned(),- harness: "claude-cloud".into(),- repo_url: None,- },- )// Sessions nothing names a bot for (the create menu's) run in-process;// explicitly selected coding agents keep their configured runtimes..with_managed_bot(inmem_bot);@@ -1364,22 +1304,17 @@ async fn run() -> anyhow::Result<()> {MacroAuthorizationState::new(Arc::new(authorization_service.clone())),),);- let model_service = Arc::new(- AgentModelsServiceImpl::new(- VisibleHarnessAccess::new(PgHarnessRepo::new(pool.clone())),- InMemoryModels::new(- Some(inmem_model_engine),- config.inmem_model.clone(),- inmem_model_access,- ),- CursorModels::new(cursor_keys, cursor_api_base_url()),- macrod_models,- model_probe_timeout,- )- .with_claude(Arc::new(agent_harness::outbound::claude::ClaudeModels(- claude_provider,- ))),- );+ let model_service = Arc::new(AgentModelsServiceImpl::new(+ VisibleHarnessAccess::new(PgHarnessRepo::new(pool.clone())),+ InMemoryModels::new(+ Some(inmem_model_engine),+ config.inmem_model.clone(),+ inmem_model_access,+ ),+ CursorModels::new(cursor_keys, cursor_api_base_url()),+ macrod_models,+ model_probe_timeout,+ ));let model_state = AgentModelsRouterState::new(model_service,MacroAuthorizationState::new(Arc::new(authorization_service.clone())),@@ -1443,7 +1378,6 @@ async fn run() -> anyhow::Result<()> {PgHarnessRepo::new(pool.clone()),pool.clone(),codex_connections,- claude_credentials.clone(),),agent_session::domain::routines::RoutineSessionsService::new((*bots_directory).clone(),@@ -1468,16 +1402,6 @@ async fn run() -> anyhow::Result<()> {MacroAuthorizationState::new(Arc::new(authorization_service.clone())),);let http_runtime_commands_readiness = runtime_commands_readiness.clone();- let claude_auth = claude_cloud_agents::inbound::auth::router(- claude_cloud_agents::inbound::auth::ClaudeAuthState::new(- Arc::new(claude_cloud_agents::domain::auth::AuthService::new(- claude_cloud_agents::outbound::oauth::ClaudeOAuth::new()?,- claude_credentials,- false,- )),- MacroAuthorizationState::new(Arc::new(authorization_service.clone())),- ),- );let http_port = config.port;let pull_requests =agent_session::inbound::axum_router::pull_requests::agent_session_pull_request_router(@@ -1542,7 +1466,6 @@ async fn run() -> anyhow::Result<()> {repositories_state,changes_state,)- .with_claude_auth(claude_auth).with_sharing(sharing).with_routine_sessions(routine_sessions).with_conversations(conversations)diff --git a/services/lexical-service/src/endpoints/agent-announcement.test.ts b/services/lexical-service/src/endpoints/agent-announcement.test.tsindex 410117c83b..50a1915faf 100644--- a/services/lexical-service/src/endpoints/agent-announcement.test.ts+++ b/services/lexical-service/src/endpoints/agent-announcement.test.ts@@ -14,9 +14,9 @@ const request = (body: unknown) =>body: JSON.stringify(body),});const connectionPrompt = {- agentTag: '@claude',- message: 'Connect Claude, then mention me again.',- chip: { appSlug: 'claude-cloud', name: 'Claude', target: 'harness' },+ agentTag: '@codex',+ message: 'Connect Codex, then mention me again.',+ chip: { appSlug: 'codex-cloud', name: 'Codex', target: 'harness' },};describe('agent announcements', () => {@@ -25,7 +25,7 @@ describe('agent announcements', () => {expect(response.status).toBe(200);expect(await response.json()).toEqual({markdown:- '`@claude` Connect Claude, then mention me again. <m-connect-app>{"appSlug":"claude-cloud","name":"Claude","target":"harness"}</m-connect-app>',+ '`@codex` Connect Codex, then mention me again. <m-connect-app>{"appSlug":"codex-cloud","name":"Codex","target":"harness"}</m-connect-app>',});});const chip = {diff --git a/tooling/claude-cloud/browser-smoke.mjs b/tooling/claude-cloud/browser-smoke.mjsdeleted file mode 100644index c6cb45fdfb..0000000000--- a/tooling/claude-cloud/browser-smoke.mjs+++ /dev/null@@ -1,257 +0,0 @@-// Local UI smoke only: creates a disposable local Macro identity, never authorizes Claude.-import { createRequire } from 'node:module';-import { parseArgs } from 'node:util';-const require = createRequire(- new URL('../../apps/web/package.json', import.meta.url)-);-const { chromium } = require('@playwright/test');-const { values } = parseArgs({- options: { origin: { type: 'string', default: 'http://localhost:25510' } },-});-const origin = new URL(values.origin);-if (origin.hostname !== 'localhost' || origin.protocol !== 'http:')- throw new Error('Localhost only');-const browser = await chromium.launch({ headless: true });-try {- const page = await browser.newPage({- viewport: { width: 1280, height: 960 },- });- await page.goto(`${origin}/app`);- await page- .getByRole('button', { name: 'Continue with email' })- .click({ timeout: 60000 });- await page- .getByPlaceholder('[email protected]')- .fill('[email protected]');- await page.getByRole('button', { name: 'Continue', exact: true }).click();- await page.waitForURL(/\/app\/(component|settings)/, { timeout: 60000 });- // Vite-only local smoke: simulate the local env override in this browser.- // Local dev intentionally does not initialize PostHog. Keep the real flag- // definition/readers, and never alter the running server's environment.- let claudeEnabled = false;- await page.route(- '**/src/lib/core/constant/featureFlags.ts*',- async (route) => {- const response = await route.fetch();- const body = await response.text();- const definition = 'export const claudeCloud = defineFlag({';- if (!body.includes(definition))- throw new Error('Claude flag definition not found');- await route.fulfill({- response,- body: body.replace(- definition,- `import.meta.env.VITE_CLAUDE_CLOUD = '${claudeEnabled}';\n${definition}`- ),- });- }- );- const claudeRequests = [];- page.on('request', (request) => {- if (!['fetch', 'xhr'].includes(request.resourceType())) return;- if (- request.url().includes('/claude-auth/') ||- (request.url().includes('/models') &&- request.postData()?.includes('claude-cloud'))- )- claudeRequests.push(request.url());- });- await page.goto(`${origin}/app/settings/harness`);- await page.getByRole('heading', { name: 'Cursor', exact: true }).waitFor();- const card = page.getByRole('region', { name: 'Claude Cloud connection' });- if (await card.count())- throw new Error('Claude connection visible with flag off');- await page.goto(`${origin}/app/settings/agents?createAgent=true`);- await page.getByRole('dialog').waitFor();- if (await page.getByRole('option', { name: 'Claude Cloud (demo)' }).count())- throw new Error('Claude harness visible with flag off');- if (claudeRequests.length)- throw new Error('Claude data fetched with flag off');- console.log(- 'PASS: flag off hides onboarding and harness selection without Claude requests.'- );- await page.goto(`${origin}/app/settings/harness`);- await page.getByRole('heading', { name: 'Cursor', exact: true }).waitFor();- claudeEnabled = true;- await page.reload();- await card.waitFor({ timeout: 60000 });- console.log('PASS: Claude connection card is visible before authorization.');- await card.getByLabel('Anthropic').waitFor();- const order = await page.getByRole('heading', { level: 2 }).allTextContents();- if (order.indexOf('Claude Cloud (demo)') >= order.indexOf('Cursor'))- throw new Error('Claude must appear above Cursor');- // Reloading after the backend build is a manual step; this script fails visibly if stale.- await page- .context()- .route('https://claude.com/**', (route) =>- route.fulfill({ body: 'Claude sign-in intercepted by local smoke test' })- );- const signInOpening = page.waitForEvent('popup');- const starting = page.waitForResponse(- (response) =>- response.url().endsWith('/claude-auth/start') &&- response.request().method() === 'POST'- );- await card- .getByRole('button', { name: 'Connect Claude', exact: true })- .click({ timeout: 30000 });- const start = await starting;- if (start.status() !== 200 || start.headers()['cache-control'] !== 'no-store')- throw new Error('Start response must be successful and non-cacheable');- const attempt = await start.json();- const consent = card.getByRole('link', { name: /Open Claude sign-in/ });- await consent.waitFor({ timeout: 15000 });- const url = new URL(await consent.getAttribute('href'));- const signIn = await signInOpening;- await signIn.waitForURL(url.href);- if (!(await signIn.evaluate(() => window.opener === null)))- throw new Error('Claude sign-in tab must not retain an opener');- await signIn.close();- console.log(- 'PASS: the first Connect Claude click opens sign-in with no opener (provider intercepted).'- );- if (- url.origin !== 'https://claude.com' ||- url.pathname !== '/cai/oauth/authorize' ||- url.searchParams.get('code_challenge_method') !== 'S256' ||- url.searchParams.get('redirect_uri') !==- 'https://platform.claude.com/oauth/code/callback'- )- throw new Error('Incorrect consent URL');- if (- (await card.getByLabel(/Paste the complete/).getAttribute('type')) !==- 'password'- )- throw new Error('Code input is not masked');- await page.screenshot({- path: '/tmp/claude-auth-settings.png',- fullPage: true,- });- console.log(- 'PASS: authenticated start returned the registered Claude PKCE consent URL and masked code entry.'- );- const completeUrl = start.url().replace(/\/start$/, '/complete');- const wrongState = await page.request.post(completeUrl, {- data: { attemptId: attempt.attemptId, code: 'dummy-code#wrong-state' },- });- if (wrongState.status() !== 400)- throw new Error('Mismatched OAuth state was not rejected');- const ownerInjection = await page.request.post(completeUrl, {- data: {- attemptId: attempt.attemptId,- code: 'dummy-code#wrong-state',- owner: 'macro|[email protected]',- },- });- if (ownerInjection.status() !== 422)- throw new Error('Caller-selected owner was not rejected');- console.log(- 'PASS: wrong state and caller-supplied ownership are rejected before provider exchange.'- );- await card.getByRole('button', { name: 'Cancel', exact: true }).click();- await card- .getByRole('button', { name: 'Connect Claude', exact: true })- .waitFor();- console.log(- 'PASS: cancel forgets the pending connection. No Claude grant or subscription turn was used.'- );- const replay = await page.request.post(completeUrl, {- data: {- attemptId: attempt.attemptId,- code: `dummy-code#${url.searchParams.get('state')}`,- },- });- if (replay.status() !== 409)- throw new Error('Canceled attempt was not rejected');- console.log('PASS: a canceled attempt cannot be exchanged.');- await page.evaluate(() => {- const original = window.open;- window.open = () => {- window.open = original;- return null;- };- });- await card- .getByRole('button', { name: 'Connect Claude', exact: true })- .click();- await card- .getByRole('link', { name: /Didn't open\? Open Claude sign-in/ })- .waitFor();- await card.getByLabel(/Paste the complete/).waitFor();- await card.getByRole('button', { name: 'Cancel', exact: true }).click();- console.log(- 'PASS: a blocked popup retains the fallback sign-in link and code entry.'- );- await page.goto(`${origin}/app/settings/agents`);- await page- .getByRole('heading', { name: 'Agents', exact: true })- .waitFor({ timeout: 30000 });- if (- await page.getByRole('region', { name: 'Claude Cloud connection' }).count()- )- throw new Error('Connection belongs in Harness, not Agents');- console.log(- 'PASS: Claude connection appears only in Harness settings, above Cursor, with the Anthropic logo.'- );- // Controlled read-only session fixture: exercise the real toolbar without- // creating a cloud session or touching another user's conversation.- const fixtureId = '00000000-0000-7000-8000-000000000123';- const cloudUrl = 'https://claude.ai/code/cse_browser_fixture';- await page.route(`**/agent-sessions/${fixtureId}**`, async (route) => {- const path = new URL(route.request().url()).pathname;- const bot = {- id: '00000000-0000-7000-8000-000000000124',- name: 'Claude demo',- handle: 'claude-demo',- };- const body = path.endsWith('/log')- ? { bot, entries: [] }- : path.endsWith('/queue')- ? []- : {- id: fixtureId,- botId: bot.id,- ownerId: 'macro|[email protected]',- canEdit: false,- name: 'Claude cloud link check',- harness: 'claude-cloud',- model: 'claude-default',- workspace: '/',- sandboxSize: 'small',- status: { kind: 'disconnected' },- createdAt: new Date().toISOString(),- modifiedAt: new Date().toISOString(),- external: { provider: 'claude-cloud', url: cloudUrl },- };- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(body),- });- });- await page.context().route('https://claude.ai/**', (route) =>- route.fulfill({- body: 'Claude link target intercepted by local smoke test',- })- );- await page.goto(`${origin}/app/agent/${fixtureId}`);- const openClaude = page.getByRole('button', {- name: 'Open in Claude',- exact: true,- });- await openClaude.waitFor({ timeout: 60000 });- const opened = page.waitForEvent('popup');- await openClaude.click();- const popup = await opened;- await popup.waitForURL(cloudUrl);- await popup.close();- await page.screenshot({- path: '/tmp/claude-session-link.png',- fullPage: true,- });- console.log(- 'PASS: the real session toolbar opens the Claude URL in a new tab (controlled session fixture).'- );-} finally {- await browser.close();-}diff --git a/tooling/claude-cloud/connect.mjs b/tooling/claude-cloud/connect.mjsdeleted file mode 100644index 2cd085d071..0000000000--- a/tooling/claude-cloud/connect.mjs+++ /dev/null@@ -1,215 +0,0 @@-// Local demo provisioning only. The browser never receives an access/refresh token.-import http from 'node:http';-import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';-import { mkdir, readFile, writeFile, lstat } from 'node:fs/promises';-import { dirname, resolve } from 'node:path';-import { parseArgs } from 'node:util';-import { spawn } from 'node:child_process';--process.umask(0o077);-const { values } = parseArgs({- options: {- owner: { type: 'string' },- output: { type: 'string', default: '.claude-cloud/credentials.json' },- 'oauth-file': { type: 'string' },- environment: { type: 'string' },- },-});-if (!values.owner || !/^[^\s@|]+@[^\s@|]+$/.test(values.owner)) {- throw new Error(- 'Use --owner <Macro email> [--output private/path.json] [--oauth-file existing-demo-grant.json]'- );-}-const output = resolve(values.output);-await mkdir(dirname(output), { recursive: true, mode: 0o700 });-const parent = await lstat(dirname(output));-if (!parent.isDirectory() || parent.isSymbolicLink() || parent.mode & 0o077)- throw new Error('Output directory must be private (0700).');-try {- await lstat(output);- throw new Error(- 'Output exists; refusing to replace credentials. Use a new output path.'- );-} catch (error) {- if (error.code !== 'ENOENT') throw error;-}--const clientId = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';-const scope = 'user:profile user:inference user:sessions:claude_code';-async function jsonRequest(url, options) {- const response = await fetch(url, {- ...options,- redirect: 'error',- signal: AbortSignal.timeout(30_000),- });- if (!response.ok)- throw new Error(- `Claude request failed (HTTP ${response.status}); response omitted.`- );- return response.json();-}--async function provision(tokens) {- if (- typeof tokens.access_token !== 'string' ||- !tokens.scope?.split(' ').includes('user:sessions:claude_code')- )- throw new Error('Grant lacks the Claude Code sessions scope.');- const headers = {- Authorization: `Bearer ${tokens.access_token}`,- 'anthropic-version': '2023-06-01',- };- const profile = await jsonRequest(- 'https://api.anthropic.com/api/oauth/profile',- { headers }- );- const organization = profile.organization?.uuid;- if (typeof organization !== 'string')- throw new Error('No Claude organization returned.');- const environments = await jsonRequest(- 'https://api.anthropic.com/v1/environments',- {- headers: {- ...headers,- 'x-organization-uuid': organization,- 'anthropic-beta':- 'environments-2026-03-01,environments-package-support-2025-12-09',- },- }- );- const candidates = environments.data.filter(- (e) =>- e.config?.type === 'cloud' &&- e.state === 'active' &&- !e.archived_at &&- (!values.environment || values.environment === e.id)- );- if (candidates.length !== 1)- throw new Error(- 'Need exactly one active cloud environment; specify --environment <env_id> if multiple exist.'- );- const acquired = tokens.acquired_at ?? Date.now();- const expiresAt = Math.floor(acquired / 1000) + tokens.expires_in;- if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now() / 1000)- throw new Error('Expired grant; sign in again.');- const credentials = {- users: {- [`macro|${values.owner}`]: {- access_token: tokens.access_token,- refresh_token: tokens.refresh_token ?? null,- expires_at: expiresAt,- organization_id: organization,- environment_id: candidates[0].id,- },- },- };- await writeFile(output, JSON.stringify(credentials, null, 2), {- mode: 0o600,- flag: 'wx',- });- console.log(- 'Claude connection saved privately. No cloud session has been created.'- );-}--if (values['oauth-file']) {- const source = await lstat(values['oauth-file']);- if (!source.isFile() || source.isSymbolicLink() || source.mode & 0o077)- throw new Error('OAuth source must be a private regular file (0600).');- await provision(JSON.parse(await readFile(values['oauth-file'], 'utf8')));-} else {- const state = randomBytes(32).toString('base64url');- const verifier = randomBytes(32).toString('base64url');- let used = false;- let redirect;- let auth;- const server = http.createServer(async (req, res) => {- res.setHeader('Cache-Control', 'no-store');- res.setHeader('Referrer-Policy', 'no-referrer');- res.setHeader(- 'Content-Security-Policy',- "default-src 'none'; frame-ancestors 'none'"- );- if (req.headers.host !== new URL(redirect).host || req.method !== 'GET') {- res.writeHead(403).end();- return;- }- const url = new URL(req.url, redirect);- if (url.pathname === '/' && !used) {- res.writeHead(302, { Location: auth.href }).end();- return;- }- if (url.pathname !== '/callback' || used) {- res.writeHead(404).end();- return;- }- const returned = Buffer.from(url.searchParams.get('state') ?? '');- if (- returned.length !== state.length ||- !timingSafeEqual(returned, Buffer.from(state))- ) {- res.writeHead(400).end('Invalid state');- return;- }- used = true;- try {- const code = url.searchParams.get('code');- if (!code || url.searchParams.has('error'))- throw new Error('Consent not granted.');- const tokens = await jsonRequest(- 'https://platform.claude.com/v1/oauth/token',- {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- grant_type: 'authorization_code',- code,- client_id: clientId,- redirect_uri: redirect,- state,- code_verifier: verifier,- }),- }- );- await provision({ ...tokens, acquired_at: Date.now() });- res- .writeHead(200, { 'Content-Type': 'text/plain' })- .end('Claude connected for the Macro demo. You can close this tab.');- } catch {- process.exitCode = 1;- console.error(- 'Claude connection failed. No credentials were printed; check consent and cloud environment access.'- );- res.writeHead(400).end('Connection failed. Return to the terminal.');- } finally {- clearTimeout(timeout);- server.close();- }- });- const timeout = setTimeout(() => {- process.exitCode = 1;- server.close();- console.error('Sign-in timed out.');- }, 20 * 60_000);- server.listen(0, '127.0.0.1', () => {- const port = server.address().port;- redirect = `http://localhost:${port}/callback`;- auth = new URL('https://claude.com/cai/oauth/authorize');- auth.search = new URLSearchParams({- code: 'true',- client_id: clientId,- response_type: 'code',- redirect_uri: redirect,- scope,- state,- code_challenge: createHash('sha256').update(verifier).digest('base64url'),- code_challenge_method: 'S256',- }).toString();- console.log(`Complete Claude sign-in at http://localhost:${port}/`);- if (process.platform === 'darwin')- spawn('open', [`http://localhost:${port}/`], { stdio: 'ignore' }).on(- 'error',- () => {}- );- });-}