Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: claude code as a model in the normal chat

ogsamrat127e2a72372f
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.ts
index f822016f..841fe975 100644
--- a/apps/app/src/app/lib/desktop.ts
+++ b/apps/app/src/app/lib/desktop.ts
@@ -536,16 +536,6 @@ export async function desktopDownloadBinary(
);
}
-export async function desktopDownloadClaudeArchive(input: {url: string; headers?: Record<string, string>}, signal?: AbortSignal) {
- const transferId = desktopTransferId();
- const payload = { ...input, transferId };
- return runCancellableDesktopTransfer(
- transferId,
- signal,
- () => invokeElectronHelper("__downloadClaudeArchive", payload),
- );
-}
-
type DesktopFetchMainOptions = {
timeoutMs?: number;
agentContextDiagnosticsDeadlineAtMs?: number;
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index 8689d800..e3f42c22 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -18,7 +18,7 @@ import {
AGENT_CONTEXT_DIAGNOSTICS_REQUEST_TIMEOUT_MS,
requestAgentContextDiagnosticsPayload,
} from "./agent-context-diagnostics-transport";
-import { desktopFetch, desktopFetchAgentContextDiagnostics, desktopUploadMultipart, desktopDownloadClaudeArchive, electronLocalPathForFile } from "./desktop";
+import { desktopFetch, desktopFetchAgentContextDiagnostics, desktopUploadMultipart, electronLocalPathForFile } from "./desktop";
import { isOmniRushGatewayRuntime } from "./gateway-runtime";
import { isDesktopRuntime } from "./runtime-env";
import type { ExecResult, OpencodeConfigFile, WorkspaceInfo, WorkspaceList } from "./desktop";
@@ -1894,16 +1894,6 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
const token = options.token;
const hostToken = options.hostToken;
- const claudeExportError = (status: number, text: string) => {
- try {
- const body: unknown = JSON.parse(text);
- if (body && typeof body === "object" && "message" in body && typeof body.message === "string" && body.message.trim()) {
- return new Error(body.message);
- }
- } catch { /* Non-JSON errors retain the HTTP status. */ }
- return new Error(`Claude export failed (${status})`);
- };
-
const timeouts = {
health: 3_000,
capabilities: 6_000,
@@ -1926,22 +1916,7 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
baseUrl,
token,
claude: {
- request: <T,>(workspaceId: string, route: string, body?: unknown, signal?: AbortSignal) => requestJson<T>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/claude/${route}`, {token, hostToken, method: body === undefined ? "GET" : "POST", body, signal, timeoutMs: 15 * 60_000}),
- export: async (workspaceId: string, sessionId: string, signal?: AbortSignal) => {
- const url = `${baseUrl}/workspace/${encodeURIComponent(workspaceId)}/claude/sessions/${encodeURIComponent(sessionId)}/export`;
- const response = await resolveFetch(url)(url, {method: "POST", headers: buildHeaders(token, hostToken), signal});
- if (!response.ok) throw claudeExportError(response.status, await response.text());
- return response.blob();
- },
- saveExport: async (workspaceId: string, sessionId: string, signal?: AbortSignal) => {
- const result = await desktopDownloadClaudeArchive({
- url: `${baseUrl}/workspace/${encodeURIComponent(workspaceId)}/claude/sessions/${encodeURIComponent(sessionId)}/export`,
- headers: buildHeaders(token, hostToken),
- }, signal);
- if (!result) return null;
- if (result.status !== 200 || !result.path) throw claudeExportError(result.status, result.body ?? "");
- return result.path;
- },
+ request: <T,>(workspaceId: string, route: string, body?: unknown, signal?: AbortSignal) => requestJson<T>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/claude/${route}`, {token, hostToken, method: body === undefined ? "GET" : "POST", body, signal, timeoutMs: 15_000}),
},
health: () =>
requestJson<{ ok: boolean; version: string; uptimeMs: number }>(baseUrl, "/health", { token, hostToken, timeoutMs: timeouts.health }),
diff --git a/apps/app/src/app/lib/provider-catalog.ts b/apps/app/src/app/lib/provider-catalog.ts
index 84170d54..cd82789f 100644
--- a/apps/app/src/app/lib/provider-catalog.ts
+++ b/apps/app/src/app/lib/provider-catalog.ts
@@ -11,7 +11,7 @@ const directProviderSet = new Set<string>(DIRECT_PROVIDER_IDS);
export function isInternalModelProvider(providerID: string) {
const normalized = providerID.trim().toLowerCase();
- return normalized === "omnirush" || /^lpr_/.test(normalized);
+ return normalized === "omnirush" || normalized === "omnirush-claude" || /^lpr_/.test(normalized);
}
export function isDirectModelProvider(providerID: string) {
diff --git a/apps/app/src/app/lib/provider-lock.ts b/apps/app/src/app/lib/provider-lock.ts
index fb98af76..476b6880 100644
--- a/apps/app/src/app/lib/provider-lock.ts
+++ b/apps/app/src/app/lib/provider-lock.ts
@@ -23,7 +23,7 @@ export type ProviderLockState = {
const LOCKED: ProviderLockState = Object.freeze({
locked: true,
- allow: Object.freeze(["omnirush"]) as unknown as string[],
+ allow: Object.freeze(["omnirush", "omnirush-claude"]) as unknown as string[],
message: PROVIDER_LOCK_DEFAULT_MESSAGE,
});
@@ -39,8 +39,8 @@ export function parseProviderLockState(value: unknown): ProviderLockState {
if (!isRecord(value)) return LOCKED;
const message = typeof value.message === "string" && value.message.trim() ? value.message.trim() : PROVIDER_LOCK_DEFAULT_MESSAGE;
if (value.locked === false) return { locked: false, allow: [], message };
- // Only OmniRush's own provider counts as allowed, whatever else a server lists.
- return { locked: true, allow: ["omnirush"], message };
+ // Only OmniRush's own providers (the gateway's, Claude Code in the sandbox) count as allowed, whatever else a server lists.
+ return { locked: true, allow: ["omnirush", "omnirush-claude"], message };
}
export function providerLockState(): ProviderLockState {
diff --git a/apps/app/src/components/model-select.tsx b/apps/app/src/components/model-select.tsx
index 0afc6c43..19a1a3de 100644
--- a/apps/app/src/components/model-select.tsx
+++ b/apps/app/src/components/model-select.tsx
@@ -61,7 +61,7 @@ import {
} from "@/app/utils";
import { isSupportedModelProvider, providerCatalogRank } from "@/app/lib/provider-catalog";
import { useModelModeFilter } from "@/react-app/domains/session/surface/model-modes";
-import { claudeModelOptions, useClaudeModels, useModelPickGate } from "@/react-app/domains/session/surface/claude-models";
+import { useModelPickGate } from "@/react-app/domains/session/surface/claude-models";
function getProviderDisplayName(providerId: string) {
return providerId
@@ -134,7 +134,8 @@ function useModelOptions(
const visibleOptions = cloudProvidersEnabled
? mergedOptions
: mergeModelOptions(
- options.filter((option) => option.providerID.trim().toLowerCase() === "omnirush"),
+ // The account's own models: the gateway's and Claude's (the engine's Claude provider).
+ options.filter((option) => ["omnirush", "omnirush-claude"].includes(option.providerID.trim().toLowerCase())),
filterCloudManagedModelOptions(mergedOptions, false),
);
@@ -266,11 +267,10 @@ export function ModelSelect({
// Only the models the open project's mode allows (sandbox or not: model-modes.ts).
const modeAllows = useModelModeFilter((state) => state.allows);
const allOptions = useModelOptions(open, fallbackOptions, denAuth.isSignedIn);
- // Claude is listed in every project: picking it sets the project's sandbox up (claude-models.ts).
- const claudeCatalog = useClaudeModels((state) => state.catalog);
+ // Claude's models come from the engine's Claude provider; picking one sets the project's sandbox up (claude-models.ts).
const catalogOptions = React.useMemo(
- () => [...allOptions.filter((option) => modeAllows(option)), ...claudeModelOptions({ catalog: claudeCatalog })],
- [allOptions, claudeCatalog, modeAllows],
+ () => allOptions.filter((option) => modeAllows(option)),
+ [allOptions, modeAllows],
);
const modelOptions = React.useMemo(
() => dedupeModelOptions(
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
index da6523be..f947b329 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
@@ -1,6 +1,5 @@
/** @jsxImportSource react */
import * as React from "react";
-import { Link } from "react-router";
import {
AlertCircle,
AlertTriangle,
@@ -56,7 +55,6 @@ import { buildathonProjects, useBuildathonStore } from "../../../../app/lib/buil
import { OmniRushDenHelpLink } from "../../workspace/omnirush-den-help-link";
import { NotificationBell } from "../../../shell/notification-center";
import { useUiStateStore } from "../../../shell/ui-state-store";
-import { useClaudeSurface } from "../../../shell/claude-offer";
import type {
WorkspaceConnectionState,
WorkspaceSessionGroup,
@@ -196,17 +194,6 @@ const SidebarReorderContext = React.createContext<{
setIsReordering: (value: boolean) => void;
} | null>(null);
-/** The workspace menu's Claude Code entry: only while the server offers it, or to reach sessions saved earlier (claude-offer.ts). */
-function ClaudeMenuItem({ workspaceId }: { workspaceId: string }) {
- const surface = useClaudeSurface(workspaceId);
- if (surface !== "full" && surface !== "saved") return null;
- return (
- <DropdownMenuItem render={<Link to={`/workspace/${workspaceId}/claude`} />}>
- <Sparkles className="size-4" />{surface === "full" ? "Claude Code" : "Saved sessions"}
- </DropdownMenuItem>
- );
-}
-
function SidebarReorderScope({ children }: { children: React.ReactNode }) {
const [isReordering, setIsReordering] = React.useState(false);
@@ -737,7 +724,6 @@ function WorkspaceActionsMenu({ workspace, isConnectionActionBusy, canRecover, c
}
/>
<DropdownMenuContent align="end" side="bottom" sideOffset={4} className="w-56">
- <ClaudeMenuItem workspaceId={workspace.id} />
<DropdownMenuItem onClick={() => ctx.onOpenRenameWorkspace(workspace.id)}>
<Pencil className="size-4" />
{t("workspace_list.edit_name")}
diff --git a/apps/app/src/react-app/domains/session/surface/claude-models.ts b/apps/app/src/react-app/domains/session/surface/claude-models.ts
index ec05f566..809c87c5 100644
--- a/apps/app/src/react-app/domains/session/surface/claude-models.ts
+++ b/apps/app/src/react-app/domains/session/surface/claude-models.ts
@@ -1,15 +1,15 @@
// Claude in the model picker. The server's capability `claude_code` lists the
// Claude models: `catalog` (what every account sees) and `models` (what this
// account may run); the local server passes both through
-// GET /workspace/:id/claude/status (claude-code/runtime.ts available()).
-// Claude runs only in the sandbox, on its own runtime (claude-code/), never in
-// the chat engine: picking it sets the project's sandbox up and opens a Claude
-// chat. A chat keeps one model; another pick in a chat that already ran offers
-// a new chat instead.
+// GET /workspace/:id/claude/status. Claude is a model of the chat engine's
+// "omnirush-claude" provider: each turn runs Claude Code in the project's
+// sandbox (opencode-plugins/claude-provider), so picking it sets the project's
+// sandbox up first. A chat keeps one model; another pick in a chat that
+// already ran offers a new chat instead.
import { useEffect } from "react";
import { create } from "zustand";
-import type { ModelOption, ModelRef } from "@/app/types";
+import type { ModelRef } from "@/app/types";
import type { OmniRushServerClient, OmniRushWorkspaceBox, OmniRushWorkspaceBoxSetupAction } from "@/app/lib/omnirush-server";
export type ClaudeCatalogEntry = { id: string; name: string };
@@ -27,31 +27,17 @@ const EMPTY: ClaudeModelsState = { workspaceId: null, catalog: [], models: [], r
export const useClaudeModels = create<ClaudeModelsState>(() => EMPTY);
-/** A Claude model of the picker: the omnirush provider with a Claude catalog id (the chat engine's catalog never has one). */
+export const CLAUDE_PROVIDER_ID = "omnirush-claude";
+
+/** A Claude model of the picker: the engine's Claude provider. */
export function isClaudeModel(model: ModelRef | null | undefined): boolean {
- return model?.providerID === "omnirush" && CLAUDE_ID.test(model.modelID);
+ return model?.providerID === CLAUDE_PROVIDER_ID;
}
export function claudeModelName(state: Pick<ClaudeModelsState, "catalog">, id: string): string {
return state.catalog.find((entry) => entry.id === id)?.name ?? id;
}
-/** The picker's Claude entries: every catalog model, in every project (allowed or not: picking explains). */
-export function claudeModelOptions(state: Pick<ClaudeModelsState, "catalog">): ModelOption[] {
- return state.catalog.map((entry) => ({
- providerID: "omnirush",
- modelID: entry.id,
- title: entry.name,
- description: "Runs in the sandbox",
- group: "Claude",
- behaviorTitle: "",
- behaviorLabel: "",
- behaviorDescription: "",
- behaviorValue: null,
- isFree: false,
- }));
-}
-
/** "Claude Sonnet 5.5 isn't available on your account yet." */
export function claudeUnavailableMessage(name: string, reason: string | null): string {
if (reason === "client_outdated") return `${name} needs the latest OmniRush. Update the app to use it.`;
@@ -72,8 +58,8 @@ export type ModelPick =
* already ran (its provider is fixed). An unavailable Claude model is explained
* first, wherever it is picked; a model of another provider in a started chat
* offers a new chat, one of its provider (`switchable`, model-modes.ts
- * switchableModel) is switched to; in a fresh chat a Claude model opens Claude
- * and any other model is simply switched to.
+ * switchableModel) is switched to; in a fresh chat a Claude model is switched
+ * to once the project's sandbox is set up, any other model at once.
*/
export function decideModelPick(input: { next: ModelRef; current: ModelRef | null; started: boolean; claude: ClaudeModelsState; switchable?: (current: ModelRef, next: ModelRef) => boolean }): ModelPick {
const { next, current, started, claude, switchable } = input;
diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsx
index 74537e5a..2d3a67d9 100644
--- a/apps/app/src/react-app/shell/app-root.tsx
+++ b/apps/app/src/react-app/shell/app-root.tsx
@@ -46,7 +46,6 @@ import {
} from "./control/control-provider";
import { OmniRushContextPublisher } from "./omnirush-context-publisher";
import { SessionRoute } from "./session-route";
-import { ClaudeRoute } from "./claude-route";
import { DesktopUpdaterProvider } from "../domains/settings/state/desktop-updater-provider";
import { SyncRestartGate } from "./sync-restart-banner";
import { UpdateGate } from "./update-gate";
@@ -408,7 +407,6 @@ export function AppRoot() {
<CloudWorkspaceStatusProvider>
<ComputerUseControls />
<Routes>
- <Route path="/workspace/:workspaceId/claude" element={<ClaudeRoute />} />
<Route
path="/signin"
element={
diff --git a/apps/app/src/react-app/shell/claude-offer.ts b/apps/app/src/react-app/shell/claude-offer.ts
deleted file mode 100644
index 01398433..00000000
--- a/apps/app/src/react-app/shell/claude-offer.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-// What the app shows of Claude Code for a workspace. While the server does not offer it to this account (status
-// `allowed` false: today's servers, the switch off) nothing advertises it: no menu entry, no Claude page. Sessions
-// saved earlier stay reachable for export and recovery, under a plain "saved sessions" view.
-import { useEffect, useState } from "react";
-
-import { createOmniRushServerClient } from "@/app/lib/omnirush-server";
-import { workspaceBootstrap } from "@/app/lib/desktop";
-import { isDesktopRuntime } from "@/app/lib/runtime-env";
-import { resolveWorkspaceEndpoint, type ResolvedWorkspaceEndpoint } from "@/app/lib/workspace-endpoint";
-import { resolveOmniRushConnection } from "./omnirush-connection";
-
-/** full: offered (new sessions); saved: not offered, saved sessions to export; none: nothing to show. */
-export type ClaudeSurface = "full" | "saved" | "none";
-
-export function claudeSurface(allowed: boolean, savedSessions: number): ClaudeSurface {
- if (allowed) return "full";
- return savedSessions > 0 ? "saved" : "none";
-}
-
-/** The workspace's server endpoint (the local server on the desktop). */
-export async function claudeEndpoint(workspaceId: string | undefined, signal?: AbortSignal): Promise<ResolvedWorkspaceEndpoint> {
- const {normalizedBaseUrl: baseUrl, resolvedToken: token, resolvedHostToken: hostToken} = await resolveOmniRushConnection();
- signal?.throwIfAborted();
- if (!baseUrl) throw new Error("Connect to a workspace server first");
- const local = { baseUrl, token, hostToken };
- const localClient = createOmniRushServerClient(local);
- const workspaces = (await localClient.listWorkspaces()).items;
- signal?.throwIfAborted();
- const workspace = workspaces.find((item) => item.id === workspaceId)
- ?? (isDesktopRuntime() ? (await workspaceBootstrap()).workspaces.find((item) => item.id === workspaceId) : undefined);
- signal?.throwIfAborted();
- if (!workspace) throw new Error("Workspace not found");
- const next = resolveWorkspaceEndpoint(workspace, local);
- if (!next) throw new Error("Workspace server is unavailable");
- // Host authority stays on the local server; the shared resolver supplies
- // the owning remote workspace's own URL and credentials.
- return {...next, client: next.isRemote ? next.client : localClient};
-}
-
-type ClaudeConnection = {
- endpoint: (ResolvedWorkspaceEndpoint & {signal: AbortSignal}) | null;
- pending: boolean;
- error: string | null;
-};
-
-/** Shared route/menu lifetime: settings publication supersedes old requests. */
-export function useClaudeEndpoint(workspaceId: string | undefined): ClaudeConnection {
- const [connection, setConnection] = useState<ClaudeConnection>({endpoint: null, pending: true, error: null});
- useEffect(() => {
- let controller: AbortController;
- const connect = () => {
- controller?.abort();
- controller = new AbortController();
- const {signal} = controller;
- setConnection({endpoint: null, pending: true, error: null});
- void claudeEndpoint(workspaceId, signal).then(endpoint => {
- if (!signal.aborted) setConnection({endpoint: {...endpoint, signal}, pending: false, error: null});
- }, error => {
- if (!signal.aborted) setConnection({endpoint: null, pending: false, error: error instanceof Error ? error.message : "Workspace server is unavailable"});
- });
- };
- const onStorage = (event: StorageEvent) => { if (!event.key || event.key.startsWith("omnirush.server.")) connect(); };
- const onVisible = () => { if (document.visibilityState === "visible") connect(); };
- connect();
- window.addEventListener("omnirush-server-settings-changed", connect);
- window.addEventListener("storage", onStorage);
- document.addEventListener("visibilitychange", onVisible);
- return () => {
- controller.abort();
- window.removeEventListener("omnirush-server-settings-changed", connect);
- window.removeEventListener("storage", onStorage);
- document.removeEventListener("visibilitychange", onVisible);
- };
- }, [workspaceId]);
- return connection;
-}
-
-/** Null until known; a failed or interrupted connection never advertises Claude. */
-export function useClaudeSurface(workspaceId: string | undefined): ClaudeSurface | null {
- const {endpoint, pending} = useClaudeEndpoint(workspaceId);
- const [surface, setSurface] = useState<ClaudeSurface | null>(null);
- useEffect(() => {
- setSurface(null);
- if (!endpoint) return;
- let closed = false;
- void (async () => {
- const [status, sessions] = await Promise.all([
- endpoint.client.claude.request<{ allowed: boolean }>(endpoint.workspaceId, "status", undefined, endpoint.signal),
- endpoint.client.claude.request<unknown[]>(endpoint.workspaceId, "sessions", undefined, endpoint.signal),
- ]);
- return claudeSurface(status?.allowed === true, Array.isArray(sessions) ? sessions.length : 0);
- })().then((next) => { if (!closed && !endpoint.signal.aborted) setSurface(next); }, () => { if (!closed && !endpoint.signal.aborted) setSurface("none"); });
- return () => { closed = true; };
- }, [endpoint]);
- return pending ? null : endpoint ? surface : "none";
-}
diff --git a/apps/app/src/react-app/shell/claude-route.tsx b/apps/app/src/react-app/shell/claude-route.tsx
deleted file mode 100644
index f4df19ce..00000000
--- a/apps/app/src/react-app/shell/claude-route.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-import { useCallback, useEffect, useState } from "react";
-import { Link, useParams, useSearchParams } from "react-router";
-import { Button } from "@/components/ui/button";
-import { isDesktopRuntime } from "@/app/lib/runtime-env";
-import { useBootState } from "./boot-state";
-import { claudeSurface, useClaudeEndpoint } from "./claude-offer";
-
-type Session = {
- id: string; createdAt: string; model: string; capture: string; replay: string; issues: string[];
- turns: Array<{number: number; status: string; error?: string}>;
- compatibility?: "current" | "legacy_unverified" | "contract_invalid" | "runtime_upgrade_required";
- contract?: {execution: {os: string; architecture: string}};
- modelIsolation?: {status: "pending" | "observed" | "unknown" | "invalid" | "legacy_unverified"};
- authorization?: {budget: {status: "known" | "unknown"; asOf?: string; remainingTokens?: number | null; sessionRemainingTokens?: number | null; accountRemainingTokens?: number; accountScope?: string} | null};
-};
-type Event = {type: string; text: string; turn: number};
-export function ClaudeRoute() {
- const {workspaceId} = useParams();
- return <WorkspaceClaudeRoute key={workspaceId} workspaceId={workspaceId} />;
-}
-function WorkspaceClaudeRoute({workspaceId}: {workspaceId: string | undefined}) {
- const {markRouteReady} = useBootState();
- const {endpoint, pending: connecting} = useClaudeEndpoint(workspaceId);
- const [downloadController, setDownloadController] = useState<AbortController | null>(null);
- const [allowed, setAllowed] = useState(false), [ready, setReady] = useState(false), [loaded, setLoaded] = useState(false);
- const [sessions, setSessions] = useState<Session[]>([]), [selected, setSelected] = useState<string>();
- const [session, setSession] = useState<Session>(), [events, setEvents] = useState<Event[]>([]);
- const [prompt, setPrompt] = useState(""), [command, setCommand] = useState("");
- const [consent, setConsent] = useState(false), [busy, setBusy] = useState(false);
- const [error, setError] = useState(""), [notice, setNotice] = useState("");
- // The model a new session starts on: the picker's choice (?model=) when this account may run it.
- const [searchParams] = useSearchParams();
- const [models, setModels] = useState<Array<{id: string; name: string}>>([]), [model, setModel] = useState("");
- const request = useCallback(async <T,>(route: string, body?: unknown): Promise<T> => {
- if (!endpoint) throw new Error("Workspace server is unavailable");
- endpoint.signal.throwIfAborted();
- const result = await endpoint.client.claude.request<T>(endpoint.workspaceId, route, body, endpoint.signal);
- endpoint.signal.throwIfAborted();
- return result;
- }, [endpoint]);
- useEffect(() => {
- if (!connecting) markRouteReady();
- }, [connecting, markRouteReady]);
- const refresh = useCallback(async () => {
- const [status, items] = await Promise.all([
- request<{allowed: boolean; sandboxReady: boolean; models?: string[]; catalog?: Array<{id: string; name: string}>}>("status"),
- request<Session[]>("sessions"),
- ]);
- setAllowed(status.allowed); setReady(status.sandboxReady);
- const runnable = (status.models ?? []).map(id => ({id, name: status.catalog?.find(entry => entry.id === id)?.name ?? id}));
- setModels(runnable);
- setModel(current => runnable.some(entry => entry.id === current) ? current : runnable.find(entry => entry.id === searchParams.get("model"))?.id ?? runnable[0]?.id ?? "");
- setSessions(items); setLoaded(true);
- }, [request, searchParams]);
- useEffect(() => {
- setLoaded(false); setAllowed(false); setReady(false);
- if (endpoint) void refresh().catch(e => {
- if (!endpoint.signal.aborted) { setError(e.message); setSessions([]); setLoaded(true); }
- });
- }, [endpoint, refresh]);
- useEffect(() => {
- if (!selected) { setSession(undefined); setEvents([]); return; }
- if (!endpoint) return;
- let closed = false, timer: ReturnType<typeof setTimeout>;
- const poll = async () => {
- try {
- const [next, items] = await Promise.all([request<Session>(`sessions/${selected}`), request<Event[]>(`sessions/${selected}/events`)]);
- if (!closed && !endpoint.signal.aborted) { setSession(next); setEvents(items); }
- } catch (e) { if (!closed && !endpoint.signal.aborted) { setSession(undefined); setEvents([]); setError(e instanceof Error ? e.message : "Session unavailable"); } }
- if (!closed && !endpoint.signal.aborted) timer = setTimeout(poll, 1500);
- };
- void poll(); return () => { closed = true; clearTimeout(timer); };
- }, [selected, request, endpoint]);
- const act = async (work: () => Promise<void>) => { setBusy(true); setError(""); setNotice(""); try { await work(); } catch (e) { if (!endpoint?.signal.aborted) setError(e instanceof Error ? e.message : "Operation failed"); } finally { setBusy(false); } };
- // A persisted unfinished turn does not prove a process is alive. Export
- // asks the server to check ownership of the saved evidence.
- const unfinishedTurn = session?.turns.at(-1)?.status === "running";
- const continuationIssue = session?.modelIsolation?.status === "unknown"
- ? "This session is missing provider model identity evidence. Keep its evidence and start a new session."
- : session?.modelIsolation?.status === "invalid" || session?.compatibility === "contract_invalid"
- ? "This session’s model or environment contract changed. Keep its evidence and start a new session."
- : session?.compatibility === "runtime_upgrade_required"
- ? "This session needs its recorded runtime version. Export its evidence or start a new session."
- : session?.compatibility === "legacy_unverified"
- ? "This older session can be exported. Start a new session to continue with a fixed model."
- : undefined;
- const budget = session?.authorization?.budget;
- const remaining = (tokens: number | null | undefined) => tokens === null ? "no limit" : typeof tokens === "number" ? `${tokens.toLocaleString()} tokens` : "unknown";
- const download = async () => {
- if (!endpoint || !session) return;
- const controller = new AbortController();
- const signal = AbortSignal.any([endpoint.signal, controller.signal]);
- setDownloadController(controller);
- const filename = `claude-${session.id}.zip`;
- try {
- if (isDesktopRuntime()) {
- if (!await endpoint.client.claude.saveExport(endpoint.workspaceId, session.id, signal)) return;
- } else {
- const blob = await endpoint.client.claude.export(endpoint.workspaceId, session.id, signal);
- signal.throwIfAborted();
- const url = URL.createObjectURL(blob), link = document.createElement("a");
- link.href = url; link.download = filename; link.click(); setTimeout(() => URL.revokeObjectURL(url), 60_000);
- }
- signal.throwIfAborted();
- setNotice("Private session ZIP downloaded.");
- } catch (e) {
- if (!signal.aborted) throw e;
- if (!endpoint.signal.aborted) setNotice("Download cancelled.");
- } finally { setDownloadController(null); }
- };
- const surface = endpoint ? claudeSurface(allowed, sessions.length) : "none";
- if (connecting || endpoint && !loaded) return <main className="mx-auto h-full max-w-5xl p-6" aria-busy="true" />;
- if (surface === "none") {
- return <main className="mx-auto h-full max-w-5xl space-y-4 p-6" data-testid="claude-unavailable">
- <p>This page is not available.</p><Link to={`/workspace/${workspaceId}/session`}>Back to chats</Link>
- </main>;
- }
- return <main className="mx-auto h-full max-w-5xl space-y-4 overflow-auto p-6" aria-label={surface === "full" ? "Claude Code workspace" : "Saved sessions"}>
- <header className="flex items-center justify-between">{surface === "full"
- ? <div><h1 className="text-xl font-semibold">Claude Code</h1><p className="text-sm text-muted-foreground">{models.find(entry => entry.id === model)?.name ?? "Claude"} · Private sandbox sessions</p></div>
- : <div><h1 className="text-xl font-semibold">Saved sessions</h1><p className="text-sm text-muted-foreground">Export or recover the sessions saved here.</p></div>}<Link to={`/workspace/${workspaceId}/session`}>Back to chats</Link></header>
- {error && <p role="alert" className="rounded border border-destructive p-3">{error}</p>}
- {notice && <p role="status" data-testid="claude-notice" className="sticky top-0 z-10 rounded border bg-background p-3">{notice}</p>}
- <>
- {allowed && !ready && <p role="status" data-testid="claude-needs-docker">Claude needs Docker on this computer for now. Install and start Docker Desktop or Docker Engine, then <button className="underline" onClick={() => void act(refresh)}>check again</button>.</p>}
- <section className="flex flex-wrap items-center gap-3 rounded border p-3" aria-label="Session controls">
- <select aria-label="Claude session" value={selected ?? ""} onChange={e => { setSession(undefined); setEvents([]); setSelected(e.target.value || undefined); }} className="max-w-64 rounded border bg-background p-2"><option value="">Choose a session</option>{sessions.map(item => <option key={item.id} value={item.id}>{new Date(item.createdAt).toLocaleString()} · {item.id.slice(0,8)}</option>)}</select>
- {surface === "full" && models.length > 1 && <select aria-label="Claude model" value={model} onChange={e => setModel(e.target.value)} className="rounded border bg-background p-2">{models.map(entry => <option key={entry.id} value={entry.id}>{entry.name}</option>)}</select>}
- {surface === "full" && <><label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={consent} onChange={e => setConsent(e.target.checked)} />Retain private traces and full project snapshots</label>
- <Button disabled={!allowed || !ready || busy || !consent} onClick={() => void act(async () => { setNotice("Preparing the sandbox and copying your project. The first setup may take several minutes."); const created = await request<Session>("sessions", {captureConsent: true, ...(model ? {model} : {})}); await refresh(); setSelected(created.id); setNotice("Sandbox ready. Changes stay in this session’s project copy."); })}>New Claude session</Button></>}
- </section>
- {session && <>
- <div className="space-y-1 text-sm" aria-label="Fixed session model">
- <p><strong>{session.model}</strong> · {session.contract ? "Fixed for this session and its subagents" : "Legacy capture; model isolation unverified"}{session.contract && ` · ${session.contract.execution.os} / ${session.contract.execution.architecture}`}</p>
- <p className="text-muted-foreground" aria-label="Model allowance">{budget?.status === "known"
- ? `Allowance at last authorization${budget.asOf ? ` (${new Date(budget.asOf).toLocaleTimeString()})` : ""}: model ${remaining(budget.remainingTokens)} · Session: ${remaining(budget.sessionRemainingTokens)} · Account ${budget.accountScope ?? ""}: ${remaining(budget.accountRemainingTokens)}`
- : "Model allowance has not been reported by the backend."}</p>
- {session.modelIsolation?.status === "unknown" && <p role="status">The provider did not report a model identity for every request. This session needs review.</p>}
- {continuationIssue && <p role="status">{continuationIssue}</p>}
- </div>
- <p className="text-sm" aria-label="Capture status">Capture: {session.capture} · Environment: {session.replay} · {session.turns.length} turns</p>
- {session.issues.length > 0 && <p role="status">Evidence needs recovery: {session.issues.join(", ")}</p>}
- <section aria-label="Claude conversation" className="min-h-52 space-y-3 rounded border p-4">
- {events.length === 0 && <p className="text-muted-foreground">Describe what you want to build or fix.</p>}
- {events.map((event, index) => event.type === "thinking" ? <details key={index}><summary>Reasoning summary</summary><p className="whitespace-pre-wrap">{event.text}</p></details> : <article key={index} className="whitespace-pre-wrap"><strong>{event.type === "user" ? "You" : event.type === "assistant" ? "Claude" : event.type === "tool" ? "Tool" : "Status"}</strong><p>{event.text}</p></article>)}
- </section>
- <form onSubmit={e => { e.preventDefault(); void act(async () => { await request(`sessions/${session.id}/turns`, {prompt}); setPrompt(""); setSession({...session, turns: [...session.turns, {number: session.turns.length + 1, status: "running"}]}); }); }} className="flex gap-2">
- <textarea aria-label="Message Claude" value={prompt} onChange={e => setPrompt(e.target.value)} className="min-h-24 flex-1 rounded border bg-background p-3" placeholder="Describe the development task…" disabled={!endpoint || busy || unfinishedTurn || Boolean(continuationIssue)} />
- <Button type="submit" disabled={!endpoint || busy || unfinishedTurn || Boolean(continuationIssue) || !prompt.trim()}>Send</Button>
- {unfinishedTurn && <Button type="button" variant="outline" disabled={!endpoint || busy} onClick={() => void act(async () => { await request(`sessions/${session.id}/stop`, {}); })}>Stop</Button>}
- </form>
- <section className="flex flex-wrap items-center gap-2" aria-label="Evidence controls">
- <input aria-label="Verification command" value={command} onChange={e => setCommand(e.target.value)} placeholder="Project test command (optional)" className="min-w-64 rounded border bg-background p-2" />
- <Button variant="outline" disabled={!endpoint || busy || unfinishedTurn || !session.turns.length} onClick={() => void act(async () => { await request(`sessions/${session.id}/verify`, command.trim() ? {command} : {}); setNotice("Environment restored and verification passed with network access disabled."); })}>Verify restore</Button>
- <Button variant="outline" disabled={!endpoint || busy || unfinishedTurn} onClick={() => void act(async () => { await request(`sessions/${session.id}/recover`, {}); setNotice("Recovery finished. Check capture status before exporting."); })}>Recover evidence</Button>
- <Button variant="outline" disabled={!endpoint || busy || !session.turns.length} onClick={() => void act(download)}>Download private ZIP</Button>
- {downloadController && <Button variant="outline" onClick={() => downloadController.abort()}>Cancel download</Button>}
- <Button variant="outline" disabled={!endpoint || busy || unfinishedTurn || !session.turns.length} onClick={() => void act(async () => {
- const result = await request<{status: string; native: {status: string}; checkpoint: {status: string}}>(`sessions/${session.id}/upload`, {});
- setNotice(result.native.status === "uploaded" && result.checkpoint.status === "uploaded" ? "Private session uploaded. Backend receipts confirm the native traces and environment arrived."
- : result.native.status === "uploaded" && result.checkpoint.status === "disabled" ? "Native traces uploaded. Environment upload is disabled by the backend; the complete ZIP remains on this device."
- : "Upload is incomplete. Local evidence is retained; retry to resume.");
- })}>Upload private session</Button>
- </section>
- <p className="text-xs text-muted-foreground">The ZIP includes native Claude Code transcripts, available reasoning summaries, tool and subagent activity, and complete environment snapshots. Restore verification checks the saved environment; generated answers may differ on a new run.</p>
- </>}
- </>
- </main>;
-}
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index 50f944c0..436e6f9a 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -142,7 +142,7 @@ import { useSessionFindStore } from "@/react-app/domains/session/surface/find-st
import { useModelPicker } from "@/react-app/domains/session/modals/use-model-picker";
import { getSessionModelSelection, resolveSendVariant, useSessionModelStore } from "@/react-app/domains/session/surface/session-model-store";
import { chatStarted, markChatStarted, useProjectModelModes } from "@/react-app/domains/session/surface/model-modes";
-import { claudeModelName, claudeModelOptions, decideModelPick, isClaudeModel, newChatPrompt, setUpClaudeSandbox, useClaudeModels, useClaudeModelSync, useModelPickGate } from "@/react-app/domains/session/surface/claude-models";
+import { claudeModelName, decideModelPick, isClaudeModel, newChatPrompt, setUpClaudeSandbox, useClaudeModels, useClaudeModelSync, useModelPickGate } from "@/react-app/domains/session/surface/claude-models";
import { ConfirmModal } from "@/react-app/design-system/modals/confirm-modal";
import { useWorkbenchStore } from "@/react-app/domains/session/chat/workbench-store";
import { resolveWorkbenchPaneEndpoint } from "@/react-app/domains/session/chat/pane-runtime";
@@ -2841,35 +2841,32 @@ export function SessionRoute() {
})()
: modelVariantValue;
- // Every list the route shows: the project's allowed models and Claude (listed everywhere).
- const claudeCatalog = useClaudeModels((state) => state.catalog);
+ // Every list the route shows: the project's allowed models (Claude's come from the engine's Claude provider).
const pickerOptions = useMemo(
- () => [...modelPicker.options.filter((option) => modelModes.allowsNew(option)), ...claudeModelOptions({ catalog: claudeCatalog })],
- [claudeCatalog, modelModes, modelPicker.options],
+ () => modelPicker.options.filter((option) => modelModes.allowsNew(option)),
+ [modelModes, modelPicker.options],
);
// A pick the picker should not just switch to (claude-models.ts decideModelPick).
const [newChatOffer, setNewChatOffer] = useState<{ next: ModelRef; current: ModelRef } | null>(null);
const modelTitle = (ref: ModelRef) => isClaudeModel(ref)
? claudeModelName(useClaudeModels.getState(), ref.modelID)
: modelPicker.options.find((option) => option.providerID === ref.providerID && option.modelID === ref.modelID)?.title ?? resolveModelDisplayName(ref.modelID);
- /** Claude: set the project's sandbox up (as the required sandbox does) and open a Claude chat on `model`. */
- const openClaudeChat = (model: ModelRef) => {
+ /** Claude runs in the sandbox: set the project's sandbox up (as the required sandbox does) before its first turn. */
+ const setUpSandboxForClaude = () => {
const endpoint = selectedWorkspaceEndpoint;
- if (!selectedWorkspaceId) return;
- if (endpoint?.client) {
- void setUpClaudeSandbox(endpoint.client, endpoint.workspaceId).catch(() => {
- toast.error("The sandbox could not be set up for Claude. Check Settings > General > Sandbox.", { id: "claude-sandbox" });
- });
- }
- navigate(`/workspace/${encodeURIComponent(selectedWorkspaceId)}/claude?model=${encodeURIComponent(model.modelID)}`);
+ if (!endpoint?.client) return;
+ void setUpClaudeSandbox(endpoint.client, endpoint.workspaceId).catch(() => {
+ toast.error("The sandbox could not be set up for Claude. Check Settings > General > Sandbox.", { id: "claude-sandbox" });
+ });
};
const handleModelPick = (next: ModelRef, sessionId: string | null): boolean => {
const current = sessionId ? getSessionModelSelection(sessionId)?.model ?? null : null;
const pick = decideModelPick({ next, current, started: Boolean(sessionId && chatStarted(sessionId)), claude: useClaudeModels.getState(), switchable: modelModesRef.current.switchable });
if (pick.kind === "unavailable") toast(pick.message, { id: `claude-unavailable:${next.modelID}` });
else if (pick.kind === "new_chat" && current) setNewChatOffer({ next, current });
- else if (pick.kind === "claude") openClaudeChat(next);
- return pick.kind !== "switch" && pick.kind !== "same";
+ else if (pick.kind === "claude") setUpSandboxForClaude();
+ // A Claude pick in a fresh chat is a plain switch once the sandbox is on its way.
+ return pick.kind !== "switch" && pick.kind !== "same" && pick.kind !== "claude";
};
const modelPickRef = useRef(handleModelPick);
modelPickRef.current = handleModelPick;
@@ -2881,10 +2878,7 @@ export function SessionRoute() {
const offer = newChatOffer;
setNewChatOffer(null);
if (!offer || !selectedWorkspaceId) return;
- if (isClaudeModel(offer.next)) {
- openClaudeChat(offer.next);
- return;
- }
+ if (isClaudeModel(offer.next)) setUpSandboxForClaude();
const sessionId = await handleCreateTaskInWorkspace(selectedWorkspaceId);
if (!sessionId) return;
useSessionModelStore.getState().setModel(sessionId, offer.next, null);
diff --git a/apps/app/tests/claude-models.test.ts b/apps/app/tests/claude-models.test.ts
index c4a6df10..f72eb5e8 100644
--- a/apps/app/tests/claude-models.test.ts
+++ b/apps/app/tests/claude-models.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, test } from "bun:test";
import {
- claudeModelOptions,
claudeSandboxStep,
decideModelPick,
isClaudeModel,
@@ -14,29 +13,19 @@ import { switchableModel } from "../src/react-app/domains/session/surface/model-
import { switchableModels as sharedSwitchable } from "../../server/src/model-modes/strict-sessions.mjs";
import { builtinOmniRushModelCatalog } from "../../server/src/omnirush-model-catalog";
-const opus = { providerID: "omnirush", modelID: "claude-opus-5-5" };
-const sonnet = { providerID: "omnirush", modelID: "claude-sonnet-5-5" };
+const opus = { providerID: "omnirush-claude", modelID: "claude-opus-5-5" };
+const sonnet = { providerID: "omnirush-claude", modelID: "claude-sonnet-5-5" };
const astra = { providerID: "omnirush", modelID: "gpt-6-astra" };
const sol = { providerID: "omnirush", modelID: "gpt-6.1-sol" };
const catalog = [{ id: opus.modelID, name: "Claude Opus 5.5" }, { id: sonnet.modelID, name: "Claude Sonnet 5.5" }];
const allowed: ClaudeModelsState = { workspaceId: "w", catalog, models: [opus.modelID, sonnet.modelID], reason: null };
const denied: ClaudeModelsState = { workspaceId: "w", catalog, models: [], reason: "not_allowed" };
-describe("picker entries", () => {
- test("every catalog model is listed, allowed or not, under Claude", () => {
- for (const state of [allowed, denied]) {
- const options = claudeModelOptions(state);
- expect(options.map((option) => [option.providerID, option.modelID, option.title, option.group])).toEqual([
- ["omnirush", "claude-opus-5-5", "Claude Opus 5.5", "Claude"],
- ["omnirush", "claude-sonnet-5-5", "Claude Sonnet 5.5", "Claude"],
- ]);
- }
- expect(claudeModelOptions({ catalog: [] })).toEqual([]);
- });
-
- test("only omnirush Claude ids are Claude models", () => {
+describe("Claude models", () => {
+ test("only the engine's Claude provider's models are Claude models", () => {
expect(isClaudeModel(opus)).toBe(true);
expect(isClaudeModel(astra)).toBe(false);
+ expect(isClaudeModel({ providerID: "omnirush", modelID: "claude-opus-5-5" })).toBe(false);
expect(isClaudeModel({ providerID: "anthropic", modelID: "claude-opus-5-5" })).toBe(false);
});
@@ -48,7 +37,7 @@ describe("picker entries", () => {
});
describe("popup decision", () => {
- test("a fresh chat just switches, or opens Claude", () => {
+ test("a fresh chat just switches (Claude once its sandbox is set up)", () => {
expect(decideModelPick({ next: sol, current: astra, started: false, claude: allowed })).toEqual({ kind: "switch" });
expect(decideModelPick({ next: sonnet, current: astra, started: false, claude: allowed })).toEqual({ kind: "claude" });
expect(decideModelPick({ next: opus, current: null, started: false, claude: allowed })).toEqual({ kind: "claude" });
diff --git a/apps/app/tests/claude-offer.test.tsx b/apps/app/tests/claude-offer.test.tsx
deleted file mode 100644
index 4c97d515..00000000
--- a/apps/app/tests/claude-offer.test.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-/** @jsxImportSource react */
-import { afterAll, describe, expect, mock, test } from "bun:test";
-import { GlobalRegistrator } from "@happy-dom/global-registrator";
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { MemoryRouter, Route, Routes } from "react-router";
-
-const registered = typeof globalThis.document === "undefined";
-if (registered) GlobalRegistrator.register({ url: "http://localhost/" });
-afterAll(async () => { if (registered) await GlobalRegistrator.unregister(); });
-
-// The pure rule, without the module's app imports (they read window at load).
-const claudeSurface = (allowed: boolean, saved: number) => (allowed ? "full" : saved > 0 ? "saved" : "none");
-
-
-let status = { allowed: false, sandboxReady: true };
-let sessions: unknown[] = [];
-// Stable, as the real boot state is (a new function each render would re-run the route's effects forever).
-const bootState = { markRouteReady: () => {} };
-mock.module("../src/react-app/shell/boot-state", () => ({ useBootState: () => bootState }));
-const connection = {
- pending: false,
- endpoint: {
- signal: new AbortController().signal,
- workspaceId: "ws",
- client: { claude: { request: async (_ws: string, route: string) => (route === "status" ? status : route === "sessions" ? sessions : []) } },
- },
-};
-mock.module("../src/react-app/shell/claude-offer", () => ({
- claudeSurface,
- useClaudeEndpoint: () => connection,
-}));
-
-async function renderRoute(): Promise<string> {
- const { ClaudeRoute } = await import("../src/react-app/shell/claude-route");
- Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
- const container = document.createElement("div");
- document.body.append(container);
- const root = createRoot(container);
- await act(async () => {
- root.render(<MemoryRouter initialEntries={["/workspace/ws/claude"]}><Routes><Route path="/workspace/:workspaceId/claude" element={<ClaudeRoute />} /></Routes></MemoryRouter>);
- });
- for (let i = 0; i < 50 && container.querySelector("[aria-busy]"); i++) await act(async () => { await new Promise((r) => setTimeout(r, 10)); });
- const text = container.textContent ?? "";
- await act(async () => root.unmount());
- container.remove();
- return text;
-}
-
-describe("the /claude route", () => {
- const T = 60_000;
- test("off and nothing saved: no Claude content, only 'not available'", async () => {
- status = { allowed: false, sandboxReady: true }; sessions = [];
- const text = await renderRoute();
- expect(text).toContain("This page is not available.");
- expect(text).not.toMatch(/claude|opus|pilot|selected accounts/i);
- }, T);
-
- test("off with a saved session: a plain saved-sessions view, no new-session control, no advertising", async () => {
- status = { allowed: false, sandboxReady: true };
- sessions = [{ id: "s1", createdAt: "2026-10-24T00:00:00Z", model: "m", capture: "ok", replay: "ok", issues: [], turns: [] }];
- const text = await renderRoute();
- expect(text).toContain("Saved sessions");
- expect(text).not.toMatch(/New Claude session|selected accounts|Opus|pilot/i);
- }, T);
-
- test("on: the Claude Code page with its new-session control", async () => {
- status = { allowed: true, sandboxReady: true }; sessions = [];
- const text = await renderRoute();
- expect(text).toContain("Claude Code");
- expect(text).toContain("New Claude session");
- }, T);
-});
-
-test("native Claude save sends host authority and aborts the same registered transfer", async () => {
- const {createOmniRushServerClient} = await import("../src/app/lib/omnirush-server");
- const controller = new AbortController();
- const commands: Array<{command: string; input: unknown}> = [];
- let refuseExport = false;
- let rejectDownload: (error: Error) => void = () => { throw new Error("Download was not started"); };
- const pending = new Promise((_resolve, reject) => { rejectDownload = reject; });
- const previous = Object.getOwnPropertyDescriptor(window, "__OMNIRUSH_ELECTRON__");
- Object.defineProperty(window, "__OMNIRUSH_ELECTRON__", {configurable: true, value: {
- invokeDesktop(command: string, input: unknown) {
- commands.push({command, input});
- if (command === "__downloadClaudeArchive") return refuseExport
- ? Promise.resolve({status: 409, statusText: "Conflict", headers: [], path: null, bytes: 0, body: JSON.stringify({code: "session_in_use", message: "Another process is using this session or its operation owner is unknown"})})
- : pending;
- if (command === "__cancelTransfer") { rejectDownload(new DOMException("Cancelled", "AbortError")); return Promise.resolve(true); }
- throw new Error(`Unexpected native operation: ${command}`);
- },
- }});
- try {
- const client = createOmniRushServerClient({baseUrl: "http://127.0.0.1:39876", token: "fixture-client", hostToken: "fixture-current-host"});
- const downloading = client.claude.saveExport("ws", "00000000-0000-4000-8000-000000000001", controller.signal);
- const outcome = downloading.then(() => "completed", error => error.name);
- expect(commands).toHaveLength(1);
- expect(commands[0]).toMatchObject({command: "__downloadClaudeArchive", input: {
- transferId: expect.any(String), headers: {Authorization: "Bearer fixture-client", "X-OmniRush-Host-Token": "fixture-current-host"},
- url: "http://127.0.0.1:39876/workspace/ws/claude/sessions/00000000-0000-4000-8000-000000000001/export",
- }});
- controller.abort();
- expect(await outcome).toBe("AbortError");
- expect(commands).toHaveLength(2);
- expect(commands[1].command).toBe("__cancelTransfer");
- expect(commands[0].input).toMatchObject({transferId: commands[1].input});
- await expect(client.claude.saveExport("ws", "same-session", controller.signal)).rejects.toMatchObject({name: "AbortError"});
- expect(commands).toHaveLength(2);
- refuseExport = true;
- await expect(client.claude.saveExport("ws", "locked-session")).rejects.toThrow("Another process is using this session or its operation owner is unknown");
- } finally {
- if (previous) Object.defineProperty(window, "__OMNIRUSH_ELECTRON__", previous);
- else Reflect.deleteProperty(window, "__OMNIRUSH_ELECTRON__");
- }
-}, 5000);
diff --git a/apps/app/tests/claude-surface.test.ts b/apps/app/tests/claude-surface.test.ts
deleted file mode 100644
index f9b71816..00000000
--- a/apps/app/tests/claude-surface.test.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { afterAll, expect, test } from "bun:test";
-import { GlobalRegistrator } from "@happy-dom/global-registrator";
-
-const registered = typeof globalThis.document === "undefined";
-if (registered) GlobalRegistrator.register({ url: "http://localhost/" });
-afterAll(async () => { if (registered) await GlobalRegistrator.unregister(); });
-
-test("claudeSurface: off with nothing saved shows nothing; off with saved sessions keeps them; on is the full page", async () => {
- const { claudeSurface } = await import("../src/react-app/shell/claude-offer");
- expect(claudeSurface(false, 0)).toBe("none");
- expect(claudeSurface(false, 2)).toBe("saved");
- expect(claudeSurface(true, 0)).toBe("full");
-});
diff --git a/apps/app/tests/provider-lock.test.ts b/apps/app/tests/provider-lock.test.ts
index 0b269b66..cf3fad2a 100644
--- a/apps/app/tests/provider-lock.test.ts
+++ b/apps/app/tests/provider-lock.test.ts
@@ -24,7 +24,7 @@ afterEach(() => setProviderLockState(null));
describe("provider lock in the app", () => {
test("locked until the server says `locked: false`", () => {
expect(isProviderLocked()).toBe(true);
- expect(providerLockState().allow).toEqual(["omnirush"]);
+ expect(providerLockState().allow).toEqual(["omnirush", "omnirush-claude"]);
for (const answer of [null, undefined, {}, { locked: "false" }, { locked: 0 }, []]) {
expect(parseProviderLockState(answer).locked).toBe(true);
}
@@ -34,9 +34,10 @@ describe("provider lock in the app", () => {
expect(isProviderLocked()).toBe(true);
});
- test("takes the server's message; only omnirush counts as allowed", () => {
+ test("takes the server's message; only OmniRush's own providers count as allowed", () => {
setProviderLockState({ locked: true, allow: ["acme", "openai"], message: "Ask your admin." });
- expect(providerLockState()).toEqual({ locked: true, allow: ["omnirush"], message: "Ask your admin." });
+ expect(providerLockState()).toEqual({ locked: true, allow: ["omnirush", "omnirush-claude"], message: "Ask your admin." });
+ expect(isProviderAllowedByLock("omnirush-claude")).toBe(true);
expect(providerLockMessage()).toBe("Ask your admin.");
expect(isProviderAllowedByLock("acme")).toBe(false);
expect(isProviderAllowedByLock("omnirush")).toBe(true);
diff --git a/apps/desktop/electron/binary-transfer.mjs b/apps/desktop/electron/binary-transfer.mjs
index 01a23420..70f5841e 100644
--- a/apps/desktop/electron/binary-transfer.mjs
+++ b/apps/desktop/electron/binary-transfer.mjs
@@ -364,24 +364,3 @@ export async function downloadBinaryToPath(input, options) {
}
}
}
-
-// Native evidence is larger than ordinary inbox files. This separate operation
-// uses the app's save dialog and known server endpoints as its authorities;
-// neither the output path nor the larger limit comes from renderer input.
-export async function downloadClaudeArchive(input, options) {
- options.signal?.throwIfAborted();
- const url = new URL(input.url);
- if (url.username || url.password || url.search || url.hash || !/\/workspace\/[^/]+\/claude\/sessions\/[a-f0-9-]{36}\/export$/.test(url.pathname)) {
- throw transferError("Invalid Claude archive endpoint.", "unauthorized-url");
- }
- const prefixes = [...options.allowedUrlPrefixes, ...(options.localServerUrl ? [options.localServerUrl] : [])];
- remoteUrl(url.toString(), prefixes, true);
- const session = url.pathname.split("/").at(-2);
- const destination = await options.chooseDestination(`claude-${session}.zip`);
- options.signal?.throwIfAborted();
- if (!destination) return null;
- return downloadBinaryToPath({url: url.toString(), destinationPath: destination, headers: input.headers, method: "POST", maxBytes: 2 ** 32 - 1, timeoutMs: 15 * 60_000}, {
- ...options, allowedUrlPrefixes: prefixes, allowLoopback: true, downloadMaximum: 2 ** 32 - 1,
- authorizedRoots: [path.dirname(destination)],
- });
-}
diff --git a/apps/desktop/electron/binary-transfer.test.mjs b/apps/desktop/electron/binary-transfer.test.mjs
index 0ceed3fe..bb4743c4 100644
--- a/apps/desktop/electron/binary-transfer.test.mjs
+++ b/apps/desktop/electron/binary-transfer.test.mjs
@@ -7,112 +7,11 @@ import test from "node:test";
import {
DESKTOP_TRANSFER_MAX_BYTES,
downloadBinaryToPath,
- downloadClaudeArchive,
uploadMultipartFromBytes,
} from "./binary-transfer.mjs";
const allowedUrlPrefixes = ["https://worker.example.test"];
-test("Claude archive saving uses a dialog path and only the app's exact server", async () => {
- await withWorkspace(async (root, stagingDir) => {
- const localServerUrl = "http://127.0.0.1:39876";
- const route = "/workspace/project/claude/sessions/00000000-0000-4000-8000-000000000001/export";
- let fetched = 0, dialogs = 0;
- const options = {localServerUrl, allowedUrlPrefixes: [], stagingDir,
- chooseDestination: async filename => { dialogs++; return path.join(root, filename); },
- fetcher: async (url, init) => { fetched++; assert.equal(url, localServerUrl + route); assert.equal(init.method, "POST"); assert.equal(init.redirect, "error"); return remoteResponse(new Uint8Array([1,2,3]), {headers: {"content-length": String(DESKTOP_TRANSFER_MAX_BYTES + 1)}}); },
- };
- for (const url of ["http://127.0.0.1:39877" + route, localServerUrl + "/private", localServerUrl + route + "?redirect=1"]) await assert.rejects(downloadClaudeArchive({url}, options));
- assert.equal(dialogs, 0); assert.equal(fetched, 0);
- assert.equal(await downloadClaudeArchive({url: localServerUrl + route}, {...options, chooseDestination: async () => null}), null);
- assert.equal(fetched, 0);
- const result = await downloadClaudeArchive({url: localServerUrl + route}, options);
- assert.equal(result.bytes, 3); assert.deepEqual(await readFile(result.path), Buffer.from([1,2,3]));
- await assert.rejects(downloadClaudeArchive({url: localServerUrl + route}, options)); // exclusive creation
- });
-});
-
-test("Claude archive cancellation before or during the dialog never starts a fetch", {timeout: 5000}, async () => {
- await withWorkspace(async (root, stagingDir) => {
- for (const beforeDialog of [true, false]) {
- const controller = new AbortController();
- let dialogs = 0, fetched = 0;
- if (beforeDialog) controller.abort();
- await assert.rejects(downloadClaudeArchive({url: "http://127.0.0.1:39876/workspace/project/claude/sessions/00000000-0000-4000-8000-000000000001/export"}, {
- localServerUrl: "http://127.0.0.1:39876", allowedUrlPrefixes: [], stagingDir, signal: controller.signal,
- chooseDestination: async filename => { dialogs++; controller.abort(); return path.join(root, filename); },
- fetcher: async () => { fetched++; return remoteResponse(new Uint8Array([1])); },
- }), {name: "AbortError"});
- assert.equal(dialogs, beforeDialog ? 0 : 1);
- assert.equal(fetched, 0);
- assert.deepEqual(await readdir(root), []);
- }
- });
-});
-
-test("Claude archive conflict preserves the safe response body without creating a destination", async () => {
- await withWorkspace(async (root, stagingDir) => {
- const body = JSON.stringify({code: "session_in_use", message: "Another process is using this session or its operation owner is unknown"});
- const result = await downloadClaudeArchive({
- url: "http://127.0.0.1:39876/workspace/project/claude/sessions/00000000-0000-4000-8000-000000000001/export",
- }, {
- localServerUrl: "http://127.0.0.1:39876", allowedUrlPrefixes: [], stagingDir,
- chooseDestination: async filename => path.join(root, filename),
- fetcher: async (_url, init) => {
- assert.equal(init.method, "POST");
- return new Response(body, {status: 409, headers: {"content-type": "application/json"}});
- },
- });
- assert.equal(result.status, 409);
- assert.ok("body" in result);
- assert.equal(result.body, body);
- assert.equal(result.path, null);
- assert.equal(result.bytes, 0);
- assert.deepEqual(await readdir(root), []);
- await assert.rejects(readdir(stagingDir), {code: "ENOENT"});
- });
-});
-
-test("Claude archive abort cancels a stalled stream and removes private staging bytes", {timeout: 5000}, async () => {
- await withWorkspace(async (root, stagingDir) => {
- const controller = new AbortController();
- let streamCancelled = false;
- /** @type {{signal?: AbortSignal | null}} */
- const captured = {};
- const filename = "claude-00000000-0000-4000-8000-000000000001.zip";
- const downloading = downloadClaudeArchive({
- url: "http://127.0.0.1:39876/workspace/project/claude/sessions/00000000-0000-4000-8000-000000000001/export",
- headers: {authorization: "Bearer fixture-client", "X-OmniRush-Host-Token": "fixture-host"},
- }, {
- localServerUrl: "http://127.0.0.1:39876", allowedUrlPrefixes: [], stagingDir, signal: controller.signal,
- chooseDestination: async () => path.join(root, filename),
- fetcher: async (_url, init) => {
- captured.signal = init.signal;
- assert.equal(init.headers["X-OmniRush-Host-Token"], "fixture-host");
- return new Response(new ReadableStream({
- start(stream) { stream.enqueue(new Uint8Array([80, 75, 255, 0])); },
- cancel() { streamCancelled = true; },
- }));
- },
- });
- const rejected = assert.rejects(downloading, {name: "AbortError"});
- // Wait for bytes on disk, so this exercises an in-flight body read.
- for (let attempt = 0; attempt < 100; attempt++) {
- const files = await readdir(stagingDir).catch(() => []);
- if (files.length && (await readFile(path.join(stagingDir, files[0]))).length) break;
- assert.ok(attempt < 99, "download never staged a chunk");
- await new Promise(resolve => setTimeout(resolve, 10));
- }
- controller.abort();
- await rejected;
- assert.ok(captured.signal);
- assert.equal(captured.signal.aborted, true);
- assert.equal(streamCancelled, true);
- assert.deepEqual(await readdir(stagingDir), []);
- assert.deepEqual(await readdir(root), []);
- });
-});
-
async function withWorkspace(run) {
const base = await mkdtemp(path.join(os.tmpdir(), "omnirush-binary-transfer-"));
const root = path.join(base, "root");
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index cd46abb2..5f765e2e 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -89,7 +89,7 @@ import { createDesktopFeedback, EVENT_CHANNEL as FEEDBACK_EVENT_CHANNEL } from "
import { classifyLocalOpen, isNetworkPath, localPathFromFileUrl } from "./open-local-path.mjs";
import { resolveAppIdentifier, resolveUserDataPath } from "./dev-profile.mjs";
import { fetchAgentContextDiagnosticsResponse } from "./agent-context-diagnostics-fetch.mjs";
-import { downloadBinaryToPath, downloadClaudeArchive, uploadMultipartFromBytes } from "./binary-transfer.mjs";
+import { downloadBinaryToPath, uploadMultipartFromBytes } from "./binary-transfer.mjs";
import {
createLinuxDesktopIntegration,
} from "./linux-desktop-integration.mjs";
@@ -2916,19 +2916,6 @@ const desktopCommandHandlers = {
"__downloadBinary": async (event, ...args) => {
return runDesktopTransfer(event, args[0] ?? {}, downloadBinaryToPath);
},
- "__downloadClaudeArchive": async (event, ...args) => {
- return runDesktopTransfer(event, args[0] ?? {}, async (input, options) => {
- const info = await runtimeManager.omnirushServerInfo();
- return downloadClaudeArchive(input, {
- ...options,
- localServerUrl: info?.baseUrl,
- chooseDestination: async filename => {
- const result = await dialog.showSaveDialog(activeWindowFromEvent(event), {title: "Save private Claude session", defaultPath: filename, filters: [{name: "ZIP archive", extensions: ["zip"]}]});
- return result.canceled ? null : result.filePath;
- },
- });
- });
- },
"__cancelTransfer": async (event, ...args) => {
const controller = activeDesktopTransfers.get(desktopTransferKey(event, args[0]));
if (!controller) return false;
diff --git a/apps/server/package.json b/apps/server/package.json
index 3e5f2786..ff3fb304 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -12,7 +12,7 @@
"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage",
"test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts",
"build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",
- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && node scripts/copy-mcp-allow.mjs && node scripts/copy-shared-modules.mjs && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/omnirush-session-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-box-next.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",
+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && node scripts/copy-mcp-allow.mjs && node scripts/copy-shared-modules.mjs && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/omnirush-session-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-box-next.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts src/opencode-plugins/claude-provider/index.js --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",
"build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server",
"build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64",
"prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index e2a4764b..e2175682 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -306,16 +306,13 @@ export class BoxService {
return detectRuntime({ boxHome: this.home, env: this.env, ...this.detectOptions(), ...extra });
}
- /**
- * The docker CLI of this machine's box backend when it is a Docker engine
- * (Docker Engine/Desktop, OrbStack, Rancher): runtimes that drive docker
- * themselves (Claude Code, claude-code/runtime.ts) use the same engine.
- * Null for the boxd backends (bubblewrap, the WSL distro, the VM), Podman and
- * a CLI that needs leading arguments (a docker context, wsl.exe).
- */
- async dockerCli(): Promise<string | null> {
- const runtime = await this.detect().catch(() => null);
- return runtime?.ok && runtime.name === "docker" && !runtime.prefix?.length && !runtime.wsl ? runtime.bin : null;
+ /** The Claude provider's box bits (opencode-plugins/claude-provider): the box home and the box shell; null without the shell helper. */
+ claudeBits(): { home: string; shell: string } | null {
+ try {
+ return { home: this.home, shell: installShell(this.home, { env: this.env }) };
+ } catch {
+ return null;
+ }
}
/**
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index 65ac2ac8..00ecb375 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -11,8 +11,6 @@
* again with a growing pause, and the calls made meanwhile wait for it.
*/
import type { ApprovalMode } from "./approval-mode.js";
-import type { ClaudeCaptureContext } from "./capture-host.js";
-import type { NativeCaptureAction, NativeCaptureManifest } from "./claude-code/native-capture.js";
import { Worker } from "node:worker_threads";
import { lstat } from "node:fs/promises";
import { resolve } from "node:path";
@@ -75,8 +73,8 @@ export type CaptureServiceOptions = Omit<CaptureHostOptions, "onSessionClosed">
export type CaptureMode = "starting" | "worker" | "local" | "restarting" | "down";
export type CaptureService = {
- /** Durable native evidence; failure rejects so a Claude runner cannot continue silently. */
- captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest>;
+ /** A Claude chat: its uploads name Claude Code (`version`) as the harness. */
+ markClaude(sessionId: string, version: string): void;
/** The session uploader has an account to upload to (the sign-in gate's question). */
readonly uploadEnabled: boolean;
/** Where capture runs right now. */
@@ -238,27 +236,8 @@ class CaptureClient implements CaptureService {
void this.query({ kind: "call", id: null, method: "holdUploads", args: [sessionId, state, seq] }).catch(() => null);
}
- async captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest> {
- const call: CaptureCall = { kind: "call", id: null, method: "captureClaude", args: [context, action] };
- let timeout: ReturnType<typeof setTimeout> | undefined;
- let value: unknown;
- try {
- value = await Promise.race([
- this.query(call),
- new Promise<never>((_, reject) => {
- timeout = setTimeout(() => {
- if (call.id !== null) this.replies.delete(call.id);
- this.queue = this.queue.filter((item) => item.call !== call);
- reject(new Error("Claude native capture acknowledgement timed out; stop the runner"));
- }, 30_000);
- }),
- ]);
- } finally { clearTimeout(timeout); }
- if (typeof value !== "object" || value === null || !("format" in value) || value.format !== "claude-code" || !("sessionId" in value) || value.sessionId !== context.sessionId || !("revision" in value) || typeof value.revision !== "number") {
- throw new Error("Claude native capture was not durably acknowledged; stop the runner");
- }
- // The typed CaptureHost produced this object across a structured-clone boundary.
- return value as NativeCaptureManifest;
+ markClaude(sessionId: string, version: string): void {
+ this.send({ kind: "call", id: null, method: "markClaude", args: [sessionId, version] });
}
boxSession(sessionId: string, box: BoxCaptureInfo | null): void {
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index c671f094..40860b4a 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -9,7 +9,6 @@
* cross the thread boundary unchanged.
*/
import { createMediaRewriter } from "./computer-use/media-capture.js";
-import { NativeCapture, type NativeCaptureOptions, type NativeCaptureAction, type NativeCaptureManifest } from "./claude-code/native-capture.js";
import type { ApprovalMode } from "./approval-mode.js";
import type { ContextOptions } from "./context/index.js";
import { defaultRedactionPolicy } from "./context/redact-policy.js";
@@ -45,7 +44,6 @@ import { SessionUploader, type RecoveredTurn, type TraceCapabilities, type Uploa
export type { EngineReplacement, EngineTarget } from "./session-upload-observer.js";
export type CaptureLog = ArchiveLifecycleLog;
-export type ClaudeCaptureContext = Pick<NativeCaptureOptions, "sessionId" | "configDir" | "producerVersion" | "transport">;
/** Prompt bodies larger than this are not parsed for the trace (nor for attachments). */
const MAX_TRACED_REQUEST_BYTES = 4 * 1024 * 1024;
@@ -145,7 +143,6 @@ function requestPayload(body: Uint8Array | null): unknown {
}
export class CaptureHost {
- private readonly nativeCaptures = new Map<string, { identity: string; capture: NativeCapture }>();
private readonly accountId: CaptureHostOptions["accountId"];
readonly sessionUploader: SessionUploader;
readonly archive: ProjectArchiveLifecycle;
@@ -243,26 +240,9 @@ export class CaptureHost {
this.sessionUploader.startSession(sessionId, workspaceId, root, { turnsBefore });
}
- /** Awaited, durable Claude evidence. Kept outside the lossy display/event queue
- * and the scrubbed legacy upload format. The runner stops on a missing ack.
- * configDir is the runner's dedicated persistent volume, never a user home.
- */
- async captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest> {
- const owner = await this.accountId?.();
- if (!owner) throw new Error("Claude native capture requires an account owner");
- const key = `${owner}/${context.sessionId}`;
- const identity = JSON.stringify(context);
- let entry = this.nativeCaptures.get(key);
- if (entry && entry.identity !== identity) throw new Error("Claude capture source or producer changed");
- if (!entry) {
- // One immutable owner per native UUID, including across sign-out/restart.
- // Changing accounts must not silently create a second copy owned by B.
- entry = { identity, capture: new NativeCapture({ ...context, directory: join(this.stateDir, "claude-native", context.sessionId), owner, surface: "gui" }) };
- this.nativeCaptures.set(key, entry);
- }
- if (action.type === "stream") return entry.capture.recordStream(action.channel, action.bytes, action.offset);
- if (action.type === "finish") return entry.capture.finish(action);
- return entry.capture.scan();
+ /** A Claude chat (opencode-plugins/claude-provider): its uploads name Claude Code, run in the box under this engine. */
+ markClaude(sessionId: string, version: string): void {
+ this.sessionUploader.markClaude(sessionId, version);
}
/** The app's permission mode, named in the setup record of the sessions started after it (sent before each startSession). */
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index 9f23e8ee..5668abec 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -7,8 +7,7 @@
* logs and closed sessions. Everything is plain data; request and response
* bodies travel as transferred buffers.
*/
-import type { CaptureHost, ClaudeCaptureContext, EngineReplacement, EngineTarget, LateWritesGate, PromptRecord } from "./capture-host.js";
-import type { NativeCaptureAction } from "./claude-code/native-capture.js";
+import type { CaptureHost, EngineReplacement, EngineTarget, LateWritesGate, PromptRecord } from "./capture-host.js";
import type { ApprovalMode } from "./approval-mode.js";
import type { BoxCaptureInfo } from "./box/service.js";
import type { CommandEventType } from "./command-events.js";
@@ -20,7 +19,7 @@ export type CaptureStopOptions = { archiveFinals: boolean };
/** CaptureHost methods callable from the main thread, with their arguments. */
export type CaptureCalls = {
- captureClaude: [context: ClaudeCaptureContext, action: NativeCaptureAction];
+ markClaude: [sessionId: string, version: string];
startSession: [sessionId: string, workspaceId: string, root: string, turnsBefore?: number];
boxSession: [sessionId: string, box: BoxCaptureInfo | null];
sessionPolicy: [sessionId: string];
@@ -176,8 +175,8 @@ export function transferables(value: HostRequest | SerializedResponse | null): A
/** Runs one call on a host (the worker's, or the in-process fallback). */
export function invokeCapture(host: CaptureHost, call: CaptureCall): unknown {
switch (call.method) {
- case "captureClaude":
- return host.captureClaude(...call.args);
+ case "markClaude":
+ return host.markClaude(...call.args);
case "startSession":
return host.startSession(...call.args);
case "boxSession":
diff --git a/apps/server/src/claude-code/README.md b/apps/server/src/claude-code/README.md
deleted file mode 100644
index df65dcd2..00000000
--- a/apps/server/src/claude-code/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Claude native evidence
-
-The CLI and dedicated GUI Claude route use this shared native runtime. The
-pinned official Agent SDK launches Claude Code inside Docker. This path does
-not use the existing OpenCode conversation engine. Backend enablement remains
-separate from local implementation and verification.
-
-`NativeCapture` preserves the original root JSONL, every discovered child JSONL
-and its metadata, and uncoalesced transport/hook journals. It never reconstructs
-native records from OmniRush display messages or walks only a selected parent
-chain. Unknown fields and opaque thinking signatures remain in private evidence.
-Thinking text is the model's exposed summary, not hidden chain-of-thought.
-
-The source must be a session-scoped persistent `CLAUDE_CONFIG_DIR`. Only the
-requested UUID and its `subagents` files are read. Authentication files, other
-sessions and symlinks are excluded. The private store is mode 0700 with 0600
-files, content-addressed 1 MiB chunks and atomic fsynced manifests. Originals
-have no redaction pass and must not enter the legacy scrubbed collector.
-
-The caller awaits `captureClaude(context, action)` through `CaptureService`.
-Stream actions carry byte offsets; duplicate retries must match the stored
-bytes. Gaps, conflicting retries, missing acknowledgements, owner changes and
-integrity failures reject. The runner must stop on rejection. A worker restart
-can retry the same offset. A scan reconciles native files after a restart and
-before finalization. Partial lines remain exact evidence and block completion;
-replacement/truncation retains the previous generation. Unchanged files are
-not reread; obsolete append-prefix chunks are pruned after manifest durability.
-
-`finish` requires a stopped producer and successful terminal result. It checks
-root presence, JSON validity, partial lines, unmatched tool calls and child
-transcripts referenced by native launch results or supplied by the runner.
-`complete` means the captured evidence passed these checks; `replay` remains
-`unverified`. The caller must establish whole-process-tree termination and
-perform environment/checkpoint and replay checks separately.
-
-`exportTo` produces a private directory with `claude/`, `events/`, optional
-`history/`, and `native-manifest.json`. Original bytes are hash-verified during
-export. Do not claim a redacted derivative is byte-exact or resumable. Export
-only behind the session's single-writer barrier.
-
-The canonical source is this directory. Copy and check the CLI consumer with:
-
-```sh
-node scripts/sync-claude-capture.mjs /path/to/omnirush-cli
-node scripts/sync-claude-capture.mjs /path/to/omnirush-cli --check
-pnpm evals:pr specs/claude-native-capture.test.ts
-```
-
-`runtime.ts` records an immutable model/harness/image/capture contract and
-brokers only that model, including SDK children. `access.ts` validates the
-backend's session/model/contract binding and keeps short-lived tokens in host
-memory. Unknown or conflicting provider identity blocks continuation; old
-captures remain exportable without claiming retroactive model isolation.
-
-The native manifest includes a versioned QC summary: human-prompt candidates,
-synthetic events, compaction, tool/results, child transcripts, exposed thinking
-and opaque blocks. Counts never replace original bytes. `verify.py` binds replay
-to the exact ZIP and independently checks the contract and model journal.
-Exact replay, soft differences, tools-ran and unverified outcomes stay distinct.
-Missing actual shell argv/exit evidence prevents a strict shell replay claim.
-
-See `docs/claude-native-pilot.md` for the product path, backend dependencies and
-verification commands. Production enablement requires backend token/capture
-adoption, usage matching, packaged OS validation and the native conversion lane.
diff --git a/apps/server/src/claude-code/access.ts b/apps/server/src/claude-code/access.ts
index 69903198..3988b56a 100644
--- a/apps/server/src/claude-code/access.ts
+++ b/apps/server/src/claude-code/access.ts
@@ -1,7 +1,18 @@
import { createHash } from "node:crypto";
-import type { ClaudeAccess, ClaudeAuthorization, ClaudeBudgetSnapshot, ClaudeGrant } from "./runtime.js";
-import { CLAUDE_MODEL_ID } from "./sandbox-assets.js";
-import { SDK_INSTALL_PIN } from "./sandbox-lock.js";
+
+export const CLAUDE_MODEL_ID = /^claude-[a-z0-9][a-z0-9.-]{0,62}$/;
+export type ClaudeBudgetSnapshot = {
+ status: "known" | "unknown"; model: string; revision?: string;
+ asOf?: string; limitTokens?: number | null; remainingTokens?: number | null; resetAt?: string | null;
+ sessionLimitTokens?: number | null; sessionUsedTokens?: number; sessionRemainingTokens?: number | null;
+ accountLimitTokens?: number; accountRemainingTokens?: number; accountScope?: "day" | "week"; accountResetAt?: string;
+};
+export type ClaudeAccess = { owner: string; capabilities?: string[]; budget?: ClaudeBudgetSnapshot; models?: string[]; catalog?: {id: string; name: string}[]; reason?: string | null };
+export type ClaudeAuthorization = { sessionId: string; owner: string; model: string; workspaceId: string; contractSha256: string; refresh?: boolean };
+export type ClaudeGrant = {
+ owner: string; baseUrl: string; token: string; sessionId: string; model: string;
+ upstreamModel: string; client: string; bindingId: string; contractSha256: string; budget: ClaudeBudgetSnapshot;
+};
export type ClaudeDeviceRequest = (route: string, init?: { method: "POST"; body: string }, owner?: string) => Promise<Response>;
const record = (value: unknown): value is Record<string, unknown> => Boolean(value && typeof value === "object" && !Array.isArray(value));
@@ -98,12 +109,10 @@ export class ClaudeDeviceAccess {
catalog = claudeCatalog(code.catalog);
const access = record(code.access) ? code.access : {};
reason = typeof access.reason === "string" ? access.reason : code.enabled === true ? null : "not_allowed";
- // The runtime supports this exact SDK/Code pair. An enabled relay
- // with an empty model list is not permission to run it.
- const pinned = record(code.sdk) && code.sdk.package === SDK_INSTALL_PIN.package && code.sdk.version === SDK_INSTALL_PIN.version
- && code.sdk.integrity === SDK_INSTALL_PIN.integrity;
- if (code.enabled === true && pinned && Array.isArray(code.models)) models = [...new Set(code.models.filter((model): model is string => typeof model === "string" && CLAUDE_MODEL_ID.test(model)))];
- if (code.enabled === true && !models.length) reason = pinned ? "no_models" : "client_outdated";
+ // Claude Code is the provider's own pinned build (assets/claude-provider); the relay checks the client's
+ // version. An enabled relay with an empty model list is not permission to run it.
+ if (code.enabled === true && Array.isArray(code.models)) models = [...new Set(code.models.filter((model): model is string => typeof model === "string" && CLAUDE_MODEL_ID.test(model)))];
+ if (code.enabled === true && !models.length) reason = "no_models";
}
} catch { /* Failed eligibility checks deny new sessions, but never hide saved evidence. */ }
this.capability = {owner: account.id, expiresAt: Date.now() + 30_000, models, catalog, reason: models.length ? null : reason};
diff --git a/apps/server/src/claude-code/bundle-manifest.ts b/apps/server/src/claude-code/bundle-manifest.ts
deleted file mode 100644
index de587bac..00000000
--- a/apps/server/src/claude-code/bundle-manifest.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import fs from "node:fs";
-import fsp from "node:fs/promises";
-import path from "node:path";
-import { createHash } from "node:crypto";
-
-export const BUNDLE_MANIFEST = "__omnirush__/manifest.json";
-export async function writeBundleManifest(directory: string, context: {
- sessionId: string; bindingId: string; contractHash: string; engineVersion: string;
-}, payload: "claude_native" | "claude_checkpoint") {
- const files: Array<{path: string; size: number; sha256: string}> = [];
- const walk = async (dir: string): Promise<void> => {
- for (const entry of await fsp.readdir(dir, {withFileTypes: true})) {
- const file = path.join(dir, entry.name), name = path.relative(directory, file).split(path.sep).join("/");
- if (name === BUNDLE_MANIFEST) continue;
- if (entry.isDirectory()) { await walk(file); continue; }
- const hash = createHash("sha256"); let size = 0;
- if (entry.isSymbolicLink()) {
- // A ZIP symlink member contains its link text, never the target bytes.
- const bytes = Buffer.from(await fsp.readlink(file)); hash.update(bytes); size = bytes.length;
- } else if (entry.isFile()) {
- for await (const chunk of fs.createReadStream(file)) { hash.update(chunk); size += chunk.length; }
- } else throw new Error("Unsupported native archive member");
- files.push({path: name, size, sha256: hash.digest("hex")});
- }
- };
- await walk(directory);
- files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
- const manifest = {
- schema: payload === "claude_native" ? "omnirush.claude.native.v1" : "omnirush.claude.checkpoint.v1",
- session_id: context.sessionId, root_session_id: context.sessionId,
- binding_id: context.bindingId, contract_hash: context.contractHash,
- harness: "claude-code", engine_version: context.engineVersion, payload, files,
- };
- const bytes = Buffer.from(JSON.stringify(manifest) + "\n"), target = path.join(directory, BUNDLE_MANIFEST);
- await fsp.mkdir(path.dirname(target), {recursive: true, mode: 0o700});
- await fsp.writeFile(target, bytes, {mode: 0o600});
- return createHash("sha256").update(bytes).digest("hex");
-}
diff --git a/apps/server/src/claude-code/chat.test.ts b/apps/server/src/claude-code/chat.test.ts
new file mode 100644
index 00000000..d3650a16
--- /dev/null
+++ b/apps/server/src/claude-code/chat.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, test } from "bun:test";
+
+import { CLAUDE_CODE_VERSION, CLAUDE_CONTRACT, claudeChatRoute } from "./chat.js";
+import type { ClaudeAccess, ClaudeAuthorization, ClaudeGrant } from "./access.js";
+// @ts-expect-error The shared provider is plain JavaScript (opencode-plugins/claude-provider, PARITY with the CLI).
+import { CLAUDE_CODE_VERSION as PROVIDER_VERSION, CONTRACT as PROVIDER_CONTRACT } from "../opencode-plugins/claude-provider/index.js";
+
+const catalog = [{ id: "claude-opus-5-5", name: "Claude Opus 5.5" }];
+const account = (models: string[]): ClaudeAccess => ({ owner: "u1", models, catalog, reason: models.length ? null : "not_allowed" });
+
+function route(models: string[], pins = new Map<string, string>()) {
+ const asked: ClaudeAuthorization[] = [];
+ const marked: string[] = [];
+ const handle = claudeChatRoute({
+ access: async () => account(models),
+ authorize: async (context) => {
+ asked.push(context);
+ return { owner: context.owner, sessionId: context.sessionId, model: context.model, token: "orc_x", baseUrl: "https://omnirush.ai/claude/", client: "desktop/3.8.0", bindingId: "b", contractSha256: context.contractSha256, upstreamModel: context.model, budget: { status: "unknown", model: context.model } } as ClaudeGrant;
+ },
+ pin: (id) => pins.get(id) ?? null,
+ setPin: (id, model) => pins.set(id, model),
+ onClaudeChat: ({ sessionID }) => marked.push(sessionID),
+ });
+ return { handle, asked, marked, pins };
+}
+
+describe("Claude turn route", () => {
+ test("the contract is the provider's own", () => {
+ expect(CLAUDE_CODE_VERSION).toBe(PROVIDER_VERSION);
+ expect(CLAUDE_CONTRACT).toBe(PROVIDER_CONTRACT);
+ });
+
+ test("a new chat gets its relay token, bound to the chat, and is pinned to Claude", async () => {
+ const r = route(["claude-opus-5-5"]);
+ expect(await r.handle({ op: "grant", sessionID: "ses_a", model: "claude-opus-5-5", resume: false, earlier: false, directory: "/p" }))
+ .toEqual({ ok: true, token: "orc_x", baseUrl: "https://omnirush.ai/claude", client: "desktop/3.8.0" });
+ expect(r.asked).toEqual([{ owner: "u1", sessionId: "ses_a", model: "claude-opus-5-5", workspaceId: "/p", contractSha256: CLAUDE_CONTRACT }]);
+ expect(r.pins.get("ses_a")).toBe("claude-opus-5-5");
+ expect(r.marked).toEqual(["ses_a"]);
+ });
+
+ test("an account without access is told plainly, and no token is asked", async () => {
+ const r = route([]);
+ expect(await r.handle({ op: "grant", sessionID: "ses_a", model: "claude-opus-5-5" })).toEqual({ ok: false, message: "Claude Opus 5.5 isn't available on your account yet." });
+ expect(r.asked).toEqual([]);
+ });
+
+ test("one model per chat: a chat on another model, or with earlier turns and no transcript, starts Claude in a new chat", async () => {
+ const r = route(["claude-opus-5-5"], new Map([["ses_astra", "gpt-6-astra"], ["ses_titled", "gpt-6-astra"]]));
+ expect(await r.handle({ op: "grant", sessionID: "ses_astra", model: "claude-opus-5-5", earlier: true })).toMatchObject({ ok: false, message: "This chat runs on gpt-6-astra. Claude Opus 5.5 starts in a new chat." });
+ // No reply yet (its title ran on the title model first): still a fresh chat, now pinned to Claude.
+ expect(await r.handle({ op: "grant", sessionID: "ses_titled", model: "claude-opus-5-5", earlier: false })).toMatchObject({ ok: true });
+ expect(r.pins.get("ses_titled")).toBe("claude-opus-5-5");
+ expect(await r.handle({ op: "grant", sessionID: "ses_old", model: "claude-opus-5-5", earlier: true, resume: false })).toMatchObject({ ok: false });
+ // A resumed Claude chat (its transcript is there) goes on.
+ expect(await r.handle({ op: "grant", sessionID: "ses_old", model: "claude-opus-5-5", earlier: true, resume: true })).toMatchObject({ ok: true });
+ expect(r.asked.map((a) => a.sessionId)).toEqual(["ses_titled", "ses_old"]);
+ });
+
+ test("end reports the turn with the chat's grant; unknown ops and models are refused", async () => {
+ const ends: unknown[] = [];
+ const handle = claudeChatRoute({
+ access: async () => account(["claude-opus-5-5"]),
+ authorize: async (c) => ({ owner: c.owner, sessionId: c.sessionId, model: c.model, token: "t", baseUrl: "https://x", client: "c", bindingId: "b", contractSha256: c.contractSha256, upstreamModel: c.model, budget: { status: "unknown", model: c.model } }),
+ pin: () => null, setPin: () => undefined,
+ onTurnEnd: (info) => { ends.push({ ...info, grant: info.grant?.token ?? null }); },
+ });
+ await handle({ op: "grant", sessionID: "ses_a", model: "claude-opus-5-5" });
+ expect(await handle({ op: "end", sessionID: "ses_a", uuid: "u", ok: true })).toEqual({ ok: true });
+ expect(ends).toEqual([{ sessionID: "ses_a", uuid: "u", ok: true, grant: "t" }]);
+ expect(await handle({ op: "nope", sessionID: "ses_a" })).toMatchObject({ ok: false });
+ expect(await handle({ op: "grant", sessionID: "ses_a", model: "gpt-6-astra" })).toMatchObject({ ok: false });
+ expect(await handle({ op: "grant", model: "claude-opus-5-5" })).toMatchObject({ ok: false });
+ });
+});
diff --git a/apps/server/src/claude-code/chat.ts b/apps/server/src/claude-code/chat.ts
new file mode 100644
index 00000000..7a3aaa48
--- /dev/null
+++ b/apps/server/src/claude-code/chat.ts
@@ -0,0 +1,77 @@
+// The app's side of a Claude chat: the route the engine's Claude provider calls for each turn
+// (opencode-plugins/claude-provider, POST with x-omnirush-usage-key). The same rules as the CLI's
+// src/claude-code/chat.js claudeChatRoute:
+// - grant: may this chat's turn run on this Claude model? One model per chat: a chat pinned to
+// another model, or one with earlier turns and no Claude transcript, is refused (the window offers
+// a new chat); an account without access gets the "not available" message. Else the chat's
+// short-lived relay token (access.ts), and the chat is pinned to the model.
+// - end: a turn finished; its native transcript goes up (onTurnEnd).
+import { createHash } from "node:crypto";
+
+import type { ClaudeAccess, ClaudeAuthorization, ClaudeGrant } from "./access.js";
+
+/** The provider's pinned Claude Code (opencode-plugins/claude-provider CLAUDE_CODE_VERSION; claude-chat.test.ts checks both). */
+export const CLAUDE_CODE_VERSION = "2.1.306";
+/** The contract the relay token is bound to: the provider's CONTRACT. */
+export const CLAUDE_CONTRACT = createHash("sha256").update(JSON.stringify({ claude_code: CLAUDE_CODE_VERSION, provider: 1, runtime: "box" })).digest("hex");
+export const CLAUDE_PROVIDER_ID = "omnirush-claude";
+/** Shown once at a Claude chat's start (phase 1: no permission asks inside the box). */
+export const CLAUDE_AUTO_NOTE = "Claude runs in Auto mode inside the sandbox: it doesn't ask before changes yet.";
+
+export function claudeNotAllowedMessage(name: string): string {
+ return `${name} isn't available on your account yet.`;
+}
+
+export type ClaudeChatInput = { op?: unknown; sessionID?: unknown; model?: unknown; resume?: unknown; earlier?: unknown; uuid?: unknown; ok?: unknown; directory?: unknown };
+export type ClaudeChatAnswer = { ok: true; token?: string; baseUrl?: string; client?: string } | { ok: false; message: string };
+
+export function claudeChatRoute(deps: {
+ access: () => Promise<ClaudeAccess>;
+ authorize: (context: ClaudeAuthorization) => Promise<ClaudeGrant>;
+ /** The chat's pinned model (the broker's one-model-per-chat pins), and pinning it. */
+ pin: (sessionId: string) => string | null;
+ setPin: (sessionId: string, model: string) => void;
+ /** A model's display name (the account's catalog). */
+ name?: (id: string) => string;
+ onClaudeChat?: (info: { sessionID: string; model: string; grant: ClaudeGrant }) => void;
+ onTurnEnd?: (info: { sessionID: string; uuid: string; ok: boolean; grant: ClaudeGrant | null }) => Promise<void> | void;
+ log?: (level: "info" | "warn", message: string, attributes?: Record<string, unknown>) => void;
+}) {
+ const grants = new Map<string, ClaudeGrant>();
+ const refuse = (message: string): ClaudeChatAnswer => ({ ok: false, message });
+ return async function handle(input: ClaudeChatInput): Promise<ClaudeChatAnswer> {
+ const sessionID = typeof input?.sessionID === "string" ? input.sessionID : "";
+ if (!sessionID) return refuse("A Claude turn needs its chat.");
+ if (input.op === "end") {
+ try { await deps.onTurnEnd?.({ sessionID, uuid: String(input.uuid || ""), ok: input.ok === true, grant: grants.get(sessionID) ?? null }); } catch { /* best effort */ }
+ return { ok: true };
+ }
+ if (input.op !== "grant") return refuse("Unknown Claude request.");
+ const model = typeof input.model === "string" ? input.model : "";
+ let account: ClaudeAccess;
+ try { account = await deps.access(); } catch (error) { return refuse(error instanceof Error ? error.message : "Claude could not start."); }
+ const entry = account.catalog?.find((e) => e.id === model);
+ if (!entry) return refuse(`${model || "This model"} isn't offered here.`);
+ const pinned = deps.pin(sessionID);
+ // A chat keeps its model once it has replies: Claude in a chat that ran on another one is a new chat (the window
+ // offers it). A chat with no reply yet is fresh (its only other request was its title, on the title model).
+ if (input.earlier === true && input.resume !== true && pinned !== entry.id) {
+ deps.log?.("info", "claude: picked in a chat on another model", {});
+ return refuse(`This chat runs on ${pinned ? deps.name?.(pinned) ?? pinned : "another model"}. ${entry.name} starts in a new chat.`);
+ }
+ if (!account.models?.includes(entry.id)) return refuse(claudeNotAllowedMessage(entry.name));
+ let grant: ClaudeGrant;
+ try {
+ const workspaceId = typeof input.directory === "string" && input.directory ? input.directory : sessionID;
+ grant = await deps.authorize({ owner: account.owner, sessionId: sessionID, model: entry.id, workspaceId, contractSha256: CLAUDE_CONTRACT });
+ } catch (error) {
+ deps.log?.("warn", "claude: no relay token", { status: (error as { status?: unknown })?.status ?? null });
+ return refuse(error instanceof Error ? error.message : "Claude could not start.");
+ }
+ if (pinned !== entry.id) deps.setPin(sessionID, entry.id);
+ grants.set(sessionID, grant);
+ while (grants.size > 256) grants.delete(grants.keys().next().value!);
+ try { deps.onClaudeChat?.({ sessionID, model: entry.id, grant }); } catch { /* capture only */ }
+ return { ok: true, token: grant.token, baseUrl: grant.baseUrl.replace(/\/+$/, ""), client: grant.client };
+ };
+}
diff --git a/apps/server/src/claude-code/native-capture.test.ts b/apps/server/src/claude-code/native-capture.test.ts
deleted file mode 100644
index f9e462e7..00000000
--- a/apps/server/src/claude-code/native-capture.test.ts
+++ /dev/null
@@ -1,1087 +0,0 @@
-import { afterEach, expect, spyOn, test } from "bun:test";
-import fs from "node:fs";
-import os from "node:os";
-import path from "node:path";
-import { spawn, spawnSync } from "node:child_process";
-import { createHash } from "node:crypto";
-import { fileURLToPath } from "node:url";
-import { NativeCapture } from "./native-capture.js";
-import { ClaudeAccessError, ClaudeDeviceAccess } from "./access.js";
-import { CLAUDE_VERSION, MANAGED_SETTINGS, MODEL, managedSettings } from "./sandbox-assets.js";
-import { SDK_INSTALL_PIN } from "./sandbox-lock.js";
-import { ClaudeRuntime } from "./runtime.js";
-import { ApiError } from "../errors.js";
-
-test("managed Claude availability requires an enabled compatible catalog, never just relay access", async () => {
- const valid = {enabled: true, version: CLAUDE_VERSION, sdk: SDK_INSTALL_PIN, models: [MODEL]};
- for (const [code, allowed] of [
- [valid, true], [{...valid, enabled: false}, false], [{...valid, models: []}, false],
- [{...valid, models: ["claude-haiku-4-5-20251001"]}, true], [{...valid, models: ["gpt-6-astra"]}, false], [{...valid, sdk: {...SDK_INSTALL_PIN, version: "0.0.0"}}, false],
- [{...valid, sdk: null}, false], [{...valid, sdk: {...SDK_INSTALL_PIN, integrity: "sha512-wrong"}}, false],
- [{...valid, sdk: {...SDK_INSTALL_PIN, package: "@anthropic-ai/claude-code"}}, false],
- [{...valid, models: [MODEL, null]}, true], [{enabled: true}, false], [null, false],
- ] as const) {
- const routes: string[] = [];
- const access = new ClaudeDeviceAccess(async route => {
- routes.push(route);
- return Response.json(route === "device/me" ? {id: "owner"} : {claude_code: code});
- }, "cli/2.7.0");
- expect((await access.access()).capabilities?.includes("claude-code")).toBe(allowed);
- expect(routes).toEqual(["device/me", "collect/capabilities"]);
- }
-});
-
-test("access lists every Claude model the server allows and the catalog for everyone", async () => {
- const sonnet = "claude-sonnet-5-5";
- const catalog = [{id: MODEL, display_name: "Claude Opus 5.5"}, {id: sonnet, display_name: "Claude Sonnet 5.5"}, {id: "gpt-6-astra", display_name: "x"}, {id: sonnet, display_name: "dup"}];
- const read = async (code: unknown) => new ClaudeDeviceAccess(async route => Response.json(route === "device/me" ? {id: "owner"} : {claude_code: code}), "desktop/3.7.6").access();
- const allowed = await read({enabled: true, sdk: SDK_INSTALL_PIN, models: [MODEL, sonnet, sonnet], catalog, access: {mode: "staff", allowed: true, reason: null}});
- expect(allowed).toMatchObject({capabilities: ["claude-code"], models: [MODEL, sonnet], reason: null});
- expect(allowed.catalog).toEqual([{id: MODEL, name: "Claude Opus 5.5"}, {id: sonnet, name: "Claude Sonnet 5.5"}]);
- const denied = await read({enabled: false, sdk: SDK_INSTALL_PIN, models: [], catalog, access: {mode: "staff", allowed: false, reason: "not_allowed"}});
- expect(denied).toMatchObject({capabilities: [], models: [], reason: "not_allowed"});
- expect(denied.catalog?.map(entry => entry.id)).toEqual([MODEL, sonnet]);
- expect((await read({enabled: true, sdk: null, models: [sonnet], catalog})).reason).toBe("client_outdated");
-});
-
-test("managed settings pin each session's own model; Opus keeps its original policy", () => {
- expect(managedSettings(MODEL)).toBe(MANAGED_SETTINGS);
- expect(JSON.parse(MANAGED_SETTINGS).deniedModels).toEqual(["sonnet", "haiku"]);
- expect(JSON.parse(managedSettings("claude-sonnet-5-5"))).toMatchObject({availableModels: ["claude-sonnet-5-5"], deniedModels: ["opus", "haiku"]});
-});
-
-test("managed grants reject provider keys and zero refresh, refresh from request time, and revoke the root", async () => {
- const context = {owner: "owner", sessionId: "00000000-0000-4000-8000-000000000001", workspaceId: "project", model: MODEL, contractSha256: "a".repeat(64)};
- const response = {token: "orc_" + "a".repeat(43), expires_in: 900, refresh_after: 600,
- base_url: "https://omnirush.ai/claude", budget: null,
- binding: {binding_id: "00000000-0000-4000-8000-000000000002", session_id: context.sessionId,
- root_session_id: context.sessionId, model: MODEL, upstream_model: MODEL, contract_hash: context.contractSha256}};
- for (const fault of [{token: "provider-key-fixture"}, {refresh_after: 0}, {refresh_after: 901}]) {
- const access = new ClaudeDeviceAccess(async () => Response.json({...response, ...fault}), "desktop/3.7.5");
- await expect(access.authorize(context)).rejects.toThrow("Invalid short-lived Claude authorization");
- }
- let now = 100_000, mints = 0;
- const clock = spyOn(Date, "now").mockImplementation(() => now);
- const requests: Array<{route: string; body: unknown; owner?: string}> = [];
- const access = new ClaudeDeviceAccess(async (route, init, owner) => {
- requests.push({route, body: JSON.parse(init!.body), owner});
- if (route.endsWith("/revoke")) return new Response(null, {status: 204});
- mints++; now += 2_000; // Mint latency consumes token lifetime.
- return Response.json(response);
- }, "desktop/3.7.5");
- try {
- const first = await access.authorize(context);
- expect(first.baseUrl).toBe("https://omnirush.ai/claude");
- expect(first.budget?.status).toBe("unknown");
- now = 699_999; await access.authorize(context); expect(mints).toBe(1);
- now = 700_000; await access.authorize(context); expect(mints).toBe(2);
- await access.authorize({...context, refresh: true}); expect(mints).toBe(3);
- expect(requests[0]).toMatchObject({route: "device/claude-token", owner: "owner", body: {
- session_id: context.sessionId, model: MODEL, contract_hash: context.contractSha256, client: "desktop/3.7.5",
- }});
- await access.revoke(context);
- expect(requests.at(-1)).toEqual({route: "device/claude-token/revoke", owner: "owner", body: {session_id: context.sessionId}});
- await access.authorize(context); expect(mints).toBe(4);
- } finally { clock.mockRestore(); }
-});
-
-test("managed access distinguishes retryable capacity from terminal allowance without exposing response bodies", async () => {
- const context = {owner: "owner", sessionId: "00000000-0000-4000-8000-000000000001", workspaceId: "project", model: MODEL, contractSha256: "a".repeat(64)};
- for (const retry of ["true", "false"]) {
- let requests = 0;
- const access = new ClaudeDeviceAccess(async () => {
- requests++;
- return Response.json({credential: "private-fixture-canary"}, {status: 429, headers: {"x-should-retry": retry, "retry-after": "30"}});
- }, "cli/2.7.0");
- try { await access.authorize(context); throw new Error("Expected rejection"); }
- catch (error) {
- expect(error).toBeInstanceOf(ClaudeAccessError);
- if (!(error instanceof ClaudeAccessError)) throw error;
- expect(error.message).toContain(retry === "false" ? "allowance" : "busy");
- expect(error.message).not.toContain("private-fixture-canary");
- expect(error.responseHeaders["x-should-retry"]).toBe(retry);
- expect(error.retryAfter).toBe("30");
- }
- expect(requests).toBe(1);
- }
-});
-
-test("session broker re-mints once on rejected authentication and never replays quota or server failures", async () => {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-broker-contract-")); roots.push(root);
- const id = "00000000-0000-4000-8000-000000000001", contractSha256 = "a".repeat(64);
- let status = 401, attempts = 0, successful = 0, authorizations = 0, refreshes = 0, first401 = true;
- let transportCalls = 0;
- const relay = Bun.serve({hostname: "127.0.0.1", port: 0, async fetch(req) {
- attempts++;
- expect(req.headers.get("x-api-key")).toMatch(/^orc_/);
- expect(req.headers.get("x-omnirush-session-id")).toBe(id);
- expect(req.headers.get("x-omnirush-box")).toBe("1");
- expect(req.headers.get("x-omnirush-client")).toBe("desktop/3.7.5");
- if (status === 200 || status === 401 && !first401) {
- successful++;
- return Response.json({type: "message", model: MODEL, content: [], stop_reason: "end_turn"});
- }
- first401 = false;
- return Response.json({type: "error", error: {type: "api_error", message: "fixture"}}, {status,
- headers: {"x-should-retry": status === 429 ? "false" : "true", "retry-after": "30"}});
- }});
- const runtime = new ClaudeRuntime({fetch: (input, init) => {
- transportCalls++;
- expect(input).toBe(`http://127.0.0.1:${relay.port}/v1/messages`);
- expect(init?.redirect).toBe("error");
- expect(init?.signal?.aborted).toBe(false);
- return globalThis.fetch(input, init);
- }, directory: root, surface: "gui", access: async () => ({owner: "owner", capabilities: ["claude-code"], models: [MODEL]}),
- authorize: async context => {
- authorizations++; if (context.refresh) refreshes++;
- return {owner: "owner", sessionId: id, model: MODEL, upstreamModel: MODEL, client: "desktop/3.7.5",
- baseUrl: `http://127.0.0.1:${relay.port}`, token: "orc_" + "a".repeat(43), contractSha256};
- }});
- // Isolate the actual HTTP broker from Docker setup; private access is confined to this boundary test.
- const session = {owner: "owner", id, model: MODEL, workspaceId: "project", contract: {}, contractSha256, turns: []};
- const broker = await Reflect.get(runtime, "broker").call(runtime, session, () => {});
- const endpoint = broker.baseUrl.replace("host.docker.internal", "127.0.0.1") + "/v1/messages";
- const request = () => fetch(endpoint, {method: "POST", headers: {authorization: `Bearer ${broker.token}`, "content-type": "application/json"},
- body: JSON.stringify({model: MODEL, messages: [], max_tokens: 1}), signal: AbortSignal.timeout(5_000)});
- try {
- const accepted = await request(); expect(accepted.status).toBe(200); await accepted.arrayBuffer();
- expect({attempts, successful, authorizations, refreshes}).toEqual({attempts: 2, successful: 1, authorizations: 2, refreshes: 1});
- expect(transportCalls).toBe(2);
- const journal = fs.readFileSync(path.join(Reflect.get(runtime, "dir").call(runtime, "owner", id), "policy", "model-requests.jsonl"), "utf8").trim().split("\n").map(line => JSON.parse(line));
- expect(journal.map(event => event.type)).toEqual(["request", "provider_identity", "response"]);
- expect(journal.at(-1)).toMatchObject({status: 200, authorizationFailures: [401], completed: true});
- for (status of [429, 503]) {
- const before = attempts, renewed = refreshes;
- const denied = await request(); expect(denied.status).toBe(status);
- expect(denied.headers.get("x-should-retry")).toBe(status === 429 ? "false" : "true");
- expect(denied.headers.get("retry-after")).toBe("30"); await denied.arrayBuffer();
- expect(attempts).toBe(before + 1); expect(refreshes).toBe(renewed); expect(successful).toBe(1);
- expect(transportCalls).toBe(attempts);
- }
- } finally { await broker.close(); relay.stop(true); }
-});
-
-const roots: string[] = [];
-afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
-function fixture() {
- const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "claude-native-"))); roots.push(root);
- const options = { directory: path.join(root, "capture"), configDir: path.join(root, "config"), sessionId: "00000000-0000-4000-8000-000000000001", producerVersion: "fixture", surface: "gui" as const, transport: "sdk" as const, owner: "actor-a" };
- const project = path.join(options.configDir, "projects", "-workspace");
- fs.mkdirSync(project, { recursive: true });
- const source = path.join(project, `${options.sessionId}.jsonl`);
- const capture = new NativeCapture(options);
- return { root, options, project, source, capture };
-}
-const line = (value: unknown) => JSON.stringify(value) + "\n";
-const user = (uuid: string) => ({ type: "user", uuid, parentUuid: null, message: { content: "hello" } });
-const finish = { type: "finish" as const, processStopped: true, successfulResult: true };
-
-test("copies every branch, unknown field, thinking signature and five child files byte for byte; excludes auth and other sessions", () => {
- const f = fixture();
- const original = line(user("prompt")) + line({ type: "assistant", uuid: "a", parentUuid: "prompt", future: { keep: true }, message: { content: [{ type: "thinking", thinking: "Visible summary", signature: "opaque-fixture" }, { type: "tool_use", id: "one", name: "Read" }, { type: "tool_use", id: "two", name: "Read" }] } })
- + line({ type: "user", uuid: "side", parentUuid: "a", message: { content: [{ type: "tool_result", tool_use_id: "one", content: "branch one" }] } })
- + line({ type: "user", uuid: "selected", parentUuid: "a", message: { content: [{ type: "tool_result", tool_use_id: "two", content: "branch two" }] } })
- + line({ type: "api-request-blob", message: { content: [{ type: "tool_use", id: "cached-context-only", name: "Bash" }, {type: "thinking", thinking: "Repeated context"}] } });
- fs.writeFileSync(f.source, original);
- fs.writeFileSync(path.join(f.project, "another-session.jsonl"), "DO_NOT_EXPORT_OTHER_SESSION");
- fs.writeFileSync(path.join(f.options.configDir, "credentials.json"), "DO_NOT_EXPORT_AUTH");
- const agents = ["child1", "child2", "child3", "child4", "child5"];
- const children = path.join(f.project, f.options.sessionId, "subagents"); fs.mkdirSync(children, { recursive: true });
- for (const agent of agents) {
- fs.writeFileSync(path.join(children, `agent-${agent}.jsonl`), line(user(agent)));
- fs.writeFileSync(path.join(children, `agent-${agent}.meta.json`), '{ "agentType": "test", "unknown": 5 }');
- }
- const manifest = f.capture.finish({ ...finish, expectedAgents: agents });
- expect(manifest.status).toBe("complete"); expect(manifest.replay).toBe("unverified");
- expect(manifest.files).toHaveLength(11);
- expect(manifest.qc).toMatchObject({ schema: 1, humanPromptCandidates: 1, childPromptRecords: 5, exposedThinkingBlocks: 1, opaqueThinkingBlocks: 0, reviewRequired: false });
- expect(manifest.files.find((file) => file.path.endsWith(`${f.options.sessionId}.jsonl`))).toMatchObject({ toolCalls: 2, toolResults: 2, thinkingBlocks: 1, pendingTools: [] });
- const out = path.join(f.root, "export"); f.capture.exportTo(out);
- expect(fs.readFileSync(path.join(out, "claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
- expect(fs.readdirSync(path.join(out, "claude/projects/-workspace"))).toEqual([f.options.sessionId, `${f.options.sessionId}.jsonl`]);
- expect(fs.existsSync(path.join(out, "credentials.json"))).toBe(false);
-});
-
-test("partial native lines survive restart and prevent completeness until their real bytes arrive", () => {
- const f = fixture(); fs.writeFileSync(f.source, line(user("a")) + '{"type":"user","message":');
- const first = f.capture.finish(finish);
- expect(first.status).toBe("incomplete"); expect(first.files[0].tailBytes).toBeGreaterThan(0);
- const recovered = new NativeCapture(f.options);
- fs.appendFileSync(f.source, '{"content":"continued"}}\n');
- expect(recovered.finish(finish).status).toBe("complete");
- expect(recovered.verify().files[0].completeLines).toBe(2);
-});
-
-test("durable stream retries are idempotent, reject conflicting bytes and gaps, and recover an unacknowledged partial write", () => {
- const f = fixture(), bytes = Buffer.from(line(user("stream")));
- f.capture.recordStream("sdk", bytes, 0);
- const recovered = new NativeCapture(f.options);
- expect(recovered.recordStream("sdk", bytes, 0).streams.sdk).toBe(bytes.length);
- expect(() => recovered.recordStream("sdk", Buffer.from("bad"), 0)).toThrow("Conflicting");
- expect(() => recovered.recordStream("sdk", bytes, bytes.length + 1)).toThrow("offset gap");
- const next = Buffer.from(line(user("next")));
- fs.appendFileSync(path.join(f.options.directory, "events/sdk.jsonl"), next.subarray(0, 5));
- recovered.recordStream("sdk", next, bytes.length);
- expect(fs.readFileSync(path.join(f.options.directory, "events/sdk.jsonl"))).toEqual(Buffer.concat([bytes, next]));
-});
-
-test("rewritten transcripts retain prior generations and corrupt or missing durable chunks reject recovery", () => {
- const f = fixture(), original = line(user("original")); fs.writeFileSync(f.source, original); f.capture.scan();
- fs.writeFileSync(f.source, line(user("replacement"))); f.capture.scan();
- const manifest = f.capture.verify(); expect(manifest.history).toHaveLength(1);
- const out = path.join(f.root, "export"); f.capture.exportTo(out);
- expect(fs.readFileSync(path.join(out, "history/0/claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
- fs.unlinkSync(path.join(f.options.directory, "chunks", manifest.history[0].chunks[0].sha256));
- expect(() => new NativeCapture(f.options)).toThrow();
-});
-
-test("missing children, unmatched calls and a live or failed producer cannot yield complete capture", () => {
- const f = fixture(); fs.writeFileSync(f.source, line({ type: "assistant", message: { content: [{ type: "tool_use", id: "pending", name: "Bash" }] } }) + line({ type: "user", toolUseResult: { status: "async_launched", agentId: "native-child" }, message: { content: [] } }));
- const manifest = f.capture.finish({ ...finish, processStopped: false, successfulResult: false, expectedAgents: ["missing"] });
- expect(manifest.status).toBe("incomplete");
- expect(manifest.issues).toContain("producer_still_running");
- expect(manifest.issues).toContain("successful_result_missing");
- expect(manifest.issues).toContain("child_transcript_missing:missing");
- expect(manifest.issues).toContain("child_transcript_missing:native-child");
- expect(manifest.issues.some((issue) => issue.startsWith("pending_tools:"))).toBe(true);
-});
-
-test("append scans keep storage proportional to referenced chunks, while invalid UTF-8 remains incomplete", () => {
- const f = fixture(); fs.writeFileSync(f.source, line(user("first")));
- for (let turn = 0; turn < 8; turn++) { fs.appendFileSync(f.source, line(user(`turn-${turn}`))); f.capture.scan(); }
- expect(fs.readdirSync(path.join(f.options.directory, "chunks"))).toHaveLength(1);
- fs.appendFileSync(f.source, Buffer.concat([Buffer.from('{"message":{"content":"'), Buffer.from([0xff]), Buffer.from('"}}\n')]));
- expect(f.capture.finish(finish).status).toBe("incomplete");
- expect(f.capture.verify().files[0].invalidLines).toBeGreaterThan(0);
-});
-
-test("owner, source, version and transcript symlink changes fail closed", () => {
- const f = fixture();
- expect(() => new NativeCapture({ ...f.options, owner: "actor-b" })).toThrow("identity mismatch");
- expect(() => new NativeCapture({ ...f.options, producerVersion: "different" })).toThrow("identity mismatch");
- expect(() => new NativeCapture({ ...f.options, configDir: f.root })).toThrow("identity mismatch");
- const secret = path.join(f.root, "secret"); fs.writeFileSync(secret, "private"); fs.symlinkSync(secret, f.source);
- expect(() => f.capture.scan()).toThrow("symlinks");
- expect(f.capture.verify().files).toHaveLength(0);
-});
-
-test("quality distinguishes human candidates, synthetic compaction and notifications, opaque reasoning and unknown native semantics without rewriting them", () => {
- const f = fixture();
- const original = line(user("human")) + line(user("human"))
- + line({ ...user("compact"), isCompactSummary: true })
- + line({ ...user("notice"), message: { content: "<task-notification>background result</task-notification>" } })
- + line({ type: "system", subtype: "compact_boundary", uuid: "boundary" })
- + line({ type: "assistant", uuid: "answer", message: { content: [{ type: "thinking", thinking: "exposed", signature: "sig" }, { type: "redacted_thinking", data: "opaque" }, { type: "future_block", payload: { preserve: true } }] } })
- + line({ type: "future_record", payload: { preserve: true } });
- fs.writeFileSync(f.source, original);
- const manifest = f.capture.finish(finish);
- expect(manifest.status).toBe("complete");
- expect(manifest.qc).toMatchObject({ humanPromptCandidates: 1, syntheticUserRecords: 2, compactionRecords: 2, exposedThinkingBlocks: 1, opaqueThinkingBlocks: 1, unknownRecordTypes: ["future_record"], unknownBlockTypes: ["future_block"], reviewRequired: true });
- const out = path.join(f.root, "export"); f.capture.exportTo(out);
- expect(fs.readFileSync(path.join(out, "claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
-});
-
-test("orphan results and conflicting execution identities remain captured but cannot be called complete", () => {
- const f = fixture();
- const original = line({ type: "assistant", uuid: "a", message: { content: [{ type: "tool_use", id: "same", name: "Read", input: { file_path: "/one" } }] } })
- + line({ type: "assistant", uuid: "b", message: { content: [{ type: "tool_use", id: "same", name: "Read", input: { file_path: "/two" } }] } })
- + line({ type: "user", uuid: "c", message: { content: [{ type: "tool_result", tool_use_id: "orphan", content: "not fabricated" }] } });
- fs.writeFileSync(f.source, original);
- const manifest = f.capture.finish(finish);
- expect(manifest.status).toBe("incomplete");
- expect(manifest.issues.some((issue) => issue.startsWith("orphan_results:"))).toBe(true);
- expect(manifest.issues.some((issue) => issue.startsWith("conflicting_tool_identity:"))).toBe(true);
- const out = path.join(f.root, "export"); f.capture.exportTo(out);
- expect(fs.readFileSync(path.join(out, "claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
-});
-
-function checkReplay(script: string): void {
- const adapter = fileURLToPath(new URL("../../../../tools/claude-native/verify.py", import.meta.url));
- const result = spawnSync("python3", ["-c", "import importlib.util, sys\nspec=importlib.util.spec_from_file_location('native_verify',sys.argv[1])\nm=importlib.util.module_from_spec(spec)\nspec.loader.exec_module(m)\n" + script, adapter], { encoding: "utf8" });
- expect({ status: result.status, error: result.stderr }).toEqual({ status: 0, error: "" });
-}
-
-test("native replay preserves command and hook cwd, reports unobserved shell evidence as soft, and never promotes ran-only or missing coverage", () => {
- checkReplay(`
-import subprocess, types
-seen=[]
-def run(argv, **kwargs):
- seen.append(argv)
- return subprocess.CompletedProcess(argv,0,b'ok\\n',b'')
-m.subprocess.run=run
-call={'id':'one','tool':'Bash','input':{'command':'sudo -n printf ok'},'native_cwd':'/outside/workspace','status':'completed','meta':{'native_tool_result':{'stdout':'ok','stderr':''}}}
-out=m.native_bash(types.SimpleNamespace(classify=lambda cmd:'command'),'container',call,{})
-assert len(seen)==1 and seen[0][-1]=='sudo -n printf ok'
-assert seen[0][seen[0].index('-w')+1]=='/outside/workspace'
-assert out['outcome']=='diverge-soft' and out['actual_shell_argv_observed'] is False
-assert out['numeric_recorded_exit'] is None
-assert m.replay_verdict({'per_call':[['one','match']]},{},[call])==('VERIFIED',True,[])
-assert m.replay_verdict({'per_call':[['one','diverge-soft']]},{},[call])[0]=='VERIFIED_WITH_SOFT_DIFFS'
-assert m.replay_verdict({'per_call':[['one','tool-worked']]},{},[call])[:2]==('TOOLS_RAN',False)
-assert m.replay_verdict({'per_call':[]},{},[call])[:2]==('UNVERIFIED',False)
-assert m.replay_verdict({'per_call':[['one','match']]},{'/workspace':['lost']},[call])[:2]==('DIFFERS',False)
-`);
-});
-
-test("native literal replay never invents redacted bytes or loosely matches edits", () => {
- checkReplay(`
-import json, pathlib, subprocess, tempfile
-with tempfile.TemporaryDirectory() as directory:
- file=pathlib.Path(directory)/'example.py'
- content='@toolkit.register(\\ncredentials: [credential, ...current.credentials]\\n[REDACTED]\\n'
- result=subprocess.run([sys.executable,'-c',m.NATIVE_EDIT],input=json.dumps({'tool':'Write','input':{'file_path':str(file),'content':content}}).encode(),capture_output=True)
- assert result.returncode==0 and file.read_text()==content
- result=subprocess.run([sys.executable,'-c',m.NATIVE_EDIT],input=json.dumps({'tool':'Edit','input':{'file_path':str(file),'old_string':'@toolkit. register(','new_string':'invented'}}).encode(),capture_output=True)
- assert result.returncode!=0 and file.read_text()==content
- result=subprocess.run([sys.executable,'-c',m.NATIVE_EDIT],input=json.dumps({'tool':'Edit','input':{'file_path':str(file),'old_string':'[REDACTED]','new_string':'literal placeholder in source'}}).encode(),capture_output=True)
- assert result.returncode==0 and file.read_text()==content.replace('[REDACTED]','literal placeholder in source')
-`);
-});
-
-test("native replay derives executions from preserved generations and rejects result identities without calls", () => {
- checkReplay(`
-import io, json, zipfile
-def lines(items): return ''.join(json.dumps(x)+'\\n' for x in items)
-tool={'id':'one','type':'tool_use','name':'Write','input':{'file_path':'/workspace/x','content':'original'}}
-result={'type':'tool_result','tool_use_id':'one','content':'written'}
-events=[{'type':'assistant','uuid':'a','message':{'content':[tool]}},{'type':'user','uuid':'b','message':{'content':[result]}}]
-hooks=[{'time':'2026-01-01T00:00:00Z','turn':1,'input':{'hook_event_name':kind,'tool_use_id':'one','tool_name':'Write','tool_input':tool['input'],'cwd':'/workspace'}} for kind in ('PreToolUse','PostToolUse')]
-file='claude/projects/-workspace/root.jsonl'
-manifest={'files':[{'path':file}],'history':[{'path':file,'generation':0}]}
-def bundle(records):
- data=io.BytesIO()
- with zipfile.ZipFile(data,'w') as z:
- z.writestr('events/hooks.jsonl',lines(hooks));z.writestr(file,lines([{'type':'user','message':{'content':'compacted'}}]));z.writestr('history/0/'+file,lines(records))
- return zipfile.ZipFile(data)
-with bundle(events) as z:
- calls=m.calls_from(z,{'id':'root'},manifest)
- assert len(calls)==1 and calls[0]['input']==tool['input']
- assert calls[0]['source']['path'].startswith('history/0/')
-with bundle(events+[{'type':'user','message':{'content':[dict(result,tool_use_id='orphan')]}}]) as z:
- try: m.calls_from(z,{'id':'root'},manifest)
- except ValueError as error: assert 'complete set' in str(error)
- else: raise AssertionError('orphan result accepted')
-`);
-});
-
-test("native replay keeps corroborated forced Agent model omission explicit and soft; other differences fail closed", () => {
- checkReplay(`
-import copy, io, json, zipfile
-def lines(rows): return ''.join(json.dumps(row)+'\\n' for row in rows).encode()
-model='claude-opus-fixture'
-session={'id':'root','owner':'owner','workspaceId':'workspace','model':model,'sdkVersion':'0.3.306','claudeVersion':'2.1.306','base':{'image':'sha256:base'},'authorization':{'upstreamModel':model}}
-contract={'schema':1,'sessionId':'root','owner':'owner','workspaceId':'workspace','model':model,'execution':{'baseImage':'sha256:base','kind':'docker','os':'linux','shell':'/bin/bash','workingDirectory':'/workspace'},'harness':{'name':'claude-code','sdkVersion':'0.3.306','claudeVersion':'2.1.306','controllerSha256':'fd1d3a901953f38fc866d6ce62ec5f80ef247f878d029ae47bb581832b26ab00'},'capture':{'scope':'managed-inference','modelIsolation':'exact'}}
-session['contract']=contract;session['contractSha256']=m.sha(json.dumps(contract,separators=(',',':')).encode())
-journal=[{'schema':1,'sessionId':'root','type':'request','requestId':'r','route':'messages','requestedModel':model,'resolvedModel':model,'contractSha256':session['contractSha256']},{'schema':1,'sessionId':'root','type':'provider_identity','requestId':'r','requestedModel':model,'resolvedModel':model,'providerModel':model,'source':'response-body'},{'schema':1,'sessionId':'root','type':'response','requestId':'r','status':200,'completed':True,'streamComplete':True,'identity':'reported','providerModels':[model]}]
-session['modelIsolation']={'status':'observed','expectedModel':model,'resolvedModel':model,'observedModels':[model],'evidenceSha256':m.sha(lines(journal)),'evidenceBytes':len(lines(journal))}
-requested={'description':'check','prompt':'preserve exactly','subagent_type':'general-purpose','model':'haiku'}
-effective={k:v for k,v in requested.items() if k!='model'}
-tool={'type':'tool_use','id':'one','name':'Agent','input':requested}
-result={'type':'tool_result','tool_use_id':'one','content':'launched'}
-native={'status':'async_launched','agentId':'child','resolvedModel':model}
-events=[{'type':'assistant','uuid':'a','message':{'content':[tool]}},{'type':'user','uuid':'b','message':{'content':[result]},'toolUseResult':native}]
-hooks=[{'time':'2026-01-01T00:00:00Z','turn':1,'input':{'hook_event_name':kind,'tool_use_id':'one','tool_name':'Agent','tool_input':copy.deepcopy(effective),'cwd':'/workspace'}} for kind in ('PreToolUse','PostToolUse')]
-hooks[1]['input']['tool_response']=copy.deepcopy(native)
-sdk=[dict(events[0],session_id='root'),{'type':'user','message':{'content':[result]},'tool_use_result':native},{'type':'assistant','parent_tool_use_id':'one','agent_id':'child','message':{'model':model,'content':[{'type':'text','text':'done'}]}}]
-file='claude/projects/-workspace/root.jsonl'
-base={'session':session,'events':events,'hooks':hooks,'sdk':sdk,'journal':journal}
-def calls(data):
- buf=io.BytesIO();stream=lines(data['sdk'])
- manifest={'files':[{'path':file},{'path':'events/sdk.jsonl','sha256':m.sha(stream),'bytes':len(stream)}]}
- if data.get('bad_sdk_hash'): manifest['files'][1]['sha256']='0'*64
- if data.get('unmanifested_sdk'): manifest['files'].pop()
- with zipfile.ZipFile(buf,'w') as z:
- z.writestr(file,lines(data['events']));z.writestr('events/hooks.jsonl',lines(data['hooks']))
- if not data.get('missing_sdk'): z.writestr('events/sdk.jsonl',stream)
- z.writestr('policy/contract.json',json.dumps({'contract':data['session']['contract'],'sha256':data['session']['contractSha256']}))
- z.writestr('policy/model-requests.jsonl',lines(data['journal']))
- with zipfile.ZipFile(buf) as z: return m.calls_from(z,data['session'],manifest)
-before=copy.deepcopy(base)
-accepted=calls(base);call=accepted[0]
-assert base==before and call['input']==requested and call['native_effective_input']==effective
-assert call['native_input_normalization']['requested_input']['model']=='haiku'
-assert call['native_input_normalization']['strict_verified'] is False
-assert all(call['native_input_normalization']['sdk_witnesses'].values())
-selected=accepted+[{'id':'write'}];replay={'per_call':[['one','subagent'],['write','match']]}
-assert m.replay_verdict(replay,{},selected)==('VERIFIED_WITH_SOFT_DIFFS',True,[])
-assert m.replay_verdict(replay,{'/workspace':['changed']},selected)[0]=='DIFFERS'
-assert m.replay_verdict({'per_call':[['one','subagent']]},{},selected)[0]=='UNVERIFIED'
-def reject(change):
- data=copy.deepcopy(base);change(data)
- try: calls(data)
- except ValueError: pass
- else: raise AssertionError('uncorroborated or tampered omission accepted')
-for field in ('prompt','description','subagent_type','extra'):
- reject(lambda d,field=field:d['hooks'][0]['input']['tool_input'].update({field:'altered'}))
-reject(lambda d:d['hooks'][0]['input'].update(tool_name='Task'))
-reject(lambda d:d['hooks'][1]['input']['tool_input'].update(model='haiku'))
-reject(lambda d:d['hooks'][1]['input']['tool_input'].update(prompt='altered'))
-reject(lambda d:d['hooks'][1]['input']['tool_response'].update(resolvedModel='haiku'))
-reject(lambda d:d['hooks'][1]['input'].update(hook_event_name='PostToolUseFailure'))
-reject(lambda d:d['session']['contract']['harness'].update(controllerSha256='0'*64))
-reject(lambda d:d['session'].update(sdkVersion='future'))
-reject(lambda d:d['session'].pop('modelIsolation'))
-reject(lambda d:d['journal'][1].update(providerModel='haiku'))
-reject(lambda d:d.update(sdk=[]))
-reject(lambda d:d.update(sdk=d['sdk'][:-1]))
-reject(lambda d:d['sdk'][2]['message'].update(model='haiku'))
-reject(lambda d:d['sdk'][2].update(agent_id='wrong-child'))
-reject(lambda d:d['sdk'][0].update(session_id='another-session'))
-reject(lambda d:d['sdk'][1].update(tool_use_result={}))
-reject(lambda d:d.update(sdk=[dict(d['sdk'][0],message={'content':[dict(tool,input=dict(requested,model='sonnet'))]})]+d['sdk'][1:]))
-for flag in ('missing_sdk','unmanifested_sdk','bad_sdk_hash'): reject(lambda d,flag=flag:d.update({flag:True}))
-# Exact inputs retain the existing path without requiring normalization witnesses.
-exact=copy.deepcopy(base)
-for hook in exact['hooks']: hook['input']['tool_input']=copy.deepcopy(requested)
-assert 'native_input_normalization' not in calls(exact)[0]
-`);
-});
-
-test("model provenance is checked independently of replay and never inferred for legacy or mixed-model evidence", () => {
- checkReplay(`
-import copy, io, json, zipfile
-session={'id':'session','owner':'owner','workspaceId':'workspace','model':'claude-opus-fixture','sdkVersion':'sdk','claudeVersion':'cli','base':{'image':'sha256:base'},'authorization':{'upstreamModel':'claude-opus-fixture'}}
-contract={'schema':1,'sessionId':'session','owner':'owner','workspaceId':'workspace','model':session['model'],'execution':{'baseImage':'sha256:base','kind':'docker','os':'linux','shell':'/bin/bash','workingDirectory':'/workspace'},'harness':{'name':'claude-code','sdkVersion':'sdk','claudeVersion':'cli'},'capture':{'scope':'managed-inference','modelIsolation':'exact'}}
-session['contract']=contract;session['contractSha256']=m.sha(json.dumps(contract,separators=(',',':')).encode())
-resolved=session['authorization']['upstreamModel']
-events=[{'type':'request','requestId':'r','route':'messages','requestedModel':session['model'],'resolvedModel':resolved,'contractSha256':session['contractSha256']},{'type':'provider_identity','requestId':'r','requestedModel':session['model'],'resolvedModel':resolved,'providerModel':resolved,'source':'response-body'},{'type':'response','requestId':'r','status':200,'completed':True,'streamComplete':True,'identity':'reported','providerModels':[resolved]}]
-def bundle(records):
- data=io.BytesIO();raw=''.join(json.dumps(dict(schema=1,sessionId='session',**x))+'\\n' for x in records).encode()
- session['modelIsolation']={'status':'observed','expectedModel':session['model'],'resolvedModel':resolved,'observedModels':[resolved],'evidenceSha256':m.sha(raw),'evidenceBytes':len(raw)}
- with zipfile.ZipFile(data,'w') as z:
- z.writestr('policy/contract.json',json.dumps({'contract':contract,'sha256':session['contractSha256']}));z.writestr('policy/model-requests.jsonl',raw)
- return zipfile.ZipFile(data)
-with bundle(events) as z:
- assert m.model_evidence(z,session)['eligible'] is True
- session['authorization']['upstreamModel']='claude-haiku-fixture'
- session['modelIsolation']['resolvedModel']='claude-haiku-fixture'
- assert m.model_evidence(z,session)['blockers']==['bound_upstream_model_mismatch']
- session['authorization']['upstreamModel']=resolved
- session['modelIsolation']['resolvedModel']=resolved
- session['modelIsolation']['evidenceSha256']='0'*64
- assert m.model_evidence(z,session)['status']=='invalid'
-mixed=copy.deepcopy(events);mixed[1]['providerModel']='another-model'
-with bundle(mixed) as z:
- result=m.model_evidence(z,session)
- assert result['status']=='invalid' and not result['eligible']
-with bundle(events[:-1]) as z:
- assert 'model_journal_incomplete' in m.model_evidence(z,session)['blockers']
-refreshed=copy.deepcopy(events);refreshed[-1]['authorizationFailures']=[401]
-with bundle(refreshed) as z:
- assert m.model_evidence(z,session)['eligible'] is True
-unknown=copy.deepcopy(events);unknown.insert(1,{'type':'authorization_retry','requestId':'r','status':401})
-with bundle(unknown) as z:
- assert 'unknown_model_event' in m.model_evidence(z,session)['blockers']
-with bundle(events) as z:
- assert m.model_evidence(z,{'id':'legacy'})['status']=='legacy_unverified'
-`);
-});
-
-test("canonical sealed archives resume native uploads, preserve ZIP bytes and keep checkpoint gates independent", async () => {
- const {createHash} = await import("node:crypto");
- const {zstdDecompressSync} = await import("node:zlib");
- const {parseNativeCaptureCapabilities, uploadNativeBundle} = await import("./upload.js");
- const {writeBundleManifest} = await import("./bundle-manifest.js");
- const {zipDirectory} = await import("./zip.js");
- const {ArchiveUploader} = await import("../session-archive/upload.js");
- const {SealStream, sealKeyring, openSealedBuffer} = await import("../session-archive/seal.js");
- const {tarMemberHeader} = await import("../session-archive/pack.js");
- const f = fixture(), nativeDirectory = path.join(f.root, "native-export"), stateDirectory = path.join(f.root, "uploads");
- fs.writeFileSync(f.source, line(user("first"))); f.capture.finish(finish); f.capture.exportTo(nativeDirectory);
- const raw = Buffer.from('[email protected](\ncredentials = ["value"]\n{"type":"redacted_thinking","data":"opaque"}\n');
- fs.writeFileSync(path.join(nativeDirectory, "literal-evidence.txt"), raw);
- const binding = {sessionId: f.options.sessionId, bindingId: "01928f3e-7c41-7b2a-9d05-4e6f8a1b2c3d", contractHash: "a".repeat(64), engineVersion: "2.1.306"};
- await writeBundleManifest(nativeDirectory, binding, "claude_native");
- const checkpointDirectory = path.join(f.root, "checkpoint"); fs.cpSync(nativeDirectory, checkpointDirectory, {recursive: true});
- const checkpointManifestSha256 = await writeBundleManifest(checkpointDirectory, binding, "claude_checkpoint");
- const checkpointFile = path.join(f.root, "checkpoint.zip"); await zipDirectory(checkpointDirectory, checkpointFile);
- const keyring = sealKeyring([Buffer.alloc(32, 7)]), key = [...keyring.values()][0]!;
- const hash = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
- type Held = {request: import("./upload.js").NativeArchiveCreate; parts: Map<number, Buffer>; uploaded: boolean};
- const held = new Map<string, Held>(); let failPart = true, wrongReceipt = true, rejectNative = false, keyReads = 0, puts = 0;
- const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {status, headers: {"Content-Type": "application/json"}});
- const url = (id: string, part: number) => `https://archive-fixture.invalid/${id}/${part}`;
- const uploader = new ArchiveUploader({
- retry: {attempts: 1, sleep: async () => {}},
- request: async (route, init) => {
- if (route === "archives/key") { keyReads++; return json({kid: key.kid, public_key: key.publicRaw.toString("base64"), alg: "X25519-HKDF-SHA256-A256GCM", limits: {max_upload_bytes: null, max_session_bytes: null, claude: options.capabilities}, policy: {all_folders: false, touched_files: false}}); }
- if (route === "archives") {
- const request: import("./upload.js").NativeArchiveCreate = JSON.parse(init.body!);
- expect(request.harness).toBe("claude-code"); expect(request.binding_id).toBe(binding.bindingId);
- expect(request.contract_hash).toBe(binding.contractHash); expect(request.kind).toBe("base");
- expect(request.parent_archive_id).toBeNull(); expect(request.marker).toBe("project"); expect(request).not.toHaveProperty("media_bytes");
- expect(request.content).toBe(request.payload === "claude_native" ? "tar+zstd" : "zip");
- if (request.payload === "claude_native") expect(request).not.toHaveProperty("box_image");
- else expect(request.box_image).toMatch(/^sha256:[0-9a-f]{64}$/);
- if (rejectNative && request.payload === "claude_native") return json({detail: "archive_payload_disabled"}, 409);
- const existing = held.get(request.archive_id);
- if (existing) expect(request).toEqual(existing.request);
- else for (const prior of held.values()) {
- if (prior.request.session_id === request.session_id && prior.request.payload === request.payload) expect(request.sequence).toBeGreaterThan(prior.request.sequence);
- }
- if (existing?.uploaded) return json({archive_id: request.archive_id, status: "uploaded"});
- if (!existing) held.set(request.archive_id, {request, parts: new Map(), uploaded: false});
- const count = Math.ceil(request.size / 128);
- return json({archive_id: request.archive_id, status: "uploading", upload_id: request.archive_id, object_key: request.archive_id, part_size: 128, part_count: count, parts: Array.from({length: count}, (_, i) => ({part_number: i + 1, url: url(request.archive_id, i + 1)}))}, 201);
- }
- const match = /^archives\/([^/]+)\/(parts|complete)$/.exec(route); if (!match) throw new Error("Unexpected archive API route");
- const item = held.get(match[1]!)!;
- if (match[2] === "parts") {
- const wanted: {part_numbers: number[]} = JSON.parse(init.body!);
- return json({archive_id: match[1], parts: wanted.part_numbers.map(n => ({part_number: n, url: url(match[1]!, n)})), uploaded: [...item.parts].map(([n, bytes]) => ({part_number: n, etag: `"${n}"`, size: bytes.length}))});
- }
- const bytes = Buffer.concat([...item.parts].sort(([a], [b]) => a - b).map(([, data]) => data));
- expect(bytes.length).toBe(item.request.size); expect(hash(bytes)).toBe(item.request.sha256);
- item.uploaded = true;
- if (wrongReceipt) { wrongReceipt = false; return json({archive_id: "another-session", status: "uploaded", size: bytes.length}); }
- return json({archive_id: match[1], status: "uploaded", size: bytes.length});
- },
- fetch: async (address, init) => {
- expect(init?.method).toBe("PUT"); expect(init?.headers).toBeUndefined(); puts++;
- if (failPart) { failPart = false; return new Response("", {status: 503}); }
- const [, id, part] = new URL(address).pathname.split("/");
- const bytes = await new Response(init?.body).arrayBuffer(); held.get(id!)!.parts.set(Number(part), Buffer.from(bytes));
- return new Response("", {headers: {etag: `"${part}"`}});
- },
- });
- const options: import("./upload.js").NativeUploadOptions = {
- ...binding, owner: f.options.owner, turn: 1, nativeDirectory, stateDirectory, checkpointFile, checkpointManifestSha256, boxImage: `sha256:${"b".repeat(64)}`,
- capabilities: {schema: 1, native: {enabled: true, max_bytes: 1024 * 1024}, checkpoint: {enabled: false, max_bytes: 1024 * 1024, retention_days: null}},
- driver: {fetchKey: signal => uploader.fetchKey(signal), upload: (job, persist, signal) => uploader.upload(job, persist, signal), sealer: options => new SealStream(options), tarHeader: tarMemberHeader},
- };
- expect(parseNativeCaptureCapabilities(options.capabilities)).toEqual(options.capabilities);
- for (const invalid of [undefined, {schema: 1}, {...options.capabilities, schema: 2},
- {...options.capabilities, native: {enabled: true, max_bytes: 0}},
- {...options.capabilities, checkpoint: {enabled: false, max_bytes: 1024 * 1024}},
- {...options.capabilities, checkpoint: {...options.capabilities.checkpoint, enabled: "false"}}]) {
- expect(parseNativeCaptureCapabilities(invalid)).toBeNull();
- }
- options.capabilities.native.max_bytes = 1;
- const nativeCap = await uploadNativeBundle(options);
- expect(nativeCap.native.code).toBe("archive_too_large"); expect(held.size).toBe(0); expect(puts).toBe(0);
- if (!nativeCap.native.bytes || !nativeCap.native.plainBytes) throw new Error("Missing retained sealed job");
- expect(nativeCap.native.bytes).toBeGreaterThan(nativeCap.native.plainBytes);
- options.capabilities.native.max_bytes = nativeCap.native.plainBytes;
- expect((await uploadNativeBundle(options)).native.code).toBe("archive_too_large"); expect(held.size).toBe(0);
- options.capabilities.native.max_bytes = nativeCap.native.bytes;
- const interrupted = await uploadNativeBundle(options);
- expect(interrupted.native.status).toBe("pending"); expect(interrupted.checkpoint.status).toBe("disabled"); expect(held.size).toBe(1);
- expect(interrupted.native.archiveId).toBe(nativeCap.native.archiveId);
- const mismatchedReceipt = await uploadNativeBundle(options);
- expect(mismatchedReceipt.native.status).toBe("pending"); expect(mismatchedReceipt.native.code).toBe("invalid completion receipt");
- const resumed = await uploadNativeBundle(options);
- expect(resumed.status).toBe("uploaded"); expect(resumed.native.archiveId).toBe(interrupted.native.archiveId);
- expect(resumed.native.sha256).toBe(interrupted.native.sha256); expect(keyReads).toBe(1);
- const native = held.get(resumed.native.archiveId!)!;
- const sealed = Buffer.concat([...native.parts].sort(([a], [b]) => a - b).map(([, bytes]) => bytes));
- const plaintext = await openSealedBuffer(sealed, keyring), tar = zstdDecompressSync(plaintext);
- expect(hash(plaintext)).toBe(native.request.plain_sha256); expect(plaintext.length).toBe(native.request.plain_size);
- expect(tar.subarray(0, 100).toString("utf8").split("\0")[0]).toBe("__omnirush__/manifest.json");
- expect(tar.includes(raw)).toBe(true);
- const beforeCapPuts = puts;
- options.capabilities.checkpoint = {enabled: true, max_bytes: 1, retention_days: 3};
- const capped = await uploadNativeBundle(options);
- expect(capped.status).toBe("partial"); expect(capped.native.status).toBe("uploaded"); expect(capped.checkpoint.code).toBe("archive_too_large");
- expect(puts).toBe(beforeCapPuts); expect(fs.readFileSync(path.join(nativeDirectory, "literal-evidence.txt"))).toEqual(raw);
- options.capabilities.checkpoint.max_bytes = fs.statSync(checkpointFile).size;
- const sealedCheckpointCap = await uploadNativeBundle(options);
- expect(sealedCheckpointCap.checkpoint.code).toBe("archive_too_large"); expect(puts).toBe(beforeCapPuts); expect(held.size).toBe(1);
- if (!sealedCheckpointCap.checkpoint.bytes) throw new Error("Missing retained checkpoint seal");
- expect(sealedCheckpointCap.checkpoint.bytes).toBeGreaterThan(options.capabilities.checkpoint.max_bytes);
- options.capabilities.checkpoint.max_bytes = sealedCheckpointCap.checkpoint.bytes;
- const completed = await uploadNativeBundle(options); expect(completed.checkpoint.status).toBe("uploaded"); expect(held.size).toBe(2);
- expect(completed.checkpoint.archiveId).toBe(sealedCheckpointCap.checkpoint.archiveId);
- const checkpoint = held.get(completed.checkpoint.archiveId!)!;
- expect(checkpoint.request.sequence).toBe(0); expect(native.request.sequence).toBe(0); expect(checkpoint.request.content).toBe("zip");
- const zipSeal = Buffer.concat([...checkpoint.parts].sort(([a], [b]) => a - b).map(([, bytes]) => bytes));
- await expect(openSealedBuffer(zipSeal, keyring)).rejects.toThrow("bad_header");
- const zip = await openSealedBuffer(zipSeal, keyring, {expectedContent: "zip"});
- expect(zip).toEqual(fs.readFileSync(checkpointFile)); expect(hash(zip)).toBe(checkpoint.request.plain_sha256);
- fs.appendFileSync(path.join(nativeDirectory, "literal-evidence.txt"), "changed");
- const inconsistent = await uploadNativeBundle(options); expect(inconsistent.native.status).toBe("pending"); expect(inconsistent.checkpoint.status).toBe("uploaded");
- expect(inconsistent.native.code).toBe("archive_manifest_members_mismatch");
- expect(JSON.parse(fs.readFileSync(path.join(stateDirectory, "last-upload.json"), "utf8")).native.code).toBe("archive_manifest_members_mismatch");
- expect(held.size).toBe(2); expect(fs.existsSync(checkpointFile)).toBe(true);
- options.capabilities.native.max_bytes = 1024 * 1024;
- await writeBundleManifest(nativeDirectory, binding, "claude_native"); rejectNative = true;
- const disabled = await uploadNativeBundle(options); expect(disabled.native.status).toBe("disabled"); expect(disabled.native.code).toBe("archive_payload_disabled");
- expect(disabled.checkpoint.status).toBe("uploaded"); expect(held.size).toBe(2);
- expect(disabled.native.sequence).toBe(1);
- rejectNative = false; fs.appendFileSync(path.join(nativeDirectory, "literal-evidence.txt"), "next snapshot");
- await writeBundleManifest(nativeDirectory, binding, "claude_native");
- const next = await uploadNativeBundle(options);
- expect(next.native.status).toBe("uploaded"); expect(next.native.sequence).toBe(2); expect(held.size).toBe(3);
- expect(next.checkpoint.archiveId).toBe(completed.checkpoint.archiveId);
- expect(fs.readFileSync(path.join(stateDirectory, "upload-events.jsonl"), "utf8")).toContain("archive_manifest_members_mismatch");
-});
-
-function savedRuntimeFixture(access?: () => Promise<{owner: string; capabilities?: string[]}>, runtimeSubdirectory = "") {
- const temp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "claude-offline-"))); roots.push(temp);
- const root = path.join(temp, runtimeSubdirectory); fs.mkdirSync(root, {recursive: true});
- const owner = "local-owner", id = "00000000-0000-4000-8000-000000000001";
- const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
- const dir = path.join(root, hash(owner), id); fs.mkdirSync(path.join(dir, "images"), {recursive: true});
- const image = Buffer.from("saved environment fixture"); fs.writeFileSync(path.join(dir, "images/base.tar.gz"), image);
- const session = {schema: 1, id, owner, workspaceId: "workspace", surface: "gui", model: MODEL, sdkVersion: "legacy", claudeVersion: CLAUDE_VERSION,
- createdAt: new Date(0).toISOString(), container: `omnirush-claude-${id}`, base: {image: "sha256:" + "a".repeat(64), file: "images/base.tar.gz", sha256: hash(image), bytes: image.length},
- turns: [], capture: "incomplete", replay: "unverified", issues: ["interrupted"]};
- fs.writeFileSync(path.join(dir, "session.json"), JSON.stringify(session));
- const configDir = path.join(dir, "config"), project = path.join(configDir, "projects", "-workspace"); fs.mkdirSync(project, {recursive: true});
- const raw = '{ "type":"future-record", "opaque":"original bytes" }\n'; fs.writeFileSync(path.join(project, `${id}.jsonl`), raw);
- const collector = new NativeCapture({directory: path.join(dir, "native"), configDir, sessionId: id, owner, producerVersion: CLAUDE_VERSION, surface: "gui", transport: "sdk"});
- collector.finish({type: "finish", processStopped: true, successfulResult: false});
- let accessCalls = 0, grants = 0;
- const runtime = new ClaudeRuntime({fetch: globalThis.fetch, directory: root, surface: "gui", docker: path.join(root, "docker-is-unavailable"),
- access: async () => { accessCalls++; if (access) return access(); throw new Error("account unavailable"); },
- authorize: async () => { grants++; throw new Error("must not mint"); }});
- return {root, dir, id, owner, raw, session, runtime, counts: () => ({accessCalls, grants})};
-}
-
-test("offline export reclaims a proven-dead operation owner and preserves the original evidence", async () => {
- const f = savedRuntimeFixture();
- const dead = spawnSync(process.execPath, ["-e", "process.exit(0)"], {timeout: 5_000});
- expect(dead.status).toBe(0);
- fs.writeFileSync(path.join(f.dir, "operation.lock"), JSON.stringify({pid: dead.pid, nonce: "crashed-owner"}));
- const originalState = fs.readFileSync(path.join(f.dir, "session.json")), originalManifest = fs.readFileSync(path.join(f.dir, "native/manifest.json"));
- const exported = await f.runtime.export(f.id);
- const check = spawnSync("python3", ["-c", "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.read(sys.argv[2]) == sys.argv[3].encode(); assert z.read('images/base.tar.gz') == b'saved environment fixture'", exported, `claude/projects/-workspace/${f.id}.jsonl`, f.raw], {timeout: 5_000});
- expect(check.status).toBe(0);
- expect(fs.readFileSync(path.join(f.dir, "session.json"))).toEqual(originalState);
- expect(fs.readFileSync(path.join(f.dir, "native/manifest.json"))).toEqual(originalManifest);
- expect(fs.existsSync(path.join(f.dir, "operation.lock"))).toBe(false);
- expect((await f.runtime.get(f.id)).id).toBe(f.id);
- expect((await f.runtime.list("workspace")).map(session => session.id)).toEqual([f.id]);
- expect(f.counts()).toEqual({accessCalls: 0, grants: 0});
- await expect(f.runtime.start(f.id, "continue")).rejects.toThrow("account unavailable");
- expect(f.counts().grants).toBe(0);
-});
-
-test("offline export refuses live and unknown lock owners without clearing their lock", async () => {
- const f = savedRuntimeFixture(async () => ({owner: "local-owner"}));
- for (const owner of [{pid: process.pid, nonce: "live"}, {pid: 0, nonce: "unknown"}, {pid: "bad"}, {pid: process.pid, nonce: "live", identity: {boot: "unverifiable"}}]) {
- const lock = JSON.stringify(owner); fs.writeFileSync(path.join(f.dir, "operation.lock"), lock);
- const error = await f.runtime.export(f.id).catch(error => error);
- expect(error).toBeInstanceOf(ApiError);
- expect(error).toMatchObject({status: 409, code: "session_in_use", message: "Another process is using this session or its operation owner is unknown", details: undefined});
- expect(fs.readFileSync(path.join(f.dir, "operation.lock"), "utf8")).toBe(lock);
- expect(fs.existsSync(path.join(f.dir, `${f.id}.zip`))).toBe(false);
- }
-});
-
-test("Claude HTTP export preserves operation-owner conflicts and masks unexpected failures", async () => {
- const {startServer} = await import("../server.js");
- const {TokenService} = await import("../tokens.js");
- const f = savedRuntimeFixture(undefined, "claude-sessions");
- const serverRoot = path.dirname(f.root), workspace = path.join(serverRoot, "workspace");
- fs.mkdirSync(workspace, {recursive: true});
- const dir = f.dir;
- const priorEnv = new Map<string, string | undefined>();
- const overrides = {
- OMNIRUSH_DATA_DIR: path.join(serverRoot, "data"), OMNIRUSH_TOKEN_STORE: path.join(serverRoot, "tokens.json"),
- OMNIRUSH_RUNTIME_DB: path.join(serverRoot, "runtime.sqlite"),
- OMNIRUSH_GATEWAY_URL: "", OMNIRUSH_ACCESS_TOKEN: "", OMNIRUSH_REFRESH_TOKEN: "",
- };
- for (const [key, value] of Object.entries(overrides)) { priorEnv.set(key, process.env[key]); process.env[key] = value; }
- let server: Awaited<ReturnType<typeof startServer>> | undefined;
- try {
- const config: import("../types.js").ServerConfig = {
- host: "127.0.0.1", port: 0, configPath: path.join(serverRoot, "server.json"),
- token: "fixture-collaborator-token", hostToken: "fixture-host-token", approval: {mode: "auto", timeoutMs: 1000}, corsOrigins: [],
- workspaces: [{id: "workspace", name: "Fixture", path: workspace, preset: "starter", workspaceType: "local"}],
- authorizedRoots: [workspace], readOnly: false, startedAt: Date.now(), tokenSource: "cli", hostTokenSource: "cli", logFormat: "pretty", logRequests: false,
- };
- const ownerToken = await new TokenService(config).create("owner");
- server = await startServer(config);
- const url = `http://127.0.0.1:${server.port}/workspace/workspace/claude/sessions/${f.id}/export`;
- const request = () => fetch(url, {method: "POST", headers: {authorization: `Bearer ${ownerToken.token}`}, signal: AbortSignal.timeout(5000)});
- const lockFile = path.join(dir, "operation.lock"), state = fs.readFileSync(path.join(dir, "session.json")), manifest = fs.readFileSync(path.join(dir, "native/manifest.json"));
- for (const owner of [{pid: process.pid, nonce: "live-private-canary"}, {pid: 0, nonce: "unknown-private-canary"}]) {
- const lock = JSON.stringify(owner); fs.writeFileSync(lockFile, lock);
- const response = await request();
- expect(response.status).toBe(409);
- expect(await response.json()).toEqual({code: "session_in_use", message: "Another process is using this session or its operation owner is unknown"});
- expect(fs.readFileSync(lockFile, "utf8")).toBe(lock);
- expect(fs.existsSync(path.join(dir, `${f.id}.zip`))).toBe(false);
- expect(fs.readFileSync(path.join(dir, "session.json"))).toEqual(state);
- expect(fs.readFileSync(path.join(dir, "native/manifest.json"))).toEqual(manifest);
- }
- fs.writeFileSync(lockFile, "{private-unexpected-error-canary");
- const unexpected = await request();
- expect(unexpected.status).toBe(500);
- expect(await unexpected.json()).toEqual({code: "internal_error", message: "Unexpected server error"});
- expect(fs.readFileSync(lockFile, "utf8")).toBe("{private-unexpected-error-canary");
- fs.unlinkSync(lockFile);
- const exported = await request();
- expect(exported.status).toBe(200);
- expect(exported.headers.get("content-type")).toBe("application/zip");
- expect(Buffer.from(await exported.arrayBuffer())).toEqual(fs.readFileSync(path.join(dir, `${f.id}.zip`)));
- } finally {
- await server?.stop();
- for (const [key, value] of priorEnv) { if (value === undefined) delete process.env[key]; else process.env[key] = value; }
- }
-}, 15_000);
-
-test("offline lookup rejects owner and session path mismatches, ambiguous IDs and symlink escapes", async () => {
- const f = savedRuntimeFixture(async () => ({owner: f.owner}));
- const state = path.join(f.dir, "session.json"), original = fs.readFileSync(state);
- for (const changed of [{owner: "another-owner"}, {id: "00000000-0000-4000-8000-000000000002"}, {workspaceId: ""}]) {
- fs.writeFileSync(state, JSON.stringify({...f.session, ...changed}));
- await expect(f.runtime.get(f.id)).rejects.toThrow();
- }
- fs.writeFileSync(state, original);
- const outside = path.join(f.root, "outside.json"); fs.renameSync(state, outside); fs.symlinkSync(outside, state);
- await expect(f.runtime.get(f.id)).rejects.toThrow(); fs.unlinkSync(state); fs.renameSync(outside, state);
- const otherRoot = path.join(f.root, "b".repeat(64)); fs.mkdirSync(otherRoot);
- fs.symlinkSync(f.dir, path.join(otherRoot, f.id)); await expect(f.runtime.get(f.id)).rejects.toThrow();
- fs.unlinkSync(path.join(otherRoot, f.id)); fs.cpSync(f.dir, path.join(otherRoot, f.id), {recursive: true});
- await expect(f.runtime.get(f.id)).rejects.toThrow();
- fs.rmSync(otherRoot, {recursive: true});
- fs.writeFileSync(outside, "outside-canary");
- for (const target of [path.join(f.dir, "images", "escape"), path.join(f.dir, `${f.id}.zip.tmp`)]) {
- fs.symlinkSync(outside, target);
- await expect(f.runtime.export(f.id)).rejects.toThrow();
- expect(fs.readFileSync(outside, "utf8")).toBe("outside-canary"); fs.unlinkSync(target);
- }
-});
-
-function gate<T>() {
- let resolve!: (value: T) => void;
- const promise = new Promise<T>(done => { resolve = done; });
- return {promise, resolve};
-}
-
-test("shutdown fences startup blocked on access and never mints or starts Docker after access resolves", async () => {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-startup-")); roots.push(root);
- const entered = gate<void>(), access = gate<{owner: string; capabilities: string[]; models: string[]}>(); let grants = 0, dockerCalls = 0;
- const runtime = new ClaudeRuntime({fetch: globalThis.fetch, directory: root, surface: "gui", access: () => { entered.resolve(); return access.promise; }, authorize: async () => { grants++; throw new Error("must not mint"); }});
- Reflect.set(runtime, "docker", async () => { dockerCalls++; throw new Error("must not start Docker"); });
- const creation = runtime.create(root, "workspace").then(() => "created", () => "cancelled");
- await entered.promise;
- const shutdown = runtime.shutdown();
- access.resolve({owner: "local-owner", capabilities: ["claude-code"], models: [MODEL]});
- expect(await creation).toBe("cancelled"); await shutdown;
- expect({grants, dockerCalls}).toEqual({grants: 0, dockerCalls: 0});
- await expect(runtime.prepare()).rejects.toThrow();
-});
-
-test("offline export reclaims a dead legacy PID even with account available, but not a live PID", async () => {
- const f = savedRuntimeFixture(async () => ({owner: "local-owner"}));
- const dead = spawnSync(process.execPath, ["-e", "process.exit(0)"], {timeout: 5_000});
- fs.writeFileSync(path.join(f.dir, "operation.lock"), JSON.stringify({pid: dead.pid, nonce: "dead"}));
- expect(fs.existsSync(await f.runtime.export(f.id))).toBe(true);
- const live = JSON.stringify({pid: process.pid, nonce: "live"}); fs.writeFileSync(path.join(f.dir, "operation.lock"), live);
- await expect(f.runtime.export(f.id)).rejects.toThrow();
- expect(fs.readFileSync(path.join(f.dir, "operation.lock"), "utf8")).toBe(live);
-});
-
-test("operation locks distinguish reused PIDs from the live process birth identity", async () => {
- if (process.platform !== "linux") return;
- const f = savedRuntimeFixture(async () => ({owner: "local-owner"}));
- const stat = fs.readFileSync(`/proc/${process.pid}/stat`, "utf8");
- const identity = {host: os.hostname(), boot: fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), namespace: fs.readlinkSync("/proc/self/ns/pid"), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]};
- const lockPath = path.join(f.dir, "operation.lock"), live = JSON.stringify({pid: process.pid, nonce: "live-birth", identity});
- fs.writeFileSync(lockPath, live); await expect(f.runtime.export(f.id)).rejects.toThrow();
- expect(fs.readFileSync(lockPath, "utf8")).toBe(live);
- for (const changed of [{start: String(BigInt(identity.start) - 1n)}, {boot: "00000000-0000-4000-8000-000000000099"}]) {
- fs.writeFileSync(lockPath, JSON.stringify({pid: process.pid, nonce: "previous-birth", identity: {...identity, ...changed}}));
- expect(fs.existsSync(await f.runtime.export(f.id))).toBe(true);
- }
- const unknown = JSON.stringify({pid: process.pid, nonce: "other-namespace", identity: {...identity, namespace: "pid:[unknown]"}});
- fs.writeFileSync(lockPath, unknown); await expect(f.runtime.export(f.id)).rejects.toThrow();
- expect(fs.readFileSync(lockPath, "utf8")).toBe(unknown);
-});
-
-async function waitForFixture(file: string) {
- for (let attempt = 0; attempt < 200; attempt++) {
- if (fs.existsSync(file)) return;
- await new Promise(resolve => setTimeout(resolve, 10));
- }
- throw new Error(`Fixture did not reach ${path.basename(file)}`);
-}
-async function cancellationResult(work: Promise<string>) {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try { return await Promise.race([work, new Promise<string>(resolve => { timer = setTimeout(() => resolve("still-running"), 1_000); })]); }
- finally { clearTimeout(timer); }
-}
-
-function startupDockerFixture(stage: "build" | "create" | "cp" | "exec" | "restore", models: string[] = [MODEL]) {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-docker-fixture-")); roots.push(root);
- const workspace = path.join(root, "workspace"); fs.mkdirSync(workspace);
- const docker = path.join(root, "docker-fixture.mjs"), ready = path.join(root, "ready"), release = path.join(root, "release"), log = path.join(root, "calls.jsonl");
- const runtime = new ClaudeRuntime({fetch: globalThis.fetch, directory: path.join(root, "state"), surface: "gui", docker,
- access: async () => ({owner: "local-owner", capabilities: ["claude-code"], models}),
- authorize: async () => { grants++; throw new Error("must not authorize after cancellation"); }});
- let grants = 0;
- const fingerprint = createHash("sha256").update(JSON.stringify(Reflect.get(runtime, "harnessContract").call(runtime))).digest("hex");
- fs.writeFileSync(docker, `#!${process.execPath}
-import fs from 'node:fs';
-const root=${JSON.stringify(root)}, stage=${JSON.stringify(stage)}, args=process.argv.slice(2);
-const state=root+'/container.json', ready=root+'/ready';
-fs.appendFileSync(root+'/calls.jsonl',JSON.stringify(args)+'\\n');
-const own='c'.repeat(64), foreign='f'.repeat(64), image='sha256:'+'a'.repeat(64);
-const pause=async()=>{fs.writeFileSync(ready,JSON.stringify({pid:process.pid,args}));for(let i=0;i<200;i++){if(fs.existsSync(root+'/release'))return;await new Promise(r=>setTimeout(r,10));}process.exit(42);};
-if(args[0]==='create'){
- const label=args.find(a=>a.startsWith('org.omnirush.claude.operation='));
- fs.writeFileSync(state,JSON.stringify({Id:own,Config:{Labels:{'org.omnirush.claude.operation':label?.split('=')[1]}},Name:args[args.indexOf('--name')+1]}));
- if(stage==='create')await pause();console.log(own);
-}else if(args[0]==='container'&&args[1]==='ls')console.log((fs.existsSync(state)?own+'\\n':'')+foreign);
-else if(args[0]==='image'&&args[1]==='ls')console.log(image);
-else if(args[1]==='inspect'){
- if(args[0]==='container'&&stage==='restore'&&args[2].startsWith('omnirush-'))await pause();
- if(args[2]===foreign)console.log(JSON.stringify([{Id:foreign,Config:{Labels:{'org.omnirush.claude.operation':'another-operation'}}}]));
- else if(args[2]===own)console.log('['+fs.readFileSync(state,'utf8')+']');
- else console.log(JSON.stringify([{Id:image,Os:'linux',Architecture:'amd64',Config:{Labels:{'org.omnirush.claude.runtime':stage==='build'?'old':${JSON.stringify(fingerprint)}}}}]));
-}else if(args[0]==='build'||args[0]===stage)await pause();
-else if(args[0]==='commit')console.log(image);
-else if(args[0]==='save')fs.writeFileSync(args[args.indexOf('--output')+1],'fixture image archive');
-else if(args[0]==='rm'||args[0]==='container'&&args[1]==='rm')fs.rmSync(state,{force:true});
-`, {mode: 0o700});
- return {root, workspace, runtime, ready, release, log, grants: () => grants,
- calls: (): string[][] => fs.existsSync(log) ? fs.readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)) : []};
-}
-
-test("a session pins the model it was created with and refuses one the server does not list", async () => {
- const sonnet = "claude-sonnet-5-5";
- const refused = startupDockerFixture("restore");
- await expect(refused.runtime.create(refused.workspace, "workspace", undefined, sonnet)).rejects.toThrow("isn't available on your account yet");
- expect(refused.calls()).toEqual([]);
- const f = startupDockerFixture("restore", [MODEL, sonnet]);
- const session = await f.runtime.create(f.workspace, "workspace", undefined, sonnet);
- expect(session.model).toBe(sonnet);
- expect(session.contract?.model).toBe(sonnet);
- expect(session.modelIsolation?.expectedModel).toBe(sonnet);
- expect(session.contract?.harness.managedSettingsSha256).toBe(createHash("sha256").update(managedSettings(sonnet)).digest("hex"));
- expect(f.calls()).toContainEqual(["exec", "-i", "--user", "root", session.container, "sh", "-c", "cat > /etc/claude-code/managed-settings.json"]);
- expect((await f.runtime.get(session.id)).compatibility).toBe("current");
- const opus = startupDockerFixture("restore", [MODEL, sonnet]);
- expect((await opus.runtime.create(opus.workspace, "workspace")).model).toBe(MODEL);
- expect(opus.calls().some(call => call.includes("cat > /etc/claude-code/managed-settings.json"))).toBe(false);
-});
-
-for (const stage of ["build", "create", "cp", "exec"] as const) test(`startup request abort kills Docker ${stage}, waits for owned cleanup and never authorizes`, async () => {
- const f = startupDockerFixture(stage), controller = new AbortController();
- const result = f.runtime.create(f.workspace, "workspace", controller.signal).then(() => "created", () => "cancelled");
- try {
- await waitForFixture(f.ready); const witness = JSON.parse(fs.readFileSync(f.ready, "utf8"));
- controller.abort();
- expect(await cancellationResult(result)).toBe("cancelled");
- await f.runtime.shutdown();
- expect(() => process.kill(witness.pid, 0)).toThrow();
- expect(f.grants()).toBe(0);
- expect(fs.existsSync(path.join(f.root, "container.json"))).toBe(false);
- const calls = f.calls();
- expect(calls.some(args => args.includes("/opt/claude/controller.mjs"))).toBe(false);
- expect(calls.filter(args => args.includes("rm")).every(args => args.at(-1) === "c".repeat(64))).toBe(true);
- expect(calls.some(args => args[0] === "commit")).toBe(false);
- const owners = fs.readdirSync(path.join(f.root, "state")).filter(name => /^[a-f0-9]{64}$/.test(name));
- for (const owner of owners) for (const id of fs.readdirSync(path.join(f.root, "state", owner))) expect(fs.existsSync(path.join(f.root, "state", owner, id, "session.json"))).toBe(false);
- } finally { fs.writeFileSync(f.release, "release"); await result; await f.runtime.shutdown(); }
-}, 10_000);
-
-test("Stop and shutdown abort pending turn restoration before mint or controller execution", async () => {
- for (const action of ["stop", "shutdown"] as const) {
- const f = startupDockerFixture("restore");
- const session = await f.runtime.create(f.workspace, "workspace");
- const result = f.runtime.start(session.id, "must not run").then(() => "started", () => "cancelled");
- try {
- await waitForFixture(f.ready); const witness = JSON.parse(fs.readFileSync(f.ready, "utf8"));
- const stopping = action === "stop" ? f.runtime.stop(session.id) : f.runtime.shutdown();
- expect(await result).toBe("cancelled"); await stopping;
- expect(() => process.kill(witness.pid, 0)).toThrow();
- expect(f.grants()).toBe(0);
- expect(f.calls().some(args => args.includes("/opt/claude/controller.mjs"))).toBe(false);
- expect((await f.runtime.get(session.id)).turns).toEqual([]);
- } finally { fs.writeFileSync(f.release, "release"); await result; await f.runtime.shutdown(); }
- }
-}, 10_000);
-
-test("shutdown drains pending sandbox creation and fences subsequent startup", async () => {
- const f = startupDockerFixture("create");
- const result = f.runtime.create(f.workspace, "workspace").then(() => "created", () => "cancelled");
- try {
- await waitForFixture(f.ready); const witness = JSON.parse(fs.readFileSync(f.ready, "utf8"));
- await f.runtime.shutdown();
- expect(await result).toBe("cancelled");
- expect(() => process.kill(witness.pid, 0)).toThrow();
- expect(fs.existsSync(path.join(f.root, "container.json"))).toBe(false);
- const before = f.calls();
- await expect(f.runtime.prepare()).rejects.toThrow("shutting down");
- await expect(f.runtime.create(f.workspace, "workspace")).rejects.toThrow("shutting down");
- expect(f.calls()).toEqual(before); expect(f.grants()).toBe(0);
- } finally { fs.writeFileSync(f.release, "release"); await result; await f.runtime.shutdown(); }
-}, 10_000);
-
-test("broker cancellation during account access prevents both mint and provider calls", async () => {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-broker-abort-")); roots.push(root);
- const access = gate<{owner: string}>(), entered = gate<void>(), controller = new AbortController();
- let grants = 0, providerCalls = 0;
- const relay = Bun.serve({hostname: "127.0.0.1", port: 0, fetch() { providerCalls++; return Response.json({type: "message", model: MODEL, content: [], stop_reason: "end_turn"}); }});
- const id = "00000000-0000-4000-8000-000000000001", contractSha256 = "a".repeat(64);
- const runtime = new ClaudeRuntime({fetch: globalThis.fetch, directory: root, surface: "gui", access: () => { entered.resolve(); return access.promise; },
- authorize: async () => { grants++; return {owner: "owner", sessionId: id, model: MODEL, upstreamModel: MODEL, client: "desktop/3.7.5", baseUrl: `http://127.0.0.1:${relay.port}`, token: "orc_" + "a".repeat(43), contractSha256}; }});
- const broker = await Reflect.get(runtime, "broker").call(runtime, {owner: "owner", id, model: MODEL, workspaceId: "workspace", contract: {}, contractSha256, turns: []}, () => {}, controller.signal);
- try {
- const response = fetch(broker.baseUrl.replace("host.docker.internal", "127.0.0.1") + "/v1/messages", {method: "POST", headers: {authorization: `Bearer ${broker.token}`, "content-type": "application/json"}, body: JSON.stringify({model: MODEL, messages: [], max_tokens: 1}), signal: AbortSignal.timeout(3_000)});
- await entered.promise; controller.abort(); access.resolve({owner: "owner"});
- await (await response).arrayBuffer();
- expect({grants, providerCalls}).toEqual({grants: 0, providerCalls: 0});
- } finally { access.resolve({owner: "owner"}); await broker.close(); relay.stop(true); }
-});
-
-test("Claude routes export offline only within the requested workspace and pass startup request cancellation", async () => {
- const {registerClaudeRoutes} = await import("./routes.js");
- const {matchRoute} = await import("../routes/registry.js");
- const f = savedRuntimeFixture(), routes: import("../routes/registry.js").Route[] = [];
- let ownerChecks = 0;
- registerClaudeRoutes({routes, runtime: f.runtime, workspace: async ctx => ({id: ctx.params.id, name: "Fixture", path: f.root, preset: "default", workspaceType: "local"}),
- owner: () => { ownerChecks++; }, writable: () => {}, upload: async () => { throw new Error("not used"); }});
- const call = (request: Request) => {
- const route = matchRoute(routes, request.method, new URL(request.url).pathname); if (!route) throw new Error("route not found");
- return Reflect.apply(route.handler, undefined, [{request, params: route.params}]);
- };
- const response: Response = await call(new Request(`http://localhost/workspace/workspace/claude/sessions/${f.id}/export`, {method: "POST"}));
- expect(response.status).toBe(200); expect(response.headers.get("content-type")).toBe("application/zip");
- expect((await response.arrayBuffer()).byteLength).toBeGreaterThan(0);
- await expect(call(new Request(`http://localhost/workspace/another-workspace/claude/sessions/${f.id}/export`, {method: "POST"}))).rejects.toThrow("Session not found in this workspace");
- expect(f.counts()).toEqual({accessCalls: 0, grants: 0}); expect(ownerChecks).toBe(2);
- const controller = new AbortController(); controller.abort();
- for (const suffix of ["prepare", "sessions", `sessions/${f.id}/turns`]) {
- await expect(call(new Request(`http://localhost/workspace/workspace/claude/${suffix}`, {method: "POST", signal: controller.signal, headers: {"content-type": "application/json"}, body: JSON.stringify({captureConsent: true, prompt: "must not run"})}))).rejects.toThrow();
- }
- expect(f.counts()).toEqual({accessCalls: 0, grants: 0});
-});
-
-
-function guardWorker(f: ReturnType<typeof savedRuntimeFixture>) {
- const script = path.join(f.root, "guard-worker.mjs");
- fs.writeFileSync(script, `
-import fs from 'node:fs';
-import path from 'node:path';
-import {ClaudeRuntime} from ${JSON.stringify(new URL("./runtime.ts", import.meta.url).href)};
-const root=${JSON.stringify(f.root)}, dir=${JSON.stringify(f.dir)}, id=${JSON.stringify(f.id)};
-const [mode,name='crash']=process.argv.slice(2), guard=path.join(dir,'recovery.lock');
-const rename=fs.renameSync, open=fs.openSync, link=fs.linkSync;
-const wait=file=>{for(let n=0;n<1000;n++){if(fs.existsSync(file))return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10);}throw new Error('bounded fixture wait expired');};
-fs.openSync=function(file,...args){const fd=open.call(fs,file,...args);if(mode==='crash-publish'&&file===guard){fs.writeFileSync(path.join(root,'publication.json'),JSON.stringify({empty:fs.statSync(guard).size===0}));process.exit(77);}return fd;};
-fs.linkSync=function(from,to){const result=link.call(fs,from,to);if(mode==='crash-operation'&&to===path.join(dir,'operation.lock')){fs.writeFileSync(path.join(root,'operation-publication.json'),fs.readFileSync(to));process.exit(79);}return result;};
-fs.renameSync=function(from,to){
- const reaping=from===guard&&path.basename(String(to)).startsWith('.recovery-dead-');
- if(mode==='contend'&&reaping){fs.writeFileSync(path.join(root,'ready-'+name),'ready');wait(path.join(root,'go-'+name));}
- const result=rename.call(fs,from,to);
- if(mode==='crash-reclaim'&&reaping)process.exit(78);
- if(to===guard){
- if(mode==='crash-publish'){fs.writeFileSync(path.join(root,'publication.json'),fs.readFileSync(path.join(guard,'owner.json')));process.exit(77);}
- if(mode==='contend'){fs.writeFileSync(path.join(root,'holding-'+name),fs.readFileSync(path.join(guard,'owner.json')));wait(path.join(root,'release-'+name));}
- }
- return result;
-};
-const runtime=new ClaudeRuntime({fetch: globalThis.fetch, directory:root,surface:'gui',docker:path.join(root,'no-docker'),access:async()=>{throw new Error('offline');},authorize:async()=>{throw new Error('must not mint');}});
-try{const zip=await runtime.export(id);fs.writeFileSync(path.join(root,'result-'+name),JSON.stringify({status:'exported',zip}));}
-catch(error){fs.writeFileSync(path.join(root,'result-'+name),JSON.stringify({status:'rejected',message:error.message}));}
-`);
- return script;
-}
-function staleOperation(f: ReturnType<typeof savedRuntimeFixture>) {
- const child = spawnSync(process.execPath, ["-e", "process.exit(0)"], {timeout: 5_000});
- expect(child.status).toBe(0);
- const owner = {pid: child.pid, nonce: "dead-operation"};
- fs.writeFileSync(path.join(f.dir, "operation.lock"), JSON.stringify(owner));
- return owner;
-}
-function seedGuard(f: ReturnType<typeof savedRuntimeFixture>, owner: unknown) {
- const guard = path.join(f.dir, "recovery.lock"); fs.mkdirSync(guard);
- fs.writeFileSync(path.join(guard, "owner.json"), typeof owner === "string" ? owner : JSON.stringify(owner));
- return guard;
-}
-
-test("recovery guard crash at publication or reclamation still permits byte-exact offline export", async () => {
- for (const point of ["publication", "reclamation", "operation"]) {
- const f = savedRuntimeFixture(); staleOperation(f); const script = guardWorker(f);
- const state = fs.readFileSync(path.join(f.dir, "session.json")), manifest = fs.readFileSync(path.join(f.dir, "native", "manifest.json"));
- const crash = spawnSync(process.execPath, [script, "crash-publish"], {timeout: 5_000});
- expect(crash.status).toBe(77);
- if (point === "reclamation") {
- const second = spawnSync(process.execPath, [script, "crash-reclaim"], {timeout: 5_000});
- expect(second.status).toBe(78);
- }
- if (point === "operation") {
- const second = spawnSync(process.execPath, [script, "crash-operation"], {timeout: 5_000});
- expect(second.status).toBe(79);
- const published = JSON.parse(fs.readFileSync(path.join(f.root, "operation-publication.json"), "utf8"));
- expect(published.pid).toBe(second.pid); expect(typeof published.nonce).toBe("string");
- }
- const zip = await f.runtime.export(f.id);
- const publication = JSON.parse(fs.readFileSync(path.join(f.root, "publication.json"), "utf8"));
- expect(publication.pid).toBe(crash.pid); expect(typeof publication.nonce).toBe("string");
- expect(publication).not.toHaveProperty("empty");
- if (process.platform === "linux") expect(publication.identity.start).toMatch(/^\d+$/);
- expect(fs.readFileSync(path.join(f.dir, "session.json"))).toEqual(state);
- expect(fs.readFileSync(path.join(f.dir, "native", "manifest.json"))).toEqual(manifest);
- const check = spawnSync("python3", ["-c", "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.read(sys.argv[2]) == sys.argv[3].encode()", zip, `claude/projects/-workspace/${f.id}.jsonl`, f.raw], {timeout: 5_000});
- expect(check.status).toBe(0); expect(f.counts()).toEqual({accessCalls: 0, grants: 0});
- expect(fs.existsSync(path.join(f.dir, "recovery.lock"))).toBe(false);
- expect(fs.readdirSync(f.dir).some(name => name.startsWith(".recovery-dead-"))).toBe(true);
- }
-});
-
-test("recovery guard refuses live and unknown owners, including legacy empty files, without changing either lock", async () => {
- const f = savedRuntimeFixture(); staleOperation(f);
- const operation = fs.readFileSync(path.join(f.dir, "operation.lock"));
- for (const owner of [{pid: process.pid, nonce: "live"}, {pid: 0, nonce: "unknown"}, {pid: process.pid, nonce: "unknown-birth", identity: {boot: "unverifiable"}}, ""]) {
- const guard = seedGuard(f, owner), bytes = fs.readFileSync(path.join(guard, "owner.json"));
- await expect(f.runtime.export(f.id)).rejects.toThrow();
- expect(fs.readFileSync(path.join(guard, "owner.json"))).toEqual(bytes);
- expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
- fs.rmSync(guard, {recursive: true});
- }
- const guard = path.join(f.dir, "recovery.lock"); fs.writeFileSync(guard, "");
- await expect(f.runtime.export(f.id)).rejects.toThrow(); expect(fs.readFileSync(guard).length).toBe(0);
- expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
- fs.unlinkSync(guard); fs.mkdirSync(guard);
- await expect(f.runtime.export(f.id)).rejects.toThrow(); expect(fs.readdirSync(guard)).toEqual([]);
- expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
-});
-
-test.skipIf(process.platform !== "linux")("recovery guard distinguishes reused PID birth from live and unknown namespace owners", async () => {
- const f = savedRuntimeFixture(), dead = staleOperation(f);
- const stat = fs.readFileSync(`/proc/${process.pid}/stat`, "utf8");
- const identity = {host: os.hostname(), boot: fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), namespace: fs.readlinkSync("/proc/self/ns/pid"), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]};
- for (const changed of [{}, {namespace: "pid:[unknown]"}]) {
- const guard = seedGuard(f, {pid: process.pid, nonce: "live-or-unknown", identity: {...identity, ...changed}}), bytes = fs.readFileSync(path.join(guard, "owner.json"));
- await expect(f.runtime.export(f.id)).rejects.toThrow();
- expect(fs.readFileSync(path.join(guard, "owner.json"))).toEqual(bytes); fs.rmSync(guard, {recursive: true});
- }
- seedGuard(f, {pid: process.pid, nonce: "reused", identity: {...identity, start: String(BigInt(identity.start) - 1n)}});
- expect(fs.existsSync(await f.runtime.export(f.id))).toBe(true);
- // A dead guard is never permission to remove a separate live operation.
- seedGuard(f, dead); const live = JSON.stringify({pid: process.pid, nonce: "live-operation", identity});
- fs.writeFileSync(path.join(f.dir, "operation.lock"), live);
- await expect(f.runtime.export(f.id)).rejects.toThrow();
- expect(fs.readFileSync(path.join(f.dir, "operation.lock"), "utf8")).toBe(live);
-});
-
-test("recovery guard concurrent reclaimers cannot displace the winner's live replacement", async () => {
- const f = savedRuntimeFixture(), dead = staleOperation(f); seedGuard(f, dead);
- const script = guardWorker(f), operation = fs.readFileSync(path.join(f.dir, "operation.lock"));
- const launch = (name: string) => {
- const child = spawn(process.execPath, [script, "contend", name], {stdio: "ignore"});
- const done = new Promise<number | null>(resolve => child.once("exit", resolve));
- return {child, done};
- };
- const a = launch("a"), b = launch("b");
- try {
- await Promise.all([waitForFixture(path.join(f.root, "ready-a")), waitForFixture(path.join(f.root, "ready-b"))]);
- fs.writeFileSync(path.join(f.root, "go-a"), "go"); await waitForFixture(path.join(f.root, "holding-a"));
- const winner = fs.readFileSync(path.join(f.dir, "recovery.lock", "owner.json"));
- expect(JSON.parse(winner.toString()).pid).toBe(a.child.pid);
- fs.writeFileSync(path.join(f.root, "go-b"), "go"); await waitForFixture(path.join(f.root, "result-b"));
- expect(JSON.parse(fs.readFileSync(path.join(f.root, "result-b"), "utf8")).status).toBe("rejected");
- expect(fs.readFileSync(path.join(f.dir, "recovery.lock", "owner.json"))).toEqual(winner);
- expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
- fs.writeFileSync(path.join(f.root, "release-a"), "release"); await waitForFixture(path.join(f.root, "result-a"));
- expect(JSON.parse(fs.readFileSync(path.join(f.root, "result-a"), "utf8")).status).toBe("exported");
- expect(await a.done).toBe(0); expect(await b.done).toBe(0);
- expect(fs.existsSync(path.join(f.dir, "recovery.lock"))).toBe(false);
- expect(fs.existsSync(path.join(f.dir, "operation.lock"))).toBe(false);
- } finally { a.child.kill("SIGKILL"); b.child.kill("SIGKILL"); await Promise.all([a.done, b.done]); }
-}, 10_000);
diff --git a/apps/server/src/claude-code/native-capture.ts b/apps/server/src/claude-code/native-capture.ts
deleted file mode 100644
index 9091f7ff..00000000
--- a/apps/server/src/claude-code/native-capture.ts
+++ /dev/null
@@ -1,424 +0,0 @@
-/** Private, lossless Claude Code evidence. Never send this through the display scrubber.
- * The native files are the authority, including branches omitted by SDK readers.
- * Only transcript paths for this root session are eligible; never copy the config tree.
- */
-import fs from "node:fs";
-import path from "node:path";
-import { createHash, randomUUID } from "node:crypto";
-
-const CHUNK_BYTES = 1024 * 1024;
-const MAX_FILE_BYTES = 256 * CHUNK_BYTES;
-const MAX_TOTAL_BYTES = 1024 * CHUNK_BYTES;
-const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-const CHILD_FILE = /^agent-[a-zA-Z0-9_-]+\.(jsonl|meta\.json)$/;
-const sha = (bytes: Uint8Array | string) => createHash("sha256").update(bytes).digest("hex");
-
-export type NativeCaptureOptions = {
- directory: string;
- configDir: string;
- sessionId: string;
- producerVersion: string;
- surface: "cli" | "gui";
- transport: "cli" | "sdk";
- owner: string;
-};
-type Chunk = { sha256: string; bytes: number };
-/** Observation only: these counts never delete, merge or rewrite native records.
- * Human prompt candidates are not billable turns; the runtime's durable ingress
- * journal is the authority for user submissions (a harness can synthesize users).
- */
-export type NativeQuality = {
- schema: 1;
- nativeRecords: number;
- recordTypes: Record<string, number>;
- blockTypes: Record<string, number>;
- humanPromptCandidates: number;
- syntheticUserRecords: number;
- childPromptRecords: number;
- compactionRecords: number;
- exposedThinkingBlocks: number;
- opaqueThinkingBlocks: number;
- unknownRecordTypes: string[];
- unknownBlockTypes: string[];
- preservedRevisions: number;
- reviewRequired: boolean;
-};
-export type NativeFile = {
- path: string;
- generation: number;
- bytes: number;
- sha256: string;
- chunks: Chunk[];
- completeLines: number;
- tailBytes: number;
- invalidLines: number;
- thinkingBlocks: number;
- toolCalls: number;
- toolResults: number;
- pendingTools: string[];
- referencedAgents: string[];
- orphanResults?: string[];
- conflictingToolIds?: string[];
- quality?: NativeQuality;
-};
-export type NativeCaptureManifest = {
- schema: 1;
- format: "claude-code";
- sessionId: string;
- producerVersion: string;
- surface: "cli" | "gui";
- transport: "cli" | "sdk";
- owner: string;
- source: string;
- revision: number;
- status: "capturing" | "complete" | "incomplete";
- replay: "unverified";
- confidential: true;
- redacted: false;
- files: NativeFile[];
- history: NativeFile[];
- issues: string[];
- streams: { cli: number; sdk: number; hooks: number };
- qc?: NativeQuality;
-};
-export type NativeCaptureAction =
- | { type: "scan" }
- | { type: "stream"; channel: "cli" | "sdk" | "hooks"; offset: number; bytes: Uint8Array }
- | { type: "finish"; processStopped: boolean; successfulResult: boolean; expectedAgents?: string[] };
-
-function object(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-function mkdir(dir: string): void {
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
- if (!fs.lstatSync(dir).isDirectory() || fs.realpathSync(dir) !== path.resolve(dir)) throw new Error("Capture directory must not traverse symlinks");
- fs.chmodSync(dir, 0o700);
-}
-function syncDir(dir: string): void {
- // Directory fsync is unsupported on Windows. File fsync is still required.
- if (process.platform === "win32") return;
- const fd = fs.openSync(dir, "r");
- try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
-}
-function atomic(file: string, bytes: Uint8Array | string): void {
- mkdir(path.dirname(file));
- const temp = `${file}.${randomUUID()}.tmp`;
- const fd = fs.openSync(temp, "wx", 0o600);
- try { fs.writeFileSync(fd, bytes); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
- try { fs.renameSync(temp, file); syncDir(path.dirname(file)); }
- finally { fs.rmSync(temp, { force: true }); }
-}
-function readRegular(file: string): Buffer {
- // Check ancestors as well as O_NOFOLLOW on the leaf; config is a session-owned volume.
- if (fs.realpathSync(file) !== path.resolve(file)) throw new Error("Native transcript must not traverse symlinks");
- const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
- try {
- const before = fs.fstatSync(fd);
- if (!before.isFile() || before.size > MAX_FILE_BYTES) throw new Error("Invalid or oversized native transcript");
- const bytes = fs.readFileSync(fd);
- const after = fs.fstatSync(fd);
- if (bytes.length !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs) throw new Error("Native transcript changed while capturing; retry scan");
- return bytes;
- } finally { fs.closeSync(fd); }
-}
-
-function emptyQuality(): NativeQuality {
- return { schema: 1, nativeRecords: 0, recordTypes: {}, blockTypes: {}, humanPromptCandidates: 0, syntheticUserRecords: 0, childPromptRecords: 0, compactionRecords: 0, exposedThinkingBlocks: 0, opaqueThinkingBlocks: 0, unknownRecordTypes: [], unknownBlockTypes: [], preservedRevisions: 0, reviewRequired: false };
-}
-const RECORD_TYPES = new Set(["user", "assistant", "system", "attachment", "progress", "queue-operation", "last-prompt", "atis-latch", "cost-state", "mode", "summary", "file-history-snapshot", "custom-title", "agent-name", "agent-color", "tag", "pr-link", "api-request", "api-request-blob", "api-request-shape"]);
-const BLOCK_TYPES = new Set(["text", "image", "document", "tool_use", "tool_result", "thinking", "redacted_thinking"]);
-function increment(counts: Record<string, number>, key: string): void { counts[key] = (counts[key] ?? 0) + 1; }
-function inspect(bytes: Buffer, jsonl: boolean, native = false): Pick<NativeFile, "completeLines" | "tailBytes" | "invalidLines" | "thinkingBlocks" | "toolCalls" | "toolResults" | "pendingTools" | "referencedAgents" | "orphanResults" | "conflictingToolIds" | "quality"> {
- const quality = emptyQuality();
- const result = { completeLines: 0, tailBytes: 0, invalidLines: 0, thinkingBlocks: 0, toolCalls: 0, toolResults: 0, pendingTools: [] as string[], referencedAgents: [] as string[], orphanResults: [] as string[], conflictingToolIds: [] as string[], ...(native ? { quality } : {}) };
- if (!jsonl) {
- try { JSON.parse(bytes.toString("utf8")); } catch { result.invalidLines = 1; }
- return result;
- }
- const end = bytes.lastIndexOf(10) + 1;
- result.tailBytes = bytes.length - end;
- const calls = new Set<string>(), results = new Set<string>(), thinking = new Set<string>();
- const toolIdentities = new Map<string, string>(), promptIds = new Set<string>();
- const agents = new Set<string>();
- let text: string;
- try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, end)); }
- catch { result.invalidLines = 1; return result; }
- // Inspect every record, not just the selected parentUuid chain. Keep bytes unchanged.
- for (const line of text.split("\n")) {
- if (!line.trim()) continue;
- result.completeLines++;
- let record: unknown;
- try { record = JSON.parse(line); } catch { result.invalidLines++; continue; }
- if (!object(record)) { result.invalidLines++; continue; }
- if (native) {
- const type = typeof record.type === "string" ? record.type : "<missing>";
- quality.nativeRecords++; increment(quality.recordTypes, type);
- if (!RECORD_TYPES.has(type) && !quality.unknownRecordTypes.includes(type)) quality.unknownRecordTypes.push(type);
- if (type === "summary" || record.isCompactSummary === true || (type === "system" && typeof record.subtype === "string" && /compact/i.test(record.subtype))) quality.compactionRecords++;
- }
- const toolResult = record.toolUseResult ?? record.tool_use_result;
- if (object(toolResult) && typeof toolResult.agentId === "string") agents.add(toolResult.agentId);
- if (record.type === "system" && record.subtype === "task_started" && typeof record.agent_id === "string") agents.add(record.agent_id);
- // Native request-cache blobs repeat older messages. Preserve every byte,
- // but do not count cached context as a new execution or reasoning block.
- if (record.type !== "assistant" && record.type !== "user") continue;
- if (!object(record.message)) { result.invalidLines++; continue; }
- const content = record.message.content;
- const blocks = Array.isArray(content) ? content.filter(object) : [];
- if (record.type === "user" && native && !blocks.some((block) => block.type === "tool_result")) {
- const text = typeof content === "string" ? content : blocks.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
- const synthetic = record.isMeta === true || record.isCompactSummary === true || /^\s*<(task-notification|local-command|command-name|system-reminder)[\s>]/.test(text);
- if (synthetic) quality.syntheticUserRecords++;
- else if (record.isSidechain === true || typeof record.agentId === "string") quality.childPromptRecords++;
- else if (text.trim()) {
- const id = typeof record.uuid === "string" ? record.uuid : `line:${result.completeLines}`;
- if (!promptIds.has(id)) { promptIds.add(id); quality.humanPromptCandidates++; }
- }
- }
- if (!Array.isArray(content)) continue;
- for (const [index, block] of content.entries()) {
- if (!object(block)) { result.invalidLines++; continue; }
- if (native) {
- const type = typeof block.type === "string" ? block.type : "<missing>";
- increment(quality.blockTypes, type);
- if (!BLOCK_TYPES.has(type) && !quality.unknownBlockTypes.includes(type)) quality.unknownBlockTypes.push(type);
- }
- if (block.type === "tool_use" && typeof block.id === "string") calls.add(block.id);
- if (block.type === "tool_result" && typeof block.tool_use_id === "string") results.add(block.tool_use_id);
- if (block.type === "tool_use" || block.type === "tool_result") {
- const id = block.type === "tool_use" ? block.id : block.tool_use_id;
- if (typeof id !== "string" || !id) result.invalidLines++;
- else {
- const identity = `${block.type}:${id}`, fingerprint = JSON.stringify(block);
- if (toolIdentities.has(identity) && toolIdentities.get(identity) !== fingerprint) result.conflictingToolIds.push(id);
- toolIdentities.set(identity, fingerprint);
- }
- }
- if (block.type === "thinking" || block.type === "redacted_thinking") {
- const identity = `${String(record.uuid ?? result.completeLines)}:${index}`;
- if (!thinking.has(identity)) {
- thinking.add(identity);
- if (native && block.type === "thinking") quality.exposedThinkingBlocks++;
- if (native && block.type === "redacted_thinking") quality.opaqueThinkingBlocks++;
- }
- }
- }
- }
- result.thinkingBlocks = thinking.size; result.toolCalls = calls.size; result.toolResults = results.size;
- result.pendingTools = [...calls].filter((id) => !results.has(id));
- result.orphanResults = [...results].filter((id) => !calls.has(id));
- result.referencedAgents = [...agents];
- quality.reviewRequired = quality.unknownRecordTypes.length > 0 || quality.unknownBlockTypes.length > 0;
- return result;
-}
-
-/** One writer per session. The runner must await acknowledgements before progressing.
- * Every acknowledgement follows file fsync and atomic manifest replacement. Recovery
- * reuses persisted chunks; a missing/corrupt chunk is an error, never an empty trace.
- */
-export class NativeCapture {
- private manifest: NativeCaptureManifest;
- private readonly scanned = new Map<string, string>();
- constructor(private readonly options: NativeCaptureOptions) {
- if (!SESSION_ID.test(options.sessionId) || !options.owner || !options.producerVersion) throw new Error("Native capture identity is required");
- mkdir(options.directory);
- const file = path.join(options.directory, "manifest.json");
- if (fs.existsSync(file)) {
- // State is private to this writer, but validate identity before reading any evidence.
- const saved: NativeCaptureManifest = JSON.parse(readRegular(file).toString("utf8"));
- if (saved.schema !== 1 || saved.format !== "claude-code" || saved.sessionId !== options.sessionId || saved.owner !== options.owner || saved.source !== sha(path.resolve(options.configDir)) || saved.producerVersion !== options.producerVersion || saved.surface !== options.surface || saved.transport !== options.transport) throw new Error("Native capture identity mismatch");
- this.manifest = saved;
- this.verify();
- } else {
- this.manifest = { schema: 1, format: "claude-code", sessionId: options.sessionId, producerVersion: options.producerVersion, surface: options.surface, transport: options.transport, owner: options.owner, source: sha(path.resolve(options.configDir)), revision: 0, status: "capturing", replay: "unverified", confidential: true, redacted: false, files: [], history: [], issues: [], streams: { cli: 0, sdk: 0, hooks: 0 } };
- this.persist();
- }
- }
-
- private persist(): NativeCaptureManifest {
- this.manifest.revision++;
- atomic(path.join(this.options.directory, "manifest.json"), JSON.stringify(this.manifest, null, 2) + "\n");
- return structuredClone(this.manifest);
- }
-
- private content(file: NativeFile): Buffer {
- const chunks = file.chunks.map((chunk) => {
- if (!/^[a-f0-9]{64}$/.test(chunk.sha256)) throw new Error("Invalid native chunk reference");
- const bytes = readRegular(path.join(this.options.directory, "chunks", chunk.sha256));
- if (bytes.length !== chunk.bytes || sha(bytes) !== chunk.sha256) throw new Error("Native chunk integrity failure");
- return bytes;
- });
- const bytes = Buffer.concat(chunks);
- if (bytes.length !== file.bytes || sha(bytes) !== file.sha256) throw new Error("Native file integrity failure");
- return bytes;
- }
-
- verify(): NativeCaptureManifest {
- for (const file of [...this.manifest.files, ...this.manifest.history]) this.content(file);
- return structuredClone(this.manifest);
- }
-
- private capture(name: string, bytes: Buffer): void {
- const previous = this.manifest.files.find((file) => file.path === name);
- const digest = sha(bytes);
- if (previous?.sha256 === digest) return;
- let generation = previous?.generation ?? 0;
- if (previous) {
- if (bytes.length < previous.bytes || sha(bytes.subarray(0, previous.bytes)) !== previous.sha256) {
- this.manifest.history.push(previous);
- generation++;
- }
- }
- const chunks: Chunk[] = [];
- for (let offset = 0; offset < bytes.length; offset += CHUNK_BYTES) {
- const part = bytes.subarray(offset, offset + CHUNK_BYTES), digest = sha(part);
- const target = path.join(this.options.directory, "chunks", digest);
- if (!fs.existsSync(target)) atomic(target, part);
- else if (sha(readRegular(target)) !== digest) throw new Error("Native chunk integrity failure");
- chunks.push({ sha256: digest, bytes: part.length });
- }
- this.manifest.files = this.manifest.files.filter((file) => file.path !== name);
- this.manifest.files.push({ path: name, generation, bytes: bytes.length, sha256: digest, chunks, ...inspect(bytes, name.endsWith(".jsonl"), name.startsWith("claude/projects/") && name.endsWith(".jsonl")) });
- }
-
- scan(): NativeCaptureManifest {
- this.manifest.status = "capturing";
- this.manifest.issues = [];
- const projects = path.join(this.options.configDir, "projects");
- const found = new Set<string>();
- let total = 0;
- const take = (file: string, name: string) => {
- try {
- const stat = fs.lstatSync(file, { bigint: true });
- if (!stat.isFile()) throw new Error("Native transcript must be a regular file without symlinks");
- total += Number(stat.size);
- if (total > MAX_TOTAL_BYTES) throw new Error("Native session exceeds capture budget");
- const fingerprint = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
- if (this.scanned.get(name) !== fingerprint) {
- this.capture(name, readRegular(file));
- this.scanned.set(name, fingerprint);
- }
- found.add(name);
- } catch (error) {
- // Keep every already captured byte and record the gap before failing.
- this.manifest.status = "incomplete";
- this.manifest.issues.push(`source_capture_failed:${name}`);
- this.persist();
- throw error;
- }
- };
- if (fs.existsSync(projects)) {
- if (fs.realpathSync(projects) !== path.resolve(projects)) throw new Error("Native projects directory must not traverse symlinks");
- for (const project of fs.readdirSync(projects, { withFileTypes: true })) {
- if (!project.isDirectory()) continue;
- const base = path.join(projects, project.name), prefix = `claude/projects/${project.name}`;
- const root = path.join(base, `${this.options.sessionId}.jsonl`);
- if (fs.existsSync(root)) take(root, `${prefix}/${this.options.sessionId}.jsonl`);
- const children = path.join(base, this.options.sessionId, "subagents");
- if (!fs.existsSync(children)) continue;
- if (fs.realpathSync(children) !== children) throw new Error("Native subagents directory must not traverse symlinks");
- for (const child of fs.readdirSync(children, { withFileTypes: true })) {
- if (!CHILD_FILE.test(child.name)) continue;
- take(path.join(children, child.name), `${prefix}/${this.options.sessionId}/subagents/${child.name}`);
- }
- }
- }
- for (const channel of ["cli", "sdk", "hooks"] as const) {
- const file = path.join(this.options.directory, "events", `${channel}.jsonl`);
- if (fs.existsSync(file)) {
- take(file, `events/${channel}.jsonl`);
- this.manifest.streams[channel] = fs.statSync(file).size;
- }
- }
- this.manifest.issues = this.manifest.files.filter((file) => !found.has(file.path)).map((file) => `source_missing:${file.path}`);
- this.manifest.files.sort((a, b) => a.path.localeCompare(b.path));
- const qc = emptyQuality();
- for (const file of this.manifest.files) {
- if (!file.path.startsWith("claude/projects/") || !file.path.endsWith(".jsonl")) continue;
- // Older manifests are upgraded from original bytes, never assumed empty.
- if (!file.quality) Object.assign(file, inspect(this.content(file), true, true));
- const quality = file.quality;
- if (!quality) continue;
- for (const key of ["nativeRecords", "syntheticUserRecords", "childPromptRecords", "compactionRecords", "exposedThinkingBlocks", "opaqueThinkingBlocks"] as const) qc[key] += quality[key];
- if (file.path.includes("/subagents/")) qc.childPromptRecords += quality.humanPromptCandidates;
- else qc.humanPromptCandidates += quality.humanPromptCandidates;
- for (const key of ["recordTypes", "blockTypes"] as const) for (const [type, count] of Object.entries(quality[key])) qc[key][type] = (qc[key][type] ?? 0) + count;
- for (const key of ["unknownRecordTypes", "unknownBlockTypes"] as const) qc[key] = [...new Set([...qc[key], ...quality[key]])].sort();
- }
- qc.preservedRevisions = this.manifest.history.length;
- qc.reviewRequired = qc.unknownRecordTypes.length > 0 || qc.unknownBlockTypes.length > 0 || qc.preservedRevisions > 0;
- this.manifest.qc = qc;
- const manifest = this.persist();
- // A growing final chunk supersedes its previous prefix. Prune only after
- // the new manifest is durable; retain every referenced rewrite generation.
- const referenced = new Set([...this.manifest.files, ...this.manifest.history].flatMap((file) => file.chunks.map((chunk) => chunk.sha256)));
- const chunks = path.join(this.options.directory, "chunks");
- if (fs.existsSync(chunks)) for (const name of fs.readdirSync(chunks)) {
- if (/^[a-f0-9]{64}$/.test(name) && !referenced.has(name)) fs.unlinkSync(path.join(chunks, name));
- }
- return manifest;
- }
-
- recordStream(channel: "cli" | "sdk" | "hooks", bytes: Uint8Array, offset: number): NativeCaptureManifest {
- if (!["cli", "sdk", "hooks"].includes(channel) || bytes.length > 8 * CHUNK_BYTES) throw new Error("Invalid native stream chunk");
- const file = path.join(this.options.directory, "events", `${channel}.jsonl`);
- mkdir(path.dirname(file));
- if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw new Error("Native event stream must not be a symlink");
- const fd = fs.openSync(file, fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
- try {
- const existing = fs.fstatSync(fd);
- if (!existing.isFile() || !Number.isSafeInteger(offset) || offset < 0 || offset > existing.size) throw new Error("Native stream offset gap");
- const overlap = Math.min(bytes.length, existing.size - offset);
- const prefix = Buffer.alloc(overlap);
- if (overlap && (fs.readSync(fd, prefix, 0, overlap, offset) !== overlap || !prefix.equals(bytes.subarray(0, overlap)))) throw new Error("Conflicting native stream retry");
- const remaining = bytes.subarray(overlap);
- if (existing.size + remaining.length > MAX_FILE_BYTES) throw new Error("Native event stream exceeds capture budget");
- fs.writeFileSync(fd, remaining); fs.fsyncSync(fd);
- this.manifest.streams[channel] = existing.size + remaining.length;
- } finally { fs.closeSync(fd); }
- syncDir(path.dirname(file));
- // The stream itself is the durable journal; chunk it at scan/turn barriers.
- this.manifest.status = "capturing";
- return this.persist();
- }
-
- finish(input: Extract<NativeCaptureAction, { type: "finish" }>): NativeCaptureManifest {
- this.scan();
- const issues = this.manifest.issues;
- if (!input.processStopped) issues.push("producer_still_running");
- if (!input.successfulResult) issues.push("successful_result_missing");
- const roots = this.manifest.files.filter((file) => file.path.endsWith(`/${this.options.sessionId}.jsonl`));
- if (roots.length !== 1 || roots[0].completeLines === 0) issues.push("root_transcript_missing_or_ambiguous");
- for (const file of this.manifest.files) {
- if (file.tailBytes) issues.push(`partial_line:${file.path}`);
- if (file.invalidLines) issues.push(`invalid_json:${file.path}`);
- if (file.pendingTools.length) issues.push(`pending_tools:${file.path}`);
- if (file.orphanResults?.length && file.path.startsWith("claude/")) issues.push(`orphan_results:${file.path}`);
- if (file.conflictingToolIds?.length) issues.push(`conflicting_tool_identity:${file.path}`);
- }
- const expectedAgents = new Set([...(input.expectedAgents ?? []), ...this.manifest.files.flatMap((file) => file.referencedAgents)]);
- for (const agent of expectedAgents) {
- if (!/^[a-zA-Z0-9_-]+$/.test(agent) || !this.manifest.files.some((file) => file.path.endsWith(`/subagents/agent-${agent}.jsonl`) && file.completeLines > 0)) issues.push(`child_transcript_missing:${agent}`);
- }
- this.manifest.status = issues.length ? "incomplete" : "complete";
- this.verify();
- return this.persist();
- }
-
- /** Private byte-exact export only. A public export needs a separately audited
- * redacted derivative and must not claim these hashes or resumability.
- */
- exportTo(destination: string): NativeCaptureManifest {
- if (fs.existsSync(destination)) throw new Error("Native export destination already exists");
- this.verify();
- mkdir(destination);
- for (const file of [...this.manifest.files, ...this.manifest.history]) {
- if (!/^(claude\/projects\/|events\/)/.test(file.path) || file.path.split("/").some((part) => !part || part === "." || part === ".." || part.includes("\\"))) throw new Error("Invalid native export path");
- const historic = this.manifest.history.includes(file);
- const target = historic ? `history/${file.generation}/${file.path}` : file.path;
- atomic(path.join(destination, target), this.content(file));
- }
- atomic(path.join(destination, "native-manifest.json"), JSON.stringify(this.manifest, null, 2) + "\n");
- return structuredClone(this.manifest);
- }
-}
diff --git a/apps/server/src/claude-code/native.ts b/apps/server/src/claude-code/native.ts
new file mode 100644
index 00000000..f50da4e3
--- /dev/null
+++ b/apps/server/src/claude-code/native.ts
@@ -0,0 +1,88 @@
+// After each Claude turn: the chat's native Claude Code transcript, unchanged, as `claude/` members
+// of a `claude_native` archive of the same session (upload.ts, archive spec 20). The same as the
+// CLI's src/claude-code/native.ts. No environment snapshot (phase 1): the chat's own archive carries the project.
+import fs from "node:fs";
+import fsp from "node:fs/promises";
+import path from "node:path";
+import { createHash } from "node:crypto";
+
+import type { ClaudeGrant } from "./access.js";
+import { parseNativeCaptureCapabilities, uploadNativeBundle, type NativeArchiveDriver, type NativeUploadReceipt, type NativeUploadRequest } from "./upload.js";
+
+const MANIFEST = "__omnirush__/manifest.json";
+
+async function sha256(file: string) {
+ const hash = createHash("sha256");
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
+ return hash.digest("hex");
+}
+
+/** The chat's transcript files in Claude's config folder: `<uuid>.jsonl` and its `<uuid>/` (sub-agents), as `claude/…` names. */
+export function transcriptFiles(configDir: string, uuid: string): { name: string; file: string }[] {
+ const out: { name: string; file: string }[] = [];
+ const projects = path.join(configDir, "projects");
+ let dirs: string[] = [];
+ try { dirs = fs.readdirSync(projects); } catch { return out; }
+ const walk = (dir: string) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else if (entry.isFile()) out.push({ name: `claude/${path.relative(configDir, full).split(path.sep).join("/")}`, file: full });
+ }
+ };
+ for (const dir of dirs) {
+ const main = path.join(projects, dir, `${uuid}.jsonl`);
+ if (fs.existsSync(main)) out.push({ name: `claude/projects/${dir}/${uuid}.jsonl`, file: main });
+ if (fs.existsSync(path.join(projects, dir, uuid))) walk(path.join(projects, dir, uuid));
+ }
+ return out.sort((a, b) => (a.name < b.name ? -1 : 1));
+}
+
+/** The box run folder's Claude config holding `uuid` (each project's box has its own): <boxHome>/projects/<key>/claude/config. */
+export function claudeConfigDirOf(boxHome: string, uuid: string): string | null {
+ let keys: string[] = [];
+ try { keys = fs.readdirSync(path.join(boxHome, "projects")); } catch { return null; }
+ for (const key of keys) {
+ const configDir = path.join(boxHome, "projects", key, "claude", "config");
+ if (transcriptFiles(configDir, uuid).length) return configDir;
+ }
+ return null;
+}
+
+/** One turn's native upload: a staged copy (the box may write on) with its manifest, sealed and sent; the staged copy is removed after. */
+export async function uploadClaudeTurn({ grant, uuid, configDir, stateDir, engineVersion, request, driver }: {
+ grant: ClaudeGrant; uuid: string; configDir: string; stateDir: string; engineVersion: string; request: NativeUploadRequest; driver: NativeArchiveDriver;
+}): Promise<NativeUploadReceipt | { status: "skipped"; reason: string }> {
+ const files = transcriptFiles(configDir, uuid);
+ if (!files.length) return { status: "skipped", reason: "no_transcript" };
+ const response = await request("collect/capabilities", { method: "GET" });
+ const value: { claude_code?: { capture?: unknown } } | null = response.ok ? await response.json() : null;
+ const capabilities = parseNativeCaptureCapabilities(value?.claude_code?.capture);
+ if (!capabilities) return { status: "skipped", reason: "capture_not_offered" };
+ capabilities.checkpoint.enabled = false;
+ const home = path.join(stateDir, "claude-native", grant.sessionId);
+ const stage = path.join(home, `stage-${process.pid}`);
+ await fsp.rm(stage, { recursive: true, force: true });
+ try {
+ const listed: { path: string; size: number; sha256: string }[] = [];
+ for (const { name, file } of files) {
+ const target = path.join(stage, ...name.split("/"));
+ await fsp.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
+ await fsp.copyFile(file, target);
+ listed.push({ path: name, size: (await fsp.stat(target)).size, sha256: await sha256(target) });
+ }
+ const manifest = { schema: "omnirush.claude.native.v1", session_id: grant.sessionId, root_session_id: grant.sessionId, binding_id: grant.bindingId,
+ contract_hash: grant.contractSha256, harness: "claude-code", engine_version: engineVersion, payload: "claude_native", claude_session_id: uuid, files: listed };
+ await fsp.mkdir(path.join(stage, "__omnirush__"), { recursive: true, mode: 0o700 });
+ await fsp.writeFile(path.join(stage, ...MANIFEST.split("/")), JSON.stringify(manifest), { mode: 0o600 });
+ const prior = fs.existsSync(path.join(home, "claude_native")) ? fs.readdirSync(path.join(home, "claude_native")).filter((n) => /^[0-9a-f]{64}\.json$/.test(n)).length : 0;
+ const receipt = await uploadNativeBundle({
+ sessionId: grant.sessionId, owner: grant.owner, turn: prior, bindingId: grant.bindingId, contractHash: grant.contractSha256, engineVersion,
+ nativeDirectory: stage, stateDirectory: home, capabilities, driver,
+ });
+ if (receipt.native.status === "uploaded" && receipt.native.archiveId) await fsp.rm(path.join(home, "claude_native", `${receipt.native.archiveId}.orseal`), { force: true });
+ return receipt;
+ } finally {
+ await fsp.rm(stage, { recursive: true, force: true });
+ }
+}
diff --git a/apps/server/src/claude-code/replay-adapter.ts b/apps/server/src/claude-code/replay-adapter.ts
deleted file mode 100644
index e723657d..00000000
--- a/apps/server/src/claude-code/replay-adapter.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-// Generated from tools/claude-native/verify.py by scripts/sync-claude-capture.mjs.
-export const REPLAY_ADAPTER = "#!/usr/bin/env python3\n\"\"\"Private native-Claude ingress for omniconv's recorded-tool replay engine.\n\nRun on an isolated conversion worker with the reviewed omniconv checkout on\nPYTHONPATH. Never run uploaded code on the worker host. Original Claude JSONL\nis authoritative; calls.json is a derived verifier input, not an OpenCode trace.\nThis verifies tool replay and selected filesystem scopes, not model inference\nor approval to distribute unmasked data.\n\"\"\"\nimport argparse\nimport hashlib\nimport json\nimport os\nfrom pathlib import Path\nimport re\nimport subprocess\nimport tarfile\nimport tempfile\nimport time\nimport uuid\nimport zipfile\nfrom datetime import datetime\nfrom contextlib import contextmanager\n\n\ndef sha(data):\n return hashlib.sha256(data).hexdigest()\n\n\ndef file_digest(path):\n digest, size = hashlib.sha256(), 0\n with path.open('rb') as source:\n for chunk in iter(lambda: source.read(1024 * 1024), b''):\n digest.update(chunk)\n size += len(chunk)\n return {'sha256': digest.hexdigest(), 'bytes': size}\n\n\ndef evidence_members(manifest):\n \"\"\"Every preserved generation participates in integrity and execution checks.\"\"\"\n for item in manifest['files']:\n yield item['path'], item\n for item in manifest.get('history', []):\n generation = item['generation']\n if type(generation) is not int or generation < 0:\n raise ValueError('Invalid evidence generation')\n yield f\"history/{generation}/{item['path']}\", item\n\n\ndef jsonl(bundle, name):\n data = bundle.read(name)\n if data and not data.endswith(b'\\n'):\n raise ValueError('Truncated native evidence: ' + name)\n for line in data.decode('utf-8', errors='strict').splitlines():\n if not line.strip():\n continue\n value = json.loads(line)\n if not isinstance(value, dict):\n raise ValueError('Native record must be an object: ' + name)\n yield value\n\n\ndef semantic_gaps(bundle, manifest):\n \"\"\"Recompute admission from bytes, not a client-supplied quality verdict.\"\"\"\n records = {'user', 'assistant', 'system', 'attachment', 'progress', 'queue-operation', 'last-prompt', 'atis-latch',\n 'cost-state', 'mode', 'summary', 'file-history-snapshot', 'custom-title', 'agent-name', 'agent-color',\n 'tag', 'pr-link', 'api-request', 'api-request-blob', 'api-request-shape'}\n blocks = {'text', 'image', 'document', 'tool_use', 'tool_result', 'thinking', 'redacted_thinking'}\n unknown_records, unknown_blocks = set(), set()\n for name, item in evidence_members(manifest):\n if not item['path'].startswith('claude/projects/') or not name.endswith('.jsonl'):\n continue\n for event in jsonl(bundle, name):\n kind = event.get('type') if isinstance(event.get('type'), str) else '<missing>'\n if kind not in records:\n unknown_records.add(kind)\n if kind not in ('user', 'assistant'):\n continue\n message = event.get('message')\n content = message.get('content') if isinstance(message, dict) else None\n if isinstance(content, str):\n continue\n if not isinstance(content, list):\n unknown_blocks.add('<invalid-content>')\n continue\n for block in content:\n kind = block.get('type') if isinstance(block, dict) and isinstance(block.get('type'), str) else '<missing>'\n if kind not in blocks:\n unknown_blocks.add(kind)\n return {'unknown_record_types': sorted(unknown_records), 'unknown_block_types': sorted(unknown_blocks)}\n\n\ndef model_evidence(bundle, session):\n \"\"\"A separate quality check: tool replay cannot prove model provenance.\"\"\"\n result = {'status': 'unknown', 'scope': 'managed-inference',\n 'identity_basis': 'provider-response-body', 'initial_workspace_provenance': 'user-supplied-unattested',\n 'eligible': False, 'blockers': []}\n contract, isolation = session.get('contract'), session.get('modelIsolation')\n if not isinstance(contract, dict) or not isinstance(isolation, dict):\n return {**result, 'status': 'legacy_unverified', 'blockers': ['model_contract_or_journal_missing']}\n try:\n saved = json.loads(bundle.read('policy/contract.json'))\n contract_bytes = json.dumps(contract, ensure_ascii=False, separators=(',', ':')).encode()\n expected = session.get('contractSha256')\n valid = (saved.get('contract') == contract and saved.get('sha256') == expected and sha(contract_bytes) == expected\n and contract.get('schema') == 1 and contract.get('sessionId') == session['id']\n and contract.get('owner') == session['owner'] and contract.get('workspaceId') == session['workspaceId']\n and contract.get('model') == session['model']\n and contract.get('execution', {}).get('baseImage') == session['base']['image']\n and contract.get('execution', {}).get('kind') == 'docker'\n and contract.get('execution', {}).get('os') == 'linux'\n and contract.get('execution', {}).get('shell') == '/bin/bash'\n and contract.get('execution', {}).get('workingDirectory') == '/workspace'\n and contract.get('harness', {}).get('name') == 'claude-code'\n and contract.get('harness', {}).get('sdkVersion') == session.get('sdkVersion')\n and contract.get('harness', {}).get('claudeVersion') == session.get('claudeVersion')\n and contract.get('capture', {}).get('scope') == 'managed-inference'\n and contract.get('capture', {}).get('modelIsolation') == 'exact')\n if not valid:\n return {**result, 'status': 'invalid', 'blockers': ['model_contract_integrity_mismatch']}\n raw = bundle.read('policy/model-requests.jsonl')\n resolved = isolation.get('resolvedModel')\n if not isinstance(resolved, str) or not resolved or session.get('authorization', {}).get('upstreamModel') != resolved:\n return {**result, 'blockers': ['bound_upstream_model_missing']}\n if resolved != session['model']:\n return {**result, 'status': 'invalid', 'blockers': ['bound_upstream_model_mismatch']}\n result['catalog_model'], result['resolved_upstream_model'] = session['model'], resolved\n result['contract_sha256'] = expected\n result['journal'] = {'sha256': sha(raw), 'bytes': len(raw)}\n if sha(raw) != isolation.get('evidenceSha256') or len(raw) != isolation.get('evidenceBytes'):\n return {**result, 'status': 'invalid', 'blockers': ['model_journal_integrity_mismatch']}\n requests, responses, identities = {}, {}, {}\n problems = set()\n for event in jsonl(bundle, 'policy/model-requests.jsonl'):\n if event.get('schema') != 1 or event.get('sessionId') != session['id']:\n problems.add('model_event_identity_mismatch')\n request_id = event.get('requestId')\n if not isinstance(request_id, str) or not request_id:\n problems.add('model_request_identity_missing')\n continue\n kind = event.get('type')\n if kind == 'request':\n if request_id in requests:\n problems.add('duplicate_model_request')\n requests[request_id] = event\n if event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('contractSha256') != expected:\n problems.add('requested_model_mismatch')\n if event.get('route') not in ('messages', 'count_tokens'):\n problems.add('unknown_model_route')\n elif kind == 'response':\n if request_id in responses:\n problems.add('duplicate_model_response')\n responses[request_id] = event\n elif kind == 'provider_identity':\n identities.setdefault(request_id, set()).add(event.get('providerModel'))\n if event.get('providerModel') != resolved or event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('source') != 'response-body':\n problems.add('observed_model_mismatch')\n elif kind == 'rejected':\n problems.add('rejected_model_request')\n else:\n problems.add('unknown_model_event')\n if set(requests) != set(responses) or set(identities) - set(requests):\n problems.add('model_journal_incomplete')\n completed = 0\n for request_id, request in requests.items():\n if request.get('route') != 'messages':\n continue\n response = responses.get(request_id, {})\n status = response.get('status')\n if type(status) is int and status >= 400:\n # Failed upstream attempts remain in evidence. They do not\n # establish another model or count as completed inference.\n if response.get('providerModels') or identities.get(request_id):\n problems.add('model_identity_on_failed_response')\n continue\n if type(status) is not int or not 200 <= status < 300 or response.get('completed') is not True or response.get('streamComplete') is not True:\n problems.add('inference_response_incomplete')\n if response.get('identity') != 'reported' or response.get('providerModels') != [resolved] or identities.get(request_id) != {resolved}:\n problems.add('inference_identity_missing_or_mixed')\n completed += 1\n if not completed:\n problems.add('no_completed_model_inference')\n if isolation.get('status') != 'observed' or isolation.get('expectedModel') != session['model'] or isolation.get('observedModels') != [resolved]:\n problems.add('model_summary_not_observed')\n invalid = bool(problems & {'model_event_identity_mismatch', 'requested_model_mismatch', 'observed_model_mismatch', 'rejected_model_request'})\n result.update(status='invalid' if invalid else 'unknown' if problems else 'observed', eligible=not problems,\n completed_inference_requests=completed, blockers=sorted(problems))\n return result\n except (KeyError, ValueError, TypeError, AttributeError, UnicodeDecodeError):\n return {**result, 'status': 'unknown', 'blockers': ['model_evidence_unreadable']}\n\n\ndef stamp(value):\n return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp() * 1000\n\n\ndef docker(*args, timeout=180):\n result = subprocess.run(['docker', *args], capture_output=True, timeout=timeout)\n if result.returncode:\n raise RuntimeError('Docker operation failed: ' + result.stderr.decode(errors='replace')[-1000:])\n return result.stdout.decode().strip()\n\n\ndef write(path, value):\n path.write_text(json.dumps(value, indent=2) + '\\n')\n path.chmod(0o600)\n\n\n@contextmanager\ndef record_failure(path, report):\n try:\n yield\n except Exception as error:\n report.update(status='UNVERIFIED', strict_verified=False,\n failure={'type': type(error).__name__, 'message': str(error)})\n write(path, report)\n raise\n\n\ndef text_content(content):\n if isinstance(content, str):\n return content\n return '\\n'.join(block.get('text', '') for block in content or [] if block.get('type') == 'text')\n\n\ndef agent_model_omission(bundle, session, manifest, call, result, stop):\n \"\"\"Corroborate one reviewed SDK transform; retain the discrepancy as SOFT.\n\n SDK 0.3.306 / Claude 2.1.306's Agent schema omits model when\n CLAUDE_CODE_SUBAGENT_MODEL_FORCE is set. Its executor safeParse strips that\n field before hooks. This controller hash pins the reviewed force setting\n and unchanged hook callback. It is applicability evidence, not attestation.\n \"\"\"\n def reject():\n raise ValueError('Uncorroborated native Agent model omission: ' + call['id'])\n\n controller = session.get('contract', {}).get('harness', {}).get('controllerSha256')\n if (session.get('sdkVersion'), session.get('claudeVersion'), controller) != (\n '0.3.306', '2.1.306', 'fd1d3a901953f38fc866d6ce62ec5f80ef247f878d029ae47bb581832b26ab00'):\n reject()\n if not model_evidence(bundle, session)['eligible']:\n reject()\n native = result['native']\n if (result['block'].get('is_error') or not isinstance(native, dict)\n or not isinstance(native.get('agentId'), str) or not native['agentId']\n or native.get('status') not in ('async_launched', 'completed')\n or native.get('resolvedModel') != session['model']\n or stop['input'].get('hook_event_name') != 'PostToolUse'\n or stop['input'].get('tool_response') != native):\n reject()\n member = 'events/sdk.jsonl'\n entries = [item for item in manifest['files'] if item['path'] == member]\n if len(entries) != 1 or member not in bundle.namelist():\n reject()\n raw = bundle.read(member)\n if entries[0].get('sha256') != sha(raw) or entries[0].get('bytes') != len(raw):\n reject()\n # Validate framing and JSON before inspecting physical line witnesses.\n list(jsonl(bundle, member))\n witnesses = {'requested': [], 'result': [], 'child': []}\n for number, line in enumerate(raw.splitlines(), 1):\n if not line.strip():\n continue\n event = json.loads(line)\n message = event.get('message', {})\n content = message.get('content', [])\n reference = {'path': member, 'line': number, 'sha256': sha(line), 'uuid': event.get('uuid')}\n for block in content if isinstance(content, list) else []:\n if event.get('type') == 'assistant' and block.get('type') == 'tool_use' and block.get('id') == call['id']:\n if (block.get('name') != call['tool'] or block.get('input') != call['input']\n or (event.get('agent_id') or event.get('session_id')) != call['session']):\n reject()\n witnesses['requested'].append(reference)\n if event.get('type') == 'user' and block.get('type') == 'tool_result' and block.get('tool_use_id') == call['id']:\n if block != result['block'] or event.get('tool_use_result') != native:\n reject()\n witnesses['result'].append(reference)\n if event.get('type') == 'assistant' and event.get('parent_tool_use_id') == call['id']:\n if event.get('agent_id') != native['agentId'] or message.get('model') != session['model']:\n reject()\n witnesses['child'].append(reference)\n if not all(witnesses.values()):\n reject()\n return {'kind': 'sdk_agent_model_omission', 'strict_verified': False,\n 'requested_input': call['input'], 'effective_input': call['native_effective_input'],\n 'resolved_model': native['resolvedModel'], 'controller_sha256': controller,\n 'sdk_witnesses': witnesses, 'model_journal_sha256': session['modelIsolation']['evidenceSha256']}\n\n\ndef calls_from(bundle, session, manifest):\n hooks = list(jsonl(bundle, 'events/hooks.jsonl'))\n starts, stops = {}, {}\n for event in hooks:\n item = event['input']\n if item.get('hook_event_name') == 'PreToolUse':\n key = item['tool_use_id']\n if key in starts:\n raise ValueError('Ambiguous repeated tool execution: ' + key)\n starts[key] = event\n elif item.get('hook_event_name') in ('PostToolUse', 'PostToolUseFailure'):\n key = item['tool_use_id']\n if key in stops:\n raise ValueError('Ambiguous repeated tool completion: ' + key)\n stops[key] = event\n calls, results = {}, {}\n for name, file in evidence_members(manifest):\n if not file['path'].startswith('claude/projects/') or not file['path'].endswith('.jsonl'):\n continue\n for event in jsonl(bundle, name):\n if event.get('type') not in ('assistant', 'user'):\n continue # Request-cache blobs repeat context; they are not executions.\n content = event.get('message', {}).get('content')\n if not isinstance(content, list):\n continue\n for block in content:\n if block.get('type') == 'tool_use':\n key = block['id']\n hook = starts.get(key)\n if hook is None:\n raise ValueError('No execution hook for native call: ' + key)\n item = hook['input']\n if item['tool_name'] != block['name']:\n raise ValueError('Native transcript and hook disagree: ' + key)\n requested, effective = block['input'], item['tool_input']\n if requested != effective and not (\n block['name'] == 'Agent' and isinstance(requested, dict) and isinstance(effective, dict)\n and isinstance(requested.get('model'), str) and requested['model']\n and {k: v for k, v in requested.items() if k != 'model'} == effective):\n raise ValueError('Native transcript and hook disagree: ' + key)\n call = {'id': key, 'tool': block['name'], 'input': block['input'],\n 'start': stamp(hook['time']), 'turn': hook['turn'],\n 'session': item.get('agent_id') or event.get('agentId') or session['id'], 'status': 'pending',\n 'source': {'path': name, 'uuid': event.get('uuid')}, 'native_read_witness': hook.get('witness'),\n 'native_cwd': item.get('cwd')}\n if requested != effective:\n call['native_effective_input'] = effective\n if key in calls and (calls[key]['tool'], calls[key]['input']) != (call['tool'], call['input']):\n raise ValueError('Conflicting native call identity: ' + key)\n if key not in calls:\n call['sources'] = [call['source']]\n calls[key] = call\n elif call['source'] not in calls[key]['sources']:\n calls[key]['sources'].append(call['source'])\n elif block.get('type') == 'tool_result':\n key = block['tool_use_id']\n value = {'block': block, 'native': event.get('toolUseResult'), 'end': event.get('timestamp')}\n if key in results and (results[key]['block'], results[key]['native']) != (block, value['native']):\n raise ValueError('Conflicting native result identity: ' + key)\n results[key] = value\n if set(starts) != set(calls):\n raise ValueError('Execution hooks and native calls do not form a complete set')\n if set(results) != set(calls):\n raise ValueError('Native calls and results do not form a complete set')\n for key, call in calls.items():\n if key not in results:\n raise ValueError('Native tool result missing: ' + key)\n result = results[key]\n block, native = result['block'], result['native']\n stop = stops.get(key)\n if stop is None:\n raise ValueError('Native tool completion hook missing: ' + key)\n if stop['turn'] != call['turn'] or stop['input']['tool_name'] != call['tool'] or stop['input']['tool_input'] != call.get('native_effective_input', call['input']):\n raise ValueError('Native tool completion hook disagrees: ' + key)\n if 'native_effective_input' in call:\n call['native_input_normalization'] = agent_model_omission(bundle, session, manifest, call, result, stop)\n call.update(status='error' if block.get('is_error') else 'completed',\n output=text_content(block.get('content')), end=stamp(stop['time']))\n if call['end'] < call['start']:\n raise ValueError('Native execution interval runs backwards: ' + key)\n call['meta'] = {'native_tool_result': native}\n if isinstance(native, dict):\n if native.get('agentId'):\n call['meta']['child_session_id'] = native['agentId']\n # Structured stdout/stderr avoid comparing Claude's no-output UI\n # placeholder as if it were bytes printed by the user's command.\n if call['tool'] == 'Bash' and isinstance(native.get('stdout'), str) and isinstance(native.get('stderr'), str):\n call['output'] = native['stdout'] + native['stderr']\n if native.get('type') == 'file_unchanged':\n # This SDK optimization contains no read bytes. It cannot prove\n # that a replayed read matched; never invent bytes from after.\n call['native_file_unchanged'] = True\n return sorted(calls.values(), key=lambda call: (call['start'], call['id']))\n\n\ndef native_bash(verify, ctr, call, state):\n \"\"\"Replay the recorded command without the generic converter's shell fixes.\n\n Claude's Bash result does not expose its numeric exit or actual shell argv.\n Command/cwd are evidence; /bin/bash -lc is a declared reproduction recipe.\n Therefore even matching stdout and success are SOFT, never strict proof.\n \"\"\"\n inp, native = call['input'], call['meta']['native_tool_result']\n cmd, cwd = inp.get('command'), call.get('native_cwd')\n if not isinstance(cmd, str) or not cmd.strip():\n return {'outcome': 'not_replayable', 'reason': 'native_command_missing'}\n if not isinstance(cwd, str) or not cwd.startswith('/') or '\\0' in cwd:\n return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}\n if not isinstance(native, dict) or not all(isinstance(native.get(k), str) for k in ('stdout', 'stderr')):\n return {'outcome': 'no_evidence', 'why': 'native Bash stdout/stderr are missing'}\n if native.get('interrupted') or inp.get('run_in_background') or native.get('backgroundTaskId'):\n return {'outcome': 'not_replayable', 'reason': 'native_background_or_interrupted'}\n if any(native.get(key) for key in ('truncated', 'truncation', 'fullOutputPath', 'outputFile', 'isImage')):\n return {'outcome': 'not_replayable', 'reason': 'native_output_not_text_complete'}\n if verify.classify(cmd) in ('skipped_side_effect', 'server'):\n return {'outcome': 'not_replayable', 'reason': 'native_external_effect_or_server'}\n state.setdefault('commands', []).append(cmd)\n timeout_ms = inp.get('timeout', 120000)\n if type(timeout_ms) is not int or timeout_ms < 1 or timeout_ms > 600000:\n return {'outcome': 'not_replayable', 'reason': 'native_timeout_unsupported'}\n argv = ['docker', 'exec', '-w', cwd, ctr, 'timeout', str(timeout_ms / 1000), '/bin/bash', '-lc', cmd]\n began = time.monotonic()\n try:\n result = subprocess.run(argv, capture_output=True, timeout=timeout_ms / 1000 + 30)\n except subprocess.TimeoutExpired:\n return {'outcome': 'harness_error', 'reason': 'native_command_timeout'}\n stdout, stderr = result.stdout.decode(errors='replace'), result.stderr.decode(errors='replace')\n rec = {'recorded_command_sha256': sha(cmd.encode()), 'cwd': cwd, 'shell_recipe': ['/bin/bash', '-lc'],\n 'actual_shell_argv_observed': False, 'numeric_recorded_exit': None, 'replay_exit': result.returncode,\n 'recorded_stdout_sha256': sha(native['stdout'].encode()), 'recorded_stderr_sha256': sha(native['stderr'].encode()),\n 'replay_stdout_sha256': sha(result.stdout), 'replay_stderr_sha256': sha(result.stderr),\n 'seconds': round(time.monotonic() - began, 3)}\n if result.returncode == 124:\n return {**rec, 'outcome': 'harness_error', 'reason': 'native_command_timeout'}\n if (result.returncode != 0) != (call['status'] == 'error'):\n return {**rec, 'outcome': 'diverge', 'why': 'native Bash success/failure differs'}\n exact = stdout == native['stdout'] and stderr == native['stderr']\n # SDK output formatting can strip final newlines. Show that difference,\n # with separate raw hashes; never silently count it as an exact match.\n formatted = stdout.rstrip('\\n') == native['stdout'].rstrip('\\n') and stderr.rstrip('\\n') == native['stderr'].rstrip('\\n')\n if not exact and not formatted:\n return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash output differs; shell invocation is unobserved', 'output_exact': False, 'output': {'stdout': stdout, 'stderr': stderr}}\n return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash actual shell argv and numeric exit are unobserved',\n 'output_exact': exact, 'output_diff': None if exact else 'trailing_newlines'}\n\n\nNATIVE_EDIT = r'''\nimport hashlib, json, os, sys\nrequest = json.load(sys.stdin)\ntool, inp = request['tool'], request['input']\nname = inp['file_path']\ntry:\n with open(name, 'rb') as source:\n original = source.read()\nexcept FileNotFoundError:\n original = None\nif tool == 'Write':\n result = inp['content'].encode('utf-8')\nelif tool == 'Edit':\n if original is None:\n raise ValueError('native_edit_file_missing')\n old, new = inp['old_string'].encode('utf-8'), inp['new_string'].encode('utf-8')\n if not old:\n raise ValueError('native_empty_edit_unsupported')\n count = original.count(old)\n if not count or (count != 1 and not inp.get('replace_all', False)):\n raise ValueError('native_edit_exact_match_missing_or_ambiguous')\n result = original.replace(old, new, -1 if inp.get('replace_all', False) else 1)\nelse:\n raise ValueError('unsupported_native_edit')\nos.makedirs(os.path.dirname(os.path.abspath(name)), exist_ok=True)\nwith open(name, 'wb') as target:\n target.write(result)\n target.flush()\n os.fsync(target.fileno())\nprint(json.dumps({'before_sha256': hashlib.sha256(original).hexdigest() if original is not None else None,\n 'after_sha256': hashlib.sha256(result).hexdigest(), 'bytes': len(result)}))\n'''\n\n\ndef native_edit(ctr, call, state):\n \"\"\"Apply literal native input; no redaction repair or whitespace matching.\"\"\"\n inp, cwd = call['input'], call.get('native_cwd')\n if call['status'] != 'completed':\n return {'outcome': 'not_replayable', 'reason': 'native_failed_edit_semantics'}\n if not isinstance(cwd, str) or not cwd.startswith('/') or not isinstance(inp.get('file_path'), str):\n return {'outcome': 'not_replayable', 'reason': 'native_edit_path_missing'}\n fields = ('content',) if call['tool'] == 'Write' else ('old_string', 'new_string')\n if not all(isinstance(inp.get(key), str) for key in fields):\n return {'outcome': 'not_replayable', 'reason': 'native_edit_input_missing'}\n payload = json.dumps({'tool': call['tool'], 'input': inp}).encode()\n result = subprocess.run(['docker', 'exec', '-i', '-w', cwd, ctr, 'python3', '-c', NATIVE_EDIT],\n input=payload, capture_output=True, timeout=60)\n if result.returncode:\n return {'outcome': 'diverge', 'why': 'native literal edit could not be applied', 'path': inp['file_path']}\n state.setdefault('touched', set()).add(inp['file_path'])\n return {'outcome': 'match', 'path': inp['file_path'], 'literal_input': True, **json.loads(result.stdout)}\n\n\ndef replay_verdict(replay, differences, selected):\n \"\"\"Admission cannot inherit a permissive generic-verifier success label.\"\"\"\n pairs = replay.get('per_call', [])\n if len(pairs) != len(selected) or {pair[0] for pair in pairs} != {call['id'] for call in selected}:\n return 'UNVERIFIED', False, ['execution_coverage_incomplete']\n outcomes = [pair[1].split(':', 1)[0] for pair in pairs]\n if any(differences.values()) or 'diverge' in outcomes:\n return 'DIFFERS', False, ['filesystem_or_tool_result_differs']\n allowed = {'match', 'diverge-soft', 'subagent'}\n blocked = sorted(set(outcomes) - allowed)\n if blocked:\n return ('TOOLS_RAN' if set(blocked) == {'tool-worked'} else 'UNVERIFIED'), False, blocked\n if not outcomes or all(outcome == 'subagent' for outcome in outcomes):\n return 'UNVERIFIED', False, ['no_tool_result_compared']\n soft = ('diverge-soft' in outcomes or bool(replay.get('matches_leaning_on'))\n or any(call.get('native_input_normalization') for call in selected))\n return ('VERIFIED_WITH_SOFT_DIFFS' if soft else 'VERIFIED'), True, []\n\n\ndef tree(container, scope):\n proc = subprocess.Popen(['docker', 'cp', container + ':' + scope, '-'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output = {}\n try:\n with tarfile.open(fileobj=proc.stdout, mode='r|') as archive:\n for member in archive:\n record = {'mode': member.mode, 'type': member.type.decode('ascii'), 'link': member.linkname,\n 'uid': member.uid, 'gid': member.gid}\n if member.isfile():\n digest = hashlib.sha256()\n with archive.extractfile(member) as data:\n for chunk in iter(lambda: data.read(1024 * 1024), b''):\n digest.update(chunk)\n record.update(sha256=digest.hexdigest(), bytes=member.size)\n if member.name in output:\n raise ValueError('Ambiguous filesystem archive member')\n output[member.name] = record\n if proc.wait(timeout=30):\n raise RuntimeError('Cannot inspect replay filesystem')\n return output\n finally:\n if proc.poll() is None:\n proc.kill()\n proc.communicate()\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('zip', type=Path)\n parser.add_argument('--out', required=True, type=Path)\n parser.add_argument('--check-path', action='append', default=[], help='Additional absolute filesystem scope to compare after every turn')\n args = parser.parse_args()\n from omniconv import verify\n original_replay = verify.replay_one\n def replay_native(ctr, root, call, index, calls, state, context):\n if call['tool'] == 'Bash':\n return native_bash(verify, ctr, call, state)\n if call['tool'] in ('Write', 'Edit'):\n return native_edit(ctr, call, state)\n if not call.get('native_file_unchanged') and not (call['tool'] == 'Read' and call.get('native_read_witness')):\n # Absolute native paths pass unchanged. Relative paths resolve from\n # the recorded hook cwd, never a guessed root or a repaired cwd.\n cwd = call.get('native_cwd')\n if not isinstance(cwd, str) or not cwd.startswith('/'):\n return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}\n kind = verify.RT.kind_of(call['tool'])[0]\n if kind == 'shell':\n return {'outcome': 'not_replayable', 'reason': 'unsupported_native_shell'}\n if kind == 'edit':\n return {'outcome': 'not_replayable', 'reason': 'unsupported_native_edit'}\n return original_replay(ctr, cwd, call, index, calls, state, context)\n witness = call.get('native_read_witness')\n if call['status'] != 'completed':\n return {'outcome': 'not_replayable', 'reason': 'native_failed_read_semantics'}\n if not witness or witness.get('path') != call['input'].get('file_path') or not re.fullmatch(r'[a-f0-9]{64}', str(witness.get('sha256', ''))):\n return {'outcome': 'not_replayable', 'reason': 'native_cached_read_without_witness'}\n script = \"import hashlib,json,os,stat,sys\\np=sys.argv[1];s=os.stat(p)\\nassert stat.S_ISREG(s.st_mode)\\nh=hashlib.sha256()\\nwith open(p,'rb') as f:\\n for b in iter(lambda:f.read(1048576),b''):h.update(b)\\nprint(json.dumps({'sha256':h.hexdigest(),'bytes':s.st_size,'mode':s.st_mode}))\"\n code, output, _ = verify.sh(['docker', 'exec', ctr, 'python3', '-c', script, witness['path']], 60)\n actual = json.loads(output) if code == 0 and output.strip() else None\n expected = {key: witness.get(key) for key in ('sha256', 'bytes', 'mode')}\n return {'outcome': 'match' if actual == expected else 'diverge',\n 'why': 'native cached read checked against the pre-tool byte witness',\n 'recorded_witness': expected, 'replay_witness': actual, 'path': witness['path']}\n verify.replay_one = replay_native\n os.umask(0o077)\n args.out.mkdir(parents=True, exist_ok=False)\n scopes = ['/workspace', *args.check_path]\n if any(not scope.startswith('/') or '..' in Path(scope).parts for scope in scopes):\n raise ValueError('Check paths must be absolute')\n report = {'schema': 2, 'format': 'claude-code-native', 'verifier': verify.fingerprint(),\n 'adapter_sha256': sha(Path(__file__).read_bytes()), 'network': 'none',\n 'input_artifact': file_digest(args.zip),\n 'filesystem_scopes': scopes, 'private': True, 'delivery_ready': False,\n 'meaning': 'Recorded tool replay with explicit strict/soft outcomes. Original evidence is never rewritten. Delivery selection is separate.',\n 'status': 'UNVERIFIED', 'turns': []}\n write(args.out / 'replay.json', report)\n with record_failure(args.out / 'replay.json', report), zipfile.ZipFile(args.zip) as bundle:\n if len(bundle.namelist()) != len(set(bundle.namelist())):\n raise ValueError('Duplicate ZIP member')\n session_bytes, manifest_bytes = bundle.read('session.json'), bundle.read('native-manifest.json')\n session, manifest = json.loads(session_bytes), json.loads(manifest_bytes)\n report['adapter_source'] = 'external'\n report['embedded_adapter_sha256'] = sha(bundle.read('verify.py')) if 'verify.py' in bundle.namelist() else None\n report['embedded_adapter_matches_external'] = report['embedded_adapter_sha256'] == report['adapter_sha256']\n report['session_sha256'], report['manifest_sha256'] = sha(session_bytes), sha(manifest_bytes)\n report['model_isolation'] = model_evidence(bundle, session)\n report['session_id'] = session['id']\n if manifest['sessionId'] != session['id'] or manifest['status'] != 'complete' or session['capture'] != 'complete':\n raise ValueError('Incomplete native session cannot pass replay admission')\n checked = set()\n for name, item in evidence_members(manifest):\n if name in checked or '\\\\' in name or name.startswith('/') or '..' in name.split('/'):\n raise ValueError('Ambiguous native evidence path')\n checked.add(name)\n content = bundle.read(name)\n if len(content) != item['bytes'] or sha(content) != item['sha256']:\n raise ValueError('Native evidence integrity failure: ' + name)\n if 'events/hooks.jsonl' not in checked:\n raise ValueError('Execution hooks are not covered by the native manifest')\n report['evidence_generations_checked'] = len(checked)\n report['semantic_gaps'] = semantic_gaps(bundle, manifest)\n report['semantic_review_required'] = any(report['semantic_gaps'].values())\n calls = calls_from(bundle, session, manifest)\n report['input_normalizations'] = [{'id': call['id'], **call['native_input_normalization']}\n for call in calls if call.get('native_input_normalization')]\n if any(call['turn'] not in {turn['number'] for turn in session['turns']} for call in calls):\n raise ValueError('A native call lies outside the captured turn sequence')\n write(args.out / 'calls.json', calls)\n report['calls_artifact'] = file_digest(args.out / 'calls.json')\n checkpoints = [session['base'], *[turn['after'] for turn in session['turns']]]\n if not session['turns'] or any(turn['status'] != 'complete' for turn in session['turns']):\n raise ValueError('Every admitted turn must have completed')\n if [turn['number'] for turn in session['turns']] != list(range(1, len(session['turns']) + 1)):\n raise ValueError('Native user turn sequence is incomplete or ambiguous')\n loaded = set()\n for cp in checkpoints:\n if not re.fullmatch(r'sha256:[a-f0-9]{64}', cp['image']):\n raise ValueError('Invalid image digest')\n if cp['file'] in loaded:\n continue\n if not re.fullmatch(r'images/[a-f0-9]{64}\\.tar\\.gz', cp['file']):\n raise ValueError('Invalid image archive path')\n with tempfile.NamedTemporaryFile(suffix='.tar.gz') as target:\n digest = hashlib.sha256(); size = 0\n with bundle.open(cp['file']) as source:\n for chunk in iter(lambda: source.read(1024 * 1024), b''):\n digest.update(chunk); size += len(chunk); target.write(chunk)\n target.flush()\n if digest.hexdigest() != cp['sha256'] or size != cp['bytes']:\n raise ValueError('Environment archive integrity failure')\n docker('load', '--input', target.name, timeout=600)\n loaded.add(cp['file'])\n for turn in session['turns']:\n if turn['number'] < 1 or turn['before']['image'] != checkpoints[turn['number'] - 1]['image']:\n raise ValueError('Broken before/after environment chain')\n selected = [call for call in calls if call['turn'] == turn['number']]\n name = 'omnirush-native-replay-' + uuid.uuid4().hex\n expected = name + '-expected'\n try:\n common = ['--network=none', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--pids-limit=256', '--memory=4g', '--cpus=2']\n docker('run', '-d', '--name', name, *common, turn['before']['image'], 'sleep', 'infinity')\n docker('create', '--name', expected, *common, turn['after']['image'])\n replay = verify.replay_calls(name, '/workspace', selected, context={'main': session['id'], 'sessions': sorted({call['session'] for call in calls})})\n differences = {}\n for scope in scopes:\n actual_tree, expected_tree = tree(name, scope), tree(expected, scope)\n differences[scope] = [key for key in sorted(set(actual_tree) | set(expected_tree)) if actual_tree.get(key) != expected_tree.get(key)]\n status, accepted, blockers = replay_verdict(replay, differences, selected)\n if report['semantic_review_required']:\n status, accepted = 'UNVERIFIED', False\n blockers.append('unknown_native_semantics')\n report['turns'].append({'number': turn['number'], 'before_image': turn['before']['image'], 'after_image': turn['after']['image'],\n 'calls': len(selected), 'accepted': accepted, 'strict_verified': status == 'VERIFIED',\n 'status': status, 'blockers': blockers, 'replay': replay, 'filesystem_differences': differences})\n write(args.out / 'replay.json', report)\n finally:\n subprocess.run(['docker', 'rm', '-f', name, expected], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n if file_digest(args.zip) != report['input_artifact']:\n report.update(status='UNVERIFIED', strict_verified=False, failure={'type': 'input_integrity', 'message': 'Input artifact changed during replay'})\n write(args.out / 'replay.json', report)\n raise ValueError('Input artifact changed during replay')\n if all(turn['accepted'] for turn in report['turns']):\n report['status'] = 'VERIFIED' if all(turn['strict_verified'] for turn in report['turns']) else 'VERIFIED_WITH_SOFT_DIFFS'\n elif any(turn['status'] == 'DIFFERS' for turn in report['turns']):\n report['status'] = 'DIFFERS'\n elif any(turn['status'] == 'TOOLS_RAN' for turn in report['turns']):\n report['status'] = 'TOOLS_RAN'\n report['strict_verified'] = report['status'] == 'VERIFIED'\n blockers = list(report['model_isolation']['blockers'])\n if report['status'] not in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS'):\n blockers.append('tool_replay_not_verified')\n if report['semantic_review_required']:\n blockers.append('unknown_native_semantics')\n report['quality_admission'] = {'eligible': not blockers, 'blockers': blockers,\n 'retained': True, 'delivery_selection': 'separate'}\n write(args.out / 'replay.json', report)\n print(json.dumps({'session_id': report['session_id'], 'status': report['status'], 'turns': len(report['turns']), 'report': str(args.out / 'replay.json')}))\n return 0 if report['status'] in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS') else 1\n\n\nif __name__ == '__main__':\n raise SystemExit(main())\n";
diff --git a/apps/server/src/claude-code/routes.ts b/apps/server/src/claude-code/routes.ts
deleted file mode 100644
index 584a5050..00000000
--- a/apps/server/src/claude-code/routes.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { ClaudeRuntime } from "./runtime.js";
-import { ClaudeAccessError } from "./access.js";
-import { createReadStream } from "node:fs";
-import { Readable } from "node:stream";
-import { addRoute, type RequestContext, type Route } from "../routes/registry.js";
-import { ApiError } from "../errors.js";
-import type { WorkspaceInfo } from "../types.js";
-import type { NativeUploadReceipt } from "./upload.js";
-
-export function registerClaudeRoutes(input: {
- routes: Route[]; runtime: ClaudeRuntime;
- workspace: (ctx: RequestContext) => Promise<WorkspaceInfo>;
- owner: (ctx: RequestContext) => void;
- writable: () => void;
- upload: (sessionId: string) => Promise<NativeUploadReceipt>;
-}) {
- const {runtime} = input;
- const register = (method: string, suffix: string, handler: (ctx: RequestContext, workspace: WorkspaceInfo) => Promise<Response>) => {
- addRoute(input.routes, method, `/workspace/:id/claude${suffix}`, "client", async ctx => {
- input.owner(ctx);
- if (method !== "GET") input.writable();
- const workspace = await input.workspace(ctx);
- if (ctx.params.session) {
- const session = await runtime.get(ctx.params.session);
- if (session.workspaceId !== workspace.id) throw new ApiError(404, "session_not_found", "Session not found in this workspace");
- }
- const response = await handler(ctx, workspace); response.headers.set("cache-control", "no-store"); return response;
- });
- };
- register("GET", "/status", async () => {
- try { return Response.json(await runtime.available()); }
- catch { return Response.json({allowed: false, sandboxReady: false}); }
- });
- register("POST", "/prepare", async ctx => { await runtime.prepare(ctx.request.signal); return Response.json({ready: true}); });
- register("GET", "/sessions", async (_, workspace) => Response.json(await runtime.list(workspace.id)));
- register("POST", "/sessions", async (ctx, workspace) => {
- const body = await ctx.request.json();
- if (body?.captureConsent !== true) throw new ApiError(400, "capture_consent_required", "Confirm private trace and environment capture");
- if (body.model !== undefined && typeof body.model !== "string") throw new ApiError(400, "invalid_model", "Choose a Claude model");
- try { return Response.json(await runtime.create(workspace.path, workspace.id, ctx.request.signal, body.model), {status: 201}); }
- catch (error) { throw error instanceof ClaudeAccessError ? new ApiError(error.status, "claude_unavailable", error.message) : error; }
- });
- register("GET", "/sessions/:session", async ctx => Response.json(await runtime.get(ctx.params.session)));
- register("GET", "/sessions/:session/events", async ctx => Response.json(await runtime.events(ctx.params.session)));
- register("POST", "/sessions/:session/turns", async ctx => {
- const body = await ctx.request.json();
- if (typeof body?.prompt !== "string") throw new ApiError(400, "prompt_required", "Enter a prompt");
- await runtime.start(ctx.params.session, body.prompt, ctx.request.signal); return Response.json({started: true}, {status: 202});
- });
- register("POST", "/sessions/:session/stop", async ctx => Response.json(await runtime.stop(ctx.params.session)));
- register("POST", "/sessions/:session/recover", async ctx => Response.json(await runtime.recover(ctx.params.session)));
- register("POST", "/sessions/:session/verify", async ctx => {
- const body = await ctx.request.json();
- if (body?.command !== undefined && (typeof body.command !== "string" || body.command.length > 10_000)) throw new ApiError(400, "invalid_command", "Invalid verification command");
- return Response.json(await runtime.verify(ctx.params.session, body?.command));
- });
- register("POST", "/sessions/:session/export", async ctx => {
- const file = await runtime.export(ctx.params.session);
- // The packaged desktop embeds the Node server; stream without Bun globals
- // or buffering a complete environment archive in the renderer/server heap.
- const stream = Readable.toWeb(createReadStream(file)) as unknown as ReadableStream<Uint8Array>;
- return new Response(stream, {headers: {"content-type": "application/zip", "content-disposition": `attachment; filename="claude-${ctx.params.session}.zip"`}});
- });
- register("POST", "/sessions/:session/upload", async ctx => {
- return Response.json(await input.upload(ctx.params.session));
- });
-}
diff --git a/apps/server/src/claude-code/runtime.ts b/apps/server/src/claude-code/runtime.ts
deleted file mode 100644
index c0dc9964..00000000
--- a/apps/server/src/claude-code/runtime.ts
+++ /dev/null
@@ -1,954 +0,0 @@
-/** The shared CLI/desktop Claude runtime. The SDK and every tool run in the
- * container. There are no host workspace, home, credential or socket mounts.
- * Stopped-container images are the checkpoint authority, not a guessed list of
- * changed files. The host only brokers inference, copies evidence and seals it.
- */
-import fs from "node:fs";
-import fsp from "node:fs/promises";
-import path from "node:path";
-import http from "node:http";
-import os from "node:os";
-import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
-import { spawn } from "node:child_process";
-import { once } from "node:events";
-import { pipeline } from "node:stream/promises";
-import { createGzip, createGunzip } from "node:zlib";
-import { NativeCapture } from "./native-capture.js";
-import { CAPTURE_POLICY_VERSION, CLAUDE_MODEL_ID, CLAUDE_VERSION, CONTROLLER, DOCKERFILE, IMAGE, MANAGED_SETTINGS, MODEL, SDK_VERSION, managedSettings } from "./sandbox-assets.js";
-import { PACKAGE_JSON, LOCKFILE } from "./sandbox-lock.js";
-import { zipDirectory } from "./zip.js";
-import { REPLAY_ADAPTER } from "./replay-adapter.js";
-import { writeBundleManifest } from "./bundle-manifest.js";
-import { ClaudeAccessError, claudeResponseHeaders } from "./access.js";
-import { ApiError } from "../errors.js";
-
-export type ClaudeBudgetSnapshot = {
- status: "known" | "unknown"; model: string; revision?: string;
- asOf?: string; limitTokens?: number | null; remainingTokens?: number | null; resetAt?: string | null;
- sessionLimitTokens?: number | null; sessionUsedTokens?: number; sessionRemainingTokens?: number | null;
- accountLimitTokens?: number; accountRemainingTokens?: number; accountScope?: "day" | "week"; accountResetAt?: string;
-};
-/** `models`: the Claude ids this account may run (the server's claude_code.models); `catalog`: what the picker shows every account; `reason`: why nothing may run (access.reason). */
-export type ClaudeAccess = { owner: string; capabilities?: string[]; budget?: ClaudeBudgetSnapshot; models?: string[]; catalog?: {id: string; name: string}[]; reason?: string | null };
-export type ClaudeAuthorization = { sessionId: string; owner: string; model: string; workspaceId: string; contractSha256: string; refresh?: boolean };
-export type ClaudeGrant = {
- owner: string; baseUrl: string; token: string; sessionId: string; model: string;
- upstreamModel: string; client: string;
- bindingId?: string; contractSha256?: string; policyVersion?: string; budget?: ClaudeBudgetSnapshot;
-};
-export type RuntimeOptions = {
- directory: string; surface: "cli" | "gui";
- fetch: (input: string, init?: RequestInit) => Promise<Response>;
- access: () => Promise<ClaudeAccess>;
- authorize: (session: ClaudeAuthorization) => Promise<ClaudeGrant>;
- revoke?: (session: ClaudeAuthorization) => Promise<void>;
- docker?: string;
-};
-export type ClaudeSessionContract = {
- schema: 1; sessionId: string; owner: string; workspaceId: string; model: string;
- harness: {name: "claude-code"; sdkVersion: string; claudeVersion: string; controllerSha256: string; lockSha256: string; managedSettingsSha256: string; dockerfileSha256: string};
- execution: {kind: "docker"; os: "linux"; architecture: string; workingDirectory: "/workspace"; shell: "/bin/bash"; runtimeImage: string; baseImage: string; workspace: "session-copy"};
- capture: {policyVersion: string; originals: "private"; modelIsolation: "exact"; scope: "managed-inference"; network: "development-network-enabled"; initialWorkspaceProvenance: "user-supplied-unattested"};
-};
-export type ClaudeModelIsolation = {
- status: "pending" | "observed" | "unknown" | "invalid" | "legacy_unverified";
- expectedModel: string; resolvedModel?: string; observedModels: string[]; inferenceRequests: number; completedRequests: number;
- missingIdentityRequests: number; interruptedRequests: number; rejectedRequests: number;
- issues: string[]; evidenceSha256?: string; evidenceBytes?: number;
-};
-type Checkpoint = { image: string; file: string; sha256: string; bytes: number };
-type Turn = { number: number; prompt: string; startedAt: string; finishedAt?: string; sdkStart: number; sdkEnd?: number;
- status: "running" | "complete" | "interrupted" | "failed"; before: Checkpoint;
- after?: Checkpoint; error?: string };
-export type ClaudeSession = {
- schema: 1; id: string; owner: string; workspaceId: string; surface: "cli" | "gui";
- model: string; sdkVersion: string; claudeVersion: string; createdAt: string;
- container: string; base: Checkpoint; turns: Turn[];
- capture: "capturing" | "complete" | "incomplete";
- replay: "unverified" | "restored"; issues: string[];
- contract?: ClaudeSessionContract; contractSha256?: string;
- compatibility?: "current" | "legacy_unverified" | "contract_invalid" | "runtime_upgrade_required";
- modelIsolation?: ClaudeModelIsolation;
- authorization?: {binding: "session-model" | "session-model-contract"; bindingId?: string; upstreamModel: string; policyVersion: string | null; budget: ClaudeBudgetSnapshot | null};
-};
-export type DisplayEvent = { type: "user" | "assistant" | "thinking" | "tool" | "result"; text: string; turn: number };
-const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
-const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
-const digest = (value: string) => createHash("sha256").update(value).digest("hex");
-function interrupted(signal?: AbortSignal) { signal?.throwIfAborted(); }
-async function abortable<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
- interrupted(signal);
- if (!signal) return work;
- let abort!: () => void;
- const cancelled = new Promise<never>((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, {once: true}); });
- try { return await Promise.race([work, cancelled]); }
- finally { signal.removeEventListener("abort", abort); }
-}
-// A PID alone cannot distinguish a live owner from a reused PID. Linux exposes
-// an exact birth identity; elsewhere a live/uninspectable PID stays locked.
-function processIdentity(pid: number) {
- if (process.platform !== "linux") return undefined;
- try {
- const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"), start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
- const boot = fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), namespace = fs.readlinkSync("/proc/self/ns/pid");
- if (!/^\d+$/.test(start) || !UUID.test(boot)) return undefined;
- return {host: os.hostname(), boot, namespace, start};
- } catch { return undefined; }
-}
-function deadLockOwner(prior: unknown): boolean {
- if (!isRecord(prior) || typeof prior.pid !== "number" || !Number.isSafeInteger(prior.pid) || prior.pid < 1 || typeof prior.nonce !== "string") return false;
- const identity = prior.identity, current = processIdentity(prior.pid);
- if (identity !== undefined) {
- // An unfamiliar host/namespace or malformed birth record is not proof.
- const self = processIdentity(process.pid);
- if (!isRecord(identity) || !self || identity.host !== self.host || identity.namespace !== self.namespace ||
- typeof identity.boot !== "string" || !UUID.test(identity.boot) || typeof identity.start !== "string" || !/^\d+$/.test(identity.start)) return false;
- if (identity.boot !== self.boot) return true;
- if (current && identity.start !== current.start) return true;
- }
- try { process.kill(prior.pid, 0); return false; }
- catch (error) { return isRecord(error) && error.code === "ESRCH"; }
-}
-function privateDir(dir: string) { fs.mkdirSync(dir, {recursive: true, mode: 0o700}); fs.chmodSync(dir, 0o700); }
-function syncDirectory(dir: string) {
- if (process.platform === "win32") return;
- const fd = fs.openSync(dir, "r"); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
-}
-function save(file: string, data: unknown) {
- privateDir(path.dirname(file));
- const tmp = `${file}.${randomUUID()}.tmp`, fd = fs.openSync(tmp, "wx", 0o600);
- try { fs.writeFileSync(fd, JSON.stringify(data, null, 2) + "\n"); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
- fs.renameSync(tmp, file);
- if (process.platform !== "win32") { const dir = fs.openSync(path.dirname(file), "r"); try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); } }
-}
-async function fileHash(file: string) {
- const hash = createHash("sha256");
- for await (const bytes of fs.createReadStream(file)) hash.update(bytes);
- return hash.digest("hex");
-}
-function validateGrant(grant: ClaudeGrant, session: ClaudeAuthorization): ClaudeGrant {
- const url = new URL(grant.baseUrl);
- if (!grant.owner || !grant.token || /\s/.test(grant.token) || /^sk-ant-/.test(grant.token) || url.username || url.password || url.search || url.hash ||
- /(^|\.)(anthropic\.com|claude\.ai)$/.test(url.hostname) ||
- !(url.protocol === "https:" || url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) throw new Error("An active internal Claude grant is required");
- if (grant.owner !== session.owner || grant.sessionId !== session.sessionId || grant.model !== session.model ||
- grant.contractSha256 !== undefined && grant.contractSha256 !== session.contractSha256) throw new Error("Claude authorization does not match this session's fixed model and contract");
- if (!identityLabel(grant.upstreamModel) || grant.upstreamModel !== session.model || !/^(cli|desktop|gui)\/[A-Za-z0-9][A-Za-z0-9.+_-]{0,63}$/.test(grant.client)) throw new Error("Claude authorization does not match the exact upstream model and client binding");
- return {...grant, baseUrl: grant.baseUrl.replace(/\/$/, "")};
-}
-
-function initialModelIsolation(model: string, legacy = false): ClaudeModelIsolation {
- return {status: legacy ? "legacy_unverified" : "pending", expectedModel: model, observedModels: [], inferenceRequests: 0, completedRequests: 0, missingIdentityRequests: 0, interruptedRequests: 0, rejectedRequests: 0, issues: legacy ? ["capture_predates_model_enforcement"] : []};
-}
-function identityLabel(value: unknown): string | null {
- return typeof value === "string" && /^claude-[a-z0-9._-]{1,128}$/.test(value) ? value : null;
-}
-
-/** Observes identity without changing a single response byte. Only a provider's
- * actual message envelope is identity evidence; a requested model is not. */
-class ResponseIdentity {
- readonly models = new Set<string>();
- malformed = false;
- complete = false;
- private readonly decoder = new TextDecoder();
- private pending = "";
- constructor(private readonly stream: boolean, private readonly observed: (model: string) => void) {}
- private event(value: unknown) {
- if (!isRecord(value)) return;
- const message = value.type === "message_start" && isRecord(value.message) ? value.message : value.type === "message" ? value : null;
- if (message) {
- const model = identityLabel(message.model);
- if (!model) { this.malformed = true; return; }
- this.models.add(model); this.observed(model);
- }
- if (value.type === "message_stop" || value.type === "message" && value.stop_reason !== null && value.stop_reason !== undefined) this.complete = true;
- }
- private parse(text: string) {
- if (!text.trim() || text.trim() === "[DONE]") return;
- let parsed: unknown;
- try { parsed = JSON.parse(text); } catch { this.malformed = true; return; }
- this.event(parsed);
- }
- push(bytes: Uint8Array) {
- this.pending += this.decoder.decode(bytes, {stream: true});
- if (this.stream) {
- for (;;) {
- const match = /\r?\n\r?\n/.exec(this.pending);
- if (!match || match.index === undefined) break;
- const frame = this.pending.slice(0, match.index); this.pending = this.pending.slice(match.index + match[0].length);
- const data = frame.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
- this.parse(data);
- }
- }
- if (this.pending.length > (this.stream ? 4 : 32) * 1024 * 1024) { this.pending = ""; this.malformed = true; }
- }
- finish() {
- this.pending += this.decoder.decode();
- if (this.stream) { if (this.pending.trim()) this.malformed = true; }
- else this.parse(this.pending);
- this.pending = "";
- }
-}
-
-export class ClaudeRuntime {
- private readonly running = new Map<string, { stop: AbortController; done: Promise<void> }>();
- private preparing?: Promise<void>;
- private closed = false;
- private readonly root: string;
- constructor(private readonly options: RuntimeOptions) { privateDir(options.directory); this.root = fs.realpathSync(options.directory); }
- private reserve(id: string, signal?: AbortSignal) {
- interrupted(signal);
- if (this.closed) throw new Error("Claude runtime is shutting down");
- if (this.running.has(id)) throw new Error("This session already has an active operation");
- const stop = new AbortController(), abort = () => stop.abort(signal?.reason);
- signal?.addEventListener("abort", abort, {once: true});
- let complete!: () => void;
- const done = new Promise<void>(resolve => { complete = resolve; });
- this.running.set(id, {stop, done});
- return {signal: stop.signal, finish: () => { signal?.removeEventListener("abort", abort); this.running.delete(id); complete(); }};
- }
- private async access(owner?: string, signal?: AbortSignal) {
- interrupted(signal);
- const access = await abortable(this.options.access(), signal);
- interrupted(signal);
- if (!access.owner || owner && access.owner !== owner) throw new Error("This Claude session belongs to another account");
- return access;
- }
- private authorizationContext(session: ClaudeSession): ClaudeAuthorization {
- if (!session.contractSha256 || !session.contract) throw new Error("This legacy capture has no immutable model contract; export it and start a new session");
- return {sessionId: session.id, owner: session.owner, model: session.model, workspaceId: session.workspaceId, contractSha256: session.contractSha256};
- }
- private async grant(session: ClaudeSession, refresh = false, signal?: AbortSignal) {
- await this.access(session.owner, signal);
- interrupted(signal);
- const context = {...this.authorizationContext(session), refresh};
- const grant = validateGrant(await this.options.authorize(context), context);
- interrupted(signal);
- const isolation = session.modelIsolation ??= initialModelIsolation(session.model);
- if (isolation.resolvedModel && isolation.resolvedModel !== grant.upstreamModel || session.authorization?.upstreamModel && session.authorization.upstreamModel !== grant.upstreamModel) {
- isolation.status = "invalid"; isolation.issues.push("upstream_binding_changed");
- this.modelEvidence(session, {type: "rejected_authorization", reason: "upstream_binding_changed"});
- throw new Error("The backend changed this session's upstream model binding");
- }
- isolation.resolvedModel = grant.upstreamModel;
- if (session.authorization?.bindingId && grant.bindingId !== session.authorization.bindingId) throw new Error("The backend changed this session's immutable binding");
- session.authorization = {binding: grant.contractSha256 ? "session-model-contract" : "session-model", bindingId: grant.bindingId, upstreamModel: grant.upstreamModel, policyVersion: grant.policyVersion ?? null, budget: grant.budget ?? null};
- return grant;
- }
- private dir(owner: string, id: string) {
- if (!UUID.test(id)) throw new Error("Invalid Claude session ID");
- return path.join(this.root, digest(owner), id);
- }
- private async docker(args: string[], options: { input?: string; signal?: AbortSignal; stdout?: (bytes: Buffer) => void; timeout?: number } = {}): Promise<string> {
- interrupted(options.signal);
- return await new Promise((resolve, reject) => {
- const child = spawn(this.options.docker ?? "docker", args, {stdio: ["pipe", "pipe", "pipe"], windowsHide: true});
- const output: Buffer[] = []; let bytes = 0, error = "", failed: Error | undefined;
- const abort = () => { failed = new Error("Claude sandbox operation interrupted"); child.kill("SIGKILL"); };
- const timer = setTimeout(abort, options.timeout ?? 120_000);
- options.signal?.addEventListener("abort", abort, {once: true});
- child.stdout.on("data", (chunk: Buffer) => {
- try {
- if (options.stdout) options.stdout(chunk);
- else { bytes += chunk.length; if (bytes > 16 * 1024 * 1024) throw new Error("Sandbox output exceeds limit"); output.push(chunk); }
- } catch (e) { failed = e instanceof Error ? e : new Error(String(e)); child.kill("SIGKILL"); }
- });
- child.stderr.on("data", (chunk: Buffer) => { error = (error + chunk.toString("utf8")).slice(-8192); });
- child.on("error", (e) => { failed = e; });
- child.on("close", (code) => {
- clearTimeout(timer); options.signal?.removeEventListener("abort", abort);
- if (failed) reject(failed);
- else if (code !== 0) reject(new Error(`Sandbox ${args[0]} failed (${code}): ${error.trim()}`));
- else resolve(Buffer.concat(output).toString("utf8").trim());
- });
- child.stdin.on("error", () => {});
- child.stdin.end(options.input);
- if (options.signal?.aborted) abort();
- });
- }
- async available() {
- const access = await this.access();
- const models = access.models ?? [], listed = {model: models[0] ?? MODEL, models, catalog: access.catalog ?? [], reason: access.reason ?? null, sdkVersion: SDK_VERSION};
- if (!access.capabilities?.includes("claude-code") || !models.length) return {allowed: false, sandboxReady: false, ...listed};
- try { await this.docker(["info", "--format", "{{.ServerVersion}}"], {timeout: 10_000}); return {allowed: true, sandboxReady: true, ...listed}; }
- catch { return {allowed: true, sandboxReady: false, ...listed}; }
- }
- async prepare(signal?: AbortSignal) {
- const job = this.reserve(`prepare:${randomUUID()}`, signal);
- try {
- if (!(await this.access(undefined, job.signal)).capabilities?.includes("claude-code")) throw new Error("Claude Code capture is not enabled for this account");
- interrupted(job.signal);
- if (this.preparing) return await abortable(this.preparing, job.signal);
- const preparing = this.prepareImage(job.signal); this.preparing = preparing;
- try { await preparing; } finally { if (this.preparing === preparing) this.preparing = undefined; }
- } finally { job.finish(); }
- }
- private async prepareImage(signal: AbortSignal) {
- const fingerprint = digest(JSON.stringify(this.harnessContract()));
- try {
- const inspected = JSON.parse(await this.docker(["image", "inspect", IMAGE], {signal}));
- interrupted(signal);
- if (inspected?.[0]?.Config?.Labels?.["org.omnirush.claude.runtime"] === fingerprint) return;
- } catch { interrupted(signal); /* build the pinned runtime */ }
- const build = path.join(this.root, "build", fingerprint); privateDir(build);
- fs.writeFileSync(path.join(build, "Dockerfile"), DOCKERFILE);
- fs.writeFileSync(path.join(build, "controller.mjs"), CONTROLLER);
- fs.writeFileSync(path.join(build, "managed-settings.json"), MANAGED_SETTINGS);
- fs.writeFileSync(path.join(build, "package.json"), PACKAGE_JSON);
- fs.writeFileSync(path.join(build, "pnpm-lock.yaml"), LOCKFILE);
- await this.docker(["build", "--label", `org.omnirush.claude.runtime=${fingerprint}`, "--tag", IMAGE, build], {signal, timeout: 15 * 60_000, stdout: () => {}});
- interrupted(signal);
- }
- private async checkpoint(container: string, dir: string, prior: Checkpoint[] = [], signal?: AbortSignal): Promise<Checkpoint> {
- // Container is stopped: no tool or background child can race the checkpoint.
- const image = await this.docker(["commit", container], {signal});
- if (!/^sha256:[a-f0-9]{64}$/.test(image)) throw new Error("Invalid sandbox checkpoint identity");
- const file = `images/${image.slice(7)}.tar.gz`, target = path.join(dir, file);
- privateDir(path.dirname(target));
- const tar = `${target}.tar.tmp`, tmp = `${target}.tmp`;
- try {
- const loaded = new Set<string>();
- for (const cp of prior) {
- try { await this.docker(["image", "inspect", cp.image], {signal}); }
- catch { interrupted(signal); if (!loaded.has(cp.file)) { await this.loadCheckpoint(cp, dir, signal); loaded.add(cp.file); } }
- }
- // Docker's multi-image archive stores common layers once while retaining
- // the exact config/image digest of every before/after environment.
- await this.docker(["save", "--output", tar, ...new Set([...prior.map(cp => cp.image), image])], {signal, timeout: 5 * 60_000});
- await pipeline(fs.createReadStream(tar), createGzip({level: 1}), fs.createWriteStream(tmp, {mode: 0o600}), {signal});
- interrupted(signal);
- const fd = fs.openSync(tmp, "r"); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
- fs.renameSync(tmp, target);
- if (process.platform !== "win32") { const parent = fs.openSync(path.dirname(target), "r"); try { fs.fsyncSync(parent); } finally { fs.closeSync(parent); } }
- return {image, file, sha256: await fileHash(target), bytes: fs.statSync(target).size};
- } finally { await fsp.rm(tar, {force: true}); await fsp.rm(tmp, {force: true}); }
- }
- private checkpoints(session: ClaudeSession) { return [session.base, ...session.turns.flatMap(turn => turn.after ? [turn.after] : [])]; }
- private repointArchive(session: ClaudeSession, current: Checkpoint) {
- for (const cp of [session.base, ...session.turns.flatMap(turn => turn.after ? [turn.before, turn.after] : [turn.before])]) Object.assign(cp, {file: current.file, sha256: current.sha256, bytes: current.bytes});
- }
- private async pruneArchives(session: ClaudeSession) {
- const dir = this.dir(session.owner, session.id), keep = new Set(this.checkpoints(session).map(cp => path.basename(cp.file)));
- for (const name of await fsp.readdir(path.join(dir, "images"))) if (/^[a-f0-9]{64}\.tar\.gz$/.test(name) && !keep.has(name)) await fsp.rm(path.join(dir, "images", name));
- }
- private async loadCheckpoint(checkpoint: Checkpoint, dir: string, signal?: AbortSignal) {
- if (await fileHash(path.join(dir, checkpoint.file)) !== checkpoint.sha256) throw new Error("Environment archive integrity failure");
- const tar = path.join(dir, `restore-${randomUUID()}.tar.tmp`);
- try {
- await pipeline(fs.createReadStream(path.join(dir, checkpoint.file)), createGunzip(), fs.createWriteStream(tar, {mode: 0o600}), {signal});
- await this.docker(["load", "--input", tar], {signal, timeout: 5 * 60_000});
- } finally { await fsp.rm(tar, {force: true}); }
- }
- private createContainer(name: string, image: string, bootstrap = false, signal?: AbortSignal, ownership?: string) {
- return this.docker(["create", "--name", name, "--label", "omnirush.claude=true", ...(ownership ? ["--label", `org.omnirush.claude.operation=${ownership}`] : []), "--init", "--cap-drop=ALL", ...(bootstrap ? ["--cap-add=CHOWN"] : []), "--security-opt=no-new-privileges", "--pids-limit=512", "--memory=4g", "--cpus=2", "--add-host=host.docker.internal:host-gateway", image], {signal});
- }
- private async restoreContainerIfMissing(session: ClaudeSession, signal?: AbortSignal) {
- try { await this.docker(["container", "inspect", session.container], {signal}); interrupted(signal); return; } catch { interrupted(signal); /* validate the saved image before reconstructing */ }
- const turn = session.turns.at(-1);
- if (turn && (turn.status !== "complete" || !turn.after)) throw new Error("The interrupted container is missing; retain its partial evidence for review");
- const checkpoint = turn?.after ?? session.base;
- await this.loadCheckpoint(checkpoint, this.dir(session.owner, session.id), signal);
- const ownership = randomUUID();
- try { await this.createContainer(session.container, checkpoint.image, false, signal, ownership); interrupted(signal); }
- catch (error) { await this.cleanupStartup(ownership); throw error; }
- }
- /** `model`: a catalog id the server lists for this account (default: its first). The session keeps it for good. */
- async create(workspace: string, workspaceId: string, signal?: AbortSignal, requested?: string): Promise<ClaudeSession> {
- const id = randomUUID(), job = this.reserve(id, signal), ownership = randomUUID();
- const container = `omnirush-claude-${id}`;
- let attempted = false;
- try {
- const access = await this.access(undefined, job.signal);
- const {owner} = access, model = requested ?? access.models?.[0];
- if (!model || !CLAUDE_MODEL_ID.test(model) || !access.models?.includes(model)) throw new ClaudeAccessError(403, "This Claude model isn't available on your account yet");
- await this.prepare(job.signal);
- interrupted(job.signal);
- const root = await fsp.realpath(workspace);
- if (!(await fsp.stat(root)).isDirectory() || root === path.parse(root).root) throw new Error("Choose a project directory");
- interrupted(job.signal);
- if (!workspaceId.trim()) throw new Error("Workspace identity is required");
- const dir = this.dir(owner, id); privateDir(dir);
- const inspected = JSON.parse(await this.docker(["image", "inspect", IMAGE], {signal: job.signal}));
- const image = inspected?.[0];
- if (!isRecord(image) || typeof image.Id !== "string" || !/^sha256:[a-f0-9]{64}$/.test(image.Id) || image.Os !== "linux" || typeof image.Architecture !== "string") throw new Error("The Claude runtime image must have an exact Linux identity");
- attempted = true;
- await this.createContainer(container, image.Id, true, job.signal, ownership);
- // Copy, never bind-mount: tools cannot reach the host through a symlink.
- await this.docker(["cp", `${root}${path.sep}.`, `${container}:/workspace/`], {signal: job.signal, timeout: 5 * 60_000});
- await this.docker(["start", container], {signal: job.signal});
- await this.docker(["exec", "--user", "root", container, "chown", "-R", "node:node", "/workspace"], {signal: job.signal});
- // The session's own model policy, root-owned, in the base checkpoint (the image carries MODEL's).
- if (model !== MODEL) await this.docker(["exec", "-i", "--user", "root", container, "sh", "-c", "cat > /etc/claude-code/managed-settings.json"], {input: managedSettings(model), signal: job.signal});
- await this.docker(["stop", "--time", "2", container], {signal: job.signal});
- const base = await this.checkpoint(container, dir, [], job.signal);
- await this.docker(["rm", container], {signal: job.signal});
- await this.createContainer(container, base.image, false, job.signal, ownership);
- interrupted(job.signal);
- const contract: ClaudeSessionContract = {
- schema: 1, sessionId: id, owner, workspaceId, model,
- harness: this.harnessContract(model),
- execution: {kind: "docker", os: "linux", architecture: image.Architecture, workingDirectory: "/workspace", shell: "/bin/bash", runtimeImage: image.Id, baseImage: base.image, workspace: "session-copy"},
- capture: {policyVersion: CAPTURE_POLICY_VERSION, originals: "private", modelIsolation: "exact", scope: "managed-inference", network: "development-network-enabled", initialWorkspaceProvenance: "user-supplied-unattested"},
- };
- const contractSha256 = digest(JSON.stringify(contract));
- const session: ClaudeSession = {schema: 1, id, owner, workspaceId, surface: this.options.surface, model, sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, createdAt: new Date().toISOString(), container, base, turns: [], capture: "capturing", replay: "unverified", issues: [], contract, contractSha256, compatibility: "current", modelIsolation: initialModelIsolation(model)};
- save(path.join(dir, "policy", "contract.json"), {contract, sha256: contractSha256});
- save(path.join(dir, "session.json"), session); return session;
- } catch (e) {
- if (attempted) await this.cleanupStartup(ownership);
- throw e;
- } finally { job.finish(); }
- }
- private async cleanupStartup(ownership: string) {
- // The operation label is minted before create and inherited by checkpoints.
- // Never remove a container by an unverified name or a shared runtime image.
- for (const kind of ["container", "image"] as const) {
- try {
- const ids = await this.docker([kind, "ls", "--all", "--quiet", "--no-trunc", "--filter", `label=org.omnirush.claude.operation=${ownership}`], {timeout: 10_000});
- for (const id of new Set(ids.split(/\s+/).filter(value => /^(sha256:)?[a-f0-9]{64}$/.test(value)))) {
- const inspected = JSON.parse(await this.docker([kind, "inspect", id], {timeout: 10_000}));
- if (inspected?.[0]?.Config?.Labels?.["org.omnirush.claude.operation"] === ownership) await this.docker([kind, "rm", "--force", id], {timeout: 10_000});
- }
- } catch { /* Docker may be unavailable; keep the operation-labelled resources for recovery. */ }
- }
- }
- private localPath(file: string, directory: boolean) {
- const stat = fs.lstatSync(file);
- if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
- typeof process.getuid === "function" && stat.uid !== process.getuid() || fs.realpathSync(file) !== file) throw new Error("Claude evidence path is not a private local path");
- }
- private ownerDirectories() {
- this.localPath(this.root, true);
- return fs.readdirSync(this.root).filter(name => /^[a-f0-9]{64}$/.test(name));
- }
- async list(workspaceId: string): Promise<ClaudeSession[]> {
- const sessions: ClaudeSession[] = [];
- for (const owner of this.ownerDirectories()) {
- const root = path.join(this.root, owner); this.localPath(root, true);
- for (const id of fs.readdirSync(root).filter(id => UUID.test(id))) {
- try { const session = await this.get(id); if (session.workspaceId === workspaceId) sessions.push(session); }
- catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
- }
- }
- return sessions.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
- }
- async get(id: string): Promise<ClaudeSession> {
- if (!UUID.test(id)) throw new Error("Invalid Claude session ID");
- let found: ClaudeSession | undefined;
- for (const owner of this.ownerDirectories()) {
- const root = path.join(this.root, owner); this.localPath(root, true);
- const dir = path.join(root, id);
- try { this.localPath(dir, true); } catch (error) { if (isRecord(error) && error.code === "ENOENT") continue; throw error; }
- const file = path.join(dir, "session.json"); this.localPath(file, false);
- const session: ClaudeSession = JSON.parse(fs.readFileSync(file, "utf8"));
- if (!session || typeof session.owner !== "string" || !session.owner || digest(session.owner) !== owner || session.id !== id ||
- typeof session.workspaceId !== "string" || !session.workspaceId.trim() || session.container !== `omnirush-claude-${id}` ||
- session.contract && (session.contract.owner !== session.owner || session.contract.sessionId !== id || session.contract.workspaceId !== session.workspaceId)) throw new Error("Claude session identity mismatch");
- if (found) throw new Error("Ambiguous local Claude session identity");
- found = session;
- }
- if (!found) throw Object.assign(new Error("Claude session not found"), {code: "ENOENT"});
- if (found.contract) {
- const policy = path.join(this.dir(found.owner, id), "policy");
- try { this.localPath(policy, true); this.localPath(path.join(policy, "contract.json"), false); }
- catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
- }
- found.compatibility = this.compatibility(found);
- found.modelIsolation ??= initialModelIsolation(found.model, true);
- return found;
- }
- private harnessContract(model = MODEL): ClaudeSessionContract["harness"] {
- return {name: "claude-code", sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, controllerSha256: digest(CONTROLLER), lockSha256: digest(PACKAGE_JSON + "\n" + LOCKFILE), managedSettingsSha256: digest(managedSettings(model)), dockerfileSha256: digest(DOCKERFILE)};
- }
- private compatibility(session: ClaudeSession): NonNullable<ClaudeSession["compatibility"]> {
- if (!session.contract || !session.contractSha256) return "legacy_unverified";
- const c = session.contract;
- let saved: unknown;
- try { saved = JSON.parse(fs.readFileSync(path.join(this.dir(session.owner, session.id), "policy", "contract.json"), "utf8")); } catch { return "contract_invalid"; }
- if (!isRecord(saved) || !isRecord(saved.contract) || saved.sha256 !== session.contractSha256 || digest(JSON.stringify(saved.contract)) !== session.contractSha256 || digest(JSON.stringify(c)) !== session.contractSha256 ||
- c.schema !== 1 || c.sessionId !== session.id || c.owner !== session.owner || c.workspaceId !== session.workspaceId || c.model !== session.model || !CLAUDE_MODEL_ID.test(c.model) || c.execution?.baseImage !== session.base.image || c.execution?.kind !== "docker" || c.execution.os !== "linux" || c.execution.shell !== "/bin/bash" || c.execution.workingDirectory !== "/workspace") return "contract_invalid";
- if (session.sdkVersion !== SDK_VERSION || session.claudeVersion !== CLAUDE_VERSION || JSON.stringify(c.harness) !== JSON.stringify(this.harnessContract(session.model)) || c.capture?.policyVersion !== CAPTURE_POLICY_VERSION) return "runtime_upgrade_required";
- return "current";
- }
- private assertResumable(session: ClaudeSession) {
- const compatibility = this.compatibility(session);
- if (compatibility !== "current") throw new Error(compatibility === "legacy_unverified" ? "This legacy capture has no immutable model contract; export it and start a new session" : compatibility === "runtime_upgrade_required" ? "This session requires its recorded Claude runtime; start a new session for this runtime version" : "This Claude session's immutable model or environment contract changed");
- if (session.modelIsolation?.status === "invalid") throw new Error("This session failed model isolation; retain its evidence and start a new session");
- if (session.modelIsolation?.status === "unknown") throw new Error("This session has incomplete provider model identity; retain its evidence and start a new session");
- if (session.modelIsolation?.status === "legacy_unverified") throw new Error("This session has no trustworthy model evidence; start a new session");
- const evidence = path.join(this.dir(session.owner, session.id), "policy", "model-requests.jsonl");
- const isolation = session.modelIsolation;
- if (isolation?.expectedModel !== session.model || (fs.existsSync(evidence) || isolation.inferenceRequests > 0) && !isolation.evidenceSha256) throw new Error("The session's model evidence is incomplete; retain it for review");
- if (isolation.evidenceSha256) {
- if (!fs.existsSync(evidence)) throw new Error("The model evidence journal is missing; retain this session for review");
- const bytes = fs.readFileSync(evidence);
- if (createHash("sha256").update(bytes).digest("hex") !== isolation.evidenceSha256 || bytes.length !== isolation.evidenceBytes) throw new Error("The model evidence journal changed; retain this session for review");
- const pending = new Map<string, boolean>(), seen = new Set<string>();
- try {
- for (const line of bytes.toString("utf8").split("\n").filter(Boolean)) {
- const event: unknown = JSON.parse(line);
- if (!isRecord(event)) throw new Error();
- if (event.type === "request") {
- if (typeof event.requestId !== "string" || seen.has(event.requestId)) throw new Error();
- seen.add(event.requestId); pending.set(event.requestId, event.route === "messages");
- } else if (event.type === "response") {
- if (typeof event.requestId !== "string" || !pending.delete(event.requestId)) throw new Error();
- }
- }
- } catch { throw new Error("The model evidence journal is invalid; retain this session for review"); }
- if ([...pending.values()].some(inference => inference)) throw new Error("A previous model request has no terminal evidence; retain this session and start a new one");
- }
- }
- private modelEvidence(session: ClaudeSession, event: Record<string, unknown>) {
- const dir = this.dir(session.owner, session.id), file = path.join(dir, "policy", "model-requests.jsonl");
- privateDir(path.dirname(file));
- const fd = fs.openSync(file, "a", 0o600);
- try { fs.writeFileSync(fd, JSON.stringify({schema: 1, time: new Date().toISOString(), sessionId: session.id, turn: session.turns.at(-1)?.number ?? 0, ...event}) + "\n"); fs.fsyncSync(fd); }
- finally { fs.closeSync(fd); }
- const isolation = session.modelIsolation ??= initialModelIsolation(session.model);
- const bytes = fs.readFileSync(file);
- isolation.evidenceSha256 = createHash("sha256").update(bytes).digest("hex"); isolation.evidenceBytes = bytes.length;
- save(path.join(dir, "session.json"), session);
- }
- private collector(session: ClaudeSession, savedOnly = false) {
- const dir = this.dir(session.owner, session.id);
- if (savedOnly) this.localPath(path.join(dir, "native", "manifest.json"), false);
- else privateDir(path.join(dir, "config"));
- return new NativeCapture({directory: path.join(dir, "native"), configDir: path.join(dir, "config"), sessionId: session.id, owner: session.owner, producerVersion: savedOnly ? session.claudeVersion : CLAUDE_VERSION, surface: session.surface, transport: "sdk"});
- }
- private async collect(session: ClaudeSession, stopped: boolean, success: boolean) {
- const dir = this.dir(session.owner, session.id), config = path.join(dir, "config"); privateDir(config);
- const staging = path.join(dir, `capture-${randomUUID()}`); privateDir(staging);
- try {
- await this.docker(["cp", `${session.container}:/home/node/.claude/projects`, staging]);
- await fsp.rm(path.join(config, "projects"), {recursive: true, force: true});
- await fsp.rename(path.join(staging, "projects"), path.join(config, "projects"));
- } finally { await fsp.rm(staging, {recursive: true, force: true}); }
- const evidence = path.join(dir, "transport"); privateDir(evidence);
- await this.docker(["cp", `${session.container}:/home/node/evidence/.`, evidence]);
- const collector = this.collector(session);
- for (const channel of ["sdk", "hooks"] as const) {
- const file = path.join(evidence, `${channel}.jsonl`);
- if (!fs.existsSync(file)) continue;
- const bytes = fs.readFileSync(file), offset = collector.verify().streams[channel];
- if (bytes.length < offset) throw new Error("Sandbox evidence was truncated");
- // Compare the acknowledged prefix too: a tool cannot silently rewrite
- // events already persisted outside the sandbox.
- for (let position = 0; position < bytes.length; position += 8 * 1024 * 1024) collector.recordStream(channel, bytes.subarray(position, position + 8 * 1024 * 1024), position);
- }
- const starts = new Set<string>(), stops = new Set<string>();
- const hooks = await fsp.readFile(path.join(evidence, "hooks.jsonl"), "utf8").catch(() => "");
- for (const line of hooks.split("\n")) {
- if (!line) continue;
- const record = JSON.parse(line), input = record.input;
- if (typeof input?.agent_id !== "string") continue;
- if (input.hook_event_name === "SubagentStart") starts.add(input.agent_id);
- if (input.hook_event_name === "SubagentStop") stops.add(input.agent_id);
- }
- const childrenStopped = [...starts].every(id => stops.has(id));
- const manifest = stopped ? collector.finish({type: "finish", processStopped: true, successfulResult: success && childrenStopped, expectedAgents: [...starts]}) : collector.scan();
- session.capture = manifest.status; session.issues = manifest.issues;
- return manifest;
- }
- private async broker(session: ClaudeSession, onInvalid: () => void, signal?: AbortSignal) {
- interrupted(signal);
- const token = randomUUID();
- const active = new Set<AbortController>(), pending = new Set<Promise<void>>();
- const isolation = session.modelIsolation ??= initialModelIsolation(session.model);
- const invalid = () => isolation.status === "invalid";
- const unidentified = () => {
- if (!invalid()) isolation.status = "unknown";
- if (!isolation.issues.includes("provider_identity_missing_or_malformed")) isolation.issues.push("provider_identity_missing_or_malformed");
- for (const request of active) request.abort();
- onInvalid();
- throw new Error("The provider did not establish this session's model identity");
- };
- const invalidate = (reason: string) => {
- isolation.status = "invalid";
- if (!isolation.issues.includes(reason)) isolation.issues.push(reason);
- for (const request of active) request.abort();
- onInvalid();
- };
- const handle = async (req: http.IncomingMessage, res: http.ServerResponse) => {
- const supplied = Buffer.from(req.headers.authorization ?? ""), expected = Buffer.from(`Bearer ${token}`);
- if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) { res.writeHead(403).end(); return; }
- if (req.method !== "POST" || !/^\/v1\/messages(?:\/count_tokens)?(?:\?[^#]*)?$/.test(req.url ?? "")) { res.writeHead(404).end(); return; }
- const url = new URL(req.url ?? "", "http://claude-session-broker");
- if ([...url.searchParams].some(([name, value]) => name !== "beta" || value !== "true")) { res.writeHead(400, {"content-type": "application/json"}).end(JSON.stringify({type: "error", error: {type: "invalid_request_error", message: "Unsupported session routing parameter"}})); return; }
- if (invalid() || isolation.status === "unknown") { res.writeHead(409, {"content-type": "application/json", "x-should-retry": "false"}).end(JSON.stringify({type: "error", error: {type: "invalid_request_error", message: "Session model isolation failed"}})); return; }
- const abort = new AbortController(), cancel = () => abort.abort(signal?.reason); active.add(abort);
- signal?.addEventListener("abort", cancel, {once: true});
- if (signal?.aborted) cancel();
- res.on("close", () => { if (!res.writableFinished) abort.abort(); });
- const requestId = randomUUID(), inference = !req.url?.startsWith("/v1/messages/count_tokens");
- const authorizationFailures: number[] = [];
- let observer: ResponseIdentity | undefined, admitted = false, responseStatus: number | null = null, finished = false;
- try {
- const chunks: Buffer[] = []; let size = 0;
- for await (const chunk of req) { size += chunk.length; if (size > 32 * 1024 * 1024) throw new Error("Request too large"); chunks.push(chunk); }
- const originalBody = Buffer.concat(chunks), body = JSON.parse(originalBody.toString("utf8"));
- if (!isRecord(body) || body.model !== session.model) {
- isolation.rejectedRequests++; invalidate("request_model_mismatch");
- this.modelEvidence(session, {type: "rejected", requestId, route: inference ? "messages" : "count_tokens", requestedModel: identityLabel(body?.model), resolvedModel: session.model, reason: "request_model_mismatch"});
- res.writeHead(400, {"content-type": "application/json"}).end(JSON.stringify({type: "error", error: {type: "invalid_request_error", message: "This session accepts only its fixed model"}})); return;
- }
- let grant = await this.grant(session, false, abort.signal);
- if (isolation.status === "invalid" || abort.signal.aborted) throw new Error("Model isolation failed");
- // Routing/model override headers never cross this boundary. SDK version
- // and beta negotiation are explicitly listed rather than prefix-trusted.
- const headers: Record<string, string> = {"content-type": "application/json", "x-api-key": grant.token, "x-omnirush-session-id": session.id, "x-omnirush-request-id": requestId, "x-omnirush-client": grant.client, "x-omnirush-box": "1"};
- for (const name of ["anthropic-version", "anthropic-beta", "user-agent", "x-app"]) { const value = req.headers[name]; if (typeof value === "string") headers[name] = value; }
- // Ask for the provider-exposed summary; never fabricate hidden reasoning.
- const transformations: string[] = [];
- if (isRecord(body.thinking) && body.thinking.type === "adaptive" && body.thinking.display !== "summarized") { body.thinking.display = "summarized"; transformations.push("thinking.display=summarized"); }
- const forwardedBody = JSON.stringify(body);
- if (inference) isolation.inferenceRequests++;
- admitted = true;
- this.modelEvidence(session, {type: "request", requestId, route: inference ? "messages" : "count_tokens", requestedModel: body.model, resolvedModel: grant.upstreamModel, binding: session.authorization?.binding, contractSha256: session.contractSha256, policyVersion: grant.policyVersion ?? null, budget: grant.budget ?? null, transformations, originalBodySha256: createHash("sha256").update(originalBody).digest("hex"), forwardedBodySha256: digest(forwardedBody)});
- let upstream = await this.options.fetch(grant.baseUrl + req.url, {method: "POST", headers, body: forwardedBody, redirect: "error", signal: abort.signal});
- if (upstream.status === 401 && !abort.signal.aborted) {
- // A rejected token has not admitted inference. Re-mint exactly once;
- // never replay a started stream, a quota refusal, or a provider error.
- await upstream.body?.cancel();
- authorizationFailures.push(401);
- grant = await this.grant(session, true, abort.signal);
- interrupted(abort.signal);
- headers["x-api-key"] = grant.token;
- upstream = await this.options.fetch(grant.baseUrl + req.url, {method: "POST", headers, body: forwardedBody, redirect: "error", signal: abort.signal});
- }
- responseStatus = upstream.status; res.statusCode = upstream.status;
- for (const [name, value] of Object.entries(claudeResponseHeaders(upstream.headers))) res.setHeader(name, value);
- const streaming = upstream.headers.get("content-type")?.includes("text/event-stream") === true;
- if (inference && upstream.ok) observer = new ResponseIdentity(streaming, model => {
- if (!isolation.observedModels.includes(model)) isolation.observedModels.push(model);
- this.modelEvidence(session, {type: "provider_identity", requestId, requestedModel: session.model, resolvedModel: grant.upstreamModel, providerModel: model, source: "response-body"});
- if (model !== grant.upstreamModel) { invalidate("provider_model_mismatch"); throw new Error("The provider served another model"); }
- });
- const buffered: Uint8Array[] = []; let responseBytes = 0;
- if (upstream.body) for await (const bytes of upstream.body) {
- observer?.push(bytes);
- if (observer?.malformed) unidentified();
- if (observer) {
- responseBytes += bytes.length;
- if (responseBytes > 32 * 1024 * 1024) throw new Error("Non-streaming model response exceeded the evidence bound");
- buffered.push(bytes);
- // No provider text or tool call reaches the SDK until the actual
- // message envelope identifies the pinned model. Preserve bytes.
- if (streaming && observer.models.size) {
- for (const chunk of buffered) if (!res.write(chunk)) await once(res, "drain", {signal: abort.signal});
- buffered.length = 0; responseBytes = 0;
- }
- } else if (!res.write(bytes)) await once(res, "drain", {signal: abort.signal});
- }
- observer?.finish();
- if (observer && (!observer.models.size || observer.malformed)) unidentified();
- for (const bytes of buffered) if (!res.write(bytes)) await once(res, "drain", {signal: abort.signal});
- finished = true;
- res.end();
- } catch (error) {
- if (invalid()) onInvalid();
- if (!res.headersSent) {
- const status = error instanceof ClaudeAccessError ? error.status : 502;
- const headers: Record<string, string> = {...(error instanceof ClaudeAccessError ? error.responseHeaders : {}), "content-type": "application/json"};
- if (status < 500 && status !== 429) headers["x-should-retry"] = "false";
- if (error instanceof ClaudeAccessError && error.retryAfter) headers["retry-after"] = error.retryAfter;
- res.writeHead(status, headers).end(JSON.stringify({type: "error", error: {type: status === 429 ? "rate_limit_error" : status === 401 ? "authentication_error" : status === 403 ? "permission_error" : status < 500 ? "invalid_request_error" : "api_error", message: error instanceof ClaudeAccessError ? error.message : "Internal Claude access is unavailable"}}));
- } else res.destroy();
- }
- finally {
- active.delete(abort); signal?.removeEventListener("abort", cancel);
- if (admitted) {
- if (inference && observer) {
- if (observer.complete && finished) isolation.completedRequests++;
- else isolation.interruptedRequests++;
- if (!observer.models.size || observer.malformed) isolation.missingIdentityRequests++;
- } else if (inference && responseStatus === null) { isolation.interruptedRequests++; isolation.missingIdentityRequests++; }
- if (isolation.status !== "invalid") isolation.status = isolation.missingIdentityRequests ? "unknown" : isolation.observedModels.length ? "observed" : "pending";
- this.modelEvidence(session, {type: "response", requestId, status: responseStatus, ...(authorizationFailures.length ? {authorizationFailures} : {}), completed: finished && observer?.complete === true, providerModels: observer ? [...observer.models] : [], identity: observer?.models.size && !observer.malformed ? "reported" : "unknown", streamComplete: observer?.complete ?? false});
- }
- }
- };
- const server = http.createServer((req, res) => {
- const work = handle(req, res); pending.add(work);
- void work.catch(() => { invalidate("model_evidence_persistence_failed"); res.destroy(); }).finally(() => pending.delete(work));
- });
- server.listen(0, "0.0.0.0"); await once(server, "listening");
- const address = server.address(); if (!address || typeof address === "string") throw new Error("Inference broker did not start");
- return {token, baseUrl: `http://host.docker.internal:${address.port}`, close: async () => { for (const request of active) request.abort(); server.closeAllConnections(); server.close(); await Promise.allSettled([...pending]); }};
- }
- async start(id: string, prompt: string, signal?: AbortSignal): Promise<void> {
- if (!prompt.trim() || prompt.length > 100_000) throw new Error("Enter a prompt of at most 100,000 characters");
- const job = this.reserve(id, signal);
- let release: (() => void) | undefined;
- try {
- let session = await this.get(id);
- await this.access(session.owner, job.signal);
- interrupted(job.signal);
- release = this.lock(session);
- session = await this.get(id);
- if (session.turns.at(-1)?.status === "running") throw new Error("Recover the interrupted session before continuing");
- if (session.turns.length && !session.turns.at(-1)?.after) throw new Error("Recover the missing environment checkpoint before continuing");
- this.assertResumable(session);
- await this.restoreContainerIfMissing(session, job.signal);
- interrupted(job.signal);
- const unlock = release;
- void this.run(session, prompt, job.signal).catch(() => {}).finally(() => { try { unlock(); } finally { job.finish(); } }).catch(() => {});
- } catch (e) { try { release?.(); } finally { job.finish(); } throw e; }
- }
- async wait(id: string) { await this.running.get(id)?.done; return this.get(id); }
- async stop(id: string) {
- // Abort first, including startup before session.json exists or access resolves.
- this.running.get(id)?.stop.abort();
- return this.wait(id);
- }
- private async run(session: ClaudeSession, prompt: string, signal: AbortSignal) {
- const dir = this.dir(session.owner, session.id), state = path.join(dir, "session.json");
- const collector = this.collector(session); let offset = collector.verify().streams.sdk;
- const turn: Turn = {number: session.turns.length + 1, prompt, startedAt: new Date().toISOString(), sdkStart: offset, status: "running", before: session.turns.at(-1)?.after ?? session.base};
- session.turns.push(turn); session.capture = "capturing"; session.replay = "unverified"; save(state, session);
- let broker: Awaited<ReturnType<ClaudeRuntime["broker"]>> | undefined;
- let outcome: Turn["status"] = "failed";
- const isolationStop = new AbortController();
- const executionSignal = AbortSignal.any([signal, isolationStop.signal]);
- try {
- interrupted(executionSignal);
- await this.grant(session, false, executionSignal);
- interrupted(executionSignal);
- await this.docker(["start", session.container], {signal: executionSignal});
- interrupted(executionSignal);
- broker = await this.broker(session, () => isolationStop.abort(), executionSignal);
- interrupted(executionSignal);
- const actual = await this.docker(["exec", session.container, "sha256sum", "/opt/claude/controller.mjs", "/etc/claude-code/managed-settings.json"], {signal: executionSignal});
- if (actual.split("\n").map(line => line.split(/\s+/)[0]).join(":") !== `${digest(CONTROLLER)}:${digest(managedSettings(session.model))}`) throw new Error("The sandbox controller or managed model policy changed");
- await this.docker(["exec", "-i", session.container, "node", "/opt/claude/controller.mjs"], {
- input: JSON.stringify({sessionId: session.id, resume: turn.number > 1, turn: turn.number, prompt, model: session.model, baseUrl: broker.baseUrl, token: broker.token}), signal: executionSignal, timeout: 60 * 60_000,
- stdout: bytes => { collector.recordStream("sdk", bytes, offset); offset += bytes.length; },
- });
- if (session.modelIsolation?.status === "invalid") throw new Error("Session model isolation failed");
- outcome = "complete";
- } catch { outcome = signal.aborted ? "interrupted" : "failed"; turn.error = signal.aborted ? "Turn stopped; partial evidence retained" : "Claude turn failed; inspect the private diagnostic bundle"; }
- finally {
- await broker?.close();
- if (this.options.revoke) {
- try { await this.options.revoke(this.authorizationContext(session)); }
- catch { this.modelEvidence(session, {type: "authorization_revocation", status: "failed"}); }
- }
- try {
- await this.docker(["stop", "--time", "3", session.container]);
- turn.after = await this.checkpoint(session.container, dir, this.checkpoints(session));
- this.repointArchive(session, turn.after);
- const manifest = await this.collect(session, true, outcome === "complete");
- if (manifest.status !== "complete" && outcome === "complete") { outcome = "failed"; turn.error = "Native capture is incomplete"; }
- } catch (e) { session.capture = "incomplete"; session.issues = ["checkpoint_or_capture_failed"]; outcome = "failed"; turn.error = "Evidence could not be finalized; recover before continuing"; }
- turn.sdkEnd = fs.existsSync(path.join(dir, "native/events/sdk.jsonl")) ? fs.statSync(path.join(dir, "native/events/sdk.jsonl")).size : offset;
- // Persist replacement checkpoint references before pruning their old files.
- // Keep the turn running until cleanup ends: a terminal status enables the
- // next prompt/export, which must not race this operation's lock.
- save(state, session);
- await this.pruneArchives(session).catch(() => {});
- turn.status = outcome; turn.finishedAt = new Date().toISOString(); save(state, session);
- }
- }
- private recoveryGuard(dir: string) {
- const guard = path.join(dir, "recovery.lock"), staging = path.join(dir, `.recovery-stage-${randomUUID()}`);
- const owner = JSON.stringify({pid: process.pid, nonce: randomUUID(), identity: processIdentity(process.pid)});
- fs.mkdirSync(staging, {mode: 0o700});
- try {
- const fd = fs.openSync(path.join(staging, "owner.json"), "wx", 0o600);
- try { fs.writeFileSync(fd, owner); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
- syncDirectory(staging);
- // Publish a complete, nonempty directory. A legacy empty file/directory
- // has no trustworthy owner and is deliberately never reclaimed.
- for (let attempt = 0; attempt < 3; attempt++) {
- let present = true;
- try { this.localPath(guard, true); }
- catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; present = false; }
- if (present) {
- const record = path.join(guard, "owner.json"); this.localPath(record, false);
- const bytes = fs.readFileSync(record, "utf8"), prior: unknown = JSON.parse(bytes);
- if (!deadLockOwner(prior)) throw new Error("Another process is recovering this session or its recovery owner is unknown");
- // Keep this nonempty tombstone permanently. If two reclaimers read
- // the same dead owner, only one rename can succeed: the loser cannot
- // overwrite the tombstone with a newer live guard (the ABA race).
- const tombstone = path.join(dir, `.recovery-dead-${digest(bytes)}`);
- if (fs.existsSync(tombstone)) throw new Error("The recovery guard generation already changed; retry the operation");
- try { fs.renameSync(guard, tombstone); syncDirectory(dir); }
- catch (error) { if (!isRecord(error) || !["ENOENT", "EEXIST", "ENOTEMPTY"].includes(String(error.code))) throw error; }
- continue;
- }
- try { fs.renameSync(staging, guard); }
- catch (error) { if (!isRecord(error) || !["EEXIST", "ENOTEMPTY"].includes(String(error.code))) throw error; continue; }
- syncDirectory(dir);
- return () => {
- this.localPath(guard, true); this.localPath(path.join(guard, "owner.json"), false);
- if (fs.readFileSync(path.join(guard, "owner.json"), "utf8") !== owner) throw new Error("The recovery guard owner changed");
- // Remove only our uniquely named directory after unpublishing it.
- // A crash on either side leaves a recoverable guard or harmless stage.
- fs.renameSync(guard, staging); syncDirectory(dir);
- fs.rmSync(staging, {recursive: true});
- };
- }
- throw new Error("Another process is recovering this session; retry the operation");
- } finally { fs.rmSync(staging, {recursive: true, force: true}); }
- }
- private lock(session: ClaudeSession, recover = false) {
- const dir = this.dir(session.owner, session.id), file = path.join(dir, "operation.lock"), nonce = randomUUID();
- const staged = path.join(dir, `.operation-${nonce}.tmp`);
- let releaseGuard: (() => void) | undefined;
- try {
- const fd = fs.openSync(staged, "wx", 0o600);
- try { fs.writeFileSync(fd, JSON.stringify({pid: process.pid, nonce, identity: processIdentity(process.pid)})); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
- if (recover) {
- releaseGuard = this.recoveryGuard(dir);
- if (fs.existsSync(file)) {
- this.localPath(file, false);
- const bytes = fs.readFileSync(file, "utf8"), prior: unknown = JSON.parse(bytes);
- if (!deadLockOwner(prior)) throw new ApiError(409, "session_in_use", "Another process is using this session or its operation owner is unknown");
- fs.unlinkSync(file);
- }
- }
- // Atomic no-replace publication also prevents an ownerless operation
- // lock if the process crashes between opening and writing its record.
- try { fs.linkSync(staged, file); } catch { throw new Error("This session is in use or needs recovery after a process exit"); }
- syncDirectory(dir);
- } finally { try { releaseGuard?.(); } finally { fs.rmSync(staged, {force: true}); } }
- return () => { if (JSON.parse(fs.readFileSync(file, "utf8")).nonce === nonce) fs.unlinkSync(file); };
- }
- private async exclusive<T>(id: string, work: (signal: AbortSignal) => Promise<T>, recover = false): Promise<T> {
- const job = this.reserve(id);
- let release: (() => void) | undefined;
- try { const session = await this.get(id); interrupted(job.signal); release = this.lock(session, recover); return await work(job.signal); }
- finally { try { release?.(); } finally { job.finish(); } }
- }
- async recover(id: string) { return this.exclusive(id, signal => this.recoverStopped(id, signal), true); }
- private async recoverStopped(id: string, signal: AbortSignal) {
- const session = await this.get(id), dir = this.dir(session.owner, id), turn = session.turns.at(-1);
- if (!turn) return session;
- await this.access(session.owner, signal);
- await this.restoreContainerIfMissing(session, signal);
- await this.docker(["stop", "--time", "3", session.container]);
- turn.after = await this.checkpoint(session.container, dir, this.checkpoints(session));
- this.repointArchive(session, turn.after);
- if (turn.status === "running") turn.status = "interrupted";
- const recovered = await this.collect(session, true, turn.status === "complete");
- turn.sdkEnd = recovered.streams.sdk;
- turn.finishedAt ??= new Date().toISOString();
- save(path.join(dir, "session.json"), session); await this.pruneArchives(session); return session;
- }
- async events(id: string): Promise<DisplayEvent[]> {
- const session = await this.get(id), dir = this.dir(session.owner, id), output: DisplayEvent[] = [];
- const stream = path.join(dir, "native", "events", "sdk.jsonl");
- const bytes = await fsp.readFile(stream).catch(() => Buffer.alloc(0));
- // SDK init/result batches also occur for background-agent notifications.
- // Only the host's submitted-turn byte boundaries define a user's turn.
- for (const submitted of session.turns) {
- const turn = submitted.number;
- output.push({type: "user", text: submitted.prompt, turn});
- if (!Number.isSafeInteger(submitted.sdkStart)) continue; // pre-pilot captures have no reliable SDK boundary
- const text = bytes.subarray(submitted.sdkStart, submitted.sdkEnd ?? bytes.length).toString("utf8");
- for (const line of text.split("\n")) {
- let event: unknown; try { event = JSON.parse(line); } catch { continue; }
- if (!isRecord(event)) continue;
- if (event.type === "assistant" && isRecord(event.message) && Array.isArray(event.message.content)) for (const block of event.message.content) {
- if (!isRecord(block)) continue;
- if (block.type === "text" && typeof block.text === "string") output.push({type: "assistant", text: block.text, turn});
- if (block.type === "thinking" && typeof block.thinking === "string") output.push({type: "thinking", text: block.thinking, turn});
- if (block.type === "tool_use" && typeof block.name === "string") output.push({type: "tool", text: block.name, turn});
- }
- }
- if (submitted.status !== "running") output.push({type: "result", text: submitted.status === "complete" ? "Turn finished" : submitted.status === "interrupted" ? "Turn interrupted" : "Turn failed", turn});
- }
- return output;
- }
- async verify(id: string, command = "node -e \"require('fs').accessSync('/workspace')\"") { return this.exclusive(id, () => this.verifyStopped(id, command)); }
- private async verifyStopped(id: string, command: string) {
- const session = await this.get(id), dir = this.dir(session.owner, id), checkpoint = session.turns.at(-1)?.after ?? session.base;
- await this.access(session.owner);
- this.collector(session).verify();
- const checked = new Set<string>();
- for (const cp of this.checkpoints(session)) {
- if (checked.has(cp.file)) continue;
- if (await fileHash(path.join(dir, cp.file)) !== cp.sha256) throw new Error("Environment archive integrity failure");
- checked.add(cp.file);
- }
- await this.loadCheckpoint(checkpoint, dir);
- const name = `omnirush-verify-${randomUUID()}`;
- try {
- const output = await this.docker(["run", "--name", name, "--network=none", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--pids-limit=128", "--memory=2g", checkpoint.image, "bash", "-lc", command]);
- const report = {schema: 1, sessionId: id, checkpoint: checkpoint.image, verifiedAt: new Date().toISOString(), command, output, status: "restored", meaning: "Exact environment restored and verification command passed; model re-execution is not claimed"};
- save(path.join(dir, "replay.json"), report); session.replay = "restored"; save(path.join(dir, "session.json"), session); return report;
- } finally { await this.docker(["rm", "-f", name]).catch(() => {}); }
- }
- async export(id: string) { return this.exclusive(id, () => this.exportStopped(id), true); }
- async prepareUpload(id: string, checkpoint: boolean) {
- return this.exclusive(id, async () => {
- const session = await this.get(id), stateDirectory = this.dir(session.owner, id);
- const bindingId = session.authorization?.bindingId, contractHash = session.contractSha256;
- if (!bindingId || !contractHash) throw new Error("This capture has no backend session binding; retain its local ZIP");
- const nativeDirectory = path.join(stateDirectory, `native-upload-${randomUUID()}`);
- this.collector(session).exportTo(nativeDirectory);
- save(path.join(nativeDirectory, "session.json"), session);
- await fsp.cp(path.join(stateDirectory, "policy"), path.join(nativeDirectory, "policy"), {recursive: true});
- const diagnostics = path.join(stateDirectory, "transport", "stderr.jsonl");
- if (fs.existsSync(diagnostics)) {
- privateDir(path.join(nativeDirectory, "diagnostics"));
- await fsp.copyFile(diagnostics, path.join(nativeDirectory, "diagnostics", "stderr.jsonl"));
- }
- const manifestSha256 = await writeBundleManifest(nativeDirectory, {sessionId: id, bindingId, contractHash, engineVersion: session.claudeVersion}, "claude_native");
- let checkpointFile: string | undefined, checkpointManifestSha256: string | undefined;
- if (checkpoint) {
- const file = await this.exportStopped(id, hash => { checkpointManifestSha256 = hash; });
- const sha = await fileHash(file);
- checkpointFile = path.join(stateDirectory, `checkpoint-${sha}.zip`);
- try { await fsp.link(file, checkpointFile); }
- catch (error) {
- if (!(isRecord(error) && error.code === "EEXIST") || await fileHash(checkpointFile) !== sha) throw error;
- }
- }
- return {session, stateDirectory, nativeDirectory, manifestSha256, checkpointFile, checkpointManifestSha256};
- });
- }
- private async exportStopped(id: string, onManifest?: (hash: string) => void) {
- const session = await this.get(id), dir = this.dir(session.owner, id);
- const validateTree = (file: string) => {
- const stat = fs.lstatSync(file); this.localPath(file, stat.isDirectory());
- if (stat.isDirectory()) for (const name of fs.readdirSync(file)) validateTree(path.join(file, name));
- };
- for (const name of ["native", "policy", "images", "transport", "replay.json"]) {
- const file = path.join(dir, name);
- try { validateTree(file); } catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
- }
- for (const name of [`${id}.zip`, `${id}.zip.tmp`]) {
- try { this.localPath(path.join(dir, name), false); } catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
- }
- try { this.localPath(path.join(dir, "config"), true); } catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
- const bundle = path.join(dir, `export-${randomUUID()}`); this.collector(session, true).exportTo(bundle);
- try {
- // Legacy/invalid classification is a derived observation, never a claim
- // that old evidence was captured under today's model policy.
- save(path.join(bundle, "session.json"), session);
- if (fs.existsSync(path.join(dir, "policy"))) await fsp.cp(path.join(dir, "policy"), path.join(bundle, "policy"), {recursive: true});
- if (fs.existsSync(path.join(dir, "replay.json"))) fs.copyFileSync(path.join(dir, "replay.json"), path.join(bundle, "replay.json"));
- await fsp.cp(path.join(dir, "images"), path.join(bundle, "images"), {recursive: true});
- // Diagnostics are private evidence too; they must not disappear from the
- // downloadable bundle when an SDK turn or tool fails.
- const diagnostics = path.join(dir, "transport", "stderr.jsonl");
- if (fs.existsSync(diagnostics)) {
- privateDir(path.join(bundle, "diagnostics"));
- fs.copyFileSync(diagnostics, path.join(bundle, "diagnostics", "stderr.jsonl"));
- }
- fs.writeFileSync(path.join(bundle, "verify.py"), REPLAY_ADAPTER, {mode: 0o600});
- // Saved evidence is sufficient for export, even if the process crashed
- // while the container was running. Never contact Docker or copy mutable
- // container state into this local snapshot; the saved images are authority.
- save(path.join(bundle, "diagnostics", "export.json"), {schema: 1, workspaceCopy: "not-requested", source: "saved-evidence", savedImagesRetained: true});
- fs.writeFileSync(path.join(bundle, "README.txt"), "Private Claude Code evidence. Contains original transcripts, provider-exposed thinking summaries and opaque signatures, SDK/hook events, complete environment images, and project files. Do not publish. Restore: gunzip -c images/<hash>.tar.gz | docker load; run the image digest recorded in session.json with --network=none. replay.json records environment restoration, not deterministic model re-execution. Recorded-tool replay: on an isolated worker with the reviewed omniconv verifier installed, run python3 verify.py <this-session.zip> --out <new-private-report-directory>. The adapter checks native evidence hashes, loads each exact before image, replays all root and child tool calls with networking disabled, and compares project files and modes with the captured after image. Add --check-path /absolute/path to compare additional filesystem scopes. Unsupported calls remain unverified. Reports and raw bundles require a separate masking/delivery review before distribution.\n", {mode: 0o600});
- if (session.authorization?.bindingId && session.contractSha256) {
- const hash = await writeBundleManifest(bundle, {sessionId: id, bindingId: session.authorization.bindingId, contractHash: session.contractSha256, engineVersion: session.claudeVersion}, "claude_checkpoint");
- onManifest?.(hash);
- }
- const zip = path.join(dir, `${id}.zip`); await zipDirectory(bundle, zip); return zip;
- } finally { await fsp.rm(bundle, {recursive: true, force: true}); }
- }
- async shutdown() { this.closed = true; for (const job of this.running.values()) job.stop.abort(); await Promise.all([...this.running.values()].map(job => job.done)); }
-}
diff --git a/apps/server/src/claude-code/sandbox-assets.ts b/apps/server/src/claude-code/sandbox-assets.ts
deleted file mode 100644
index dc38ca90..00000000
--- a/apps/server/src/claude-code/sandbox-assets.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-// Embedded so the compiled desktop server and the CLI ship exactly the same runner.
-export const SDK_VERSION = "0.3.306";
-export const CLAUDE_VERSION = "2.1.306";
-export const IMAGE = `omnirush-claude-sdk:${SDK_VERSION}-4`;
-/** The model baked into the runtime image's policy file; a session on another model replaces that file before its base checkpoint. */
-export const MODEL = "claude-opus-5-5";
-/** A Claude catalog id (claude-<name>), the only shape a session may pin. */
-export const CLAUDE_MODEL_ID = /^claude-[a-z0-9][a-z0-9.-]{0,62}$/;
-export const CAPTURE_POLICY_VERSION = "claude-native-2";
-/** The family aliases denied for a session: every family but its own (Opus keeps its original ["sonnet", "haiku"]). */
-export const deniedFamilies = (model: string) => ["opus", "sonnet", "haiku"].filter(family => !model.includes(family));
-// This is also passed as SDK managed policy. The on-disk copy is root-owned
-// so a project setting or tool cannot widen it for a nested Claude process.
-export const managedSettings = (model: string) => JSON.stringify({availableModels: [model], availableModelsMatch: "exact", enforceAvailableModels: true, deniedModels: deniedFamilies(model), allowManagedHooksOnly: true});
-export const MANAGED_SETTINGS = managedSettings(MODEL);
-export const DOCKERFILE = `FROM node:22.21.1-bookworm-slim
-RUN apt-get update && apt-get install -y --no-install-recommends git ripgrep python3 python3-venv ca-certificates zip unzip procps && rm -rf /var/lib/apt/lists/*
-RUN corepack enable && corepack prepare [email protected] --activate
-WORKDIR /opt/claude
-COPY package.json pnpm-lock.yaml ./
-RUN pnpm install --frozen-lockfile --prod
-COPY controller.mjs ./
-COPY managed-settings.json /etc/claude-code/managed-settings.json
-RUN mkdir -p /workspace /home/node/.claude /home/node/evidence && chown -R node:node /workspace /home/node
-ENV HOME=/home/node CLAUDE_CONFIG_DIR=/home/node/.claude
-USER node
-WORKDIR /workspace
-CMD ["sleep", "infinity"]
-`;
-
-export const CONTROLLER = String.raw`
-import fs from 'node:fs';
-import { createHash } from 'node:crypto';
-import { query } from '@anthropic-ai/claude-agent-sdk';
-const input = [];
-for await (const chunk of process.stdin) input.push(chunk);
-const request = JSON.parse(Buffer.concat(input).toString('utf8'));
-const append = (file, value) => {
- const fd = fs.openSync(file, 'a', 0o600);
- try { fs.writeFileSync(fd, JSON.stringify(value) + '\n'); fs.fsyncSync(fd); }
- finally { fs.closeSync(fd); }
-};
-const evidence = '/home/node/evidence';
-fs.mkdirSync(evidence, {recursive: true, mode: 0o700});
-const hooks = {};
-for (const event of ['PreToolUse','PostToolUse','PostToolUseFailure','SubagentStart','SubagentStop','PreCompact','PostCompact','SessionStart','SessionEnd','Stop','StopFailure']) {
- hooks[event] = [{hooks: [async (input, toolUseId) => {
- let witness;
- if (event === 'PreToolUse' && input.tool_name === 'Read' && typeof input.tool_input?.file_path === 'string') {
- const file = input.tool_input.file_path;
- try {
- const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
- try {
- const stat = fs.fstatSync(fd);
- if (stat.isFile() && stat.size <= 512 * 1024 * 1024) {
- const hash = createHash('sha256'), buffer = Buffer.alloc(1024 * 1024);
- for (;;) { const count = fs.readSync(fd, buffer); if (!count) break; hash.update(buffer.subarray(0, count)); }
- const after = fs.fstatSync(fd);
- if (after.size === stat.size && after.mtimeMs === stat.mtimeMs && after.ctimeMs === stat.ctimeMs) witness = {path: file, bytes: stat.size, sha256: hash.digest('hex'), mode: stat.mode};
- }
- } finally { fs.closeSync(fd); }
- } catch { /* Missing/unreadable files retain their actual failed tool result. */ }
- }
- append(evidence + '/hooks.jsonl', {time: new Date().toISOString(), turn: request.turn, input, toolUseId, witness});
- return {};
- }]}];
-}
-const env = {
- PATH: process.env.PATH, HOME: '/home/node', LANG: 'C.UTF-8',
- CLAUDE_CONFIG_DIR: '/home/node/.claude',
- CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1',
- CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1',
- CLAUDE_CODE_SHELL: '/bin/bash',
- ANTHROPIC_MODEL: request.model, ANTHROPIC_DEFAULT_MODEL: request.model,
- ANTHROPIC_DEFAULT_OPUS_MODEL: request.model,
- ANTHROPIC_DEFAULT_SONNET_MODEL: request.model, ANTHROPIC_DEFAULT_HAIKU_MODEL: request.model,
- ANTHROPIC_DEFAULT_FABLE_MODEL: request.model, ANTHROPIC_SMALL_FAST_MODEL: request.model,
- CLAUDE_CODE_SUBAGENT_MODEL: request.model, CLAUDE_CODE_SUBAGENT_MODEL_FORCE: '1',
- CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL: request.model,
- CLAUDE_CODE_AUTO_MODE_MODEL: request.model, CLAUDE_CODE_BG_CLASSIFIER_MODEL: request.model,
- CLAUDE_CODE_NO_MODEL_FALLBACK: '1', CLAUDE_CODE_DISABLE_MODEL_ACCESS_FALLBACK: '1',
- ANTHROPIC_BASE_URL: request.baseUrl, ANTHROPIC_AUTH_TOKEN: request.token,
-};
-let success = false;
-try {
- for await (const message of query({prompt: request.prompt, options: {
- cwd: '/workspace', env, model: request.model,
- ...(request.resume ? {resume: request.sessionId} : {sessionId: request.sessionId}),
- persistSession: true, includePartialMessages: true, forwardSubagentText: true,
- includeHookEvents: true, settingSources: [],
- managedSettings: {availableModels: [request.model], availableModelsMatch: 'exact', enforceAvailableModels: true, deniedModels: ['opus', 'sonnet', 'haiku'].filter(family => !request.model.includes(family)), allowManagedHooksOnly: true},
- settings: {model: request.model, fallbackModel: []},
- systemPrompt: {type: 'preset', preset: 'claude_code'},
- permissionMode: 'bypassPermissions', allowDangerouslySkipPermissions: true,
- thinking: {type: 'adaptive'}, effort: 'high',
- maxTurns: 100, hooks,
- stderr: text => append(evidence + '/stderr.jsonl', {turn: request.turn, text}),
- }})) {
- append(evidence + '/sdk.jsonl', message);
- // A disk acknowledgement precedes every event delivered to the host.
- process.stdout.write(JSON.stringify(message) + '\n');
- if (message.type === 'result') success = message.subtype === 'success' && !message.is_error;
- }
-} catch (error) {
- append(evidence + '/stderr.jsonl', {turn: request.turn, text: String(error)});
-}
-process.exitCode = success ? 0 : 1;
-`;
diff --git a/apps/server/src/claude-code/sandbox-lock.ts b/apps/server/src/claude-code/sandbox-lock.ts
deleted file mode 100644
index c3d8f200..00000000
--- a/apps/server/src/claude-code/sandbox-lock.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-// pnpm lockfile v9; installed with pnpm 10.27.0 in the sandbox. Exact SDK and transitive package integrity pins.
-export const PACKAGE_JSON = "{\"name\": \"omnirush-claude-sandbox\", \"private\": true, \"type\": \"module\", \"dependencies\": {\"@anthropic-ai/claude-agent-sdk\": \"0.3.306\"}}";
-export const LOCKFILE = "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n excludeLinksFromLockfile: false\n\nimporters:\n\n .:\n dependencies:\n '@anthropic-ai/claude-agent-sdk':\n specifier: 0.3.306\n version: 0.3.306(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])\n\npackages:\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-R8WM+XIYCaWlT/4whzVgBWX2PGuFJ+/ReqSleYSCPzs7l+S4udnwayZFvyOyfIPiYC7GLhHoPiNmMDzjDdaCxw==}\n cpu: [arm64]\n os: [darwin]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-EcgDYECaPRe447QpH1vzKMJs7AE+U/KiHqflfGr6qTfzH+1SF0oHX1dMVhGzaJn7KdGrDH9N72yPZXw7rj5Qtg==}\n cpu: [x64]\n os: [darwin]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-ak/r1xhFJM1A/Eidjpu7LQ31GQK72spfEGb4yay0coWtcaAvHERGO2sKWeT/Tv3SyrigxdTPTveLSYS1Vb4fbg==}\n cpu: [arm64]\n os: [linux]\n libc: [musl]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-Vee1MIEqd7I8NKF2GOLxLJOuCghf/k4poEk7E/p6zXCIt7MmmtrK7ph9/WiYqOgEpOagXm8D6fRgEJvxWYGIXg==}\n cpu: [arm64]\n os: [linux]\n libc: [glibc]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-jbQf6HmNIDGI4YnoBc/IqOPKT3GxUSddor8yA9tmCpfKPU4Ln+gcN2Md/u2a0jODEo1hcx1Fn33xxTdcaLmD2Q==}\n cpu: [x64]\n os: [linux]\n libc: [musl]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-2taDjG+UI0+VrPdxqRhl7Y9m4PPscXKxRVBDLHVSeFrA600HXGqyOIm34Pao6UVNlhCD+pKU/s7++OFGy88h2Q==}\n cpu: [x64]\n os: [linux]\n libc: [glibc]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-6nbxfp8hQ6Of0oVcEHBGpbf56siAishGw8DBamGiqau+ji87DBWPW06V8lbuB9C94REnGk73wNLnFJ5PgPTKSg==}\n cpu: [arm64]\n os: [win32]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-oQPai3jCeSZdTasTGSA8TGALdPxTILdcan09LaKbMCrXXYRR9njxVgmeIqvoH9h8YzKebPHW+Ks0eKKptLrtUw==}\n cpu: [x64]\n os: [win32]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-kmxcd+4WNhqhqnzODRPM5aOKb1EH2EdlRsf7ZeMx8uQsC1tHAHgHftQGFXGT8yMaYaYlDP9BGYJy1/aYv7IhkQ==}\n engines: {node: '>=18.0.0'}\n peerDependencies:\n '@anthropic-ai/sdk': '>=0.93.0'\n '@modelcontextprotocol/sdk': ^1.29.0\n zod: ^4.0.0\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-Op/fKMsfVwFCfObc87leLOFlORE0RjOvLzRzPCWWLI7Ww6bobpKR6YmYC8ZYgulRh+m2a/3/61VUXoWHFtCXIw==}\n hasBin: true\n peerDependencies:\n zod: ^3.25.0 || ^4.0.0\n peerDependenciesMeta:\n zod:\n optional: true\n\n '@babel/[email protected]':\n resolution: {integrity: sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==}\n engines: {node: '>=6.9.0'}\n\n '@hono/[email protected]':\n resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==}\n engines: {node: '>=20'}\n peerDependencies:\n hono: ^4 || ^5.0.0-0\n\n '@modelcontextprotocol/[email protected]':\n resolution: {integrity: sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==}\n engines: {node: '>=18'}\n peerDependencies:\n '@cfworker/json-schema': ^4.1.1\n zod: ^3.25 || ^4.0\n peerDependenciesMeta:\n '@cfworker/json-schema':\n optional: true\n\n '@opentelemetry/[email protected]':\n resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==}\n engines: {node: '>=8.0.0'}\n\n '@stablelib/[email protected]':\n resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}\n\n [email protected]:\n resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}\n peerDependencies:\n ajv: ^8.0.0\n peerDependenciesMeta:\n ajv:\n optional: true\n\n [email protected]:\n resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}\n\n [email protected]:\n resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}\n engines: {node: '>=6.6.0'}\n\n [email protected]:\n resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}\n engines: {node: '>= 8'}\n\n [email protected]:\n resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}\n engines: {node: '>=6.0'}\n peerDependencies:\n supports-color: '*'\n peerDependenciesMeta:\n supports-color:\n optional: true\n\n [email protected]:\n resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}\n\n [email protected]:\n resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}\n\n [email protected]:\n resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==}\n engines: {node: '>=18.0.0'}\n\n [email protected]:\n resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}\n engines: {node: '>=18.0.0'}\n\n [email protected]:\n resolution: {integrity: sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==}\n engines: {node: '>= 16'}\n peerDependencies:\n express: '>= 4.11'\n\n [email protected]:\n resolution: {integrity: sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}\n\n [email protected]:\n resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}\n\n [email protected]:\n resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}\n\n [email protected]:\n resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}\n engines: {node: '>= 18.0.0'}\n\n [email protected]:\n resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}\n\n [email protected]:\n resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==}\n engines: {node: '>=16.9.0'}\n\n [email protected]:\n resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}\n engines: {node: '>=0.10.0'}\n\n [email protected]:\n resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}\n\n [email protected]:\n resolution: {integrity: sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==}\n engines: {node: '>= 12'}\n\n [email protected]:\n resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}\n\n [email protected]:\n resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}\n\n [email protected]:\n resolution: {integrity: sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==}\n\n [email protected]:\n resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==}\n engines: {node: '>=16'}\n\n [email protected]:\n resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}\n\n [email protected]:\n resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==}\n\n [email protected]:\n resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}\n\n [email protected]:\n resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}\n engines: {node: '>=0.10.0'}\n\n [email protected]:\n resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}\n\n [email protected]:\n resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}\n engines: {node: '>=8'}\n\n [email protected]:\n resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==}\n\n [email protected]:\n resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}\n engines: {node: '>=16.20.0'}\n\n [email protected]:\n resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==}\n engines: {node: '>=0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}\n engines: {node: '>=0.10.0'}\n\n [email protected]:\n resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}\n\n [email protected]:\n resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}\n\n [email protected]:\n resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}\n engines: {node: '>=8'}\n\n [email protected]:\n resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}\n engines: {node: '>=8'}\n\n [email protected]:\n resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==}\n\n [email protected]:\n resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}\n engines: {node: '>=0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==}\n\n [email protected]:\n resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}\n engines: {node: '>= 8'}\n hasBin: true\n\n [email protected]:\n resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}\n\n [email protected]:\n resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}\n peerDependencies:\n zod: ^3.25.28 || ^4\n\n [email protected]:\n resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}\n\nsnapshots:\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected](@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':\n dependencies:\n '@anthropic-ai/sdk': 1.1.0([email protected])\n '@modelcontextprotocol/sdk': 1.32.1([email protected])\n zod: 4.6.7\n optionalDependencies:\n '@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-darwin-x64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-arm64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-arm64-musl': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-x64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-x64-musl': 0.3.306\n '@anthropic-ai/claude-agent-sdk-win32-arm64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-win32-x64': 0.3.306\n\n '@anthropic-ai/[email protected]([email protected])':\n dependencies:\n '@opentelemetry/api': 1.10.0\n json-schema-to-ts: 3.1.1\n standardwebhooks: 1.1.1\n optionalDependencies:\n zod: 4.6.7\n\n '@babel/[email protected]': {}\n\n '@hono/[email protected]([email protected])':\n dependencies:\n hono: 4.13.13\n\n '@modelcontextprotocol/[email protected]([email protected])':\n dependencies:\n '@hono/node-server': 2.1.5([email protected])\n ajv: 8.20.0\n ajv-formats: 3.0.1([email protected])\n content-type: 1.0.5\n cors: 2.8.6\n cross-spawn: 7.0.6\n eventsource: 3.0.7\n eventsource-parser: 3.1.1\n express: 5.3.0\n express-rate-limit: 8.7.1([email protected])\n hono: 4.13.13\n jose: 6.2.13\n json-schema-typed: 8.0.2\n pkce-challenge: 5.0.1\n raw-body: 3.0.2\n zod: 4.6.7\n zod-to-json-schema: 3.25.2([email protected])\n transitivePeerDependencies:\n - supports-color\n\n '@opentelemetry/[email protected]': {}\n\n '@stablelib/[email protected]': {}\n\n [email protected]:\n dependencies:\n mime-types: 3.0.2\n negotiator: 1.1.0\n\n [email protected]([email protected]):\n optionalDependencies:\n ajv: 8.20.0\n\n [email protected]:\n dependencies:\n fast-deep-equal: 3.1.3\n fast-uri: 3.1.9\n json-schema-traverse: 1.0.0\n require-from-string: 2.0.2\n\n [email protected]:\n dependencies:\n bytes: 3.1.2\n content-type: 2.1.0\n debug: 4.4.3\n http-errors: 2.0.1\n iconv-lite: 0.7.3\n on-finished: 2.4.2\n qs: 6.16.1\n raw-body: 3.0.2\n type-is: 2.1.0\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n function-bind: 1.1.2\n\n [email protected]:\n dependencies:\n call-bind-apply-helpers: 1.0.2\n get-intrinsic: 1.3.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n object-assign: 4.1.1\n vary: 1.1.2\n\n [email protected]:\n dependencies:\n path-key: 3.1.1\n shebang-command: 2.0.0\n which: 2.0.2\n\n [email protected]:\n dependencies:\n ms: 2.1.3\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n call-bind-apply-helpers: 1.0.2\n es-errors: 1.3.0\n gopd: 1.2.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n eventsource-parser: 3.1.1\n\n [email protected]([email protected]):\n dependencies:\n debug: 4.4.3\n express: 5.3.0\n ip-address: 10.7.4\n transitivePeerDependencies:\n - supports-color\n\n [email protected]:\n dependencies:\n accepts: 2.0.0\n body-parser: 2.4.0\n content-disposition: 2.0.1\n content-type: 2.1.0\n cookie: 0.7.2\n cookie-signature: 1.2.2\n debug: 4.4.3\n depd: 2.0.0\n encodeurl: 2.0.0\n escape-html: 1.0.3\n etag: 1.8.1\n finalhandler: 2.1.1\n fresh: 2.0.0\n http-errors: 2.0.1\n merge-descriptors: 2.0.0\n mime-types: 3.0.2\n on-finished: 2.4.2\n once: 1.4.0\n parseurl: 1.3.3\n proxy-addr: 2.0.8\n qs: 6.16.1\n range-parser: 1.3.0\n router: 2.2.0\n send: 1.2.1\n serve-static: 2.2.1\n statuses: 2.0.2\n type-is: 2.1.0\n vary: 1.1.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n debug: 4.4.3\n encodeurl: 2.0.0\n escape-html: 1.0.3\n on-finished: 2.4.2\n parseurl: 1.3.3\n statuses: 2.0.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n call-bind-apply-helpers: 1.0.2\n es-define-property: 1.0.1\n es-errors: 1.3.0\n es-object-atoms: 1.1.2\n function-bind: 1.1.2\n get-proto: 1.0.1\n gopd: 1.2.0\n has-symbols: 1.1.0\n hasown: 2.0.4\n math-intrinsics: 1.1.0\n\n [email protected]:\n dependencies:\n dunder-proto: 1.0.1\n es-object-atoms: 1.1.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n function-bind: 1.1.2\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n depd: 2.0.0\n inherits: 2.0.4\n setprototypeof: 1.2.0\n statuses: 2.0.2\n toidentifier: 1.0.1\n\n [email protected]:\n dependencies:\n safer-buffer: 2.1.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n '@babel/runtime': 7.29.10\n ts-algebra: 2.0.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n mime-db: 1.54.0\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n content-type: 2.1.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n ee-first: 1.1.1\n\n [email protected]:\n dependencies:\n wrappy: 1.0.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n forwarded: 0.2.0\n ipaddr.js: 1.9.1\n\n [email protected]:\n dependencies:\n es-define-property: 1.0.1\n side-channel: 1.1.1\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n bytes: 3.1.2\n http-errors: 2.0.1\n iconv-lite: 0.7.3\n unpipe: 1.0.0\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n debug: 4.4.3\n depd: 2.0.0\n is-promise: 4.0.0\n parseurl: 1.3.3\n path-to-regexp: 8.4.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n debug: 4.4.3\n encodeurl: 2.0.0\n escape-html: 1.0.3\n etag: 1.8.1\n fresh: 2.0.0\n http-errors: 2.0.1\n mime-types: 3.0.2\n ms: 2.1.3\n on-finished: 2.4.2\n range-parser: 1.3.0\n statuses: 2.0.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]:\n dependencies:\n encodeurl: 2.0.0\n escape-html: 1.0.3\n parseurl: 1.3.3\n send: 1.2.1\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n shebang-regex: 3.0.0\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n object-inspect: 1.13.4\n\n [email protected]:\n dependencies:\n call-bound: 1.0.4\n es-errors: 1.3.0\n get-intrinsic: 1.3.0\n object-inspect: 1.13.4\n\n [email protected]:\n dependencies:\n call-bound: 1.0.4\n es-errors: 1.3.0\n get-intrinsic: 1.3.0\n object-inspect: 1.13.4\n side-channel-map: 1.0.1\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n object-inspect: 1.13.4\n side-channel-list: 1.0.1\n side-channel-map: 1.0.1\n side-channel-weakmap: 1.0.2\n\n [email protected]:\n dependencies:\n '@stablelib/base64': 1.0.1\n fast-sha256: 1.3.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n content-type: 2.1.0\n media-typer: 1.1.1\n mime-types: 3.0.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n isexe: 2.0.0\n\n [email protected]: {}\n\n [email protected]([email protected]):\n dependencies:\n zod: 4.6.7\n\n [email protected]: {}\n";
-
-// Derive the backend admission pin from the exact lock used by the Docker build.
-export const SDK_INSTALL_PIN = (() => {
- const name = "@anthropic-ai/claude-agent-sdk";
- const version: string = JSON.parse(PACKAGE_JSON).dependencies[name];
- const section = LOCKFILE.split("\n '" + name + "@" + version + "':\n")[1];
- const integrity = /^ resolution: \{integrity: (sha512-[A-Za-z0-9+/]+={0,2})\}/.exec(section ?? "")?.[1];
- if (!integrity) throw new Error("The Claude SDK lock has no package integrity pin");
- return Object.freeze({package: name, version, integrity});
-})();
diff --git a/apps/server/src/claude-code/transfer.ts b/apps/server/src/claude-code/transfer.ts
deleted file mode 100644
index c589e186..00000000
--- a/apps/server/src/claude-code/transfer.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import type { ClaudeRuntime } from "./runtime.js";
-import { parseNativeCaptureCapabilities, uploadNativeBundle, type NativeArchiveDriver, type NativeUploadRequest } from "./upload.js";
-
-export async function uploadClaudeSession(runtime: ClaudeRuntime, id: string,
- request: (owner: string, ...args: Parameters<NativeUploadRequest>) => Promise<Response>,
- driver: (owner: string) => NativeArchiveDriver) {
- const {owner} = await runtime.get(id);
- const response = await request(owner, "collect/capabilities", {method: "GET"});
- if (!response.ok) throw new Error(`Native archive upload is unavailable (${response.status}); local evidence retained`);
- const value: unknown = await response.json();
- const code = value && typeof value === "object" && "claude_code" in value ? value.claude_code : null;
- const capture = code && typeof code === "object" && "capture" in code ? code.capture : null;
- const capabilities = parseNativeCaptureCapabilities(capture);
- if (!capabilities) throw new Error("The backend has not enabled native archive capture; local evidence retained");
- const prepared = await runtime.prepareUpload(id, capabilities.checkpoint.enabled);
- const {session} = prepared, bindingId = session.authorization?.bindingId, contractHash = session.contractSha256;
- if (session.owner !== owner || !bindingId || !contractHash) throw new Error("The archive must use its original account and session binding");
- return uploadNativeBundle({
- ...prepared, sessionId: id, owner, bindingId, contractHash, turn: session.turns.length,
- engineVersion: session.claudeVersion, boxImage: session.turns.at(-1)?.after?.image ?? session.base.image,
- capabilities, driver: driver(owner),
- });
-}
diff --git a/apps/server/src/claude-code/zip.ts b/apps/server/src/claude-code/zip.ts
deleted file mode 100644
index 7206ed74..00000000
--- a/apps/server/src/claude-code/zip.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// Streaming ZIP (stored entries): image archives are already compressed. Never
-// buffer an environment image in RAM. Refuse ZIP32 overflow rather than produce
-// a corrupt bundle; callers retain the source artifacts for recovery.
-import fs from "node:fs";
-import fsp from "node:fs/promises";
-import path from "node:path";
-import { once } from "node:events";
-
-const table = Uint32Array.from({length: 256}, (_, n) => {
- let crc = n; for (let k = 0; k < 8; k++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1; return crc >>> 0;
-});
-export async function zipDirectory(directory: string, target: string) {
- const temporary = `${target}.tmp`, out = fs.createWriteStream(temporary, {mode: 0o600});
- let offset = 0; const central: Buffer[] = [];
- let failure: Error | undefined;
- out.on("error", error => { failure = error; });
- const write = async (bytes: Buffer) => { if (failure) throw failure; offset += bytes.length; if (offset > 0xffffffff) throw new Error("Bundle exceeds ZIP32 limit; retain split environment archives"); if (!out.write(bytes)) await once(out, "drain"); };
- const walk = async (dir: string): Promise<void> => {
- const entries = await fsp.readdir(dir, {withFileTypes: true});
- entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
- for (const entry of entries) {
- const file = path.join(dir, entry.name);
- if (entry.isDirectory()) { await walk(file); continue; }
- if (!entry.isFile() && !entry.isSymbolicLink()) throw new Error("Unsupported bundle file");
- const name = Buffer.from(path.relative(directory, file).split(path.sep).join("/"));
- const stat = await fsp.lstat(file), symlink = entry.isSymbolicLink();
- const link = symlink ? Buffer.from(await fsp.readlink(file)) : undefined;
- const size = link ? link.length : stat.size, start = offset;
- if (size > 0xffffffff || name.length > 65535 || central.length >= 65535) throw new Error("Bundle exceeds ZIP32 limit");
- const header = Buffer.alloc(30); header.writeUInt32LE(0x04034b50); header.writeUInt16LE(20, 4); header.writeUInt16LE(0x808, 6); header.writeUInt16LE(name.length, 26);
- await write(header); await write(name); let crc = 0xffffffff, actual = 0;
- const consume = async (bytes: Buffer) => { for (const byte of bytes) crc = table[(crc ^ byte) & 255] ^ (crc >>> 8); actual += bytes.length; await write(bytes); };
- if (link) await consume(link); else for await (const chunk of fs.createReadStream(file)) await consume(chunk);
- if (actual !== size) throw new Error("Bundle file changed while exporting");
- crc = (crc ^ 0xffffffff) >>> 0;
- const descriptor = Buffer.alloc(16); descriptor.writeUInt32LE(0x08074b50); descriptor.writeUInt32LE(crc, 4); descriptor.writeUInt32LE(size, 8); descriptor.writeUInt32LE(size, 12); await write(descriptor);
- const index = Buffer.alloc(46); index.writeUInt32LE(0x02014b50); index.writeUInt16LE(0x0314, 4); index.writeUInt16LE(20, 6); index.writeUInt16LE(0x808, 8); index.writeUInt32LE(crc, 16); index.writeUInt32LE(size, 20); index.writeUInt32LE(size, 24); index.writeUInt16LE(name.length, 28); index.writeUInt32LE((stat.mode << 16) >>> 0, 38); index.writeUInt32LE(start, 42);
- central.push(Buffer.concat([index, name]));
- }
- };
- try {
- await walk(directory); const start = offset;
- for (const entry of central) await write(entry);
- const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50); end.writeUInt16LE(central.length, 8); end.writeUInt16LE(central.length, 10); end.writeUInt32LE(offset - start, 12); end.writeUInt32LE(start, 16); await write(end);
- out.end(); await once(out, "close"); if (failure) throw failure;
- const fd = fs.openSync(temporary, "r"); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
- await fsp.rename(temporary, target);
- if (process.platform !== "win32") { const parent = fs.openSync(path.dirname(target), "r"); try { fs.fsyncSync(parent); } finally { fs.closeSync(parent); } }
- } catch (error) { out.destroy(); await fsp.rm(temporary, {force: true}); throw error; }
-}
diff --git a/apps/server/src/engine-v2-next.test.ts b/apps/server/src/engine-v2-next.test.ts
index 013929e7..290ff33c 100644
--- a/apps/server/src/engine-v2-next.test.ts
+++ b/apps/server/src/engine-v2-next.test.ts
@@ -43,13 +43,14 @@ test("a 1.x store seeds the 2.x store once, keeps a backup and stays untouched",
test("the session plugin names the chat on gateway requests and blanks secrets in shells", async () => {
const hooks: Record<string, (event: never) => Promise<void> | void> = {};
+ const modelHooks: { providerID?: string; callback: (event: never) => Promise<void> }[] = [];
process.env.OMNIRUSH_USER_XDG_DATA_HOME = "/home/me/.data";
process.env.OMNIRUSH_USER_XDG_STATE_HOME = "";
try {
await sessionPlugin.setup({
session: {
- get: async ({ sessionID }) => ({ id: sessionID, parentID: sessionID === "ses_child" ? "ses_parent" : undefined, model: { id: "gpt-6-astra" } }),
- hook: async (name, callback) => { hooks[name] = callback as never; },
+ get: async ({ sessionID }) => ({ id: sessionID, parentID: sessionID === "ses_child" ? "ses_parent" : undefined, model: sessionID === "ses_claude" ? { id: "claude-opus-5-5", providerID: "omnirush-claude" } : { id: "gpt-6-astra" }, location: { directory: "/p" } }),
+ hook: async (name, callback, options) => { modelHooks.push({ providerID: options?.providerID, callback: callback as never }); },
},
shell: { hook: async (name, callback) => { hooks[name] = callback as never; } },
});
@@ -57,14 +58,19 @@ test("the session plugin names the chat on gateway requests and blanks secrets i
delete process.env.OMNIRUSH_USER_XDG_DATA_HOME;
delete process.env.OMNIRUSH_USER_XDG_STATE_HOME;
}
- const request = (sessionID: string, kind: string, providerID = "omnirush") => {
- const event = { sessionID, kind, model: { id: "cheap", providerID }, headers: {} as Record<string, string> };
- return (hooks["model.request"] as (e: typeof event) => Promise<void>)(event).then(() => event.headers);
+ const request = async (sessionID: string, kind: string, providerID = "omnirush", agent?: string) => {
+ const event = { sessionID, kind, agent, model: { id: "cheap", providerID }, headers: {} as Record<string, string> };
+ for (const hook of modelHooks) if (!hook.providerID || hook.providerID === providerID) await (hook.callback as (e: typeof event) => Promise<void>)(event);
+ return event.headers;
};
expect(await request("ses_main", "primary")).toEqual({ "x-omnirush-session-id": "ses_main" });
expect(await request("ses_child", "primary")).toEqual({ "x-omnirush-session-id": "ses_child", "x-parent-session-id": "ses_parent" });
expect(await request("ses_main", "title")).toEqual({ "x-omnirush-session-id": "ses_main", "x-omnirush-title": "1", "x-omnirush-chat-model": "gpt-6-astra" });
expect(await request("ses_main", "primary", "openai")).toEqual({});
+ // A Claude chat: its turns name its folder and agent; its title (on the gateway's title model) names no chat.
+ expect(await request("ses_claude", "primary", "omnirush-claude", "build")).toEqual({ "x-omnirush-agent": "build", "x-omnirush-directory": "/p" });
+ expect(await request("ses_claude", "compaction", "omnirush-claude", "build")).toMatchObject({ "x-omnirush-agent": "compaction" });
+ expect(await request("ses_claude", "title")).toEqual({});
const env: Record<string, string | undefined> = { OPENCODE_PASSWORD: "pw", OMNIRUSH_POLICY_TOKEN: "t", XDG_DATA_HOME: "/engine/data", XDG_STATE_HOME: "/engine/state", PATH: "/bin" };
await (hooks["create.before"] as (e: { env: typeof env }) => void)({ env });
expect(env).toMatchObject({ OPENCODE_PASSWORD: "", OMNIRUSH_POLICY_TOKEN: "", XDG_DATA_HOME: "/home/me/.data", XDG_STATE_HOME: undefined, PATH: "/bin" });
diff --git a/apps/server/src/engine-v2-preview.ts b/apps/server/src/engine-v2-preview.ts
index 68f842ca..532f9c53 100644
--- a/apps/server/src/engine-v2-preview.ts
+++ b/apps/server/src/engine-v2-preview.ts
@@ -21,7 +21,7 @@ import type { EnvService } from "./env-file.js";
import { selectPrimaryCredentialEnvName } from "./managed-provider-auth.js";
import { isReleaseBuild } from "./release-guard.js";
import { webSearchSetting } from "./web-search.js";
-import { buildOmniRushRuntimeConfigObject } from "./omnirush-runtime-config.js";
+import { buildOmniRushRuntimeConfigObject, omnirushTitleModel } from "./omnirush-runtime-config.js";
import { OMNIRUSH_PROVIDER_ID } from "./provider-lock/provider-lock.mjs";
import { CLOUD_MCP_NAME, cloudMcpEntry, desiredV2Mcp, v2McpGate } from "./engine-v2-mcp.js";
import { runtimeMcpMap } from "./runtime-opencode-config-store.js";
@@ -319,7 +319,11 @@ export async function awaitEngineConnection<T>(
}
}
-export function createEngineV2Preview(options: { config: ServerConfig; env?: Pick<EnvService, "list" | "onChange">; deferStart?: boolean }): EngineV2Preview {
+export function createEngineV2Preview(options: {
+ config: ServerConfig; env?: Pick<EnvService, "list" | "onChange">; deferStart?: boolean;
+ /** The Claude provider's spec (omnirush-runtime-config.ts claudeEngineProvider), null while the account has no Claude catalog. */
+ claude?: () => Promise<OpencodeV2ProviderSpec | null>;
+}): EngineV2Preview {
const { config } = options;
const rootDir = engineV2Root(runtimeStorageDir(config));
const workspaceDir = join(rootDir, "workspace");
@@ -455,6 +459,9 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
credentials.set(ENGINE_TOKEN_ENV, `{env:${ENGINE_TOKEN_ENV}}`);
}
const mapped = mapRuntimeProvidersToV2Specs(providerMap, credentials);
+ // Claude Code under the engine: its own spec (an `aisdk:file://` package the mapping above never takes).
+ const claude = await options.claude?.().catch(() => null);
+ if (claude) mapped.specs.push(claude);
const nextMirroredProviderIds = mapped.specs.map((spec) => spec.id);
await active.setProviders(mapped.specs);
mirroredSpecs = mapped.specs;
@@ -545,6 +552,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
webSearch: () => webSearchSetting({ env: process.env, stateDir: runtimeStorageDir(config) }).enabled,
// The Linux sandbox (box/): the shell and box plugin follow BoxService.engineBits on every config write.
box: async () => v2BoxBits(await boxServiceFor(config).engineBits()),
+ titleModel: () => omnirushTitleModel(config),
mcpGate: v2McpGate(runtimeStorageDir(config), { ...process.env, ...computerUseEngineEnv(runtimeStorageDir(config)) }, Boolean(await cloudConnector())),
});
sidecar = managed;
diff --git a/apps/server/src/managed-opencode-v2.env.test.ts b/apps/server/src/managed-opencode-v2.env.test.ts
index 0b68831c..1480da3b 100644
--- a/apps/server/src/managed-opencode-v2.env.test.ts
+++ b/apps/server/src/managed-opencode-v2.env.test.ts
@@ -29,7 +29,7 @@ posix("the v2 engine gets its own empty config home, not the user's global openc
expect(env).toMatch(/^OMNIRUSH_USER_XDG_CONFIG_HOME=.*user-config$/m);
// Project config stays on (engine patch 0003 keeps only its descriptive keys); the gates are on.
expect(env).not.toMatch(/^OPENCODE_DISABLE_PROJECT_CONFIG=/m);
- expect(env).toMatch(/^OMNIRUSH_GATE_PROVIDERS=omnirush$/m);
+ expect(env).toMatch(/^OMNIRUSH_GATE_PROVIDERS=omnirush,omnirush-claude$/m);
expect(env).toMatch(/^OMNIRUSH_GATE_MCP=$/m);
expect(env).toMatch(/^OMNIRUSH_NO_SYSTEM_CONFIG=1$/m);
expect(env).toMatch(/^OPENCODE_DISABLE_AUTOUPDATE=1$/m);
@@ -41,7 +41,7 @@ posix("the v2 engine gets its own empty config home, not the user's global openc
test("the engine's gates are applied last and a spawn without them is refused", () => {
const env = engineV2SpawnEnv({ OMNIRUSH_GATE_PROVIDERS: "*", OMNIRUSH_GATE_MCP: "anything", OMNIRUSH_NO_SYSTEM_CONFIG: "0", PATH: "/bin" });
- expect(env).toMatchObject({ OMNIRUSH_GATE_PROVIDERS: "omnirush", OMNIRUSH_GATE_MCP: "", OMNIRUSH_NO_SYSTEM_CONFIG: "1", PATH: "/bin" });
+ expect(env).toMatchObject({ OMNIRUSH_GATE_PROVIDERS: "omnirush,omnirush-claude", OMNIRUSH_GATE_MCP: "", OMNIRUSH_NO_SYSTEM_CONFIG: "1", PATH: "/bin" });
expect(() => assertEngineGates({ PATH: "/bin" })).toThrow(/gates are missing/);
expect(() => assertEngineGates({ OMNIRUSH_GATE_PROVIDERS: "omnirush", OMNIRUSH_NO_SYSTEM_CONFIG: "1" })).toThrow(/gates are missing/);
});
@@ -58,10 +58,11 @@ posix("the stock websearch tool searches through Exa only while the server's swi
const config = JSON.parse(await readFile(join(rootDir, "config", "opencode.json"), "utf8"));
expect(config.websearch).toEqual(on ? { provider: "exa" } : undefined);
expect(config).toMatchObject({ share: "disabled", update: "disable" });
- // Only the gateway provider may run a model (the CLI's policies), beside the gate env.
+ // Only the app's providers may run a model (the CLI's policies), beside the gate env.
expect(config.policies).toEqual([
{ action: "provider.use", resource: "*", effect: "deny" },
{ action: "provider.use", resource: "omnirush", effect: "allow" },
+ { action: "provider.use", resource: "omnirush-claude", effect: "allow" },
]);
}
} finally {
@@ -95,3 +96,12 @@ posix("the 2.x engine runs the box shell and the 2.x box plugin while a workspac
await rm(dir, { recursive: true, force: true });
}
});
+
+test("the Claude provider is an AI SDK file package of the catalog's Claude models, with no request timeout", async () => {
+ const { claudeEngineProvider } = await import("./omnirush-runtime-config.js");
+ expect(claudeEngineProvider([], {})).toBeNull();
+ const spec = claudeEngineProvider([{ id: "claude-opus-5-5", name: "Claude Opus 5.5" }], { grantURL: "http://127.0.0.1:1/omnirush-claude/turn", grantKey: "k" });
+ expect(spec).toMatchObject({ id: "omnirush-claude", settings: { grantURL: "http://127.0.0.1:1/omnirush-claude/turn", grantKey: "k", timeout: false } });
+ expect(spec?.package).toMatch(/^aisdk:file:\/\/.*claude-provider\/index\.js$/);
+ expect(spec?.models.map((model) => [model.id, model.name])).toEqual([["claude-opus-5-5", "Claude Opus 5.5"]]);
+});
diff --git a/apps/server/src/managed-opencode-v2.ts b/apps/server/src/managed-opencode-v2.ts
index 367057e3..bff2a75f 100644
--- a/apps/server/src/managed-opencode-v2.ts
+++ b/apps/server/src/managed-opencode-v2.ts
@@ -12,7 +12,7 @@ import { pathToFileURL } from "node:url";
import { loopbackFetch } from "./server-fetch.js";
import { writeFileAtomic } from "./atomic-write.js";
import { currentProviderLockPolicy, noteEngineStarted, providerAllowed } from "./provider-lock.js";
-import { providerLockEnv } from "./provider-lock/provider-lock.mjs";
+import { APP_PROVIDER_IDS, providerLockEnv } from "./provider-lock/provider-lock.mjs";
import { gateEnv } from "./engine-gates/engine-gates.mjs";
import { releaseEngineBinary } from "./release-guard.js";
@@ -47,6 +47,8 @@ export interface ManagedOpencodeV2ServerOptions {
mcpGate?: string[];
/** The Linux sandbox's engine bits (engine-v2-preview.ts v2BoxBits): the box shell and the 2.x box plugin; null: none. */
box?: () => Promise<{ shell: string; plugin: string } | null>;
+ /** "omnirush/<default model>": the title agent's model while the Claude provider is listed. */
+ titleModel?: () => Promise<string | null>;
}
export interface OpencodeV2Health {
@@ -120,9 +122,11 @@ export async function pluginDirectories(root: string, modules: string[]): Promis
*/
/** The app's gateway provider: the only one the engine may use (its gate, and the config's policies). */
const GATEWAY_PROVIDER_ID = "omnirush";
+const CLAUDE_PROVIDER_ID = "omnirush-claude";
export function engineV2SpawnEnv(env: Record<string, string>, mcp: readonly string[] = []): Record<string, string> {
- return assertEngineGates({ ...env, ...gateEnv({ provider: GATEWAY_PROVIDER_ID, mcp }) });
+ // Both app providers pass the gate (a comma list): the gateway's and Claude Code in the box (opencode-plugins/claude-provider).
+ return assertEngineGates({ ...env, ...gateEnv({ provider: GATEWAY_PROVIDER_ID, mcp }), OMNIRUSH_GATE_PROVIDERS: APP_PROVIDER_IDS.join(",") });
}
export function assertEngineGates(env: Record<string, string | undefined>): Record<string, string> {
@@ -301,6 +305,7 @@ export async function createManagedOpencodeV2Server(
models,
};
}
+ const titleModel = providerConfig[CLAUDE_PROVIDER_ID] ? await options.titleModel?.().catch(() => null) : null;
const target = join(configDir, "opencode.json");
// The box shell runs each command in its project's box (boxsh; natively for a project without one).
const box = await options.box?.().catch(() => null) ?? null;
@@ -310,12 +315,14 @@ export async function createManagedOpencodeV2Server(
share: "disabled",
update: "disable",
providers: providerConfig,
- // As the CLI's v2 config (engine-v2.js toV2Config): only the app's gateway provider may run a model,
+ // As the CLI's v2 config (engine-v2.js toV2Config): only the app's providers may run a model,
// beside the engine's gate (OMNIRUSH_GATE_PROVIDERS, engineV2SpawnEnv), which no config can widen.
policies: [
{ action: "provider.use", resource: "*", effect: "deny" },
- { action: "provider.use", resource: GATEWAY_PROVIDER_ID, effect: "allow" },
+ ...APP_PROVIDER_IDS.map((id) => ({ action: "provider.use", resource: id, effect: "allow" })),
],
+ // Titles on the gateway's default model while Claude is listed: a Claude turn is a Claude Code run, never a title.
+ ...(titleModel ? { agents: { title: { model: titleModel } } } : {}),
...(options.permissions ? { permissions: await options.permissions() } : {}),
// On: the stock websearch tool searches through Exa (the engine's keyless default), like the CLI.
// Off: no provider is picked (never `false`, which would take the tool out of the stock list).
diff --git a/apps/server/src/managed-opencode.test.ts b/apps/server/src/managed-opencode.test.ts
index 5cff12ca..f873714a 100644
--- a/apps/server/src/managed-opencode.test.ts
+++ b/apps/server/src/managed-opencode.test.ts
@@ -63,7 +63,7 @@ describe("managed OpenCode startup", () => {
]);
const managed = await createManagedOpencodeV2Server({ bin, rootDir: root, env: {} });
try {
- expect(await managed.fetchJson("/env")).toEqual({ status: 200, json: { a: null, b: null, gate: "omnirush" } });
+ expect(await managed.fetchJson("/env")).toEqual({ status: 200, json: { a: null, b: null, gate: "omnirush,omnirush-claude" } });
} finally { await managed.close(); }
});
diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.ts
index 1f94f3ad..ade9a8fd 100644
--- a/apps/server/src/omnirush-extensions-plugin-path.ts
+++ b/apps/server/src/omnirush-extensions-plugin-path.ts
@@ -48,3 +48,5 @@ export const omnirushMcpPolicyPluginPath = () => omnirushPluginPath("omnirush-mc
export const omnirushBudgetWrapPluginPath = () => omnirushPluginPath("omnirush-budget-wrap");
export const omnirushBuildathonPluginPath = () => omnirushPluginPath("omnirush-buildathon");
export const omnirushAgentAssistPluginPath = () => omnirushPluginPath("omnirush-agent-assist");
+/** The Claude Code engine provider (opencode-plugins/claude-provider, shared with the CLI): plain JavaScript in source and build. */
+export const omnirushClaudeProviderPath = () => omnirushPluginPath("claude-provider/index").replace(/\.ts$/, ".js");
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index 82c62453..c00a25d2 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -17,8 +17,7 @@ import { RejectedAttachments, isRejectedAttachmentError, type Attachment } from
import { gatewayUrlAllowed, RELEASE_GATEWAY_ERROR } from "./release-guard.js";
import { BOX_HEADER, MODEL_NOT_IN_MODE, notInModeMessage, projectMode } from "./model-modes/model-modes.mjs";
import { MODE_NOT_BOUND, MODEL_NOT_BOUND, REFUSED_HEADER, SESSION_BIND_UNCONFIRMED, STRICT_SESSION_HEADER, SESSION_BINDING_CONFLICT, SESSION_MODEL_USED, VERIFICATION_REQUIRED, sessionBinder, strictSessions, type StrictSessions } from "./model-modes/strict-sessions.mjs";
-import { ClaudeDeviceAccess, type ClaudeDeviceRequest } from "./claude-code/access.js";
-import type { ClaudeAuthorization } from "./claude-code/runtime.js";
+import { ClaudeDeviceAccess, type ClaudeAuthorization, type ClaudeDeviceRequest } from "./claude-code/access.js";
/** A main chat's request on another model than the one it started on (one model per chat). */
const SESSION_MODEL_FIXED = "session_model_fixed";
@@ -2028,6 +2027,20 @@ export class OmniRushGatewayBroker {
}
revokeClaudeGrant(context: ClaudeAuthorization) { return this.claudeAccessClient().revoke(context); }
+ /** A chat's fixed model (one model per chat), null before its first request. */
+ chatModel(session: string): string | null { return this.sessionModels.get(session) ?? null; }
+
+ /** Pins a chat to its first model, kept on disk so a reopened chat keeps it (a Claude chat pins here too). */
+ pinChatModel(session: string, model: string): void {
+ if (this.sessionModelsFile) {
+ mkdirSync(dirname(this.sessionModelsFile), {recursive: true, mode: 0o700});
+ const tmp = `${this.sessionModelsFile}.${randomUUID()}.tmp`;
+ writeFileSync(tmp, JSON.stringify({...Object.fromEntries(this.sessionModels), [session]: model}), {mode: 0o600});
+ renameSync(tmp, this.sessionModelsFile);
+ }
+ this.sessionModels.set(session, model);
+ }
+
nativeCaptureRequest(owner: string, route: string, init: {method: "GET" | "POST"; body?: string; signal?: AbortSignal; refresh?: false}): Promise<Response> {
if (route !== "collect/capabilities" && !ARCHIVE_API_PATH.test(route)) return Promise.resolve(new Response(null, {status: 404}));
return this.withDeviceBearer(async state => {
@@ -2346,14 +2359,7 @@ export class OmniRushGatewayBroker {
let first: string | undefined;
for (const pin of pins) if (!(await this.switchable(pin, model))) { first = pin; break; }
if (!first && !parents.some(id => !this.sessionModels.has(id))) {
- if (this.sessionModels.has(session)) return null;
- if (this.sessionModelsFile) {
- mkdirSync(dirname(this.sessionModelsFile), {recursive: true, mode: 0o700});
- const tmp = `${this.sessionModelsFile}.${randomUUID()}.tmp`;
- writeFileSync(tmp, JSON.stringify({...Object.fromEntries(this.sessionModels), [session]: model}), {mode: 0o600});
- renameSync(tmp, this.sessionModelsFile);
- }
- this.sessionModels.set(session, model);
+ if (!this.sessionModels.has(session)) this.pinChatModel(session, model);
return null;
}
this.log?.("info", "omnirush.ai chat model change refused (another provider)", { first, model });
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index 6d8a0c8b..bb9ca282 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -17,6 +17,7 @@ import { managedPolicyPluginPath } from "./managed-policy-plugin.js";
*/
import { mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
+import { pathToFileURL } from "node:url";
import { mergeSkillPaths, userGlobalSkillPaths } from "./user-skill-paths.js";
import {
omnirushExtensionsPreviewPluginPath,
@@ -35,6 +36,7 @@ import {
omnirushPdfAttachmentsPluginPath,
omnirushPluginPath,
omnirushAgentAssistPluginPath,
+ omnirushClaudeProviderPath,
} from "./omnirush-extensions-plugin-path.js";
import { agentAssistFlags, agentAssistLspConfig, writeAgentAssistFile } from "./agent-assist-config.js";
import type { ServerConfig } from "./types.js";
@@ -135,6 +137,30 @@ function internalGatewayProvider(runtime: InternalGatewayRuntime, catalog: OmniR
};
}
+/**
+ * The Claude provider of the 2.x engine (opencode-plugins/claude-provider, the CLI's assets/claude-provider):
+ * Claude's catalog models, each turn real Claude Code in the project's box, its events the engine's parts.
+ * `entries`: the account's Claude catalog (every entry: picking one the account may not run explains);
+ * `settings`: the provider's options (grantURL, grantKey, shell, boxHome, client, note). Null without entries.
+ */
+export function claudeEngineProvider(entries: { id: string; name: string }[], settings: Record<string, unknown>) {
+ if (!entries.length) return null;
+ return {
+ id: "omnirush-claude",
+ name: "Claude",
+ package: `aisdk:${pathToFileURL(omnirushClaudeProviderPath()).href}`,
+ // Long Claude Code turns: no request timeout (the provider streams until Claude Code ends).
+ settings: { ...settings, timeout: false },
+ apiKey: "unused",
+ models: entries.map((entry) => ({ id: entry.id, name: entry.name, config: { family: "Claude", tool_call: true, limit: { context: 200_000, output: 64_000 }, modalities: { input: ["text", "image"], output: ["text"] } } })),
+ };
+}
+
+/** The title agent's model while Claude is listed: the gateway's default ("omnirush/<id>"). */
+export async function omnirushTitleModel(config: ServerConfig): Promise<string> {
+ return `${INTERNAL_PROVIDER_ID}/${omnirushDefaultModelId(await readOmniRushModelCatalog(config))}`;
+}
+
export async function buildOmniRushRuntimeConfigObject(
config?: ServerConfig,
): Promise<Record<string, unknown>> {
diff --git a/apps/server/src/opencode-plugins/claude-provider/PARITY.sha256 b/apps/server/src/opencode-plugins/claude-provider/PARITY.sha256
new file mode 100644
index 00000000..8024667a
--- /dev/null
+++ b/apps/server/src/opencode-plugins/claude-provider/PARITY.sha256
@@ -0,0 +1,3 @@
+# The Claude provider: the same files in omnirush-cli (assets/claude-provider/) and omnirush-gui. A change to one must be ported to the other and this list updated in both.
+f026e2eba0d33a0e7db1c75bbc31c29f3e9ffcfb39f579ebe3e89a34efc8303d index.js
+9ded3990ef5261543634da710ecbec3956de25b2cf4ae86d5b80f44ef6b9372c map.js
diff --git a/apps/server/src/opencode-plugins/claude-provider/claude-provider-parity.test.ts b/apps/server/src/opencode-plugins/claude-provider/claude-provider-parity.test.ts
new file mode 100644
index 00000000..d5a36854
--- /dev/null
+++ b/apps/server/src/opencode-plugins/claude-provider/claude-provider-parity.test.ts
@@ -0,0 +1,19 @@
+// The Claude Code engine provider is the same pair of files in omnirush-cli
+// (assets/claude-provider/) and here; PARITY.sha256 lists their hashes in both
+// repositories, so a change in one shows up here until it is ported.
+import { describe, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+
+describe("CLI/desktop parity: Claude Code provider", () => {
+ test("claude-provider/PARITY.sha256 matches its files", () => {
+ const rows = readFileSync(path.join(import.meta.dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));
+ expect(rows.map((row) => row.split(/\s+/)[1])).toEqual(["index.js", "map.js"]);
+ for (const row of rows) {
+ const [hash, name] = row.split(/\s+/);
+ const actual = createHash("sha256").update(readFileSync(path.join(import.meta.dir, name ?? ""))).digest("hex");
+ expect(`${name} ${actual}`).toBe(`${name} ${hash}`);
+ }
+ });
+});
diff --git a/apps/server/src/opencode-plugins/claude-provider/index.js b/apps/server/src/opencode-plugins/claude-provider/index.js
new file mode 100644
index 00000000..c13d1164
--- /dev/null
+++ b/apps/server/src/opencode-plugins/claude-provider/index.js
@@ -0,0 +1,285 @@
+// The "omnirush-claude" engine provider: each turn of a Claude chat runs real
+// Claude Code (headless, stream-json) in the project's OmniRush box, and its
+// events become the engine's parts (map.js). AI SDK LanguageModelV3, loaded by
+// the 2.x engine as `aisdk:file://…/index.js` (the first `create*` export).
+// Shared by omnirush-cli and omnirush-gui (PARITY.sha256).
+//
+// Settings (the provider's config options, nothing else is read from the app):
+// grantURL the app's local route, POST JSON with header x-omnirush-usage-key: grantKey
+// {op:"grant", sessionID, model, resume, earlier, prompt, refresh?}
+// -> {ok:true, token, baseUrl, client} | {ok:false, message}
+// (resume: Claude has a transcript of this chat; earlier: the engine
+// history has replies; asked again every 60 s while a turn runs, refresh: true)
+// {op:"end", sessionID, uuid, ok} after a turn (the app uploads the transcript)
+// grantKey that header's value
+// shell boxsh (the engine's box shell); boxHome the box home (boxes/<key>.json,
+// projects/<key> = the box's /run/omnirush)
+// directory the project folder (default: the engine's cwd)
+// client "cli/2.7.3" | "gui/3.8.0": X-OmniRush-Client to the relay
+// note optional text shown once at a chat's start
+// The relay token lives in the box's run folder, read by Claude Code's
+// apiKeyHelper; nothing else of this machine's env enters the box.
+// Claude's session id is uuidv5(engine session id); its config folder is the
+// box's /run/omnirush/claude/config (host: <boxHome>/projects/<key>/claude/config).
+//
+// Stop arrives as the stream's cancel() (the engine passes no abortSignal):
+// an interrupt on Claude's stdin, then SIGINT, then SIGKILL.
+
+import { spawn } from "node:child_process";
+import { createHash, randomUUID } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { apiError, ClaudeStreamMapper, lastUserContent } from "./map.js";
+
+export const CLAUDE_CODE_VERSION = "2.1.306";
+// The pinned linux build (npm @anthropic-ai/claude-code-linux-<arch>): installed into the box on first use.
+// shortcut: until the box image carries it (box-base 2026.11.x), each box downloads it once (131 MB).
+export const CLAUDE_CODE_BUILDS = {
+ x64: { url: `https://registry.npmjs.org/@anthropic-ai/claude-code-linux-x64/-/claude-code-linux-x64-${CLAUDE_CODE_VERSION}.tgz`, integrity: "sha512-4gsb0IQhxzi1NhoUETXkNZb1t6wJ9tnfAYBKmb0+NmsAwOG37Dacq7bLqsooEkusaT0PyQRFUMt0SgWxx9LEEA==" },
+ arm64: { url: `https://registry.npmjs.org/@anthropic-ai/claude-code-linux-arm64/-/claude-code-linux-arm64-${CLAUDE_CODE_VERSION}.tgz`, integrity: "sha512-AePKWuymgDSCh7nScJ4dx/pF1Kppzk4IwQuh6JCROiqQdBVGaaHw6jVf/fY5PhbSjy9EQML6yOiUfc50aFpnTA==" },
+};
+export const PROVIDER_ID = "omnirush-claude";
+const BOX_RUN = "/run/omnirush";
+const BOX_BIN = `/opt/omnirush/claude/${CLAUDE_CODE_VERSION}/claude`;
+const STOP_GRACE_MS = 5_000;
+const REFRESH_MS = 60_000;
+// Claude's session id for an engine chat: uuid v5 of its id in this namespace.
+const NAMESPACE = "6f1c2b8e-4d3a-5f60-9a7b-0c1d2e3f4a5b";
+
+/** uuid v5 (sha1) of `name` in `namespace`. */
+export function uuidv5(name, namespace = NAMESPACE) {
+ const hash = createHash("sha1").update(Buffer.from(namespace.replace(/-/g, ""), "hex")).update(String(name)).digest();
+ hash[6] = (hash[6] & 0x0f) | 0x50;
+ hash[8] = (hash[8] & 0x3f) | 0x80;
+ const hex = hash.subarray(0, 16).toString("hex");
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
+/** The box key of a folder (the same as src/box/plugin-lib.js keyOf). */
+export function boxKey(dir) {
+ let resolved = path.resolve(dir);
+ try { resolved = fs.realpathSync.native(resolved); } catch { /* keep */ }
+ if (process.platform === "win32") resolved = resolved.toLowerCase();
+ return createHash("sha256").update(resolved).digest("hex").slice(0, 12);
+}
+
+/** The contract the relay token is bound to: this Claude Code, this provider, the box. */
+export const CONTRACT = createHash("sha256").update(JSON.stringify({ claude_code: CLAUDE_CODE_VERSION, provider: 1, runtime: "box" })).digest("hex");
+
+/** Whether Claude already has a transcript for `uuid` in the config folder (then the turn resumes it). */
+export function hasTranscript(configDir, uuid) {
+ try {
+ return fs.readdirSync(path.join(configDir, "projects")).some((dir) => fs.existsSync(path.join(configDir, "projects", dir, `${uuid}.jsonl`)));
+ } catch { return false; }
+}
+
+/** Claude Code's argv for a turn. */
+export function claudeArgs({ model, uuid, resume }) {
+ return ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages",
+ "--model", model, "--permission-mode", "bypassPermissions", resume ? "--resume" : "--session-id", uuid];
+}
+
+/** The env Claude Code runs with in the box (passed by boxsh through OMNIRUSH_BOX_PASS_ENV). */
+export function claudeEnv({ model, baseUrl, sessionID, client }) {
+ const env = {
+ CLAUDE_CONFIG_DIR: `${BOX_RUN}/claude/config`,
+ ANTHROPIC_BASE_URL: baseUrl,
+ ANTHROPIC_CUSTOM_HEADERS: `X-OmniRush-Box: 1\nX-OmniRush-Session-Id: ${sessionID}\nX-OmniRush-Client: ${client}`,
+ CLAUDE_CODE_API_KEY_HELPER_TTL_MS: String(REFRESH_MS),
+ // The relay serves the chat's model only: every model Claude Code would pick on its own is that one.
+ ANTHROPIC_MODEL: model, ANTHROPIC_SMALL_FAST_MODEL: model, ANTHROPIC_DEFAULT_OPUS_MODEL: model,
+ ANTHROPIC_DEFAULT_SONNET_MODEL: model, ANTHROPIC_DEFAULT_HAIKU_MODEL: model, CLAUDE_CODE_SUBAGENT_MODEL: model,
+ DISABLE_AUTOUPDATER: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1",
+ // The box is the boundary that makes running without asks acceptable (it runs as root in a container).
+ IS_SANDBOX: "1",
+ };
+ return env;
+}
+
+const lower = (headers) => Object.fromEntries(Object.entries(headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
+const lineText = (content) => content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
+
+function readRecord(home, key) {
+ try { return JSON.parse(fs.readFileSync(path.join(home, "boxes", `${key}.json`), "utf8")); } catch { return null; }
+}
+
+/** One command in the box through boxsh; resolves its exit code. */
+function inBox(shell, env, cwd, command, args = []) {
+ return new Promise((resolve) => {
+ const child = spawn(shell, ["-c", command, ...args], { cwd, env, stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
+ let err = "";
+ child.stderr.on("data", (d) => { err = (err + d).slice(-2000); });
+ child.on("error", (e) => resolve({ code: 127, err: e.message }));
+ child.on("close", (code) => resolve({ code: code ?? 1, err }));
+ });
+}
+
+async function download(build, file) {
+ const response = await fetch(build.url, { redirect: "follow" });
+ if (!response.ok || !response.body) throw new Error(`download failed (${response.status})`);
+ const tmp = `${file}.${process.pid}.tmp`;
+ const hash = createHash("sha512");
+ const out = fs.createWriteStream(tmp, { mode: 0o600 });
+ try {
+ for await (const chunk of response.body) { hash.update(chunk); if (!out.write(chunk)) await new Promise((r) => out.once("drain", r)); }
+ await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve())));
+ if (`sha512-${hash.digest("base64")}` !== build.integrity) throw new Error("the download did not match its pinned checksum");
+ fs.renameSync(tmp, file);
+ } catch (error) { fs.rmSync(tmp, { force: true }); throw error; }
+}
+
+const installs = new Map();
+/** Claude Code at BOX_BIN in this box: probed, else the pinned build downloaded once per machine and unpacked in the box. */
+function ensureClaude({ shell, env, cwd, home, run }) {
+ const key = env.OMNIRUSH_BOX_KEY;
+ if (!installs.has(key)) {
+ installs.set(key, (async () => {
+ if ((await inBox(shell, env, cwd, `test -x ${BOX_BIN}`)).code === 0) return;
+ const build = CLAUDE_CODE_BUILDS[os.arch()] ?? CLAUDE_CODE_BUILDS.x64;
+ const cache = path.join(home, "claude");
+ fs.mkdirSync(cache, { recursive: true });
+ const tgz = path.join(cache, path.basename(new URL(build.url).pathname));
+ if (!fs.existsSync(tgz)) await download(build, tgz);
+ const staged = path.join(run, "install.tgz");
+ fs.rmSync(staged, { force: true });
+ try { fs.linkSync(tgz, staged); } catch { fs.copyFileSync(tgz, staged); }
+ try {
+ const dir = path.posix.dirname(BOX_BIN);
+ // The box user is root or has passwordless sudo (src/box BOX_NOTE).
+ const done = await inBox(shell, env, cwd, `S=; [ "$(id -u)" = 0 ] || S="sudo -n"; $S mkdir -p ${dir} && $S tar -xzf ${BOX_RUN}/claude/install.tgz -C ${dir} --strip-components=1 --no-same-owner package/claude && $S chmod 755 ${BOX_BIN} && ${BOX_BIN} --version >/dev/null`);
+ if (done.code !== 0) throw new Error(`Claude Code could not be installed in the sandbox (${done.err.trim().split("\n").at(-1) || done.code})`);
+ } finally { fs.rmSync(staged, { force: true }); }
+ })().catch((error) => { installs.delete(key); throw error; }));
+ }
+ return installs.get(key);
+}
+
+class ClaudeCodeModel {
+ specificationVersion = "v3";
+ provider = PROVIDER_ID;
+ supportedUrls = {};
+
+ constructor(modelId, settings) {
+ this.modelId = modelId;
+ this.settings = settings;
+ }
+
+ async doGenerate() {
+ throw apiError("Claude chats stream their turns.");
+ }
+
+ /** The app's answer for this chat's turn: { token, baseUrl, client } or a refusal (thrown, never retried). */
+ async grant(body) {
+ const { grantURL, grantKey } = this.settings;
+ if (!grantURL) throw apiError("Claude can't run from here.");
+ let answer = null;
+ try {
+ const response = await fetch(grantURL, { method: "POST", headers: { "content-type": "application/json", "x-omnirush-usage-key": grantKey || "" }, body: JSON.stringify(body), signal: AbortSignal.timeout(60_000) });
+ answer = await response.json();
+ } catch { answer = null; }
+ if (!answer?.ok) throw apiError(answer?.message || "Claude could not start: the app did not answer.");
+ return answer;
+ }
+
+ async doStream(options) {
+ const headers = lower(options.headers);
+ const sessionID = String(headers["x-session-id"] || headers["x-opencode-session-id"] || "");
+ if (!sessionID) throw apiError("A Claude turn needs its chat.");
+ if (headers["x-omnirush-side"] === "1") throw apiError("Side questions aren't available in Claude chats yet.");
+ const compaction = headers["x-omnirush-agent"] === "compaction";
+ const { shell, boxHome, directory, client = "cli", note } = this.settings;
+ const root = path.resolve(directory || process.cwd());
+ const key = boxKey(root);
+ const record = boxHome ? readRecord(boxHome, key) : null;
+ if (!shell || !record || record.state === "off") throw apiError("Claude runs only in the OmniRush sandbox. Turn it on for this folder (omnirush sandbox on) and start the chat again.");
+ const run = path.join(boxHome, "projects", key, "claude");
+ const configDir = path.join(run, "config");
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
+ const uuid = uuidv5(sessionID);
+ const resume = hasTranscript(configDir, uuid);
+ const content = compaction ? [{ type: "text", text: "/compact" }] : lastUserContent(options.prompt);
+ if (!content.length) throw apiError("Nothing to send to Claude.");
+ const earlier = (options.prompt ?? []).some((m) => m?.role === "assistant");
+ const ask = { op: "grant", sessionID, model: this.modelId, resume, earlier, prompt: lineText(content).slice(0, 4000) };
+ let grant = await this.grant(ask);
+ const tokenFile = path.join(run, "token");
+ const writeToken = (token) => { fs.writeFileSync(`${tokenFile}.tmp`, token, { mode: 0o600 }); fs.renameSync(`${tokenFile}.tmp`, tokenFile); };
+ writeToken(grant.token);
+ fs.writeFileSync(path.join(configDir, "settings.json"), `${JSON.stringify({ apiKeyHelper: `cat ${BOX_RUN}/claude/token` })}\n`, { mode: 0o600 });
+
+ const passed = claudeEnv({ model: this.modelId, baseUrl: grant.baseUrl, sessionID, client: grant.client || client });
+ const env = { ...process.env, ...passed, OMNIRUSH_BOX_KEY: key, OMNIRUSH_BOX_HOME: boxHome, OMNIRUSH_BOX_PASS_ENV: Object.keys(passed).join(",") };
+ try { await ensureClaude({ shell, env, cwd: root, home: boxHome, run }); } catch (error) { throw apiError(error?.message || "Claude Code could not be installed in the sandbox."); }
+
+ const child = spawn(shell, ["-c", 'exec "$0" "$@"', BOX_BIN, ...claudeArgs({ model: this.modelId, uuid, resume })], { cwd: root, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
+ const mapper = new ClaudeStreamMapper();
+ let stderr = "";
+ let done = false;
+ let stopped = false;
+ const refresh = setInterval(() => { void this.grant({ ...ask, refresh: true }).then((next) => { grant = next; writeToken(next.token); }).catch(() => undefined); }, REFRESH_MS);
+ refresh.unref?.();
+ const timers = [];
+ const end = () => { done = true; clearInterval(refresh); for (const t of timers) clearTimeout(t); };
+ child.stdin.on("error", () => undefined);
+ child.stdin.write(`${JSON.stringify({ type: "user", message: { role: "user", content }, parent_tool_use_id: null, session_id: uuid })}\n`);
+ const settings = this.settings;
+ return {
+ stream: new ReadableStream({
+ start(controller) {
+ const send = (part) => { if (!done) controller.enqueue(part); };
+ send({ type: "stream-start", warnings: [] });
+ if (note && !resume && !earlier && !compaction) for (const part of mapper.note(note)) send(part);
+ child.stderr.on("data", (d) => { stderr = (stderr + d).slice(-4000); });
+ let buffer = "";
+ child.stdout.on("data", (chunk) => {
+ buffer += chunk;
+ let at;
+ while ((at = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, at).trim();
+ buffer = buffer.slice(at + 1);
+ if (!line) continue;
+ let event;
+ try { event = JSON.parse(line); } catch { continue; }
+ for (const part of mapper.push(event)) send(part);
+ // The turn is over: Claude exits once its input ends.
+ if (event.type === "result") child.stdin.end();
+ }
+ });
+ child.on("error", (error) => { if (done) return; send({ type: "error", error: apiError(`Claude Code could not start in the sandbox (${error.message}).`) }); end(); controller.close(); });
+ child.on("close", (code) => {
+ if (done) return;
+ const tail = stderr.trim().split("\n").filter(Boolean).at(-1);
+ const last = mapper.finish(`Claude Code stopped before the turn finished${tail ? `: ${tail.slice(0, 300)}` : ` (exit ${code})`}.`);
+ for (const part of mapper.close()) send(part);
+ send(last);
+ end();
+ controller.close();
+ // The turn's native transcript goes up with the chat (best effort).
+ void fetch(settings.grantURL, { method: "POST", headers: { "content-type": "application/json", "x-omnirush-usage-key": settings.grantKey || "" }, body: JSON.stringify({ op: "end", sessionID, uuid, ok: last.type === "finish" }) }).catch(() => undefined);
+ });
+ },
+ cancel() {
+ if (done || stopped) return;
+ stopped = true;
+ end();
+ try { child.stdin.write(`${JSON.stringify({ type: "control_request", request_id: randomUUID(), request: { subtype: "interrupt" } })}\n`); child.stdin.end(); } catch { /* gone */ }
+ const stillRunning = () => child.exitCode === null && child.signalCode === null;
+ timers.push(setTimeout(() => { if (stillRunning()) child.kill("SIGINT"); }, STOP_GRACE_MS));
+ timers.push(setTimeout(() => { if (stillRunning()) child.kill("SIGKILL"); }, STOP_GRACE_MS * 2));
+ for (const t of timers) t.unref?.();
+ },
+ }),
+ };
+ }
+}
+
+/** The engine's factory: settings are the provider's config options. */
+export function createOmnirushClaude(settings = {}) {
+ const provider = (id) => new ClaudeCodeModel(id, settings);
+ provider.languageModel = provider;
+ return provider;
+}
+
+export default createOmnirushClaude;
diff --git a/apps/server/src/opencode-plugins/claude-provider/map.js b/apps/server/src/opencode-plugins/claude-provider/map.js
new file mode 100644
index 00000000..e8d85da8
--- /dev/null
+++ b/apps/server/src/opencode-plugins/claude-provider/map.js
@@ -0,0 +1,196 @@
+// Claude Code's stream-json lines -> AI SDK LanguageModelV3 stream parts, for the
+// engine's session loop (assets/claude-provider/index.js). Pure: no I/O.
+// Shared by omnirush-cli and omnirush-gui (PARITY.sha256).
+//
+// - Text and thinking stream live from `stream_event` deltas; a message that
+// came without them (no partial messages) is sent whole from `assistant`.
+// - Claude's tools ran inside Claude Code: `tool-call` / `tool-result` with
+// providerExecuted, named and shaped as the 2.0.32 engine's own tools so
+// its cards render them (Bash -> shell, Task/Agent -> subagent, file_path
+// -> path, old_string -> oldString, ...). Any other tool keeps its name.
+// - Sub-agent events (parent_tool_use_id) are folded: the parent's tool
+// result carries what the sub-agent answered.
+// - Every failure is an APICallError with status 400 and
+// `x-should-retry: false`: the engine never sends the turn again (a
+// status-less error is retried, and the turn would run twice).
+
+export const NOTE_COMPACTED = "Claude compacted the conversation.";
+
+const ERROR_MARK = Symbol.for("vercel.ai.error");
+const API_ERROR_MARK = Symbol.for("vercel.ai.error.AI_APICallError");
+
+/** An AI SDK APICallError the engine never retries (AI SDK isInstance reads only the marker symbols). */
+export function apiError(message, { url = "omnirush-claude://turn", statusCode = 400 } = {}) {
+ const error = new Error(String(message || "Claude Code failed").slice(0, 2000));
+ error.name = "AI_APICallError";
+ error[ERROR_MARK] = true;
+ error[API_ERROR_MARK] = true;
+ return Object.assign(error, { url, statusCode, requestBodyValues: {}, responseHeaders: { "x-should-retry": "false" }, responseBody: undefined, data: undefined, isRetryable: false });
+}
+
+const pick = (input, map) => {
+ const out = {};
+ for (const [from, to] of Object.entries(map)) if (input[from] !== undefined) out[to] = input[from];
+ return out;
+};
+
+const TOOLS = {
+ Bash: ["shell", { command: "command", description: "description", timeout: "timeout" }],
+ Read: ["read", { file_path: "path", offset: "offset", limit: "limit" }],
+ Edit: ["edit", { file_path: "path", old_string: "oldString", new_string: "newString", replace_all: "replaceAll" }],
+ Write: ["write", { file_path: "path", content: "content" }],
+ Grep: ["grep", { pattern: "pattern", path: "path", glob: "include" }],
+ Glob: ["glob", { pattern: "pattern", path: "path" }],
+ WebFetch: ["webfetch", { url: "url", prompt: "prompt" }],
+ WebSearch: ["websearch", { query: "query" }],
+ Task: ["subagent", { description: "description", prompt: "prompt", subagent_type: "agent" }],
+ Agent: ["subagent", { description: "description", prompt: "prompt", subagent_type: "agent" }],
+};
+
+/** { toolName, input } in the engine's names; an unknown tool as Claude named it. */
+export function engineTool(name, input) {
+ const known = TOOLS[name];
+ const args = input && typeof input === "object" && !Array.isArray(input) ? input : {};
+ return known ? { toolName: known[0], input: pick(args, known[1]) } : { toolName: String(name || "tool"), input: args };
+}
+
+/** A tool_result's content as the plain string the engine stores. */
+export function resultText(content) {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content);
+ return content.map((item) => (item?.type === "text" ? item.text : item?.type === "image" ? "[image]" : JSON.stringify(item))).join("\n");
+}
+
+/** The V3 usage of a turn: input = the last call's context (what the next call carries), output = the turn's. */
+export function turnUsage(last = {}, result = {}) {
+ const noCache = Number(last.input_tokens) || 0;
+ const cacheRead = Number(last.cache_read_input_tokens) || 0;
+ const cacheWrite = Number(last.cache_creation_input_tokens) || 0;
+ const output = Number(result.output_tokens ?? last.output_tokens) || 0;
+ return { inputTokens: { total: noCache + cacheRead + cacheWrite, noCache, cacheRead, cacheWrite }, outputTokens: { total: output, text: undefined, reasoning: undefined } };
+}
+
+/** Why a result line failed, in Claude's own words when it gave some. */
+function failure(result) {
+ const errors = Array.isArray(result.errors) ? result.errors.filter((e) => typeof e === "string") : [];
+ const text = typeof result.result === "string" && result.result.trim() ? result.result.trim() : errors.join("; ");
+ return text || `Claude Code stopped (${result.subtype || "error"}).`;
+}
+
+export class ClaudeStreamMapper {
+ constructor() {
+ this.message = null;
+ this.blocks = new Map();
+ this.streamed = new Set();
+ this.tools = new Map();
+ this.usage = {};
+ this.result = null;
+ this.notes = 0;
+ }
+
+ /** The parts for one parsed stream-json line. */
+ push(event) {
+ if (!event || typeof event !== "object" || event.parent_tool_use_id) return [];
+ if (event.type === "stream_event") return this.streamEvent(event.event ?? {});
+ if (event.type === "assistant") return this.assistant(event.message ?? {});
+ if (event.type === "user") return this.user(event.message ?? {});
+ if (event.type === "system" && event.subtype === "compact_boundary") return this.note(NOTE_COMPACTED);
+ if (event.type === "result") this.result = event;
+ return [];
+ }
+
+ note(text) {
+ const id = `note-${++this.notes}`;
+ return [{ type: "text-start", id }, { type: "text-delta", id, delta: text }, { type: "text-end", id }];
+ }
+
+ streamEvent(e) {
+ if (e.type === "message_start") {
+ this.message = e.message?.id ?? `msg-${this.streamed.size}`;
+ this.streamed.add(this.message);
+ this.blocks.clear();
+ this.usage = { ...(e.message?.usage ?? {}) };
+ return [];
+ }
+ if (e.type === "message_delta") {
+ if (e.usage) this.usage = { ...this.usage, ...e.usage };
+ return [];
+ }
+ const id = `${this.message}:${e.index}`;
+ if (e.type === "content_block_start") {
+ const kind = e.content_block?.type === "text" ? "text" : e.content_block?.type === "thinking" ? "reasoning" : null;
+ if (!kind) return [];
+ this.blocks.set(e.index, kind);
+ const first = kind === "text" ? e.content_block.text : e.content_block.thinking;
+ return [{ type: `${kind}-start`, id }, ...(first ? [{ type: `${kind}-delta`, id, delta: first }] : [])];
+ }
+ const kind = this.blocks.get(e.index);
+ if (!kind) return [];
+ if (e.type === "content_block_delta") {
+ const delta = kind === "text" ? (e.delta?.type === "text_delta" ? e.delta.text : null) : e.delta?.type === "thinking_delta" ? e.delta.thinking : null;
+ return delta ? [{ type: `${kind}-delta`, id, delta }] : [];
+ }
+ if (e.type === "content_block_stop") {
+ this.blocks.delete(e.index);
+ return [{ type: `${kind}-end`, id }];
+ }
+ return [];
+ }
+
+ assistant(message) {
+ const parts = [];
+ // Claude Code's own error line ("API Error: ...") repeats what the turn's error part says.
+ const whole = !this.streamed.has(message.id) && message.model !== "<synthetic>";
+ (Array.isArray(message.content) ? message.content : []).forEach((block, index) => {
+ if (block?.type === "tool_use") {
+ const call = engineTool(block.name, block.input);
+ this.tools.set(block.id, call.toolName);
+ parts.push({ type: "tool-call", toolCallId: block.id, toolName: call.toolName, input: JSON.stringify(call.input), providerExecuted: true });
+ return;
+ }
+ if (!whole) return;
+ const id = `${message.id ?? "msg"}:${index}`;
+ if (block?.type === "text" && block.text) parts.push({ type: "text-start", id }, { type: "text-delta", id, delta: block.text }, { type: "text-end", id });
+ if (block?.type === "thinking" && block.thinking) parts.push({ type: "reasoning-start", id }, { type: "reasoning-delta", id, delta: block.thinking }, { type: "reasoning-end", id });
+ });
+ if (whole && message.usage) this.usage = { ...message.usage };
+ return parts;
+ }
+
+ user(message) {
+ if (!Array.isArray(message.content)) return [];
+ return message.content.filter((block) => block?.type === "tool_result" && this.tools.has(block.tool_use_id)).map((block) => ({
+ type: "tool-result", toolCallId: block.tool_use_id, toolName: this.tools.get(block.tool_use_id), result: resultText(block.content),
+ ...(block.is_error ? { isError: true } : {}), providerExecuted: true,
+ }));
+ }
+
+ /** The end parts of blocks a cut stream left open. */
+ close() {
+ const parts = [...this.blocks.entries()].map(([index, kind]) => ({ type: `${kind}-end`, id: `${this.message}:${index}` }));
+ this.blocks.clear();
+ return parts;
+ }
+
+ /** The turn's last part: finish, or the error that ended it (no result line: Claude Code stopped). */
+ finish(why = "Claude Code stopped before the turn finished.") {
+ const result = this.result;
+ if (!result) return { type: "error", error: apiError(why) };
+ if (result.is_error || result.subtype !== "success") return { type: "error", error: apiError(failure(result)) };
+ return { type: "finish", finishReason: { unified: "stop", raw: result.stop_reason ?? "end_turn" }, usage: turnUsage(this.usage, result.usage ?? {}) };
+ }
+}
+
+/** The last user message of a V3 prompt as Claude Code input content: text, images (base64); other files by path or name. */
+export function lastUserContent(prompt) {
+ const message = (Array.isArray(prompt) ? prompt : []).filter((m) => m?.role === "user").at(-1);
+ const out = [];
+ for (const part of Array.isArray(message?.content) ? message.content : []) {
+ if (part?.type === "text" && part.text) out.push({ type: "text", text: part.text });
+ else if (part?.type === "file" && /^image\//.test(part.mediaType || "") && (typeof part.data === "string" || part.data instanceof Uint8Array)) {
+ const data = typeof part.data === "string" ? part.data.replace(/^data:[^,]*,/, "") : Buffer.from(part.data).toString("base64");
+ out.push({ type: "image", source: { type: "base64", media_type: part.mediaType, data } });
+ } else if (part?.type === "file") out.push({ type: "text", text: `[attached file: ${part.filename || (part.data instanceof URL ? part.data.href : "unnamed")}]` });
+ }
+ return out;
+}
diff --git a/apps/server/src/opencode-plugins/omnirush-session-next.ts b/apps/server/src/opencode-plugins/omnirush-session-next.ts
index b714079b..08b4ae32 100644
--- a/apps/server/src/opencode-plugins/omnirush-session-next.ts
+++ b/apps/server/src/opencode-plugins/omnirush-session-next.ts
@@ -5,20 +5,23 @@ import { SHELL_SECRET_ENV } from "./shell-secret-env.js";
* - Every model request to the app's gateway names its chat (x-omnirush-session-id) and,
* for a sub-agent, its parent chat, so the broker binds the chat (strict sessions) and
* keeps one model per chat. A title request is marked and names the chat's model.
+ * - A Claude chat (opencode-plugins/claude-provider): its turns name the chat's folder and agent (a compaction
+ * runs /compact in Claude Code); its title, on the gateway's title model, names no chat (it never binds there).
* - Agent shells never see the app's secrets (the engine password included).
* The server refuses v2 chats while this plugin is not active (engine-v2-preview.ts).
*/
export const OMNIRUSH_SESSION_PLUGIN_ID = "omnirush.session";
const PROVIDER_ID = "omnirush";
+const CLAUDE_PROVIDER_ID = "omnirush-claude";
-type SessionInfo = { parentID?: unknown; model?: { id?: unknown } | null };
+type SessionInfo = { parentID?: unknown; model?: { id?: unknown; providerID?: unknown } | null; location?: { directory?: unknown } | null };
export default {
id: OMNIRUSH_SESSION_PLUGIN_ID,
async setup(ctx: {
session: {
get(input: { sessionID: string }): Promise<unknown>;
- hook(name: "model.request", callback: (event: { sessionID: string; kind: string; model: { id: string; providerID: string }; headers: Record<string, string> }) => Promise<void>, options?: { providerID?: string }): Promise<unknown>;
+ hook(name: "model.request", callback: (event: { sessionID: string; kind: string; agent?: string; model: { id: string; providerID: string }; headers: Record<string, string> }) => Promise<void>, options?: { providerID?: string }): Promise<unknown>;
};
shell: { hook(name: "create.before", callback: (event: { env: Record<string, string | undefined> }) => Promise<void> | void): Promise<unknown> };
}) {
@@ -35,6 +38,12 @@ export default {
};
await ctx.session.hook("model.request", async (event) => {
if (event.model.providerID !== PROVIDER_ID || !event.sessionID) return;
+ // A Claude chat's title: no chat named, so the broker neither pins nor binds the chat to the title model.
+ // Read fresh: the chat's model is set by its first prompt, after an earlier lookup may have been kept.
+ if (event.kind === "title") {
+ sessions.delete(event.sessionID);
+ if ((await info(event.sessionID)).model?.providerID === CLAUDE_PROVIDER_ID) return;
+ }
event.headers["x-omnirush-session-id"] = event.sessionID;
// The server's broker marks an accepted quota wrap's compaction (engine-v2-budget-wrap.ts).
if (event.kind === "compaction") event.headers["x-omnirush-request-kind"] = "compaction";
@@ -46,6 +55,13 @@ export default {
if (chatModel) event.headers["x-omnirush-chat-model"] = chatModel;
}
}, { providerID: PROVIDER_ID });
+ await ctx.session.hook("model.request", async (event) => {
+ if (event.model.providerID !== CLAUDE_PROVIDER_ID || !event.sessionID) return;
+ const agent = event.kind === "compaction" ? "compaction" : event.agent;
+ if (agent) event.headers["x-omnirush-agent"] = String(agent);
+ const directory = (await info(event.sessionID)).location?.directory;
+ if (typeof directory === "string" && directory) event.headers["x-omnirush-directory"] = directory;
+ }, { providerID: CLAUDE_PROVIDER_ID });
// Captured before any shell runs: the engine's own XDG folders are not the user's.
const userXdg = Object.fromEntries(["DATA", "STATE", "CONFIG"].map((kind) =>
[`XDG_${kind}_HOME`, process.env[`OMNIRUSH_USER_XDG_${kind}_HOME`]]));
diff --git a/apps/server/src/provider-lock.test.ts b/apps/server/src/provider-lock.test.ts
index f976eafd..567c8ced 100644
--- a/apps/server/src/provider-lock.test.ts
+++ b/apps/server/src/provider-lock.test.ts
@@ -40,7 +40,7 @@ afterEach(async () => {
describe("provider lock: fails closed", () => {
test("locked at start, and for every answer that is not a clear `locked: false`", () => {
- expect(currentProviderLockPolicy()).toMatchObject({ locked: true, allow: ["omnirush"] });
+ expect(currentProviderLockPolicy()).toMatchObject({ locked: true, allow: ["omnirush", "omnirush-claude"] });
for (const answer of [null, undefined, {}, { schema_versions: [1, 2] }, { providers: null }, { providers: { locked: "false" } }, { providers: { locked: 0 } }, { providers: [] }]) {
applyProviderLockAnswer(answer);
expect(currentProviderLockPolicy().locked).toBe(true);
@@ -55,9 +55,10 @@ describe("provider lock: fails closed", () => {
expect(currentProviderLockPolicy().locked).toBe(true);
});
- test("the server's message is taken; only omnirush counts as allowed, whatever the list says", () => {
+ test("the server's message is taken; only the app's providers count as allowed, whatever the list says", () => {
applyProviderLockAnswer({ providers: { locked: true, allow: ["acme", "openai", "BAD ID", 7], message: "Ask your admin." } });
- expect(currentProviderLockPolicy()).toMatchObject({ locked: true, allow: ["omnirush"], message: "Ask your admin." });
+ expect(currentProviderLockPolicy()).toMatchObject({ locked: true, allow: ["omnirush", "omnirush-claude"], message: "Ask your admin." });
+ expect(providerAllowed("omnirush-claude")).toBe(true);
expect(providerAllowed("acme")).toBe(false);
expect(providerAllowed("openai")).toBe(false);
expect(providerAllowed("omnirush")).toBe(true);
@@ -174,7 +175,7 @@ describe("provider lock: engine environment", () => {
HOME: "/h",
OPENCODE_CONFIG_DIR: "/app/dir",
OMNIRUSH_PROVIDER_LOCK: "1",
- OMNIRUSH_PROVIDER_ALLOW: "omnirush",
+ OMNIRUSH_PROVIDER_ALLOW: "omnirush,omnirush-claude",
OMNIRUSH_PROVIDER_LOCK_MESSAGE: "Only OmniRush models are available.",
OPENCODE_DISABLE_MODELS_FETCH: "1",
});
@@ -215,7 +216,7 @@ describe("provider lock: engine environment", () => {
const dumped = JSON.parse(await readFile(dumpPath, "utf8"));
expect(dumped).toMatchObject({
OMNIRUSH_PROVIDER_LOCK: "1",
- OMNIRUSH_PROVIDER_ALLOW: "omnirush",
+ OMNIRUSH_PROVIDER_ALLOW: "omnirush,omnirush-claude",
OPENCODE_DISABLE_MODELS_FETCH: "1",
OPENCODE_MODELS_URL: null,
OPENCODE_CONFIG_CONTENT: null,
diff --git a/apps/server/src/provider-lock.ts b/apps/server/src/provider-lock.ts
index 93299d39..faa78038 100644
--- a/apps/server/src/provider-lock.ts
+++ b/apps/server/src/provider-lock.ts
@@ -26,10 +26,10 @@ import { parse as parseJsonc } from "jsonc-parser";
import { ApiError } from "./errors.js";
import {
+ APP_PROVIDER_IDS,
lockEngineConfig,
lockedProviderPolicy,
modelRefAllowed,
- OMNIRUSH_PROVIDER_ID,
PLUGINS_OFF_MESSAGE,
providerLockEnv,
providerLockPolicy,
@@ -62,8 +62,8 @@ function samePolicy(left: ProviderLockPolicy, right: ProviderLockPolicy): boolea
*/
export function applyProviderLockAnswer(capabilities: unknown): boolean {
const parsed = providerLockPolicy(capabilities ?? null);
- // Only OmniRush's own provider counts as allowed, whatever else a server lists.
- const next = parsed.locked ? { ...parsed, allow: parsed.allow.filter((id) => id === OMNIRUSH_PROVIDER_ID) } : parsed;
+ // Only OmniRush's own providers (the gateway's, Claude Code in the box) count as allowed, whatever else a server lists.
+ const next = parsed.locked ? { ...parsed, allow: parsed.allow.filter((id) => (APP_PROVIDER_IDS as readonly string[]).includes(id)) } : parsed;
const changed = !samePolicy(current, next);
current = next;
return changed;
@@ -117,11 +117,11 @@ export const PROVIDER_RESERVED_MESSAGE = "The OmniRush provider is set by the ap
/**
* A provider a route may write into the app's runtime config: never the
- * app's own (`omnirush`, which only the app sets, locked or not), and only
+ * app's own (`omnirush`, `omnirush-claude`: only the app sets them, locked or not), and only
* allowed providers while locked. Throws 403 otherwise.
*/
export function assertProviderWritable(providerId: string, policy: ProviderLockPolicy = current): void {
- if (providerId.trim().toLowerCase() === OMNIRUSH_PROVIDER_ID) throw new ApiError(403, PROVIDER_RESERVED_CODE, PROVIDER_RESERVED_MESSAGE);
+ if ((APP_PROVIDER_IDS as readonly string[]).includes(providerId.trim().toLowerCase())) throw new ApiError(403, PROVIDER_RESERVED_CODE, PROVIDER_RESERVED_MESSAGE);
assertProviderAllowed(providerId, policy);
}
diff --git a/apps/server/src/provider-lock/PARITY.sha256 b/apps/server/src/provider-lock/PARITY.sha256
index 6a737686..4ccbedfa 100644
--- a/apps/server/src/provider-lock/PARITY.sha256
+++ b/apps/server/src/provider-lock/PARITY.sha256
@@ -1,4 +1,4 @@
# The model-provider lock module: the same files in omnirush-cli (src/provider-lock/) and omnirush-gui (apps/server/src/provider-lock/).
# A change to one must be ported to the other and this list updated in both.
-c9a83c525b2273e9d6ef0265c684e6c98726371b91778db1d031caf42eb3e213 provider-lock.mjs
-c44dcf519ebaff78013e192961f987db1ebf15f36f6dabbf7091f290f1e0dd32 provider-lock.d.mts
+9e54e0a2f7aa110cb13373ffb0a8739d4c50e24972b8359503342dfd2679502a provider-lock.mjs
+b435bfa00b201d516c17bff2ecc6715a2463033711696d4b087d8ce176470849 provider-lock.d.mts
diff --git a/apps/server/src/provider-lock/provider-lock.d.mts b/apps/server/src/provider-lock/provider-lock.d.mts
index 482d3eec..fcdbc913 100644
--- a/apps/server/src/provider-lock/provider-lock.d.mts
+++ b/apps/server/src/provider-lock/provider-lock.d.mts
@@ -2,6 +2,7 @@
// src/provider-lock/ and omnirush-gui apps/server/src/provider-lock/; PARITY.sha256).
export const OMNIRUSH_PROVIDER_ID: "omnirush";
+export const APP_PROVIDER_IDS: readonly ["omnirush", "omnirush-claude"];
export const PROVIDER_LOCK_MESSAGE: string;
export const PLUGINS_OFF_MESSAGE: string;
export const PROVIDER_ID_PATTERN: RegExp;
diff --git a/apps/server/src/provider-lock/provider-lock.mjs b/apps/server/src/provider-lock/provider-lock.mjs
index 0ece70fa..500d40bb 100644
--- a/apps/server/src/provider-lock/provider-lock.mjs
+++ b/apps/server/src/provider-lock/provider-lock.mjs
@@ -22,6 +22,8 @@
// so the desktop's bundler and the CLI's plain node both load it as is.
export const OMNIRUSH_PROVIDER_ID = "omnirush";
+/** The app's own providers: the gateway's, and Claude Code in the box (assets/claude-provider). */
+export const APP_PROVIDER_IDS = Object.freeze([OMNIRUSH_PROVIDER_ID, "omnirush-claude"]);
export const PROVIDER_LOCK_MESSAGE = "Only OmniRush models are available.";
export const PLUGINS_OFF_MESSAGE = "Custom plugins are off while OmniRush models are locked.";
export const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -52,7 +54,7 @@ function cleanMessage(value) {
/** The locked policy every missing, failed or malformed answer means. */
export function lockedProviderPolicy(source = "default") {
- return { locked: true, allow: [OMNIRUSH_PROVIDER_ID], message: PROVIDER_LOCK_MESSAGE, source };
+ return { locked: true, allow: [...APP_PROVIDER_IDS], message: PROVIDER_LOCK_MESSAGE, source };
}
/**
@@ -68,7 +70,7 @@ export function providerLockPolicy(capabilities) {
if (block.locked === false) return { locked: false, allow: [], message, source: "server" };
// Only OmniRush's own provider can be allowed: other ids in `allow` are ignored (the engine would not
// trust their definitions anyway).
- const allow = [OMNIRUSH_PROVIDER_ID];
+ const allow = [...APP_PROVIDER_IDS];
return { locked: true, allow, message, source: "server" };
}
@@ -140,7 +142,8 @@ export function lockEngineConfig(config, policy) {
}
out.provider = kept;
}
- out.enabled_providers = [...policy.allow];
+ // The gateway's provider always; another app provider only where this config defines it.
+ out.enabled_providers = policy.allow.filter((id) => id === OMNIRUSH_PROVIDER_ID || (isRecord(out.provider) && id in out.provider));
if ("disabled_providers" in out) {
delete out.disabled_providers;
removed.push("disabled_providers");
diff --git a/apps/server/src/runtime-config-global-providers.test.ts b/apps/server/src/runtime-config-global-providers.test.ts
index f91284de..9a3a6954 100644
--- a/apps/server/src/runtime-config-global-providers.test.ts
+++ b/apps/server/src/runtime-config-global-providers.test.ts
@@ -120,7 +120,7 @@ describe("global runtime providers", () => {
const enginePlugin = await fetch(`${base}/opencode/config`, { method: "PATCH", headers: clientHeaders(), body: JSON.stringify({ plugin: ["opencode-wakatime"] }) });
expect(enginePlugin.status).toBe(403);
const status = await fetch(`${base}/omnirush/provider-lock`, { headers: clientHeaders() });
- expect(await readJsonObject(status)).toMatchObject({ locked: true, allow: ["omnirush"], plugins: { off: true, message: "Custom plugins are off while OmniRush models are locked." } });
+ expect(await readJsonObject(status)).toMatchObject({ locked: true, allow: ["omnirush", "omnirush-claude"], plugins: { off: true, message: "Custom plugins are off while OmniRush models are locked." } });
expect(runtimeProviderMap(await readGlobalRuntimeOpencodeConfig(config))).toEqual({});
} finally {
applyProviderLockAnswer({ providers: { locked: false } });
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 63f20032..1201cda6 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1,5 +1,5 @@
+import { randomBytes, timingSafeEqual } from "node:crypto";
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
-import { uploadClaudeSession } from "./claude-code/transfer.js";
import { ArchiveUploader } from "./session-archive/upload.js";
import { SealStream } from "./session-archive/seal.js";
import { tarMemberHeader } from "./session-archive/pack.js";
@@ -206,7 +206,7 @@ import {
watchProviderLock,
} from "./provider-lock.js";
import { normalizeBackend } from "./box/backends/index.js";
-import { buildOmniRushRuntimeConfigObject, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";
+import { buildOmniRushRuntimeConfigObject, claudeEngineProvider, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";
import { assertMcpAllowed, mcpAllowed, mcpDisabledMessage, mcpPolicyForConfig, refuseAccountLinkedMcp } from "./mcp-policy.js";
import { currentMcpPolicy, MCP_FILTER_MISSING, mcpFilterMissing, rememberMcpPolicy, watchMcpPolicy, workspaceMcpReport, writeWorkspaceMcp } from "./mcp-allow/state.js";
import { omnirushMcpPolicyPluginPath } from "./omnirush-extensions-plugin-path.js";
@@ -258,8 +258,8 @@ import { GOOD_SESSION_ID_PATTERN, readGoodSession } from "./omnirush-good-sessio
import { PROJECT_ARCHIVE_BASE_IDLE_MS, PROJECT_ARCHIVE_BASE_MAX_DEFER_MS, projectArchiveSettings } from "./project-archive.js";
import type { ArchiveApiRequestInit } from "./session-archive/upload.js";
import { runtimeStorageDir } from "./runtime-db.js";
-import { ClaudeRuntime } from "./claude-code/runtime.js";
-import { registerClaudeRoutes } from "./claude-code/routes.js";
+import { CLAUDE_AUTO_NOTE, CLAUDE_CODE_VERSION, claudeChatRoute, type ClaudeChatInput } from "./claude-code/chat.js";
+import { claudeConfigDirOf, uploadClaudeTurn } from "./claude-code/native.js";
import { prepareDesktopInstallLog } from "./install-log-host.js";
import pkg from "../package.json" with { type: "json" };
import constants from "../../../constants.json" with { type: "json" };
@@ -373,6 +373,8 @@ const voiceServicesByServer = new WeakMap<ServerConfig, OmniRushVoiceService>();
/** The broker's integrity read (rate-limited there), per server, for the checklist bar's "Good session ★". */
const sessionIntegrityByServer = new WeakMap<ServerConfig, OmniRushGatewayBroker["sessionIntegrity"]>();
const modelSwitchRefusalsByServer = new WeakMap<ServerConfig, OmniRushGatewayBroker["modelSwitchRefusal"]>();
+/** Each server's Claude turn route (claude-code/chat.ts) and the key its engine's Claude provider sends. */
+const claudeTurnsByServer = new WeakMap<ServerConfig, { key: string; handle: ReturnType<typeof claudeChatRoute> }>();
/** Recent gateway fallbacks per sub-agent session, for the swarm plugin's task-result note. */
const subagentGatewayFallbacks = new WeakMap<ServerConfig, Map<string, Array<Record<string, unknown>>>>();
@@ -1594,7 +1596,50 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// persisted policy at startup; there is no running workspace to reload.
if (config.workspaces.length > 0) cloudProviderSync.markReloadPending();
};
- const engineV2Preview = createEngineV2Preview({ config, env, deferStart: true });
+ // Claude chats (claude-code/chat.ts): the engine's Claude provider asks /omnirush-claude/turn, with this key, for each turn.
+ const claudeKey = randomBytes(24).toString("base64url");
+ const claudeTurn = claudeChatRoute({
+ access: () => gatewayBroker.claudeAccess(),
+ authorize: (context) => gatewayBroker.claudeGrant(context),
+ pin: (sessionId) => gatewayBroker.chatModel(sessionId),
+ setPin: (sessionId, model) => gatewayBroker.pinChatModel(sessionId, model),
+ onClaudeChat: ({ sessionID }) => captureServicesByServer.get(config)?.markClaude(sessionID, CLAUDE_CODE_VERSION),
+ // The turn's native transcript, unchanged, as `claude/` members of the chat's claude_native archive (only a chat whose uploads are on).
+ onTurnEnd: async ({ sessionID, uuid, grant }) => {
+ const capture = captureServicesByServer.get(config);
+ const bits = boxServiceFor(config).claudeBits();
+ const configDir = grant && uuid && bits ? claudeConfigDirOf(bits.home, uuid) : null;
+ if (!grant || !configDir || !capture?.uploadEnabled || !capture.hasSession(sessionID)) return;
+ const uploader = new ArchiveUploader({ fetch: externalFetch, request: (route, init) => gatewayBroker.nativeCaptureRequest(grant.owner, route, init) });
+ const receipt = await uploadClaudeTurn({
+ // The archive names the bare Claude Code version (the collector refuses "claude-code/<v>" there).
+ grant, uuid, configDir, stateDir: runtimeStorageDir(config), engineVersion: CLAUDE_CODE_VERSION,
+ request: (route, init) => gatewayBroker.nativeCaptureRequest(grant.owner, route, init),
+ driver: { fetchKey: (signal) => uploader.fetchKey(signal), upload: (job, persist, signal) => uploader.upload(job, persist, signal), sealer: (options) => new SealStream(options), tarHeader: tarMemberHeader },
+ }).catch((error: unknown) => ({ status: "failed", reason: error instanceof Error ? error.message : String(error) }));
+ logger.log("info", "claude: native transcript upload", { status: receipt.status, native: "native" in receipt ? receipt.native.status : null, code: "native" in receipt ? receipt.native.code ?? null : "reason" in receipt ? receipt.reason : null });
+ },
+ log: (level, message, attributes) => logger.log(level, message, attributes),
+ });
+ claudeTurnsByServer.set(config, { key: claudeKey, handle: claudeTurn });
+ // The Claude models the engine was last given: the status route mirrors again when the account's catalog differs (a sign-in after start).
+ let mirroredClaude: string | null = null;
+ const engineV2Preview = createEngineV2Preview({
+ config, env, deferStart: true,
+ claude: async () => {
+ const bits = boxServiceFor(config).claudeBits();
+ const access = await gatewayBroker.claudeAccess().catch((error: unknown) => {
+ logger.log("info", "claude: no catalog for the engine yet", { error: error instanceof Error ? error.message.slice(0, 200) : "unknown" });
+ throw error;
+ });
+ mirroredClaude = (access.catalog ?? []).map((entry) => entry.id).join(",");
+ return claudeEngineProvider(access.catalog ?? [], {
+ grantURL: `http://127.0.0.1:${config.port}/omnirush-claude/turn`, grantKey: claudeKey,
+ ...(bits ? { shell: bits.shell, boxHome: bits.home } : {}),
+ client: `gui/${config.appVersion?.trim() || SERVER_VERSION}`, note: CLAUDE_AUTO_NOTE,
+ });
+ },
+ });
engineV2Refreshers.set(config, () => engineV2Preview.refreshProviders());
engineV2ByServer.set(config, engineV2Preview);
/** A chat on the 2.x engine, read where it lives (its folder), or null. */
@@ -1642,26 +1687,14 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
bestPracticesReloads,
);
- // Claude Code drives docker itself: the box backend's Docker engine when it is one, else `docker` on PATH.
- let claudeDocker: string | undefined;
- const claudeRuntime = new ClaudeRuntime({
- get docker() { return claudeDocker; },
- directory: join(runtimeStorageDir(config), "claude-sessions"), surface: "gui", fetch: externalFetch,
- access: () => gatewayBroker.claudeAccess(),
- authorize: context => gatewayBroker.claudeGrant(context),
- revoke: context => gatewayBroker.revokeClaudeGrant(context),
- });
- registerClaudeRoutes({routes, runtime: claudeRuntime,
- workspace: async ctx => {
- claudeDocker = (await boxServiceFor(config).dockerCli().catch(() => null)) ?? undefined;
- return resolveWorkspaceWithoutBootstrap(config, ctx.params.id);
- },
- owner: ctx => requireClientScope(ctx, "owner"),
- writable: () => ensureWritable(config),
- upload: id => uploadClaudeSession(claudeRuntime, id, (owner, route, init) => gatewayBroker.nativeCaptureRequest(owner, route, init), owner => {
- const uploader = new ArchiveUploader({fetch: externalFetch, request: (route, init) => gatewayBroker.nativeCaptureRequest(owner, route, init)});
- return {fetchKey: signal => uploader.fetchKey(signal), upload: (job, persist, signal) => uploader.upload(job, persist, signal), sealer: options => new SealStream(options), tarHeader: tarMemberHeader};
- }),
+ // The picker's Claude entries (claude-models.ts): the account's Claude catalog and the ids it may run.
+ addRoute(routes, "GET", "/workspace/:id/claude/status", "client", async (ctx) => {
+ requireClientScope(ctx, "owner");
+ const access = await gatewayBroker.claudeAccess().catch(() => null);
+ if (access && (access.catalog ?? []).map((entry) => entry.id).join(",") !== mirroredClaude) void engineV2Preview.refreshProviders().catch(() => undefined);
+ const response = jsonResponse({ allowed: Boolean(access?.models?.length), catalog: access?.catalog ?? [], models: access?.models ?? [], reason: access ? access.reason ?? null : "unavailable" });
+ response.headers.set("cache-control", "no-store");
+ return response;
});
const serverOptions: {
@@ -1805,6 +1838,20 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
return finalize(new Response(null, { status: 204 }));
}
+ // The engine's Claude provider (claude-code/chat.ts): its key, never a client token.
+ if (url.pathname === "/omnirush-claude/turn") {
+ authMode = "client";
+ const turn = claudeTurnsByServer.get(config);
+ const key = Buffer.from(request.headers.get("x-omnirush-usage-key") ?? "");
+ if (!turn || request.method !== "POST" || key.length !== Buffer.byteLength(turn.key) || !timingSafeEqual(key, Buffer.from(turn.key))) {
+ return finalize(jsonResponse({ ok: false, message: "forbidden" }, 403));
+ }
+ const input = await request.json().catch(() => null) as ClaudeChatInput | null;
+ const answer = input ? await turn.handle(input).catch((error: unknown) => ({ ok: false, message: error instanceof Error ? error.message : String(error) })) : { ok: false, message: "bad request" };
+ const response = jsonResponse(answer);
+ response.headers.set("cache-control", "no-store");
+ return finalize(response);
+ }
const gatewayMount = url.pathname.match(/^\/omnirush-gateway\/v1\/(.+)$/);
if (gatewayMount?.[1]) {
authMode = "client";
@@ -2067,7 +2114,6 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
return {
...server,
stop: async () => {
- const claudeStopped = claudeRuntime.shutdown();
// First, and synchronously: a stop is also how a user sign-out reaches
// this server (the desktop clears the account, then restarts it), so
// archive part uploads in flight are aborted before anything else runs.
@@ -2075,7 +2121,6 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// is still stored (an app quit, a restart), never after a sign-out.
// Before them, each chat in a box gets its last checkpoint (bounded; only when chats ran in a
// box this run, and the account answers it is still stored within a second).
- await claudeStopped;
stopBoxDefaultWatch();
stopWebSearchWatch();
stopMcpPolicyWatch();
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 1eb5ec36..a700d094 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -4747,6 +4747,8 @@ export class SessionUploader {
private readonly boxes = new Map<string, BoxCaptureInfo>();
/** Chats that used computer use, for the envelope's `environment.computer_use`. */
private readonly computerUse = new Map<string, ComputerUseEnvironment>();
+ /** Claude chats (markClaude): their Claude Code version. */
+ private readonly claudeChats = new Map<string, string>();
private readonly boxToolchains: ToolchainCache | null;
private readonly excludedHashes: HashCache = new Map();
private spoolCounter = 0;
@@ -5275,7 +5277,17 @@ export class SessionUploader {
const mcpServers = this.stateDir ? mcpServersInUse(workspaceMcpReport(this.stateDir, root)) : null;
// Only a chat that used computer use gets the field.
const computerUse = this.computerUse.get(sessionId) ?? null;
- return { ...environment, ...boxEnvironment(environment, box?.label ?? null), ...(toolchain ? { toolchain } : {}), ...(box ? { sandbox: box.label } : {}), ...(importedFrom ? { imported_from: importedFrom } : {}), ...(mcpServers ? { mcp_servers: mcpServers } : {}), ...(computerUse ? { computer_use: computerUse } : {}) };
+ // A Claude chat: Claude Code is the harness, run in the box under this engine, whose stored events the upload holds (the CLI: the same).
+ const claude = this.claudeChats.get(sessionId);
+ const harness = claude ? { engine_version: `claude-code/${claude}`, harness: { name: "claude-code", engine: "claude-code", version: claude, build_tag: environment.harness.build_tag, host_engine: environment.engine_version, runtime: "box", engine_schema: "opencode-v2" }, engine_schema: "opencode-v2" } as unknown as Partial<UploadEnvironment> : {};
+ return { ...environment, ...harness, ...boxEnvironment(environment, box?.label ?? null), ...(toolchain ? { toolchain } : {}), ...(box ? { sandbox: box.label } : {}), ...(importedFrom ? { imported_from: importedFrom } : {}), ...(mcpServers ? { mcp_servers: mcpServers } : {}), ...(computerUse ? { computer_use: computerUse } : {}) };
+ }
+
+ /** A Claude chat (opencode-plugins/claude-provider) and its Claude Code version. */
+ markClaude(sessionId: string, version: string): void {
+ if (!sessionId || !version) return;
+ this.claudeChats.set(sessionId, version);
+ while (this.claudeChats.size > 512) this.claudeChats.delete(this.claudeChats.keys().next().value as string);
}
/**
diff --git a/evals/packages/labs/src/capture-efficiency.ts b/evals/packages/labs/src/capture-efficiency.ts
index b7a0988a..62257498 100644
--- a/evals/packages/labs/src/capture-efficiency.ts
+++ b/evals/packages/labs/src/capture-efficiency.ts
@@ -11,7 +11,6 @@ import { zstdDecompressSync } from "node:zlib";
import { startCaptureService, type CaptureService } from "../../../../apps/server/src/capture-client.js";
import type { TraceCapabilities } from "../../../../apps/server/src/session-uploader.js";
-import { NativeCapture } from "../../../../apps/server/src/claude-code/native-capture.js";
const CONTROL_TOKEN = "capture-lab-control";
const UPLOAD_TOKEN = "capture-lab-upload";
@@ -194,7 +193,6 @@ async function startCaptureEfficiencyLabRuntime(): Promise<CaptureEfficiencyLab>
let stopped = false;
let services: CaptureService[] = [];
const signedIn: Record<Actor, string | null> = { "actor-a": "actor-a", "actor-b": "actor-b" };
- const nativeContexts = new Map<string, { actor: Actor; configDir: string; source: string; expected: string }>();
const server = createServer((request, response) => {
void (async () => {
@@ -250,65 +248,6 @@ async function startCaptureEfficiencyLabRuntime(): Promise<CaptureEfficiencyLab>
const body = await readJson(request);
const requestedSessionId = stringValue(body, "sessionId");
- if (path.startsWith("/control/native/")) {
- if (!/^[a-f0-9-]{36}$/.test(requestedSessionId)) throw new Error("invalid native session id");
- const actor = actorValue(body), index = ACTORS.indexOf(actor);
- if (path === "/control/native/seed") {
- const configDir = join(tempRoot, "native-sources", actor, requestedSessionId);
- const project = join(configDir, "projects", "-fixture-workspace");
- const source = join(project, `${requestedSessionId}.jsonl`);
- await mkdir(project, { recursive: true });
- const records = [
- { type: "user", uuid: "prompt", parentUuid: null, message: { content: `task for ${actor}` } },
- { type: "assistant", uuid: "tools", parentUuid: "prompt", futureNativeField: actor, message: { content: [{ type: "thinking", thinking: "Visible summary", signature: "opaque-fixture" }, { type: "tool_use", id: "side-call", name: "Read" }, { type: "tool_use", id: "main-call", name: "Read" }] } },
- { type: "user", uuid: "side-result", parentUuid: "tools", message: { content: [{ type: "tool_result", tool_use_id: "side-call", content: "side branch" }] } },
- { type: "user", uuid: "main-result", parentUuid: "tools", message: { content: [{ type: "tool_result", tool_use_id: "main-call", content: "main branch" }] } },
- ];
- const expected = records.map((record) => JSON.stringify(record) + "\n").join("");
- await writeFile(source, expected.slice(0, -3));
- await writeFile(join(configDir, "credentials.json"), "DO_NOT_EXPORT_AUTH");
- await writeFile(join(project, "unrelated.jsonl"), "DO_NOT_EXPORT_OTHER_SESSION");
- const subagents = join(project, requestedSessionId, "subagents"); await mkdir(subagents, { recursive: true });
- for (let child = 0; child < 5; child++) {
- await writeFile(join(subagents, `agent-child${child}.jsonl`), JSON.stringify({ type: "user", uuid: `child${child}`, parentUuid: null, message: { content: `child ${child}` } }) + "\n");
- await writeFile(join(subagents, `agent-child${child}.meta.json`), '{"agentType":"fixture"}');
- }
- nativeContexts.set(requestedSessionId, { actor, configDir, source, expected });
- sendJson(response, 202, { rootSha256: createHash("sha256").update(expected).digest("hex") }); return;
- }
- const context = nativeContexts.get(requestedSessionId);
- if (!context || context.actor !== actor) { sendJson(response, 403, { error: "native owner mismatch" }); return; }
- const captureContext = { sessionId: requestedSessionId, configDir: context.configDir, producerVersion: "native-lab", transport: "sdk" as const };
- if (path === "/control/native/account") {
- signedIn[actor] = isRecord(body) && body.signedIn === null ? null : stringValue(body, "signedIn");
- sendJson(response, 202, { ok: true }); return;
- }
- if (path === "/control/native/repair") {
- await appendFile(context.source, context.expected.slice(-3)); sendJson(response, 202, { ok: true }); return;
- }
- if (path === "/control/native/restart") {
- await services[index].stop({ archiveFinals: false }); services[index] = makeService(actor);
- sendJson(response, 202, { ok: true }); return;
- }
- if (path === "/control/native/stream") {
- const text = stringValue(body, "text"), offset = numberValue(body, "offset");
- if (offset === null) throw new Error("stream offset required");
- const manifest = await services[index].captureClaude(captureContext, { type: "stream", channel: "sdk", offset, bytes: Buffer.from(text) });
- sendJson(response, 202, manifest); return;
- }
- if (path === "/control/native/finish") {
- const manifest = await services[index].captureClaude(captureContext, { type: "finish", processStopped: true, successfulResult: true, expectedAgents: ["child0", "child1", "child2", "child3", "child4"] });
- sendJson(response, 202, manifest); return;
- }
- if (path === "/control/native/export") {
- const capture = new NativeCapture({ ...captureContext, directory: join(stateRoot, actor, "claude-native", requestedSessionId), owner: actor, surface: "gui" });
- const destination = join(tempRoot, "exports", requestedSessionId);
- const manifest = capture.exportTo(destination);
- const files = await Promise.all(manifest.files.map(async (file) => ({ path: file.path, text: await readFile(join(destination, file.path), "utf8") })));
- sendJson(response, 202, { manifest, files }); return;
- }
- throw new Error("unknown native control");
- }
if (path === "/control/start") {
const actor = actorValue(body);
const workspace = stringValue(body, "workspace");
diff --git a/evals/specs/claude-native-capture.test.ts b/evals/specs/claude-native-capture.test.ts
deleted file mode 100644
index 82ef7803..00000000
--- a/evals/specs/claude-native-capture.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { createHash } from "node:crypto";
-import { expect } from "vitest";
-import { startCaptureEfficiencyLab } from "@omnirush/labs";
-import { needs, test } from "@omnirush/testkit";
-
-test("Claude native evidence survives capture-worker restart and exports every conversation branch and child", { timeout: 60_000 }, async ({ evidence }) => {
- needs({ placement: "local", commands: ["bun"] });
- const lab = await startCaptureEfficiencyLab();
- const sessionId = "00000000-0000-4000-8000-000000000001";
- const actor = "actor-a";
- const request = async (operation: string, extra: Record<string, unknown> = {}, status = 202) => {
- const response = await fetch(`${lab.baseUrl}/control/native/${operation}`, {
- method: "POST", headers: { authorization: `Bearer ${lab.controlToken}`, "content-type": "application/json" },
- body: JSON.stringify({ sessionId, actor, ...extra }), signal: AbortSignal.timeout(10_000),
- });
- const body = await response.json(); expect(response.status, JSON.stringify(body)).toBe(status); return body;
- };
- try {
- const seeded = await request("seed");
- const partial = await request("finish");
- expect(partial.status).toBe("incomplete");
- expect(partial.issues).toContain(`partial_line:claude/projects/-fixture-workspace/${sessionId}.jsonl`);
- await request("finish", { actor: "actor-b" }, 403);
- await request("account", { signedIn: null });
- await request("finish", {}, 500);
- await request("account", { signedIn: "actor-b" });
- await request("finish", {}, 500);
- await request("account", { signedIn: actor });
- const event = JSON.stringify({ type: "stream_event", event: { type: "content_block_delta", delta: { type: "thinking_delta", thinking: "visible delta" } } }) + "\n";
- await request("stream", { text: event, offset: 0 });
- await request("restart");
- const duplicate = await request("stream", { text: event, offset: 0 });
- expect(duplicate.streams.sdk).toBe(Buffer.byteLength(event));
- await request("stream", { text: "conflicting", offset: 0 }, 500);
- await request("repair");
- const complete = await request("finish");
- expect(complete.status).toBe("complete");
- expect(complete.replay).toBe("unverified");
- expect(complete.files).toHaveLength(12);
- expect((await lab.witness()).modes).toEqual(["worker", "worker"]);
- const exported = await request("export");
- const files: Array<{ path: string; text: string }> = exported.files;
- const root = files.find((file) => file.path.endsWith(`/${sessionId}.jsonl`));
- if (!root) throw new Error("native root missing");
- expect(createHash("sha256").update(root.text).digest("hex")).toBe(seeded.rootSha256);
- expect(root.text).toContain("side-result"); expect(root.text).toContain("main-result");
- expect(root.text).toContain("opaque-fixture"); expect(root.text).toContain("futureNativeField");
- expect(files.filter((file) => file.path.includes("/subagents/") && file.path.endsWith(".jsonl"))).toHaveLength(5);
- expect(files.filter((file) => file.path.endsWith(".meta.json"))).toHaveLength(5);
- expect(files.find((file) => file.path === "events/sdk.jsonl")?.text).toBe(event);
- expect(JSON.stringify(files)).not.toContain("DO_NOT_EXPORT_AUTH");
- expect(JSON.stringify(files)).not.toContain("DO_NOT_EXPORT_OTHER_SESSION");
- expect((await lab.witness()).attempts).toHaveLength(0);
- evidence.recordAssertionEvidence("Native branches, subagents and opaque fields survive byte-exact private export", "The source SHA-256 matched; both branch results, five child JSONL files and five sidecars survived. Auth and unrelated-session canaries were absent; no raw evidence went to the legacy collector.", true);
- evidence.recordAssertionEvidence("Incomplete capture fails closed and stream retries survive worker restart", "A truncated record stayed incomplete; a real suffix repaired it. Retrying the same offset after worker restart did not duplicate bytes, conflicting retry failed, and another actor was denied. Capture completion remained replay-unverified.", true);
- } finally { await lab.stop(); }
-});
diff --git a/evals/specs/claude-native.e2e.test.ts b/evals/specs/claude-native.e2e.test.ts
deleted file mode 100644
index 54756eab..00000000
--- a/evals/specs/claude-native.e2e.test.ts
+++ /dev/null
@@ -1,293 +0,0 @@
-import { expect } from "vitest";
-import { spec } from "@omnirush/testkit";
-import { claudeNativeWorld, claudeConnectionWorld } from "../worlds/claude-native.ts";
-const test = spec.world(claudeNativeWorld, {needs: {placement: "local", commands: ["bun", "docker", "pnpm"]}, timeout: 120_000});
-
-test("Claude GUI runs three native sandbox turns with five children and exports a verified environment", {timeout: 15 * 60_000}, async ({world, user, probe, evidence}) => {
- await user.see("New Claude session", {timeoutMs: 60_000});
- expect((await world.request("sessions", {captureConsent: true}, "invalid-client")).status).toBe(401);
- expect((await world.request("sessions", {captureConsent: true}, world.collaboratorToken)).status).toBe(403);
- if (world.packaged) expect(await world.runtimeWitness()).toEqual({protocol: "file:", bridge: true, embeddedServerSelected: true});
- await user.click("Retain private traces and full project snapshots");
- await user.click("New Claude session");
- const createPollStatuses: number[] = [];
- await probe.eventually(async () => {
- const response = await world.request("sessions"); createPollStatuses.push(response.status);
- return response;
- }, {within: 180_000, until: response => response.status === 200 && Array.isArray(response.body) && response.body.length === 1});
- expect(createPollStatuses.every(status => status === 200)).toBe(true);
- await user.see("Message Claude", {timeoutMs: 180_000, editable: true});
- await world.control({rejectInferenceOnce: true});
- const mintsBeforeTurns = (await world.witness()).mintRequests.length;
- for (let turn = 1; turn <= 3; turn++) {
- await user.type("Message Claude", `fixture-turn-${turn}: ${turn === 1 ? "Build the module and ask five subagents to check it." : "Continue developing and check the prior changes."}`);
- await user.click("Send");
- await probe.eventually(() => world.session(), {within: 180_000, until: session => session?.turns.length === turn && session.turns[turn - 1].status !== "running"});
- const session = await world.session();
- expect(session.turns[turn - 1].status, JSON.stringify(session)).toBe("complete");
- expect(session.capture).toBe("complete");
- expect(session.modelIsolation.status).toBe("observed");
- expect(session.modelIsolation.observedModels).toEqual(["claude-opus-5-5"]);
- const authorizationWitness = await world.witness();
- expect(authorizationWitness.tokenRejections).toBe(1);
- // One initial mint per turn, plus exactly one remint after the real 401.
- expect(authorizationWitness.mintRequests.length - mintsBeforeTurns).toBe(turn + 1);
- expect(session.authorization.budget.status).toBe(turn === 3 ? "unknown" : "known");
- const budgetText = turn === 3 ? "Model allowance has not been reported by the backend." : turn === 2 ? "model no limit · Session: no limit · Account day: 18,000 tokens" : "model 7,000 tokens · Session: 4,000 tokens · Account day: 18,000 tokens";
- await probe.eventually(() => probe.dom('[aria-label="Model allowance"]'), {within: 10_000, until: result => result.elements[0]?.text.includes(budgetText) === true});
- await probe.eventually(() => probe.dom('textarea[aria-label="Message Claude"]:not(:disabled)'), {within: 10_000, until: result => result.elements.length === 1});
- await user.see("Message Claude", {editable: true});
- if (turn === 1) {
- await user.reload(); await user.see("Claude session");
- await probe.eventually(() => probe.dom('[aria-label="Claude session"] option'), {within: 30_000, until: result => result.elements.length === 2});
- await user.click("Claude session"); await user.press("End"); await user.press("Enter");
- await user.see("Message Claude", {editable: true});
- }
- await world.control({budgetMode: turn === 1 ? "unlimited" : "unknown"});
- }
- await user.type("Verification command", "test -f /home/node/environment-marker && test -x /workspace/check.sh && test ! -e /workspace/seed.txt && test $(ls /workspace/child-*.txt | wc -l) -eq 5 && grep 'second turn' /workspace/answer.txt");
- await user.click("Verify restore");
- await user.see({testId: "claude-notice"}, {text: "Environment restored and verification passed with network access disabled.", timeoutMs: 180_000});
- world.prepareDownload();
- await user.click("Download private ZIP");
- await user.see({testId: "claude-notice"}, {text: "Private session ZIP downloaded.", timeoutMs: 180_000});
- await world.control({checkpointEnabled: false});
- await user.click("Upload private session");
- await user.see({testId: "claude-notice"}, {text: "Native traces uploaded. Environment upload is disabled by the backend; the complete ZIP remains on this device.", timeoutMs: 180_000});
- const nativeOnly = await world.witness();
- expect(nativeOnly.archives.map((archive: {request: {payload: string}}) => archive.request.payload)).toEqual(["claude_native"]);
- await world.control({checkpointEnabled: true});
- await user.click("Upload private session");
- await user.see({testId: "claude-notice"}, {text: "Private session uploaded. Backend receipts confirm the native traces and environment arrived.", timeoutMs: 180_000});
- const session = await world.session(), result = await world.nativeEvidence(session.id), witness = await world.witness();
- if (world.packaged) expect(await world.downloaded()).toBe(result.zipBytes);
- const display = (await world.request(`sessions/${session.id}/events`)).body;
- expect(display.filter((event: {type: string}) => event.type === "user")).toHaveLength(3);
- expect(display.filter((event: {type: string}) => event.type === "result")).toHaveLength(3);
- expect(display.some((event: {type: string; text: string; turn: number}) => event.type === "tool" && event.text === "Read" && event.turn === 3)).toBe(true);
- expect(display.map((event: {turn: number}) => event.turn)).toEqual(display.map((event: {turn: number}) => event.turn).sort((a: number, b: number) => a-b));
- const desktop = await world.desktopExport(session.id);
- expect(desktop?.status).toBe(200); expect(desktop?.bytes).toBe(result.zipBytes);
- if (world.packaged) expect(await world.cancelDesktopExport(session.id)).toEqual({active: true, outcome: "cancelled", stillActive: false});
- expect(result.manifest.transport).toBe("sdk");
- expect(result.manifest.status).toBe("complete");
- expect(result.manifest.files.filter((file: {path: string}) => /subagents\/agent-.*\.jsonl$/.test(file.path))).toHaveLength(5);
- expect(result.manifest.files.some((file: {thinkingBlocks: number}) => file.thinkingBlocks > 0)).toBe(true);
- expect(result.manifest.streams.sdk).toBeGreaterThan(0); expect(result.manifest.streams.hooks).toBeGreaterThan(0);
- expect(result.manifest.qc.humanPromptCandidates).toBe(3);
- expect(result.manifest.qc.childPromptRecords).toBeGreaterThanOrEqual(5);
- expect(result.manifest.qc.exposedThinkingBlocks).toBeGreaterThan(0);
- expect(result.readWitnesses).toHaveLength(1);
- expect(result.replay.status).toBe("restored"); expect(result.zipBytes).toBeGreaterThan(0);
- expect(new Set([result.state.base.file, ...result.state.turns.map((turn: {after: {file: string}}) => turn.after.file)]).size).toBe(1);
- expect(witness.uploadRetryInjected).toBe(true); expect(witness.uploadLossInjected).toBe(true);
- expect(witness.uploadsComplete).toBe(2); expect(witness.uploadedBytes).toBe(result.zipBytes);
- expect(witness.presignedAuthLeaks).toBe(0);
- expect(witness.archives.map((archive: {request: {payload: string}}) => archive.request.payload).sort()).toEqual(["claude_checkpoint", "claude_native"]);
- expect(witness.archives.every((archive: {request: {session_id: string; contract_hash: string}}) => archive.request.session_id === session.id && archive.request.contract_hash === result.state.contractSha256)).toBe(true);
- expect(witness.hostFiles).toEqual(world.initialHostFiles);
- const layout = await world.layout();
- expect(layout.lastMessageBottom).toBeLessThanOrEqual(layout.conversationBottom);
- expect(layout.composerTop).toBeGreaterThanOrEqual(layout.conversationBottom);
- expect(witness.requests.every((r: {userAgent: string; model: string}) => /claude-cli/.test(r.userAgent) && r.model === "claude-opus-5-5")).toBe(true);
- expect(witness.inferenceDenials).toEqual([]);
- expect(witness.requests.every((r: {app: string; beta: string; box: string; client: string; session: string}) => r.app === "cli" && r.beta.includes("claude-code-") && r.box === "1" && /^desktop\/[0-9]/.test(r.client) && r.session === session.id)).toBe(true);
- expect(result.state.modelIsolation.status).toBe("observed");
- expect(result.state.modelIsolation.observedModels).toEqual(["claude-opus-5-5"]);
- const authorizationRetries = result.modelRequests.filter((event: {authorizationFailures?: number[]}) => event.authorizationFailures?.length);
- expect(authorizationRetries).toHaveLength(1);
- expect(authorizationRetries[0]).toMatchObject({type: "response", status: 200, authorizationFailures: [401]});
- expect(result.state.contract.model).toBe("claude-opus-5-5");
- expect(result.state.contract.execution).toMatchObject({kind: "docker", os: "linux", workspace: "session-copy"});
- const callsBeforeMutation = witness.calls;
- const restoreModel = await world.mutateSession(session.id, "model");
- try { expect((await world.request(`sessions/${session.id}/turns`, {prompt: "Do not reuse a changed model"})).status).not.toBe(202); }
- finally { await restoreModel(); }
- const restoreContract = await world.mutateSession(session.id, "legacy");
- try {
- expect((await world.request(`sessions/${session.id}/turns`, {prompt: "Do not resume an unattested legacy session"})).status).not.toBe(202);
- expect((await world.exportReceipt(session.id)).status).toBe(200);
- } finally { await restoreContract(); }
- expect((await world.witness()).calls).toBe(callsBeforeMutation);
- const before = witness.calls; await world.access(false);
- const paused = await world.request(`sessions/${session.id}/turns`, {prompt: "This must not reach inference"});
- if (paused.status === 202) {
- const denied = await probe.eventually(() => world.session(), {within: 180_000, until: state => state.turns.length === 4 && state.turns[3].status !== "running"});
- expect(denied.turns[3].status).toBe("failed");
- }
- expect((await world.witness()).calls).toBe(before);
- expect((await world.request(`sessions/${session.id}`)).status).toBe(200);
- expect((await world.exportReceipt(session.id)).status).toBe(200);
- await world.access(true);
- await user.screenshot();
- if (world.packaged) {
- await world.switchToEmptyWorkspace();
- await user.see("New Claude session");
- await probe.eventually(() => probe.dom('[aria-label="Claude conversation"]'), {within: 30_000, until: state => state.elements.length === 0});
- expect((await probe.dom('textarea[aria-label="Message Claude"]')).elements).toHaveLength(0);
- expect((await probe.dom('[aria-label="Claude session"] option')).elements).toHaveLength(1);
- }
- evidence.recordAssertionEvidence("GUI uses native Claude Code and captures every child inside the sandbox", "Three real SDK turns resumed one UUID across a page reload; five child transcripts, thinking blocks, SDK events and hooks were retained. Host project was unchanged. Unselected accounts and collaborator tokens could not start work.", true);
- evidence.recordAssertionEvidence("One model remains fixed across children and resume", "A child explicitly requested Haiku, but all actual managed inference requests and provider identities stayed on Opus. A changed model and missing legacy contract both blocked continuation without upstream calls; the legacy evidence remained exportable.", true);
- evidence.recordAssertionEvidence("GUI resumes after one rejected inference grant without contaminating model evidence", "The first turn received a real HTTP 401. Exactly one additional grant mint recovered it; the saved policy response records [401] followed by 200. All three GUI turns, including resume after reload, completed with observed Opus-only identity and a restored replay.", true);
- evidence.recordAssertionEvidence("Private ZIP retains restorable full environments", "The exported checkpoint loaded into a separate network-disabled container. The verification command checked a file outside the project, executable mode, deletion, all five child outputs and the second-turn edit.", true);
- evidence.recordAssertionEvidence("Sealed native and environment uploads recover independently", "Canonical ORSEAL01 multipart upload recovered from a transient 503 and a lost acknowledged part. The fixture decrypted both payloads, verified plaintext hashes and every native manifest member, and received no device bearer on presigned PUTs. Native traces completed while checkpoint upload was disabled, then the checkpoint resumed after enablement.", true);
- evidence.recordAssertionEvidence("Desktop archive transfer streams the full local-server bundle", "The actual desktop transfer helper saved the same ZIP from the real product server to a test-selected save-dialog destination, beyond the ordinary inbox transfer size cap.", true);
- if (world.packaged) evidence.recordAssertionEvidence("Packaged Electron runs the Claude journey through its embedded server", "The installed-layout binary loaded file assets and its actual preload bridge without a development renderer or server override. Three turns, five children, restore, upload and the real native save dialog completed against the packaged embedded server.", true);
-});
-
-const connectionTest = spec.world(claudeConnectionWorld, {needs: {placement: "local", commands: ["bun", "pnpm"]}, timeout: 120_000});
-connectionTest("Claude connection refresh keeps host authority, remote isolation and cancellation", {timeout: 120_000}, async ({world, user, probe, evidence}) => {
- await user.see("New Claude session", {timeoutMs: 60_000});
- await probe.eventually(() => probe.dom('[aria-label="Claude session"] option'), {within: 15_000, until: result => result.elements.length === 2});
- await user.click("Claude session"); await user.press("End"); await user.press("Enter");
- await user.see("Message Claude", {editable: true});
- const initial = await world.connectionWitness();
- expect(initial.requests.filter((request: {accepted: boolean}) => !request.accepted)).toEqual([]);
- // The HTTP fixture requires host authority even with a valid owner bearer.
- expect((await world.request("sessions")).status).toBe(403);
- await world.connectionControl({hostToken: "fixture-host-2"});
- expect((await world.request("sessions", undefined, undefined, "fixture-host-1")).status).toBe(403);
- const beforeRotation = (await world.connectionWitness()).requests.length;
- await world.publishHostToken("fixture-host-2");
- await probe.eventually(() => world.connectionWitness(), {within: 15_000, until: state => state.requests.slice(beforeRotation).some((request: {route: string; accepted: boolean}) => request.route.endsWith("/events") && request.accepted)});
- await user.type("Message Claude", "Resume after host-token rotation"); await user.click("Send");
- await probe.eventually(() => probe.dom('[aria-label="Capture status"]'), {within: 10_000, until: result => result.elements[0]?.text.includes("2 turns") === true});
- await user.click("Download private ZIP");
- await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.startedExports === 1});
- await user.click("Cancel download");
- await user.see({testId: "claude-notice"}, {text: "Download cancelled."});
- await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.cancelledExports === 1});
- const local = (await world.connectionWitness()).requests.slice(beforeRotation);
- expect(local.every((request: {accepted: boolean; hostMatches: boolean}) => request.accepted && request.hostMatches)).toBe(true);
- expect(local.some((request: {route: string}) => request.route.endsWith("/turns"))).toBe(true);
- expect(local.some((request: {route: string}) => request.route.endsWith("/export"))).toBe(true);
-
- await world.navigateConnectionWorkspace(true);
- await probe.eventually(() => probe.dom('[aria-label="Claude session"] option'), {within: 15_000, until: result => result.elements.length === 2});
- await user.click("Claude session"); await user.press("End"); await user.press("Enter");
- await user.see("Message Claude", {editable: true});
- await user.type("Message Claude", "Use the remote workspace credentials"); await user.click("Send");
- await probe.eventually(() => probe.dom('[aria-label="Capture status"]'), {within: 10_000, until: result => result.elements[0]?.text.includes("3 turns") === true});
- const remote = (await world.connectionWitness()).requests.filter((request: {remote: boolean}) => request.remote);
- expect(remote.length).toBeGreaterThan(0);
- expect(remote.every((request: {accepted: boolean; hostPresent: boolean}) => request.accepted && !request.hostPresent)).toBe(true);
-
- await world.connectionControl({holdCreate: true});
- await user.click("Retain private traces and full project snapshots"); await user.click("New Claude session");
- await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.requests.some((request: {remote: boolean; method: string; route: string}) => request.remote && request.method === "POST" && request.route.endsWith("/sessions"))});
- await world.navigateConnectionWorkspace(false);
- await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.cancelledCreates === 1});
- await world.connectionControl({available: false, crashedTurn: true, exportMode: "blocked"});
- await world.publishHostToken("fixture-host-2");
- await user.see({text: "Saved sessions"}, {timeoutMs: 10_000});
- await user.click("Claude session"); await user.press("End"); await user.press("Enter");
- await user.see("Download private ZIP");
- await user.click("Download private ZIP");
- await user.see({text: "Another process is using this session or its operation owner is unknown"}, {timeoutMs: 10_000});
- expect((await probe.dom('[data-testid="claude-notice"]')).elements).toHaveLength(0);
- await world.connectionControl({exportMode: "complete"});
- await user.click("Download private ZIP");
- await user.see({testId: "claude-notice"}, {text: "Private session ZIP downloaded."});
- const offline = await world.connectionWitness();
- expect(offline.available).toBe(false); expect(offline.lastTurnStatus).toBe("running");
- expect(offline.completedExports).toBe(1);
- expect(offline.requests.some((request: {route: string}) => request.route.endsWith("/recover"))).toBe(false);
- expect((await world.witness()).calls).toBe(0);
- evidence.recordAssertionEvidence("Claude requests retain current local host authority and isolate remote credentials", "A missing host token was refused. The mounted route refreshed on settings publication and resumed polling, a turn and export with the rotated token. Remote polling and turns used the remote bearer and received no local host header.", true);
- evidence.recordAssertionEvidence("Route cancellation reaches HTTP requests", "Cancelling a stalled archive closed its response stream without a download success notice. Navigating away from a pending session creation aborted its HTTP request. This focused fixture made zero inference calls and prepared no sandbox.", true);
- evidence.recordAssertionEvidence("Saved evidence remains downloadable after an unfinished turn while Claude is unavailable", "A saved running turn did not disable export when both account access and sandbox readiness were off. The server's active-owner refusal remained visible; after that lock cleared, export succeeded without recovery or any inference call. The historical turn still read running.", true);
-});
-
-test("Claude rejects invalid session grants and quota denial without retrying or hiding saved evidence", {timeout: 12 * 60_000}, async ({world, probe, evidence}) => {
- const faults = [
- {bindingFault: "session"}, {bindingFault: "model"}, {bindingFault: "upstream"}, {bindingFault: "contract"},
- {expiresIn: 901}, {expiresIn: 10, refreshAfter: 11}, {refreshAfter: 0}, {budgetMode: "wrong-model"}, {budgetMode: "wrong-session"}, {mintStatus: 429},
- ];
- const created = await world.request("sessions", {captureConsent: true});
- expect(created.status).toBe(201);
- const id = created.body.id;
- for (const [index, fault] of faults.entries()) {
- await world.control({bindingFault: null, expiresIn: 900, refreshAfter: 600, mintStatus: 200, budgetMode: "known", ...fault});
- const before = await world.witness();
- expect((await world.request(`sessions/${id}/turns`, {prompt: "fixture-turn-grant: This must not reach inference."})).status).toBe(202);
- const state = await probe.eventually(async () => (await world.request(`sessions/${id}`)).body, {within: 180_000, until: session => session.turns.length === index + 1 && session.turns[index].status !== "running"});
- expect(state.turns[index].status).toBe("failed");
- const after = await world.witness();
- expect(after.calls).toBe(before.calls);
- expect(after.mintRequests.length).toBe(before.mintRequests.length + 1);
- expect(after.mintRequests.at(-1)).toMatchObject({session_id: id, model: "claude-opus-5-5", contract_hash: state.contractSha256});
- expect(after.mintRequests.at(-1).project_key).toMatch(/^[a-f0-9]{12}$/);
- expect(after.mintRequests.at(-1).client).toBeTruthy();
- }
- expect((await world.exportReceipt(id)).status).toBe(200);
- evidence.recordAssertionEvidence("Short-lived grants bind inference to the immutable session contract", "Wrong session, requested or upstream model, contract bindings and invalid expiration/refresh values all refused inference. Each failed attempt made exactly one token request and preserved an exportable session.", true);
- evidence.recordAssertionEvidence("Model quota exhaustion does not create an automatic retry storm", "A 429 from the session token endpoint stopped before inference after one token request, while the saved environment remained readable and exportable.", true);
-});
-
-test("Claude accepts valid refresh boundaries and preserves model quota metadata", {timeout: 8 * 60_000}, async ({world, user, probe, evidence}) => {
- await user.see("New Claude session", {timeoutMs: 60_000});
- await world.control({refreshAfter: 1, expiresIn: 1, budgetMode: "null"});
- await user.click("Retain private traces and full project snapshots");
- await user.click("New Claude session");
- await user.see("Message Claude", {timeoutMs: 180_000, editable: true});
- for (let turn = 1; turn <= 2; turn++) {
- const before = await world.witness();
- await user.type("Message Claude", `fixture-turn-authorization-${turn}: Check the model allowance response from inside this sandbox.`);
- await user.click("Send");
- const session = await probe.eventually(() => world.session(), {within: 180_000, until: state => state?.turns.length === turn && state.turns[turn - 1].status !== "running"});
- expect(session.turns[turn - 1].status).toBe("complete");
- expect(session.capture).toBe("complete");
- expect(session.modelIsolation.status).toBe("observed");
- expect(session.authorization.budget.status).toBe(turn === 1 ? "unknown" : "known");
- const after = await world.witness();
- expect(after.calls - before.calls).toBe(2);
- if (turn === 1) expect(after.mintRequests.length - before.mintRequests.length).toBeGreaterThan(1);
- const label = turn === 1 ? "Model allowance has not been reported by the backend." : "model 7,000 tokens";
- await probe.eventually(() => probe.dom('[aria-label="Model allowance"]'), {within: 10_000, until: value => value.elements[0]?.text.includes(label) === true});
- await probe.eventually(() => probe.dom('textarea[aria-label="Message Claude"]:not(:disabled)'), {within: 10_000, until: value => value.elements.length === 1});
- await world.control({refreshAfter: 900, expiresIn: 900, budgetMode: "known"});
- }
- const session = await world.session();
- const proof = await world.request(`sessions/${session.id}/verify`, {command: `node -e 'const p=require("./authorization-checked.json"), h=p.headers; if(p.status!==429 || h["x-should-retry"]!=="false" || h["retry-after"]!=="60" || h["x-omnirush-grant-scope"]!=="model" || h["x-omnirush-grant-bucket"]!=="model:claude-opus-5-5" || h["x-omnirush-grant-resets-at"]!=="2037-09-24T00:00:00Z" || h["x-ratelimit-limit-tokens"]!=="8000" || h["x-ratelimit-remaining-tokens"]!=="0" || h["x-private-provider-secret"]!==undefined) process.exit(1)'`});
- expect(proof.status).toBe(200); expect(proof.body.status).toBe("restored");
- evidence.recordAssertionEvidence("Valid boundary grants run without inventing an allowance", "Two SDK turns completed with refresh_after one and equal to expires_in. The short-lived grant caused fresh mint requests; budget:null stayed visibly unknown and the next valid snapshot displayed the model allowance.", true);
- evidence.recordAssertionEvidence("Quota refusal metadata survives the managed broker without provider secrets", "A sandbox tool observed 429, no-retry, Retry-After, model scope, bucket, reset and token limits. An unrelated provider-secret header was absent. Network-disabled restore verified the recorded response.", true);
-});
-
-test("Claude refuses contaminated provider identities and marks missing identity as unknown", {timeout: 12 * 60_000}, async ({world, probe, evidence}) => {
- for (const responseModel of ["claude-haiku-4-5-20251001", null]) {
- await world.control({responseModel});
- const created = await world.request("sessions", {captureConsent: true});
- expect(created.status).toBe(201);
- const id = created.body.id;
- const beforeCalls = (await world.witness()).calls;
- expect((await world.request(`sessions/${id}/turns`, {prompt: "fixture-turn-identity: Inspect the project."})).status).toBe(202);
- const state = await probe.eventually(async () => (await world.request(`sessions/${id}`)).body, {within: 180_000, until: session => session.turns.length === 1 && session.turns[0].status !== "running"});
- expect(state.modelIsolation.status).toBe(responseModel ? "invalid" : "unknown");
- if (responseModel) expect(state.modelIsolation.observedModels).toContain(responseModel);
- else expect(state.modelIsolation.observedModels).toEqual([]);
- expect(state.turns[0].status).toBe("failed");
- const display = (await world.request(`sessions/${id}/events`)).body;
- expect(display.filter((event: {type: string}) => event.type === "tool")).toEqual([]);
- const before = (await world.witness()).calls;
- expect(before).toBe(beforeCalls + 1);
- expect((await world.request(`sessions/${id}/turns`, {prompt: "Do not continue unverified identity"})).status).not.toBe(202);
- expect((await world.witness()).calls).toBe(before);
- const archive = await world.exportReceipt(id);
- expect(archive.status).toBe(200); expect(archive.bytes).toBeGreaterThan(0);
- }
- await world.control({resetResponseModel: true});
- const guarded = await world.request("sessions", {captureConsent: true});
- expect(guarded.status).toBe(201);
- const beforeGuard = (await world.witness()).calls;
- expect((await world.request(`sessions/${guarded.body.id}/turns`, {prompt: "fixture-turn-broker-guard: Probe the managed session model boundary."})).status).toBe(202);
- const guardedState = await probe.eventually(async () => (await world.request(`sessions/${guarded.body.id}`)).body, {within: 180_000, until: session => session.turns.length === 1 && session.turns[0].status !== "running"});
- expect(guardedState.modelIsolation.status).toBe("invalid");
- expect(guardedState.modelIsolation.rejectedRequests).toBeGreaterThan(0);
- const afterGuard = await world.witness();
- expect(afterGuard.calls).toBe(beforeGuard + 1);
- expect(afterGuard.requests.every((request: {model: string}) => request.model === "claude-opus-5-5")).toBe(true);
- evidence.recordAssertionEvidence("Provider identity is checked before any tool can run", "A response naming another model made the session invalid; a response without identity made it unknown. Each stopped after exactly one upstream call and exposed no tool call to the SDK. Both refused another turn while preserving exportable evidence.", true);
- evidence.recordAssertionEvidence("The managed broker blocks a tool-requested model switch", "A sandbox tool attempted to request Haiku using its own scoped session bearer. The request was recorded as rejected and invalidated the session; only the original Opus request reached upstream.", true);
-});
diff --git a/evals/worlds/claude-native.ts b/evals/worlds/claude-native.ts
deleted file mode 100644
index 0c9eb7be..00000000
--- a/evals/worlds/claude-native.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import fs from "node:fs/promises";
-import { mkdtempSync } from "node:fs";
-import path from "node:path";
-import { tmpdir } from "node:os";
-import { spawn, execFile, type ChildProcess } from "node:child_process";
-import { promisify } from "node:util";
-import { fileURLToPath } from "node:url";
-import { chrome, desktop, localHost } from "@omnirush/hosts";
-import { allocateFreePort, browserScript, evaluateOnSurface, navigate } from "@omnirush/cdp";
-import { eventually } from "@omnirush/testkit";
-// Electron's executable JavaScript module has no published declaration file.
-// @ts-expect-error Tests exercise the actual main-process transfer helper.
-import { downloadClaudeArchive } from "../../apps/desktop/electron/binary-transfer.mjs";
-
-const repo = fileURLToPath(new URL("../..", import.meta.url));
-const execute = promisify(execFile);
-export async function claudeNativeWorld() { return createClaudeWorld(false); }
-export async function claudeConnectionWorld() { return createClaudeWorld(true); }
-async function createClaudeWorld(connectionOnly: boolean) {
- const packaged = !connectionOnly && Boolean(process.env.OMNIRUSH_EVAL_ELECTRON_BINARY);
- const root = mkdtempSync(path.join(tmpdir(), "omnirush-claude-journey-"));
- const log = await fs.open(path.join(root, "server.log"), "a");
- const lab = spawn("bun", ["--conditions=development", "evals/packages/labs/src/claude-runtime-server.ts"], {cwd: repo, env: {...process.env, CLAUDE_LAB_DIR: root, CLAUDE_LAB_INFERENCE_ONLY: packaged ? "1" : "0", CLAUDE_LAB_CONNECTION_ONLY: connectionOnly ? "1" : "0"}, stdio: ["ignore", log.fd, log.fd]});
- const ready: {baseUrl: string; token: string; hostToken: string; workspaceId: string; gateway: string} = await eventually(async () => JSON.parse(await fs.readFile(path.join(root, "ready.json"), "utf8")), {within: 60_000});
- const viteLog = await fs.open(path.join(root, "vite.log"), "a");
- let vite: ChildProcess | undefined;
- let app!: Awaited<ReturnType<typeof chrome>> | Awaited<ReturnType<typeof desktop>>;
- let collaboratorToken = "owt_claude_fixture";
- try {
- if (packaged) {
- app = await desktop({name: "claude-native-packaged", host: localHost(), prepareSharedResources: false,
- profileDir: path.join(root, "electron-profile"), timeoutMs: 90_000,
- env: {OMNIRUSH_RUNTIME_DB: path.join(root, "runtime.sqlite"),
- OMNIRUSH_ACCESS_TOKEN: "device-fixture", OMNIRUSH_REFRESH_TOKEN: "refresh-fixture", OMNIRUSH_GATEWAY_URL: `${ready.gateway}/v1`,
- OMNIRUSH_ELECTRON_START_URL: "", ELECTRON_START_URL: "", OMNIRUSH_AUTO_UPDATE: "0"},
- });
- const connection = await evaluateOnSurface(app, browserScript(async folderPath => {
- const bridge = window.__OMNIRUSH_ELECTRON__;
- if (!bridge || location.protocol !== "file:") throw new Error("The installed-layout renderer/preload did not load");
- const initial = await bridge.invokeDesktop("omnirushServerInfo");
- const response = await fetch(`${initial.baseUrl}/workspaces/local`, {method: "POST", headers: {authorization: `Bearer ${initial.ownerToken}`, "content-type": "application/json"}, body: JSON.stringify({folderPath, name: "Claude fixture", preset: "starter"})});
- if (!response.ok) throw new Error(`Packaged workspace registration failed: ${response.status}`);
- const workspaces = await response.json();
- const workspace = workspaces.workspaces.find((entry: {path: string; id: string}) => entry.path === folderPath);
- if (!workspace) throw new Error("Packaged workspace registration did not return the project");
- await bridge.invokeDesktop("workspaceSetSelected", workspace.id);
- await bridge.invokeDesktop("workspaceSetRuntimeActive", workspace.id);
- const info = await bridge.invokeDesktop("omnirushServerInfo");
- if (!workspace || !info.baseUrl || !info.ownerToken || !info.clientToken) throw new Error("Packaged embedded server did not provide owner and collaborator endpoints");
- location.hash = `/workspace/${workspace.id}/claude`;
- return {baseUrl: info.baseUrl, token: info.ownerToken, clientToken: info.clientToken, workspaceId: workspace.id};
- }, [path.join(root, "project")]));
- Object.assign(ready, connection); collaboratorToken = connection.clientToken;
- } else {
- const port = await allocateFreePort();
- vite = spawn("pnpm", ["--filter", "@omnirush/app", "dev", "--host", "127.0.0.1", "--port", String(port)], {cwd: repo, env: {...process.env, OMNIRUSH_DEV_MODE: "1"}, detached: true, stdio: ["ignore", viteLog.fd, viteLog.fd]});
- const url = `http://127.0.0.1:${port}`;
- await eventually(async () => (await fetch(url)).ok, {within: 60_000, until: value => value});
- app = await chrome({name: "claude-native", host: localHost(), startUrl: url, headless: true});
- await eventually(() => evaluateOnSurface(app, () => location.origin), {within: 30_000, until: origin => origin === url});
- await evaluateOnSurface(app, browserScript((base, token, hostToken) => {
- localStorage.setItem("omnirush.server.urlOverride", base);
- localStorage.setItem("omnirush.server.token", token);
- localStorage.setItem("omnirush.server.hostToken", hostToken);
- }, [ready.baseUrl, ready.token, ready.hostToken]));
- await navigate(app.client, `${url}/workspace/${ready.workspaceId}/claude`);
- }
- } catch (error) {
- await app?.[Symbol.asyncDispose]();
- lab.kill("SIGTERM");
- if (vite?.pid) try { process.kill(-vite.pid, "SIGTERM"); } catch { /* already stopped */ }
- await log.close(); await viteLog.close();
- throw error;
- }
- const request = async (route: string, body?: unknown, token = ready.token, hostToken?: string) => {
- const headers: Record<string, string> = {authorization: `Bearer ${token}`, "content-type": "application/json"};
- if (hostToken) headers["x-omnirush-host-token"] = hostToken;
- const response = await fetch(`${ready.baseUrl}/workspace/${ready.workspaceId}/claude/${route}`, {method: body === undefined ? "GET" : "POST", headers, body: body === undefined ? undefined : JSON.stringify(body)});
- return {status: response.status, body: await response.json()};
- };
- let dialogTask: Promise<void> | undefined;
- const initialHostFiles = await fs.readdir(path.join(root, "project"));
- return {app, root, request, packaged, collaboratorToken, initialHostFiles,
- async connectionWitness() { return (await fetch(`${ready.baseUrl}/fixture/witness`)).json(); },
- async connectionControl(body: {hostToken?: string; holdCreate?: boolean; available?: boolean; crashedTurn?: boolean; exportMode?: "stream" | "blocked" | "complete"}) {
- await fetch(`${ready.baseUrl}/fixture/control`, {method: "POST", body: JSON.stringify(body)});
- },
- async publishHostToken(hostToken: string) {
- await evaluateOnSurface(app, browserScript(token => {
- localStorage.setItem("omnirush.server.hostToken", token);
- window.dispatchEvent(new CustomEvent("omnirush-server-settings-changed"));
- }, [hostToken]));
- },
- async navigateConnectionWorkspace(remote: boolean) {
- await evaluateOnSurface(app, browserScript(id => {
- history.pushState(null, "", `/workspace/${id}/claude`);
- window.dispatchEvent(new PopStateEvent("popstate"));
- }, [remote ? "rem_ws_remote" : ready.workspaceId]));
- },
- async cancelDesktopExport(id: string) {
- if (!packaged || process.platform !== "linux") throw new Error("Native cancellation proof requires packaged Linux Electron/xdotool");
- const transferId = `claude-cancel-${id}`;
- const pending = evaluateOnSurface(app, browserScript(async (baseUrl, token, sessionId, transfer) => {
- const input = {url: `${baseUrl}/workspace/${sessionId.workspaceId}/claude/sessions/${sessionId.id}/export`, headers: {authorization: `Bearer ${token}`}, transferId: transfer};
- try { await window.__OMNIRUSH_ELECTRON__.invokeDesktop("__downloadClaudeArchive", input); return "completed"; }
- catch { return "cancelled"; }
- }, [ready.baseUrl, ready.token, {id, workspaceId: ready.workspaceId}, transferId]));
- const windowId = await eventually(async () => (await execute("xdotool", ["search", "--onlyvisible", "--name", "Save private Claude session"], {timeout: 2000})).stdout.trim().split("\n")[0], {within: 15_000, until: value => Boolean(value)});
- const cancel = () => evaluateOnSurface(app, browserScript(transfer => window.__OMNIRUSH_ELECTRON__.invokeDesktop("__cancelTransfer", transfer), [transferId]));
- const active = await cancel();
- await execute("xdotool", ["windowfocus", "--sync", windowId]);
- await execute("xdotool", ["key", "--clearmodifiers", "Escape"]);
- return {active, outcome: await pending, stillActive: await cancel()};
- },
- async runtimeWitness() {
- return evaluateOnSurface(app, async () => {
- const bridge = window.__OMNIRUSH_ELECTRON__;
- const info = await bridge.invokeDesktop("omnirushServerInfo");
- // Normal desktop bootstrap stores its own embedded server URL here.
- return {protocol: location.protocol, bridge: typeof bridge.invokeDesktop === "function", embeddedServerSelected: localStorage.getItem("omnirush.server.urlOverride") === info.baseUrl};
- });
- },
- prepareDownload() {
- if (!packaged) return;
- if (process.platform !== "linux") throw new Error("The packaged native save-dialog driver currently requires Linux/xdotool");
- dialogTask = (async () => {
- const windowId = await eventually(async () => (await execute("xdotool", ["search", "--onlyvisible", "--name", "Save private Claude session"], {timeout: 2000})).stdout.trim().split("\n")[0], {within: 180_000, until: value => Boolean(value)});
- await execute("xdotool", ["windowfocus", "--sync", windowId]);
- await execute("xdotool", ["key", "--clearmodifiers", "ctrl+l"]);
- await execute("xdotool", ["key", "--clearmodifiers", "ctrl+a"]);
- await execute("xdotool", ["type", "--clearmodifiers", "--delay", "1", path.join(root, "desktop-download.zip")]);
- await execute("xdotool", ["key", "--clearmodifiers", "alt+s"]);
- })();
- void dialogTask.catch(() => undefined);
- },
- async downloaded() {
- await dialogTask;
- if (!packaged) return null;
- return eventually(async () => (await fs.stat(path.join(root, "desktop-download.zip"))).size, {within: 30_000, until: bytes => bytes > 0});
- },
- async layout() {
- return evaluateOnSurface(app, () => {
- const conversation = document.querySelector('[aria-label="Claude conversation"]');
- const composer = document.querySelector('textarea[aria-label="Message Claude"]');
- if (!conversation || !composer || !conversation.lastElementChild) throw new Error("Conversation layout unavailable");
- return {composerTop: composer.getBoundingClientRect().top, conversationBottom: conversation.getBoundingClientRect().bottom, lastMessageBottom: conversation.lastElementChild.getBoundingClientRect().bottom};
- });
- },
- async desktopExport(id: string) {
- return downloadClaudeArchive({url: `${ready.baseUrl}/workspace/${ready.workspaceId}/claude/sessions/${id}/export`, headers: {authorization: `Bearer ${ready.token}`}}, {
- localServerUrl: ready.baseUrl, allowedUrlPrefixes: [], stagingDir: path.join(root, "desktop-transfers"), fetcher: fetch,
- chooseDestination: async (filename: string) => path.join(root, filename),
- });
- },
- async session() { return (await request("sessions")).body[0]; },
- async witness() { return (await fetch(`${ready.gateway}/witness`)).json(); },
- async access(enabled: boolean) { await fetch(`${ready.gateway}/control`, {method: "POST", body: JSON.stringify({access: enabled})}); },
- async control(body: Record<string, unknown>) { await fetch(`${ready.gateway}/control`, {method: "POST", body: JSON.stringify(body)}); },
- async switchToEmptyWorkspace() {
- if (!packaged) throw new Error("The workspace navigation witness requires the packaged desktop");
- const folderPath = path.join(root, "other-project"); await fs.mkdir(folderPath);
- await evaluateOnSurface(app, browserScript(async folder => {
- const bridge = window.__OMNIRUSH_ELECTRON__;
- const info = await bridge.invokeDesktop("omnirushServerInfo");
- const response = await fetch(`${info.baseUrl}/workspaces/local`, {method: "POST", headers: {authorization: `Bearer ${info.ownerToken}`, "content-type": "application/json"}, body: JSON.stringify({folderPath: folder, name: "Other Claude project", preset: "starter"})});
- if (!response.ok) throw new Error(`Second workspace registration failed: ${response.status}`);
- const state = await response.json();
- const workspace = state.workspaces.find((entry: {path: string; id: string}) => entry.path === folder);
- if (!workspace) throw new Error("Second workspace was not created");
- await bridge.invokeDesktop("workspaceSetSelected", workspace.id);
- await bridge.invokeDesktop("workspaceSetRuntimeActive", workspace.id);
- location.hash = `/workspace/${workspace.id}/claude`;
- }, [folderPath]));
- },
- async exportReceipt(id: string) {
- const response = await fetch(`${ready.baseUrl}/workspace/${ready.workspaceId}/claude/sessions/${id}/export`, {method: "POST", headers: {authorization: `Bearer ${ready.token}`}});
- let bytes = 0;
- const reader = response.body?.getReader();
- if (reader) try { while (true) { const chunk = await reader.read(); if (chunk.done) break; bytes += chunk.value.byteLength; } }
- finally { reader.releaseLock(); }
- return {status: response.status, bytes};
- },
- async mutateSession(id: string, mutation: "model" | "legacy") {
- for (const owner of await fs.readdir(path.join(root, "claude-sessions"))) {
- const file = path.join(root, "claude-sessions", owner, id, "session.json");
- const raw = await fs.readFile(file, "utf8").catch(() => null); if (!raw) continue;
- const state = JSON.parse(raw);
- if (mutation === "model") state.model = "claude-haiku-4-5-20251001";
- else delete state.contract;
- await fs.writeFile(file, JSON.stringify(state, null, 2));
- return async () => { await fs.writeFile(file, raw); };
- }
- throw new Error("Session metadata unavailable");
- },
- async nativeEvidence(id: string) {
- const owners = await fs.readdir(path.join(root, "claude-sessions"));
- for (const owner of owners) {
- const dir = path.join(root, "claude-sessions", owner, id);
- try {
- const manifest = JSON.parse(await fs.readFile(path.join(dir, "native", "manifest.json"), "utf8"));
- const state = JSON.parse(await fs.readFile(path.join(dir, "session.json"), "utf8"));
- const replay = JSON.parse(await fs.readFile(path.join(dir, "replay.json"), "utf8"));
- const readWitnesses = (await fs.readFile(path.join(dir, "transport", "hooks.jsonl"), "utf8")).split("\n").filter(Boolean).map(line => JSON.parse(line)).filter(event => event.witness?.sha256);
- const modelRequests = (await fs.readFile(path.join(dir, "policy", "model-requests.jsonl"), "utf8")).split("\n").filter(Boolean).map(line => JSON.parse(line));
- const bundle = await fs.stat(path.join(dir, `${id}.zip`)).catch(() => null);
- return {manifest, state, replay, readWitnesses, modelRequests, zipBytes: bundle?.size ?? 0};
- } catch { /* owner directory not this session */ }
- }
- throw new Error("Complete session evidence unavailable");
- },
- async [Symbol.asyncDispose]() {
- await fs.writeFile(path.join(root, "fixture-witness.json"), JSON.stringify(await (await fetch(`${ready.gateway}/witness`)).json(), null, 2)).catch(() => {});
- await app[Symbol.asyncDispose](); lab.kill("SIGTERM");
- if (vite?.pid) try { process.kill(-vite.pid, "SIGTERM"); } catch { /* already stopped */ }
- await log.close(); await viteLog.close();
- // Evidence remains in the isolated root for debugging a failing journey.
- },
- };
-}
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index 7726d6b3..63e0bed6 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -1196,7 +1196,6 @@ export type DesktopCommandMap = {
__fetch: { args: [url: string, init?: DesktopFetchInit]; result: DesktopFetchResult };
__uploadMultipart: { args: [input: DesktopMultipartUploadInput]; result: DesktopFetchResult };
__downloadBinary: { args: [input: DesktopBinaryDownloadInput]; result: DesktopBinaryDownloadResult };
- __downloadClaudeArchive: { args: [input: {transferId: string; url: string; headers?: Record<string, string>}]; result: DesktopBinaryDownloadResult | null };
__cancelTransfer: { args: [transferId: string]; result: boolean };
__homeDir: { args: []; result: string };
__joinPath: { args: [...segments: string[]]; result: string };
diff --git a/scripts/sync-claude-capture.mjs b/scripts/sync-claude-capture.mjs
index 6cf69717..73df2bb1 100644
--- a/scripts/sync-claude-capture.mjs
+++ b/scripts/sync-claude-capture.mjs
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-// The GUI and CLI consume the same dependency-free native evidence collector.
+// The GUI and CLI share the Claude account side: access.ts (eligibility, the per-chat relay token) and upload.ts (the native transcript archive).
// Usage: node scripts/sync-claude-capture.mjs /path/to/omnirush-cli [--check]
import fs from "node:fs";
import path from "node:path";
@@ -9,18 +9,13 @@ import { createHash } from "node:crypto";
const [cli, flag] = process.argv.slice(2);
if (!cli || (flag && flag !== "--check")) throw new Error("Expected CLI checkout and optional --check");
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
-const adapterPath = path.join(root, "apps/server/src/claude-code/replay-adapter.ts");
-const adapter = `// Generated from tools/claude-native/verify.py by scripts/sync-claude-capture.mjs.\nexport const REPLAY_ADAPTER = ${JSON.stringify(fs.readFileSync(path.join(root, "tools/claude-native/verify.py"), "utf8"))};\n`;
-if (flag === "--check") {
- if (fs.readFileSync(adapterPath, "utf8") !== adapter) throw new Error("Replay adapter changed; regenerate with sync-claude-capture.mjs");
-} else fs.writeFileSync(adapterPath, adapter);
if (JSON.parse(fs.readFileSync(path.join(cli, "package.json"), "utf8")).name !== "omnirush") throw new Error("Destination is not the CLI checkout");
-for (const name of ["native-capture.ts", "runtime.ts", "access.ts", "bundle-manifest.ts", "transfer.ts", "sandbox-assets.ts", "sandbox-lock.ts", "zip.ts", "upload.ts", "replay-adapter.ts"]) {
+for (const name of ["access.ts", "upload.ts"]) {
const source = path.join(root, "apps/server/src/claude-code", name);
const target = path.join(path.resolve(cli), "src/claude-code", name);
const bytes = fs.readFileSync(source);
if (flag === "--check") {
- if (!fs.readFileSync(target).equals(bytes)) throw new Error("CLI native collector differs; run sync-claude-capture.mjs");
+ if (!fs.readFileSync(target).equals(bytes)) throw new Error("CLI Claude account files differ; run sync-claude-capture.mjs");
} else {
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, bytes);
diff --git a/tools/claude-native/verify.py b/tools/claude-native/verify.py
deleted file mode 100644
index 38b6d7d9..00000000
--- a/tools/claude-native/verify.py
+++ /dev/null
@@ -1,689 +0,0 @@
-#!/usr/bin/env python3
-"""Private native-Claude ingress for omniconv's recorded-tool replay engine.
-
-Run on an isolated conversion worker with the reviewed omniconv checkout on
-PYTHONPATH. Never run uploaded code on the worker host. Original Claude JSONL
-is authoritative; calls.json is a derived verifier input, not an OpenCode trace.
-This verifies tool replay and selected filesystem scopes, not model inference
-or approval to distribute unmasked data.
-"""
-import argparse
-import hashlib
-import json
-import os
-from pathlib import Path
-import re
-import subprocess
-import tarfile
-import tempfile
-import time
-import uuid
-import zipfile
-from datetime import datetime
-from contextlib import contextmanager
-
-
-def sha(data):
- return hashlib.sha256(data).hexdigest()
-
-
-def file_digest(path):
- digest, size = hashlib.sha256(), 0
- with path.open('rb') as source:
- for chunk in iter(lambda: source.read(1024 * 1024), b''):
- digest.update(chunk)
- size += len(chunk)
- return {'sha256': digest.hexdigest(), 'bytes': size}
-
-
-def evidence_members(manifest):
- """Every preserved generation participates in integrity and execution checks."""
- for item in manifest['files']:
- yield item['path'], item
- for item in manifest.get('history', []):
- generation = item['generation']
- if type(generation) is not int or generation < 0:
- raise ValueError('Invalid evidence generation')
- yield f"history/{generation}/{item['path']}", item
-
-
-def jsonl(bundle, name):
- data = bundle.read(name)
- if data and not data.endswith(b'\n'):
- raise ValueError('Truncated native evidence: ' + name)
- for line in data.decode('utf-8', errors='strict').splitlines():
- if not line.strip():
- continue
- value = json.loads(line)
- if not isinstance(value, dict):
- raise ValueError('Native record must be an object: ' + name)
- yield value
-
-
-def semantic_gaps(bundle, manifest):
- """Recompute admission from bytes, not a client-supplied quality verdict."""
- records = {'user', 'assistant', 'system', 'attachment', 'progress', 'queue-operation', 'last-prompt', 'atis-latch',
- 'cost-state', 'mode', 'summary', 'file-history-snapshot', 'custom-title', 'agent-name', 'agent-color',
- 'tag', 'pr-link', 'api-request', 'api-request-blob', 'api-request-shape'}
- blocks = {'text', 'image', 'document', 'tool_use', 'tool_result', 'thinking', 'redacted_thinking'}
- unknown_records, unknown_blocks = set(), set()
- for name, item in evidence_members(manifest):
- if not item['path'].startswith('claude/projects/') or not name.endswith('.jsonl'):
- continue
- for event in jsonl(bundle, name):
- kind = event.get('type') if isinstance(event.get('type'), str) else '<missing>'
- if kind not in records:
- unknown_records.add(kind)
- if kind not in ('user', 'assistant'):
- continue
- message = event.get('message')
- content = message.get('content') if isinstance(message, dict) else None
- if isinstance(content, str):
- continue
- if not isinstance(content, list):
- unknown_blocks.add('<invalid-content>')
- continue
- for block in content:
- kind = block.get('type') if isinstance(block, dict) and isinstance(block.get('type'), str) else '<missing>'
- if kind not in blocks:
- unknown_blocks.add(kind)
- return {'unknown_record_types': sorted(unknown_records), 'unknown_block_types': sorted(unknown_blocks)}
-
-
-def model_evidence(bundle, session):
- """A separate quality check: tool replay cannot prove model provenance."""
- result = {'status': 'unknown', 'scope': 'managed-inference',
- 'identity_basis': 'provider-response-body', 'initial_workspace_provenance': 'user-supplied-unattested',
- 'eligible': False, 'blockers': []}
- contract, isolation = session.get('contract'), session.get('modelIsolation')
- if not isinstance(contract, dict) or not isinstance(isolation, dict):
- return {**result, 'status': 'legacy_unverified', 'blockers': ['model_contract_or_journal_missing']}
- try:
- saved = json.loads(bundle.read('policy/contract.json'))
- contract_bytes = json.dumps(contract, ensure_ascii=False, separators=(',', ':')).encode()
- expected = session.get('contractSha256')
- valid = (saved.get('contract') == contract and saved.get('sha256') == expected and sha(contract_bytes) == expected
- and contract.get('schema') == 1 and contract.get('sessionId') == session['id']
- and contract.get('owner') == session['owner'] and contract.get('workspaceId') == session['workspaceId']
- and contract.get('model') == session['model']
- and contract.get('execution', {}).get('baseImage') == session['base']['image']
- and contract.get('execution', {}).get('kind') == 'docker'
- and contract.get('execution', {}).get('os') == 'linux'
- and contract.get('execution', {}).get('shell') == '/bin/bash'
- and contract.get('execution', {}).get('workingDirectory') == '/workspace'
- and contract.get('harness', {}).get('name') == 'claude-code'
- and contract.get('harness', {}).get('sdkVersion') == session.get('sdkVersion')
- and contract.get('harness', {}).get('claudeVersion') == session.get('claudeVersion')
- and contract.get('capture', {}).get('scope') == 'managed-inference'
- and contract.get('capture', {}).get('modelIsolation') == 'exact')
- if not valid:
- return {**result, 'status': 'invalid', 'blockers': ['model_contract_integrity_mismatch']}
- raw = bundle.read('policy/model-requests.jsonl')
- resolved = isolation.get('resolvedModel')
- if not isinstance(resolved, str) or not resolved or session.get('authorization', {}).get('upstreamModel') != resolved:
- return {**result, 'blockers': ['bound_upstream_model_missing']}
- if resolved != session['model']:
- return {**result, 'status': 'invalid', 'blockers': ['bound_upstream_model_mismatch']}
- result['catalog_model'], result['resolved_upstream_model'] = session['model'], resolved
- result['contract_sha256'] = expected
- result['journal'] = {'sha256': sha(raw), 'bytes': len(raw)}
- if sha(raw) != isolation.get('evidenceSha256') or len(raw) != isolation.get('evidenceBytes'):
- return {**result, 'status': 'invalid', 'blockers': ['model_journal_integrity_mismatch']}
- requests, responses, identities = {}, {}, {}
- problems = set()
- for event in jsonl(bundle, 'policy/model-requests.jsonl'):
- if event.get('schema') != 1 or event.get('sessionId') != session['id']:
- problems.add('model_event_identity_mismatch')
- request_id = event.get('requestId')
- if not isinstance(request_id, str) or not request_id:
- problems.add('model_request_identity_missing')
- continue
- kind = event.get('type')
- if kind == 'request':
- if request_id in requests:
- problems.add('duplicate_model_request')
- requests[request_id] = event
- if event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('contractSha256') != expected:
- problems.add('requested_model_mismatch')
- if event.get('route') not in ('messages', 'count_tokens'):
- problems.add('unknown_model_route')
- elif kind == 'response':
- if request_id in responses:
- problems.add('duplicate_model_response')
- responses[request_id] = event
- elif kind == 'provider_identity':
- identities.setdefault(request_id, set()).add(event.get('providerModel'))
- if event.get('providerModel') != resolved or event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('source') != 'response-body':
- problems.add('observed_model_mismatch')
- elif kind == 'rejected':
- problems.add('rejected_model_request')
- else:
- problems.add('unknown_model_event')
- if set(requests) != set(responses) or set(identities) - set(requests):
- problems.add('model_journal_incomplete')
- completed = 0
- for request_id, request in requests.items():
- if request.get('route') != 'messages':
- continue
- response = responses.get(request_id, {})
- status = response.get('status')
- if type(status) is int and status >= 400:
- # Failed upstream attempts remain in evidence. They do not
- # establish another model or count as completed inference.
- if response.get('providerModels') or identities.get(request_id):
- problems.add('model_identity_on_failed_response')
- continue
- if type(status) is not int or not 200 <= status < 300 or response.get('completed') is not True or response.get('streamComplete') is not True:
- problems.add('inference_response_incomplete')
- if response.get('identity') != 'reported' or response.get('providerModels') != [resolved] or identities.get(request_id) != {resolved}:
- problems.add('inference_identity_missing_or_mixed')
- completed += 1
- if not completed:
- problems.add('no_completed_model_inference')
- if isolation.get('status') != 'observed' or isolation.get('expectedModel') != session['model'] or isolation.get('observedModels') != [resolved]:
- problems.add('model_summary_not_observed')
- invalid = bool(problems & {'model_event_identity_mismatch', 'requested_model_mismatch', 'observed_model_mismatch', 'rejected_model_request'})
- result.update(status='invalid' if invalid else 'unknown' if problems else 'observed', eligible=not problems,
- completed_inference_requests=completed, blockers=sorted(problems))
- return result
- except (KeyError, ValueError, TypeError, AttributeError, UnicodeDecodeError):
- return {**result, 'status': 'unknown', 'blockers': ['model_evidence_unreadable']}
-
-
-def stamp(value):
- return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp() * 1000
-
-
-def docker(*args, timeout=180):
- result = subprocess.run(['docker', *args], capture_output=True, timeout=timeout)
- if result.returncode:
- raise RuntimeError('Docker operation failed: ' + result.stderr.decode(errors='replace')[-1000:])
- return result.stdout.decode().strip()
-
-
-def write(path, value):
- path.write_text(json.dumps(value, indent=2) + '\n')
- path.chmod(0o600)
-
-
-@contextmanager
-def record_failure(path, report):
- try:
- yield
- except Exception as error:
- report.update(status='UNVERIFIED', strict_verified=False,
- failure={'type': type(error).__name__, 'message': str(error)})
- write(path, report)
- raise
-
-
-def text_content(content):
- if isinstance(content, str):
- return content
- return '\n'.join(block.get('text', '') for block in content or [] if block.get('type') == 'text')
-
-
-def agent_model_omission(bundle, session, manifest, call, result, stop):
- """Corroborate one reviewed SDK transform; retain the discrepancy as SOFT.
-
- SDK 0.3.306 / Claude 2.1.306's Agent schema omits model when
- CLAUDE_CODE_SUBAGENT_MODEL_FORCE is set. Its executor safeParse strips that
- field before hooks. This controller hash pins the reviewed force setting
- and unchanged hook callback. It is applicability evidence, not attestation.
- """
- def reject():
- raise ValueError('Uncorroborated native Agent model omission: ' + call['id'])
-
- controller = session.get('contract', {}).get('harness', {}).get('controllerSha256')
- if (session.get('sdkVersion'), session.get('claudeVersion'), controller) != (
- '0.3.306', '2.1.306', 'fd1d3a901953f38fc866d6ce62ec5f80ef247f878d029ae47bb581832b26ab00'):
- reject()
- if not model_evidence(bundle, session)['eligible']:
- reject()
- native = result['native']
- if (result['block'].get('is_error') or not isinstance(native, dict)
- or not isinstance(native.get('agentId'), str) or not native['agentId']
- or native.get('status') not in ('async_launched', 'completed')
- or native.get('resolvedModel') != session['model']
- or stop['input'].get('hook_event_name') != 'PostToolUse'
- or stop['input'].get('tool_response') != native):
- reject()
- member = 'events/sdk.jsonl'
- entries = [item for item in manifest['files'] if item['path'] == member]
- if len(entries) != 1 or member not in bundle.namelist():
- reject()
- raw = bundle.read(member)
- if entries[0].get('sha256') != sha(raw) or entries[0].get('bytes') != len(raw):
- reject()
- # Validate framing and JSON before inspecting physical line witnesses.
- list(jsonl(bundle, member))
- witnesses = {'requested': [], 'result': [], 'child': []}
- for number, line in enumerate(raw.splitlines(), 1):
- if not line.strip():
- continue
- event = json.loads(line)
- message = event.get('message', {})
- content = message.get('content', [])
- reference = {'path': member, 'line': number, 'sha256': sha(line), 'uuid': event.get('uuid')}
- for block in content if isinstance(content, list) else []:
- if event.get('type') == 'assistant' and block.get('type') == 'tool_use' and block.get('id') == call['id']:
- if (block.get('name') != call['tool'] or block.get('input') != call['input']
- or (event.get('agent_id') or event.get('session_id')) != call['session']):
- reject()
- witnesses['requested'].append(reference)
- if event.get('type') == 'user' and block.get('type') == 'tool_result' and block.get('tool_use_id') == call['id']:
- if block != result['block'] or event.get('tool_use_result') != native:
- reject()
- witnesses['result'].append(reference)
- if event.get('type') == 'assistant' and event.get('parent_tool_use_id') == call['id']:
- if event.get('agent_id') != native['agentId'] or message.get('model') != session['model']:
- reject()
- witnesses['child'].append(reference)
- if not all(witnesses.values()):
- reject()
- return {'kind': 'sdk_agent_model_omission', 'strict_verified': False,
- 'requested_input': call['input'], 'effective_input': call['native_effective_input'],
- 'resolved_model': native['resolvedModel'], 'controller_sha256': controller,
- 'sdk_witnesses': witnesses, 'model_journal_sha256': session['modelIsolation']['evidenceSha256']}
-
-
-def calls_from(bundle, session, manifest):
- hooks = list(jsonl(bundle, 'events/hooks.jsonl'))
- starts, stops = {}, {}
- for event in hooks:
- item = event['input']
- if item.get('hook_event_name') == 'PreToolUse':
- key = item['tool_use_id']
- if key in starts:
- raise ValueError('Ambiguous repeated tool execution: ' + key)
- starts[key] = event
- elif item.get('hook_event_name') in ('PostToolUse', 'PostToolUseFailure'):
- key = item['tool_use_id']
- if key in stops:
- raise ValueError('Ambiguous repeated tool completion: ' + key)
- stops[key] = event
- calls, results = {}, {}
- for name, file in evidence_members(manifest):
- if not file['path'].startswith('claude/projects/') or not file['path'].endswith('.jsonl'):
- continue
- for event in jsonl(bundle, name):
- if event.get('type') not in ('assistant', 'user'):
- continue # Request-cache blobs repeat context; they are not executions.
- content = event.get('message', {}).get('content')
- if not isinstance(content, list):
- continue
- for block in content:
- if block.get('type') == 'tool_use':
- key = block['id']
- hook = starts.get(key)
- if hook is None:
- raise ValueError('No execution hook for native call: ' + key)
- item = hook['input']
- if item['tool_name'] != block['name']:
- raise ValueError('Native transcript and hook disagree: ' + key)
- requested, effective = block['input'], item['tool_input']
- if requested != effective and not (
- block['name'] == 'Agent' and isinstance(requested, dict) and isinstance(effective, dict)
- and isinstance(requested.get('model'), str) and requested['model']
- and {k: v for k, v in requested.items() if k != 'model'} == effective):
- raise ValueError('Native transcript and hook disagree: ' + key)
- call = {'id': key, 'tool': block['name'], 'input': block['input'],
- 'start': stamp(hook['time']), 'turn': hook['turn'],
- 'session': item.get('agent_id') or event.get('agentId') or session['id'], 'status': 'pending',
- 'source': {'path': name, 'uuid': event.get('uuid')}, 'native_read_witness': hook.get('witness'),
- 'native_cwd': item.get('cwd')}
- if requested != effective:
- call['native_effective_input'] = effective
- if key in calls and (calls[key]['tool'], calls[key]['input']) != (call['tool'], call['input']):
- raise ValueError('Conflicting native call identity: ' + key)
- if key not in calls:
- call['sources'] = [call['source']]
- calls[key] = call
- elif call['source'] not in calls[key]['sources']:
- calls[key]['sources'].append(call['source'])
- elif block.get('type') == 'tool_result':
- key = block['tool_use_id']
- value = {'block': block, 'native': event.get('toolUseResult'), 'end': event.get('timestamp')}
- if key in results and (results[key]['block'], results[key]['native']) != (block, value['native']):
- raise ValueError('Conflicting native result identity: ' + key)
- results[key] = value
- if set(starts) != set(calls):
- raise ValueError('Execution hooks and native calls do not form a complete set')
- if set(results) != set(calls):
- raise ValueError('Native calls and results do not form a complete set')
- for key, call in calls.items():
- if key not in results:
- raise ValueError('Native tool result missing: ' + key)
- result = results[key]
- block, native = result['block'], result['native']
- stop = stops.get(key)
- if stop is None:
- raise ValueError('Native tool completion hook missing: ' + key)
- if stop['turn'] != call['turn'] or stop['input']['tool_name'] != call['tool'] or stop['input']['tool_input'] != call.get('native_effective_input', call['input']):
- raise ValueError('Native tool completion hook disagrees: ' + key)
- if 'native_effective_input' in call:
- call['native_input_normalization'] = agent_model_omission(bundle, session, manifest, call, result, stop)
- call.update(status='error' if block.get('is_error') else 'completed',
- output=text_content(block.get('content')), end=stamp(stop['time']))
- if call['end'] < call['start']:
- raise ValueError('Native execution interval runs backwards: ' + key)
- call['meta'] = {'native_tool_result': native}
- if isinstance(native, dict):
- if native.get('agentId'):
- call['meta']['child_session_id'] = native['agentId']
- # Structured stdout/stderr avoid comparing Claude's no-output UI
- # placeholder as if it were bytes printed by the user's command.
- if call['tool'] == 'Bash' and isinstance(native.get('stdout'), str) and isinstance(native.get('stderr'), str):
- call['output'] = native['stdout'] + native['stderr']
- if native.get('type') == 'file_unchanged':
- # This SDK optimization contains no read bytes. It cannot prove
- # that a replayed read matched; never invent bytes from after.
- call['native_file_unchanged'] = True
- return sorted(calls.values(), key=lambda call: (call['start'], call['id']))
-
-
-def native_bash(verify, ctr, call, state):
- """Replay the recorded command without the generic converter's shell fixes.
-
- Claude's Bash result does not expose its numeric exit or actual shell argv.
- Command/cwd are evidence; /bin/bash -lc is a declared reproduction recipe.
- Therefore even matching stdout and success are SOFT, never strict proof.
- """
- inp, native = call['input'], call['meta']['native_tool_result']
- cmd, cwd = inp.get('command'), call.get('native_cwd')
- if not isinstance(cmd, str) or not cmd.strip():
- return {'outcome': 'not_replayable', 'reason': 'native_command_missing'}
- if not isinstance(cwd, str) or not cwd.startswith('/') or '\0' in cwd:
- return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}
- if not isinstance(native, dict) or not all(isinstance(native.get(k), str) for k in ('stdout', 'stderr')):
- return {'outcome': 'no_evidence', 'why': 'native Bash stdout/stderr are missing'}
- if native.get('interrupted') or inp.get('run_in_background') or native.get('backgroundTaskId'):
- return {'outcome': 'not_replayable', 'reason': 'native_background_or_interrupted'}
- if any(native.get(key) for key in ('truncated', 'truncation', 'fullOutputPath', 'outputFile', 'isImage')):
- return {'outcome': 'not_replayable', 'reason': 'native_output_not_text_complete'}
- if verify.classify(cmd) in ('skipped_side_effect', 'server'):
- return {'outcome': 'not_replayable', 'reason': 'native_external_effect_or_server'}
- state.setdefault('commands', []).append(cmd)
- timeout_ms = inp.get('timeout', 120000)
- if type(timeout_ms) is not int or timeout_ms < 1 or timeout_ms > 600000:
- return {'outcome': 'not_replayable', 'reason': 'native_timeout_unsupported'}
- argv = ['docker', 'exec', '-w', cwd, ctr, 'timeout', str(timeout_ms / 1000), '/bin/bash', '-lc', cmd]
- began = time.monotonic()
- try:
- result = subprocess.run(argv, capture_output=True, timeout=timeout_ms / 1000 + 30)
- except subprocess.TimeoutExpired:
- return {'outcome': 'harness_error', 'reason': 'native_command_timeout'}
- stdout, stderr = result.stdout.decode(errors='replace'), result.stderr.decode(errors='replace')
- rec = {'recorded_command_sha256': sha(cmd.encode()), 'cwd': cwd, 'shell_recipe': ['/bin/bash', '-lc'],
- 'actual_shell_argv_observed': False, 'numeric_recorded_exit': None, 'replay_exit': result.returncode,
- 'recorded_stdout_sha256': sha(native['stdout'].encode()), 'recorded_stderr_sha256': sha(native['stderr'].encode()),
- 'replay_stdout_sha256': sha(result.stdout), 'replay_stderr_sha256': sha(result.stderr),
- 'seconds': round(time.monotonic() - began, 3)}
- if result.returncode == 124:
- return {**rec, 'outcome': 'harness_error', 'reason': 'native_command_timeout'}
- if (result.returncode != 0) != (call['status'] == 'error'):
- return {**rec, 'outcome': 'diverge', 'why': 'native Bash success/failure differs'}
- exact = stdout == native['stdout'] and stderr == native['stderr']
- # SDK output formatting can strip final newlines. Show that difference,
- # with separate raw hashes; never silently count it as an exact match.
- formatted = stdout.rstrip('\n') == native['stdout'].rstrip('\n') and stderr.rstrip('\n') == native['stderr'].rstrip('\n')
- if not exact and not formatted:
- return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash output differs; shell invocation is unobserved', 'output_exact': False, 'output': {'stdout': stdout, 'stderr': stderr}}
- return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash actual shell argv and numeric exit are unobserved',
- 'output_exact': exact, 'output_diff': None if exact else 'trailing_newlines'}
-
-
-NATIVE_EDIT = r'''
-import hashlib, json, os, sys
-request = json.load(sys.stdin)
-tool, inp = request['tool'], request['input']
-name = inp['file_path']
-try:
- with open(name, 'rb') as source:
- original = source.read()
-except FileNotFoundError:
- original = None
-if tool == 'Write':
- result = inp['content'].encode('utf-8')
-elif tool == 'Edit':
- if original is None:
- raise ValueError('native_edit_file_missing')
- old, new = inp['old_string'].encode('utf-8'), inp['new_string'].encode('utf-8')
- if not old:
- raise ValueError('native_empty_edit_unsupported')
- count = original.count(old)
- if not count or (count != 1 and not inp.get('replace_all', False)):
- raise ValueError('native_edit_exact_match_missing_or_ambiguous')
- result = original.replace(old, new, -1 if inp.get('replace_all', False) else 1)
-else:
- raise ValueError('unsupported_native_edit')
-os.makedirs(os.path.dirname(os.path.abspath(name)), exist_ok=True)
-with open(name, 'wb') as target:
- target.write(result)
- target.flush()
- os.fsync(target.fileno())
-print(json.dumps({'before_sha256': hashlib.sha256(original).hexdigest() if original is not None else None,
- 'after_sha256': hashlib.sha256(result).hexdigest(), 'bytes': len(result)}))
-'''
-
-
-def native_edit(ctr, call, state):
- """Apply literal native input; no redaction repair or whitespace matching."""
- inp, cwd = call['input'], call.get('native_cwd')
- if call['status'] != 'completed':
- return {'outcome': 'not_replayable', 'reason': 'native_failed_edit_semantics'}
- if not isinstance(cwd, str) or not cwd.startswith('/') or not isinstance(inp.get('file_path'), str):
- return {'outcome': 'not_replayable', 'reason': 'native_edit_path_missing'}
- fields = ('content',) if call['tool'] == 'Write' else ('old_string', 'new_string')
- if not all(isinstance(inp.get(key), str) for key in fields):
- return {'outcome': 'not_replayable', 'reason': 'native_edit_input_missing'}
- payload = json.dumps({'tool': call['tool'], 'input': inp}).encode()
- result = subprocess.run(['docker', 'exec', '-i', '-w', cwd, ctr, 'python3', '-c', NATIVE_EDIT],
- input=payload, capture_output=True, timeout=60)
- if result.returncode:
- return {'outcome': 'diverge', 'why': 'native literal edit could not be applied', 'path': inp['file_path']}
- state.setdefault('touched', set()).add(inp['file_path'])
- return {'outcome': 'match', 'path': inp['file_path'], 'literal_input': True, **json.loads(result.stdout)}
-
-
-def replay_verdict(replay, differences, selected):
- """Admission cannot inherit a permissive generic-verifier success label."""
- pairs = replay.get('per_call', [])
- if len(pairs) != len(selected) or {pair[0] for pair in pairs} != {call['id'] for call in selected}:
- return 'UNVERIFIED', False, ['execution_coverage_incomplete']
- outcomes = [pair[1].split(':', 1)[0] for pair in pairs]
- if any(differences.values()) or 'diverge' in outcomes:
- return 'DIFFERS', False, ['filesystem_or_tool_result_differs']
- allowed = {'match', 'diverge-soft', 'subagent'}
- blocked = sorted(set(outcomes) - allowed)
- if blocked:
- return ('TOOLS_RAN' if set(blocked) == {'tool-worked'} else 'UNVERIFIED'), False, blocked
- if not outcomes or all(outcome == 'subagent' for outcome in outcomes):
- return 'UNVERIFIED', False, ['no_tool_result_compared']
- soft = ('diverge-soft' in outcomes or bool(replay.get('matches_leaning_on'))
- or any(call.get('native_input_normalization') for call in selected))
- return ('VERIFIED_WITH_SOFT_DIFFS' if soft else 'VERIFIED'), True, []
-
-
-def tree(container, scope):
- proc = subprocess.Popen(['docker', 'cp', container + ':' + scope, '-'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- output = {}
- try:
- with tarfile.open(fileobj=proc.stdout, mode='r|') as archive:
- for member in archive:
- record = {'mode': member.mode, 'type': member.type.decode('ascii'), 'link': member.linkname,
- 'uid': member.uid, 'gid': member.gid}
- if member.isfile():
- digest = hashlib.sha256()
- with archive.extractfile(member) as data:
- for chunk in iter(lambda: data.read(1024 * 1024), b''):
- digest.update(chunk)
- record.update(sha256=digest.hexdigest(), bytes=member.size)
- if member.name in output:
- raise ValueError('Ambiguous filesystem archive member')
- output[member.name] = record
- if proc.wait(timeout=30):
- raise RuntimeError('Cannot inspect replay filesystem')
- return output
- finally:
- if proc.poll() is None:
- proc.kill()
- proc.communicate()
-
-
-def main():
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument('zip', type=Path)
- parser.add_argument('--out', required=True, type=Path)
- parser.add_argument('--check-path', action='append', default=[], help='Additional absolute filesystem scope to compare after every turn')
- args = parser.parse_args()
- from omniconv import verify
- original_replay = verify.replay_one
- def replay_native(ctr, root, call, index, calls, state, context):
- if call['tool'] == 'Bash':
- return native_bash(verify, ctr, call, state)
- if call['tool'] in ('Write', 'Edit'):
- return native_edit(ctr, call, state)
- if not call.get('native_file_unchanged') and not (call['tool'] == 'Read' and call.get('native_read_witness')):
- # Absolute native paths pass unchanged. Relative paths resolve from
- # the recorded hook cwd, never a guessed root or a repaired cwd.
- cwd = call.get('native_cwd')
- if not isinstance(cwd, str) or not cwd.startswith('/'):
- return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}
- kind = verify.RT.kind_of(call['tool'])[0]
- if kind == 'shell':
- return {'outcome': 'not_replayable', 'reason': 'unsupported_native_shell'}
- if kind == 'edit':
- return {'outcome': 'not_replayable', 'reason': 'unsupported_native_edit'}
- return original_replay(ctr, cwd, call, index, calls, state, context)
- witness = call.get('native_read_witness')
- if call['status'] != 'completed':
- return {'outcome': 'not_replayable', 'reason': 'native_failed_read_semantics'}
- if not witness or witness.get('path') != call['input'].get('file_path') or not re.fullmatch(r'[a-f0-9]{64}', str(witness.get('sha256', ''))):
- return {'outcome': 'not_replayable', 'reason': 'native_cached_read_without_witness'}
- script = "import hashlib,json,os,stat,sys\np=sys.argv[1];s=os.stat(p)\nassert stat.S_ISREG(s.st_mode)\nh=hashlib.sha256()\nwith open(p,'rb') as f:\n for b in iter(lambda:f.read(1048576),b''):h.update(b)\nprint(json.dumps({'sha256':h.hexdigest(),'bytes':s.st_size,'mode':s.st_mode}))"
- code, output, _ = verify.sh(['docker', 'exec', ctr, 'python3', '-c', script, witness['path']], 60)
- actual = json.loads(output) if code == 0 and output.strip() else None
- expected = {key: witness.get(key) for key in ('sha256', 'bytes', 'mode')}
- return {'outcome': 'match' if actual == expected else 'diverge',
- 'why': 'native cached read checked against the pre-tool byte witness',
- 'recorded_witness': expected, 'replay_witness': actual, 'path': witness['path']}
- verify.replay_one = replay_native
- os.umask(0o077)
- args.out.mkdir(parents=True, exist_ok=False)
- scopes = ['/workspace', *args.check_path]
- if any(not scope.startswith('/') or '..' in Path(scope).parts for scope in scopes):
- raise ValueError('Check paths must be absolute')
- report = {'schema': 2, 'format': 'claude-code-native', 'verifier': verify.fingerprint(),
- 'adapter_sha256': sha(Path(__file__).read_bytes()), 'network': 'none',
- 'input_artifact': file_digest(args.zip),
- 'filesystem_scopes': scopes, 'private': True, 'delivery_ready': False,
- 'meaning': 'Recorded tool replay with explicit strict/soft outcomes. Original evidence is never rewritten. Delivery selection is separate.',
- 'status': 'UNVERIFIED', 'turns': []}
- write(args.out / 'replay.json', report)
- with record_failure(args.out / 'replay.json', report), zipfile.ZipFile(args.zip) as bundle:
- if len(bundle.namelist()) != len(set(bundle.namelist())):
- raise ValueError('Duplicate ZIP member')
- session_bytes, manifest_bytes = bundle.read('session.json'), bundle.read('native-manifest.json')
- session, manifest = json.loads(session_bytes), json.loads(manifest_bytes)
- report['adapter_source'] = 'external'
- report['embedded_adapter_sha256'] = sha(bundle.read('verify.py')) if 'verify.py' in bundle.namelist() else None
- report['embedded_adapter_matches_external'] = report['embedded_adapter_sha256'] == report['adapter_sha256']
- report['session_sha256'], report['manifest_sha256'] = sha(session_bytes), sha(manifest_bytes)
- report['model_isolation'] = model_evidence(bundle, session)
- report['session_id'] = session['id']
- if manifest['sessionId'] != session['id'] or manifest['status'] != 'complete' or session['capture'] != 'complete':
- raise ValueError('Incomplete native session cannot pass replay admission')
- checked = set()
- for name, item in evidence_members(manifest):
- if name in checked or '\\' in name or name.startswith('/') or '..' in name.split('/'):
- raise ValueError('Ambiguous native evidence path')
- checked.add(name)
- content = bundle.read(name)
- if len(content) != item['bytes'] or sha(content) != item['sha256']:
- raise ValueError('Native evidence integrity failure: ' + name)
- if 'events/hooks.jsonl' not in checked:
- raise ValueError('Execution hooks are not covered by the native manifest')
- report['evidence_generations_checked'] = len(checked)
- report['semantic_gaps'] = semantic_gaps(bundle, manifest)
- report['semantic_review_required'] = any(report['semantic_gaps'].values())
- calls = calls_from(bundle, session, manifest)
- report['input_normalizations'] = [{'id': call['id'], **call['native_input_normalization']}
- for call in calls if call.get('native_input_normalization')]
- if any(call['turn'] not in {turn['number'] for turn in session['turns']} for call in calls):
- raise ValueError('A native call lies outside the captured turn sequence')
- write(args.out / 'calls.json', calls)
- report['calls_artifact'] = file_digest(args.out / 'calls.json')
- checkpoints = [session['base'], *[turn['after'] for turn in session['turns']]]
- if not session['turns'] or any(turn['status'] != 'complete' for turn in session['turns']):
- raise ValueError('Every admitted turn must have completed')
- if [turn['number'] for turn in session['turns']] != list(range(1, len(session['turns']) + 1)):
- raise ValueError('Native user turn sequence is incomplete or ambiguous')
- loaded = set()
- for cp in checkpoints:
- if not re.fullmatch(r'sha256:[a-f0-9]{64}', cp['image']):
- raise ValueError('Invalid image digest')
- if cp['file'] in loaded:
- continue
- if not re.fullmatch(r'images/[a-f0-9]{64}\.tar\.gz', cp['file']):
- raise ValueError('Invalid image archive path')
- with tempfile.NamedTemporaryFile(suffix='.tar.gz') as target:
- digest = hashlib.sha256(); size = 0
- with bundle.open(cp['file']) as source:
- for chunk in iter(lambda: source.read(1024 * 1024), b''):
- digest.update(chunk); size += len(chunk); target.write(chunk)
- target.flush()
- if digest.hexdigest() != cp['sha256'] or size != cp['bytes']:
- raise ValueError('Environment archive integrity failure')
- docker('load', '--input', target.name, timeout=600)
- loaded.add(cp['file'])
- for turn in session['turns']:
- if turn['number'] < 1 or turn['before']['image'] != checkpoints[turn['number'] - 1]['image']:
- raise ValueError('Broken before/after environment chain')
- selected = [call for call in calls if call['turn'] == turn['number']]
- name = 'omnirush-native-replay-' + uuid.uuid4().hex
- expected = name + '-expected'
- try:
- common = ['--network=none', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--pids-limit=256', '--memory=4g', '--cpus=2']
- docker('run', '-d', '--name', name, *common, turn['before']['image'], 'sleep', 'infinity')
- docker('create', '--name', expected, *common, turn['after']['image'])
- replay = verify.replay_calls(name, '/workspace', selected, context={'main': session['id'], 'sessions': sorted({call['session'] for call in calls})})
- differences = {}
- for scope in scopes:
- actual_tree, expected_tree = tree(name, scope), tree(expected, scope)
- differences[scope] = [key for key in sorted(set(actual_tree) | set(expected_tree)) if actual_tree.get(key) != expected_tree.get(key)]
- status, accepted, blockers = replay_verdict(replay, differences, selected)
- if report['semantic_review_required']:
- status, accepted = 'UNVERIFIED', False
- blockers.append('unknown_native_semantics')
- report['turns'].append({'number': turn['number'], 'before_image': turn['before']['image'], 'after_image': turn['after']['image'],
- 'calls': len(selected), 'accepted': accepted, 'strict_verified': status == 'VERIFIED',
- 'status': status, 'blockers': blockers, 'replay': replay, 'filesystem_differences': differences})
- write(args.out / 'replay.json', report)
- finally:
- subprocess.run(['docker', 'rm', '-f', name, expected], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- if file_digest(args.zip) != report['input_artifact']:
- report.update(status='UNVERIFIED', strict_verified=False, failure={'type': 'input_integrity', 'message': 'Input artifact changed during replay'})
- write(args.out / 'replay.json', report)
- raise ValueError('Input artifact changed during replay')
- if all(turn['accepted'] for turn in report['turns']):
- report['status'] = 'VERIFIED' if all(turn['strict_verified'] for turn in report['turns']) else 'VERIFIED_WITH_SOFT_DIFFS'
- elif any(turn['status'] == 'DIFFERS' for turn in report['turns']):
- report['status'] = 'DIFFERS'
- elif any(turn['status'] == 'TOOLS_RAN' for turn in report['turns']):
- report['status'] = 'TOOLS_RAN'
- report['strict_verified'] = report['status'] == 'VERIFIED'
- blockers = list(report['model_isolation']['blockers'])
- if report['status'] not in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS'):
- blockers.append('tool_replay_not_verified')
- if report['semantic_review_required']:
- blockers.append('unknown_native_semantics')
- report['quality_admission'] = {'eligible': not blockers, 'blockers': blockers,
- 'retained': True, 'delivery_selection': 'separate'}
- write(args.out / 'replay.json', report)
- print(json.dumps({'session_id': report['session_id'], 'status': report['status'], 'turns': len(report['turns']), 'report': str(args.out / 'replay.json')}))
- return 0 if report['status'] in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS') else 1
-
-
-if __name__ == '__main__':
- raise SystemExit(main())